如何处理Radio Button Onclicklistener

时间:2014-01-03 11:27:26

标签: java android listview

我正在使用radiobutton,我想根据所选的单选按钮更改变量的值。到现在为止我试过这段代码。

                   public int i = 1;

> > @Override       public void onClick(View v) {
>    
>                   // get selected radio button from radioGroup
>               int selectedId = radioSexGroup.getCheckedRadioButtonId();
>    
>               // find the radiobutton by returned id
>                   radioSexButton = (RadioButton) findViewById(selectedId);
>                   
>                   if(radioMAle.isSelected() == true)
>                   {
>                       i=i+0;
>                       Log.e("MALE RADIO", "RADIO BUTTON MALE");
>                    
>                   }
>                   
>                   else if(radioFeMAle.isSelected() == true)
>                   {
>                         i=i+1;
>                   }
>    
>                   Log.e("RAdio button ID", Integer.toString(i));
>                                   
>               }
>           });
>         }

我希望当用户选择男性单选按钮值i = 1并且当他选择女性i = 2时。 让我知道如何做到这一点,谢谢

2 个答案:

答案 0 :(得分:1)

您通常会在RadioGroup上设置一个监听器,告诉您所选按钮的更改时间。然后使用checkedId(布局中的android:id)来确定要执行的操作。

radioSexGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.button1:
                i = 0;
                break;
            case R.id.button2:
                i = 1;
                break;
        }
    }
});

答案 1 :(得分:-1)

http://developer.android.com/guide/topics/ui/controls/radiobutton.html

参考上面的链接

public void onRadioButtonClicked(View view) {
    // Is the button now checked?
    boolean checked = ((RadioButton) view).isChecked();

    // Check which radio button was clicked
    switch(view.getId()) {
        case R.id.radio_pirates:
            if (checked)

i=1;
            break;
        case R.id.radio_ninjas:
            if (checked)

i=2;
            break;
    }
}