Android Dyanmic按钮布局

时间:2016-01-14 18:46:47

标签: android

创建动态按钮时,我希望它们在垂直方向上堆叠一个。我不知道如何创造这种效果。

for(int i = 0; i <notificationArrayList.size(); i++)
    {
        if(i == 0)
        {lp.addRule(RelativeLayout.BELOW, R.id.searchButton);}
        else
        {} //maybe tell the code here to stack under the lastID?
        Notification oNote = notificationArrayList.get(i);
        Button btn = new Button(this);
        btn.setId(i);
        final int id_ = btn.getId();
        btn.setText(oNote.NotificationText);
        btn.setBackgroundColor(Color.rgb(70, 80, 90));
        rl.setLayoutParams(lp);
        rl.addView(btn, lp);
    }

也许在else语句中得到最后一个id并以这种方式添加RelativeLayout?

2 个答案:

答案 0 :(得分:1)

最简单的方法是将所有按钮放在LinearLayout中,然后在搜索按钮下方添加LinearLayout。这会产生更简单的代码,但绘制性能会稍差。伪代码就像:

LinearLayout ll = new LinearLayout(context);
for(i=0; i<numButtons; i++) {
  ll.addView(new Button(context));
}
RelativeLayout.LayoutParam lp = new RelativeLayout.LayoutParam();
lp.addRule(RelativeLayout.BELOW, R.id.searchButton);
relativeLayout.addView(ll,lp);

答案 1 :(得分:0)

这个例子可以给你一个想法:

public class MyActivity extends Activity {

private RelativeLayout rel;
private EditText editText;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_mine);

    rel = (RelativeLayout) findViewById(R.id.main_rel);
    editText = (EditText) findViewById(R.id.pref_edit_text);

    Button button = new Button(this);
    button.setText("Delete");

    // create the layout params that will be used to define how your
    // button will be displayed
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
            LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

    // add the rule that places your button below your object (here a editText)
    params.addRule(RelativeLayout.BELOW, editText.getId());

    // set the layoutParams on the button
    button.setLayoutParams(params);

    // add button to your RelativeLayout
    rel.addView(button);
}
}