Alex Hakman
Alex Hakman

Reputation: 62

Android - Change button background in for loop?

I was wondering if its possible to change the buttons background in a for loop

This is the code i have tried:

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

Where value = an integer between 0 and 10.

Error i get is a nullpointer exception. Please help me.

Upvotes: 0

Views: 622

Answers (2)

NJY404
NJY404

Reputation: 358

Yes, it's possible. The code below iterates through button views & update their colors.

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

Or if you want to do more done just change the background, this method takes all the buttons inside the layout & returns an array list of buttons.

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

Upvotes: 0

I don't understand why are you doing that, if all the buttons have the same background just create a common style. If you have a dynamic numbers of buttons you need to create a ListView or RecyclerView and create a cell layout with a button.

Upvotes: 1

Related Questions