RelativeLayout with buttons

♀尐吖头ヾ 提交于 2019-12-13 04:43:54

问题


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?


回答1:


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

}


来源:https://stackoverflow.com/questions/5343299/relativelayout-with-buttons

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!