RelativeLayout与按钮

时间:2011-03-17 18:08:28

标签: android relativelayout

我想动态地向RelativeLayout添加按钮数,但我的代码不起作用。它将它们添加到显示屏上的相同位置。

private void createButtons() {
        buttons = new ArrayList<Button>();  
        RelativeLayout bg = (RelativeLayout) findViewById(R.id.Bg);
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);

        for(int i = 0; i < channels.size(); i++){ 
            Button newButton = new Button(this);
            newButton.setId(i);
            newButton.setText(channels.get(i).getTitle());
            buttons.add(newButton);
            if(i > 0){
                lp.addRule(RelativeLayout.RIGHT_OF, i-1);
                bg.addView(newButton, lp);
            }else{
                bg.addView(newButton);
            }
        }

    }

我应该如何解决这个问题呢?

1 个答案:

答案 0 :(得分:2)

你有几个问题。首先,您需要为每个按钮创建布局新布局参数,以避免@rogerkk指出的问题。其次,您尝试使用第一个按钮的ID为零。这不起作用。

这是修复这两个问题的函数的返工。

private void createButtons() {
    buttons = new ArrayList<Button>();  
    RelativeLayout bg = (RelativeLayout) findViewById(R.id.Bg);

    for(int i = 0; i < channels.size(); i++){ 
        Button newButton = new Button(this);
        newButton.setId(i+1); // ID of zero will not work
        newButton.setText(channels.get(i).getTitle());
        buttons.add(newButton);
        // New layout params for each button
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);

        if(i > 0){
            // using getId() here in case you change how you assign IDs 
           int id =buttons.get(i-1).getId();
           lp.addRule(RelativeLayout.RIGHT_OF, id);
        }
        bg.addView(newButton,lp);            
    }

}