RelativeLayout的带按钮 [英] RelativeLayout with buttons

查看:150
本文介绍了RelativeLayout的带按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要添加按钮的数量来动态RelativeLayout的,但我的code不起作用。它增加了它们在显示器上的相同位置。

I want to add number of buttons to RelativeLayout dynamically, but my code doesn't work. It adds them to the same place on the display.

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);
            }
        }

    }

我应该怎么修复,使其工作?

What should I fix to make it work?

推荐答案

您有几个问题。首先,你需要为每个按钮,以避免@rogerkk指出问题后创建布局新布局PARAMS。其次,你要使用一个零的ID为第一个按钮。这是行不通的。

You have a couple of problem. First off, you need to create layout new layout params for each button to avoid the problem that @rogerkk pointed out. Second, you are trying to use an ID of zero for the first button. This will not work.

下面是解决这两个问题的函数的返工。

Here is a rework of the function that fixes these two problems.

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);            
    }

}

这篇关于RelativeLayout的带按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆