按水平顺序添加动态按钮



我正在尝试以水平顺序动态添加一些按钮。我尝试了几种选择,但它们都没有起作用。我究竟做错了什么?

RelativeLayout layout = (RelativeLayout) findViewById(R.id.pickItem);
RelativeLayout.LayoutParams buttonParams =
        new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT);
buttonParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
buttonParams.addRule(RelativeLayout.CENTER_VERTICAL);
String userName;
List<CheckBox> usersButtonList=new ArrayList<CheckBox>();
int i=0;
for(User user : users){
    userName=user.getName();
    CheckBox Userbutton = new CheckBox(this);
    usersButtonList.add(Userbutton);
    Userbutton.setText(userName);
    Userbutton.setId(i);
    Userbutton .setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            boolean isChecked=((CheckBox)v).isChecked();
            String s= (String)((CheckBox)v).getText();
            updateActiveUsers(isChecked,s);
        }
    });
    if(i!=0)
    {
        buttonParams.addRule(RelativeLayout.ALIGN_RIGHT,(i-1));
    }
    layout.addView(Userbutton,buttonParams);
    i++;
}

这有一些错误。首先,就像@easyjoin Dev所说,在布局XML中用LinearLayout替换RelativeLayout,并将方向设置为水平。它应该看起来像这样

<LinearLayout
    android:id="@+id/pickItem"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">
</LinearLayout>

然后将代码中的两条顶线更改为

LinearLayout layout = (LinearLayout) findViewById(R.id.pickItem);
LinearLayout.LayoutParams buttonParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

由于您有ViewGroup.LayoutParams.FILL_PARENT,它将占用整个可用空间。让我知道您是否需要更多帮助,或者这不起作用

最新更新