0

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.

Alex Hakman
  • 62
  • 1
  • 8
  • 1
    I would place your buttons in a viewgroup and iterate through all views in that viewgroup. then get a reference to each button and change its background. I think it would be a cleaner solution: check out this link: [http://stackoverflow.com/questions/8299056/iterating-through-viewgroup] – JustLearning Nov 18 '16 at 14:03
  • i think you should use the exact parent view of all buttons as `parentview.findViewById`. and show your code where you are creating these buttons. cuz your ids are not matching with any views thats why button is null. – SRB Bans Nov 18 '16 at 14:59

2 Answers2

1

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.

0

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;
    }
NJY404
  • 349
  • 3
  • 14