单选按钮找不到单击的方法

时间:2017-06-17 15:30:12

标签: java android radio-button radio-group

我的单选按钮不会找到onRadioButtonClicked上的单击方法。该方法说它从未使用过,当我尝试使用radioButton时,应用程序崩溃,因为没有onRadioButtonClicked方法。

<RadioGroup
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <RadioButton
                android:id="@+id/rbTerrorist"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:onClick="onRadioButtonClicked"
                android:text="Terrorist" />

            <RadioButton
                android:id="@+id/rbCounterTerrorist"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:onClick="onRadioButtonClicked"
                android:text="Counter-Terrorist" />
        </RadioGroup>

 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.rbTerrorist:
                if (checked)
                    // Pirates are the best
                    break;
            case R.id.rbCounterTerrorist:
                if (checked)
                    // Ninjas rule
                    break;
            default:
                break;
        }
    }

1 个答案:

答案 0 :(得分:1)

RadioButtonRadioGroup应该使用的是OnCheckedChangeListener

使用此方法

    RadioGroup rb = (RadioGroup) findViewById(R.id.your_Radio_group_id);
    rb.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            switch (checkedId) {
                case R.id.rbTerrorist:
                    // to task                                         
                    break;
                case R.id.rbCounterTerrorist:
                    // to task                                         
                    break;
            }
        }

    });