Question

I'm creating buttons dynamically ...

for(int i=0; i<colSize;i++){
    final Button btn = new Button(this);    
    btn.setText(SectionName[i]);        
    btn.setTextSize(10);
    btn.setPadding(8, 3,8, 3);   
    btn.setTextColor(Color.WHITE);
    btn.setTypeface(Typeface.SERIF, Typeface.BOLD);

    btn.setOnClickListener(new OnClickListener() {  
        @Override
        public void onClick(View v) {               
            //***Every time that I click my button is selected !:)
            btn.setSelected(true);      
        }                   

     });  

    }

But how could I deselect the other buttons that were selected, I just want one Button selected! :)

Was it helpful?

Solution

Declare a variable to store the Id of the Clicked Button ::

private int EnabledButton;

set an ID on every button when are created ::

btn.setId(i);

or a tag ::

btn.setTag(i);   

then in that Listener get the "EnabledButton", and call a function to deselect the other buttons::

 btn.setOnClickListener(new OnClickListener() {  
        @Override
        public void onClick(View v) {                 
        EnabledButton=btn.getId();
        DeselectButtons();        
        btn.setSelected(true);      
    }                   

 });  

The Function to deselect the other Buttons ::

public void DeselectButtons() {
    for(int i=0; i<NumberofButtons;i++){            
                    if (EnabledButton!= i)
        this.findViewById(i).setSelected(false);
    }           

}

OTHER TIPS

  1. The brutal way (works if you have few buttons) - save your button references and create private method which loops through your buttons and deselects once you don't need
  2. Extend your button class and make it listen for custom event which is generated when one of the buttons is clicked
  3. Look at the RadioGroup implementation
  4. Variation of #1. Instead of creating separate listeners for your buttons create just one and reuse it for all buttons. Extend that listener from OnClickListener and add List field. Each time you assign listener to the button add button reference to that list. Now, when onClick is triggered simply loop through the list and disable "other" buttons
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top