我试图将2个buttons动态添加到我的relative layout中。我希望它看起来像这样:



但目前看起来像这样:



在@Abdallah Alaraby的帮助下:

    myButton1 = new Button(this);
    myButton1.setBackgroundResource(R.drawable.button);
    myButton1.setText("bttn1");

    myButton2 = new Button(this);
    myButton2.setBackgroundResource(R.drawable.button);
    myButton2.setText("bttn2");


    RelativeLayout rl = (RelativeLayout)findViewById(R.id.rl_dynamic_bttn);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);

lp1.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
lp.addRule(RelativeLayout.RIGHT_OF, myButton2.getId());
rl.addView(myButton1, lp1);
rl.addView(myButton2, lp);
...
...

}


我尝试了各种不同的分配选项,但似乎没有任何效果。有人知道如何使这张照片看起来像第一张照片吗?

问题可能出在my_button2.getId()上吗?也许无法识别?

最佳答案

lp.addRule(RelativeLayout.RIGHT_OF, myButton2.getId());
rl.addView(myButton1, lp);
rl.addView(myButton2, lp);


两个按钮都使用相同的规则,请尝试以下操作:

RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);

myButton1.setId(1)
lp1.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
lp.addRule(RelativeLayout.RIGHT_OF, myButton2.getId());
rl.addView(myButton1, lp1);
rl.addView(myButton2, lp);


如果myButton2没有分配的ID,则默认ID为-1,它将不起作用。您必须先使用myButton2.setId(int)才能使用myButton2.getId()

10-05 18:07