我正在尝试向我的buttons
动态添加2 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()
吗?也许它不被认可?
答案 0 :(得分:2)
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.getId()之前使用myButton2.setId(int)