1

我想在滑动抽屉的内容中添加一些按钮,它的内容是相对布局。按钮将在 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);

现在如何将所有按钮添加到相对布局中?谢谢您的帮助。

4

2 回答 2

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); 
    }
于 2012-05-25T10:29:30.900 回答
0

只需这样做:

layout.addView(btn);
于 2012-05-25T10:27:33.680 回答