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

别说谁变了你拦得住时间么 提交于 2019-12-04 16:31:47

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

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