我想在Sliding Drawer的内容中添加一些按钮,其内容是相对布局。 该按钮将在Java代码中定义,相对布局已在xml布局中定义。所以,假设我想添加4个按钮:
for (int i=0; i<4; i++) {
Button btn = new Button(this);
btn.setId(i);
btn.setText("some_text");
}
然后我初始化相对布局:
RelativeLayout layout = (RelativeLayout)findViewById(R.id.slidingDrawerContent);
现在如何将所有Button添加到相对布局中?谢谢你的帮助。
答案 0 :(得分:3)
RelativeLayout layout = (RelativeLayout)findViewById(R.id.slidingDrawerContent);
for (int i=0; i<4; i++) {
Button btn = new Button(this);
btn.setId(i);
btn.setText("some_text");
layout.add(btn);
}
或
有点提前
RelativeLayout layout = (RelativeLayout)findViewById(R.id.slidingDrawerContent);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT );
for (int i=0; i<4; i++) {
Button btn = new Button(this);
btn.setId(i);
btn.setText("some_text");
// lp.addRule(RelativeLayout.RIGHT_OF, <Id>);
layout.addView(tv2, lp);
}
答案 1 :(得分:0)
只需这样做:
layout.addView(btn);