我正试图解决这个难题:“如何将列表中的其余按钮放在第一个按钮下。”
为了解决这个问题,我试图设置一个布尔值来检测第一个按钮,并在下面的任何内容上应用规则,但是button1似乎每次都在button0的顶部。
我在下面列出了MainActivity。布局xml只有一个相对布局。
public class MainActivity extends Activity implements View.OnClickListener {
private ArrayList<Category> categories = new ArrayList<Category>();
private ArrayList<Button> buttons = new ArrayList<Button>();
private boolean firstButton = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RelativeLayout relLayout = (RelativeLayout) findViewById(R.id.mainLayout);
categories.add(new Category("Mobility",CategoryTypes.MOBILITY));
categories.add(new Category("Flexibility",CategoryTypes.FLEXIBILITY));
categories.add(new Category("Mobility",CategoryTypes.MOBILITY));
categories.add(new Category("Flexibility",CategoryTypes.FLEXIBILITY));
categories.add(new Category("Mobility",CategoryTypes.MOBILITY));
categories.add(new Category("Mobility",CategoryTypes.MOBILITY));
for (int i = 0; i < 6; i++)
{
makeButton(this, "Buttons"+i,i);
}
for (int i = 0; i < buttons.size(); i++)
{
addButtonToLayout(buttons.get(i),relLayout,i);
System.out.println(buttons.get(i).getLayoutParams());
}
}
//This method constructs a button object, sets its text, id and an OnClickListener. Finally adds the buttons to buttons arraylist
void makeButton (Context context, String buttonText, int id)
{
Button button = new Button(context);
button.setText(buttonText);
button.setId(id);
button.setOnClickListener(this);
buttons.add(button);
System.out.println(button.getId());
}
//Method to add button to layout. The LayoutParams are used to add the rule that the buttons should be underneath each other.
void addButtonToLayout (Button button, RelativeLayout layout, int index)
{
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
RelativeLayout.LayoutParams paramsForSecondButton = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
if (firstButton)
{
firstButton = false;
System.out.println(buttons.get(index).getText());
//TODO: [BUG] Doesn't add the first button for some reason.
}
else if (!firstButton)
{
params.addRule(RelativeLayout.BELOW, buttons.get(index-1).getId());
}
//paramsForSecondButton.addRule(RelativeLayout.BELOW, buttons.get(0).getId());
//params.addRule(RelativeLayout.BELOW, buttons.get(index).getId());
button.setLayoutParams(params);
// buttons.get(1).setLayoutParams(paramsForSecondButton);
layout.addView(button);
}
这是布局的图像:
答案 0 :(得分:2)
answer类似的问题可以帮助您。
您失败的原因是您使用的是ID。 Android使用“保留”ID来处理应用程序的常规内容区域。
使用您的代码,我能够为每个ID添加1000并生成预期结果。
以这种方式定位按钮也不是一个好主意。除非你有理由,否则LinearLayout
将以计算时间的一半价格完成工作。
答案 1 :(得分:0)
在这种情况下你试过了吗?
if (firstButton)
{
firstButton = false;
params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
}
else if (!firstButton)
{
params.addRule(RelativeLayout.BELOW, buttons.get(index-1).getId());
}