1. 程式人生 > >RadioButton的使用(三個button,實現互斥,一次只能選中一個)

RadioButton的使用(三個button,實現互斥,一次只能選中一個)

效果:只能選中一個radiobutton

實現的方法:

1.首先我們要將三個radiobutton的layout設定成可以點選的,然後我們將這三個radio設定成不可以點選的,我們通過點選layout來實現,radiobutton的選中,通過設定               android:focusable="true"    android:clickable="true"屬性來實現

2.我們在每一個layout中設定一個tag,用於管理當前點選的是哪個radiobutton

   例子:                 <RelativeLayout
                        android:id="@+id/rl_alipay"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:paddingTop="@dimen/largePadding"
                        android:paddingBottom="@dimen/largePadding"
                        android:background="@drawable/selector_list_item"
                        android:focusable="true"
                        android:clickable="true"
                        android:tag="alipay">

3.我們在activity中分別例項化上面radiobutton和layout的物件

pyRadioButton= (RadioButton) findViewById(R.id.rb_alipay);
wxRadioButton= (RadioButton) findViewById(R.id.rb_webchat);
baiduRadioButton= (RadioButton) findViewById(R.id.rb_bd);
pyRelativeLayout= (RelativeLayout) findViewById(R.id.rl_alipay);
wxRelaticeLayout
= (RelativeLayout) findViewById(R.id.rl_wechat); bdRelativeLayout= (RelativeLayout) findViewById(R.id.rl_bd);

4.建立愛一個hasmap用於儲存三個radiobutton物件,並且給他們賦予一個值,值為下面的值

private HashMap<String,RadioButton> channels = new HashMap<>(3);
channels.put(CHANNEL_ALIPAY,pyRadioButton);
channels.put(CHANNEL_WECHAT
,wxRadioButton); channels.put(CHANNEL_BFB,baiduRadioButton);

/**
 * 銀聯支付渠道
 */
private static final String CHANNEL_UPACP = "upacp";
/**
 * 微信支付渠道
 */
private static final String CHANNEL_WECHAT = "wx";
/**
 * 支付支付渠道
 */
private static final String CHANNEL_ALIPAY = "alipay";
/**
 * 百度支付渠道
 */
private static final String CHANNEL_BFB = "bfb";
/**
 * 京東支付渠道
 */
private static final String CHANNEL_JDPAY_WAP = "jdpay_wap";

6.設定三個layout佈局的點選事件

pyRelativeLayout.setOnClickListener(this);
wxRelaticeLayout.setOnClickListener(this);
bdRelativeLayout.setOnClickListener(this);
/**
 * radiobutton的點選事件,讓每個按鈕互斥
 * @param v
*/
@Override
public void onClick(View v) {
selectPayChannle(v.getTag().toString());
}

呼叫一個方法,這個方法就是根據,當前點選的是哪個layout,來實現radiobutton的互斥,選中

public void selectPayChannle(String paychannel){


    for (Map.Entry<String,RadioButton> entry:channels.entrySet()){

    //    payChannel = paychannel;
RadioButton rb = entry.getValue();
        if(entry.getKey().equals(paychannel)){

            boolean isCheck = rb.isChecked();
rb.setChecked(!isCheck);
}
        else
rb.setChecked(false);
}


}

流程大概是這樣:遍歷hasmap中的物件,然後抓取每個物件的值是否和點選layout傳進去的值相同,相同取反,每點選的點選,點選的設定成不點選狀態

********************以上所有的步驟已經完成