Creating Buttons Dynamically, Could I select one and deselect the other buttons?

南笙酒味 提交于 2020-01-01 18:23:07

问题


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! :)


回答1:


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

}



回答2:


  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


来源:https://stackoverflow.com/questions/2059454/creating-buttons-dynamically-could-i-select-one-and-deselect-the-other-buttons

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!