Android - 在for循环中更改按钮背景?

时间:2016-11-18 13:58:00

标签: android for-loop button

我想知道是否可以在for循环中更改按钮背景

这是我尝试过的代码:

           for(int i=0;i<=value;i++) {
               Button button = (Button) view.findViewById(R.id.button + i);
               button.setBackground(getResources().getDrawable(R.drawable.ic_favorite_border_black_24dp, null));
            }    

其中value = 0到10之间的整数。

我得到的错误是一个nullpointer异常。请帮帮我。

2 个答案:

答案 0 :(得分:1)

我不明白为什么你这样做,如果所有的按钮具有相同的背景,只需创建一个共同的风格。如果您有动态数量的按钮,则需要创建ListView或RecyclerView并使用按钮创建单元格布局。

答案 1 :(得分:0)

是的,有可能。下面的代码遍历按钮视图并更新其颜色。

public void changeButtonBackground(ViewGroup layout,int color){
        for(int i =0; i< layout.getChildCount(); i++){
            View v =layout.getChildAt(i);
            if(v instanceof Button){
                Button btn = (Button)v;
                btn.setBackgroundColor(color);
            }
        }
    }

或者,如果您想做更多事情,只需更改背景,此方法将获取布局内的所有按钮并返回按钮的数组列表。

public List<Button> getAllButtons(ViewGroup layout){
        List<Button> views = new ArrayList<>();
        for(int i =0; i< layout.getChildCount(); i++){
            View v =layout.getChildAt(i);
            if(v instanceof Button){
                views.add((Button)v);
            }
        }
        return views;
    }