我正在使用YouTube教程系列来创建Android应用。使用此代码时:
someRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
我的'setOnCheckedListener'错误。
错误是这样的:
方法 setOnCheckedChangeListener(RadioGroup.OnCheckedChangeListener)中 类型RadioGroup不适用于参数(new CompoundButton.OnCheckedChangeListener(){})
我已经读过我应该导入android.widget.RadioGroup.OnCheckedChangeListener;
而不是CompoundButton的监听器,但是我使用了CompoundButton。
我该怎么做才能解决此错误?
答案 0 :(得分:1)
您的程序包导入似乎相互冲突。
尝试使用这种方式
someRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
答案 1 :(得分:0)
希望这会帮助你。以下是如何使用RadioGroup
和setOnCheckedChangeListener
的基本示例。
private void setupRadios() {
RadioButton radioMale =(RadioButton) findViewById(R.id.radioMale);
RadioButton radioFemail = (RadioButton) findViewById(R.id.radioFemale);
RadioButton radioOther = (RadioButton) findViewById(R.id.radioOther);
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radio_group);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
int buttonId = radioGroup.getCheckedRadioButtonId();
switch(buttonId) {
case R.id.radioMale:
Toast.makeText(getApplicationContext(), "Your Male", Toast.LENGTH_SHORT).show();
break;
case R.id.radioFemale:
Toast.makeText(getApplicationContext(), "Your Female", Toast.LENGTH_SHORT).show();
break;
case R.id.radioOther:
Toast.makeText(getApplicationContext(), "Your Other", Toast.LENGTH_SHORT).show();
break;
}
}
});
}
<RadioGroup
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/input_validation"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="@+id/radio_group">
<RadioButton
android:id="@+id/radioMale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Male" />
<RadioButton
android:id="@+id/radioFemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female" />
<RadioButton
android:id="@+id/radioOther"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Other" />
</RadioGroup>
默认情况下,不会选中任何单选按钮。单击后,将选中单选按钮。