创建按钮动态,我可以选择一个,并取消其它按钮? [英] Creating Buttons Dynamically, Could I select one and deselect the other buttons?

查看:137
本文介绍了创建按钮动态,我可以选择一个,并取消其它按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我动态创建按钮...

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

     });  

    }

但我怎么能取消被选中的其他按钮,我只是想要一个Button选择! :)

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

推荐答案

声明一个变量来存储所点击按钮的ID ::

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

private int EnabledButton;

在每个按钮设置一个ID在创建时::

set an ID on every button when are created ::

btn.setId(i);

或标签::

or a tag ::

btn.setTag(i);   

然后在监听器获得EnabledButton,并调用一个函数来取消选择其他按钮::

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

}

这篇关于创建按钮动态,我可以选择一个,并取消其它按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆