In Android, how do I target all buttons other than the one clicked?

65 views Asked by At

I have a LinearLayout created programmatically and I've placed buttons inside this layout to act as an accordion. When tapped they expand open to show, and they work fine.

I'm using a 9 patch image to add the bottom border and arrow/triangle I need for each accordion image. What I want to do is flip the arrow (using another 9 patch image) and return the previously selected items to the other arrow/triangle.

I have the first working: flipping the arrow when touched. I'm just applying a new image to the button that was tapped.

I can't figure out how to tell the other items to flip back. My plan was to target all buttons, apply the "unflipped" arrow, then applying the "flipped" arrow to the tapped button.

I tried using:

for(int x=0;x<accordionMenu.getChildCount();x++){
     accordionMenu.getChildAt(x).setBackground(accordStyle);
}

but this also targets the items inside the accordion not just the button.

How do I target all buttons and only the buttons to apply the "unflipped" arrow before targeting the tapped button to apply the "flipped" arrow?

1

There are 1 answers

0
ρяσѕρєя K On BEST ANSWER

Use instanceof to check View is Button or other View before applying background color as:

 for(int x=0;x<accordionMenu.getChildCount();x++){
        View view = accordionMenu.getChildAt(i);          
        if (view instanceof Button) {
           view.setBackground(accordStyle);
         }
   }