在android中重叠按钮

时间:2014-10-27 16:56:01

标签: java android

在android中,我试图以编程方式添加按钮,但添加的所有按钮都是重叠的。我使用的代码有点像这样:

for(int i = (int) 'a'; i <= (int) 'z'; i++)
{
    Button button = new Button(this);
    char letter = (char)i;
    String letterOnButton = Character.toString(letter);
    button.setText(letterOnButton);
    RelativeLayout rl = (RelativeLayout)findViewById(R.id.dynbuttons);
    LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
    rl.addView(button,lp);
}

它不会抛出按钮,但我只能看到&#34; z&#34;按钮。

有关如何解决这个问题的想法吗?

2 个答案:

答案 0 :(得分:1)

如上所述,LinearLayout将是最好的解决方案,但是如果你仍然想要使用RelativeLayout,请尝试为每个按钮设置一个id,并使用上面建议的参数RIGHT_OF / BELOW ...给后续充气,参数“layout_alignLeft”将产生相同的效果,即在同一位置充气所有按钮

RelativeLayout rl = (RelativeLayout) findViewById(R.id.layout);
        int id = 0;

        for (int i = (int) 'a'; i <= (int) 'z'; i++) {
            Button button = new Button(this);
            char letter = (char) i;
            String letterOnButton = Character.toString(letter);
            button.setText(letterOnButton);
            button.setId(i);
            LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT);
            lp.addRule(RelativeLayout.BELOW, id);
            rl.addView(button, lp);
            id = i;
        }

答案 1 :(得分:0)

我会选择LinearLayout代替RelativeLayout,如下所示:

LinearLayout ll = (LinearLayout)findViewById(R.id.dynbuttons);
LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
for(int i = (int) 'a'; i <= (int) 'z'; i++) {
    Button button = new Button(this);
    char letter = (char)i;
    String letterOnButton = Character.toString(letter);
    button.setText(letterOnButton);
    ll.addView(button,lp);
}

如果您仍想使用RelativeLayout,则必须为每个按钮设置参数layout_alignLeft