我正在尝试以水平顺序动态添加一些按钮。我尝试了几个选项,但没有一个可行。 我究竟做错了什么?
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++;
}
答案 0 :(得分:0)
这有一些问题。首先,像@EasyJoin Dev所说,在布局xml中用RelativeLayout
替换LinearLayout
并将方向设置为水平。它应该看起来像这样
<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
,它将占用整个空间。如果您需要更多帮助或者这不起作用,请告诉我