Android Studio非法状态异常:找不到Android的方法(视图):onClick
我正在使用单选按钮切换项目中的颜色。当用户单击其中一个单选按钮时,我希望关联的主题保存到SharedReferences。设置了必要的主题,但单击单选按钮时,会引发以下错误:Android Studio非法状态异常:找不到Android的方法(视图):onClick,android,android-studio,Android,Android Studio,我正在使用单选按钮切换项目中的颜色。当用户单击其中一个单选按钮时,我希望关联的主题保存到SharedReferences。设置了必要的主题,但单击单选按钮时,会引发以下错误: java.lang.IllegalStateException: Could not find method onThemeRadio(View) in a parent or ancestor Context for android:onClick attribute defined on view class
java.lang.IllegalStateException: Could not find method onThemeRadio(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.widget.RadioButton with id 'theme2'
下面显示了相关的XML和Java块。
爪哇:
XML:
我读过一些类似的问题,但没有一个修复有效或适用。
提前谢谢 根据您提供的有限代码很难判断。但是根据错误消息,您似乎没有在正确的位置使用onThemeRadio(View)方法。它需要是活动类上使用该XML布局的方法。使用Android Studio来帮助解决这个问题。例如,Android Studio是否将onThemeRadio(视图)作为未使用的方法突出显示?还是XML中的onclick属性被标记为该方法丢失或具有错误的签名?这些迹象表明这种方法是错误的。您还可以使用突出显示的onclick属性旁边弹出的灯泡,在正确的位置自动创建该方法。在您包含的相关Java代码中,onThemeRadio()方法作为活动类的成员存在,该活动类的内容视图中包含您所包含的XML?@GregMoens。java包括以下行:setContentView(R.layout.activity\u设置);在其onCreate()中。
public void onThemeRadio(View view){
SharedPreferences themeStorage = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor themeStorageEditor = themeStorage.edit();
boolean checked = ((RadioButton)view).isChecked();
int themeId = themeStorage.getInt("themeId",1);
switch(view.getId()) {
case R.id.theme1:
if (checked)
themeId = 1;
break;
case R.id.theme2:
if (checked)
themeId = 2;
break;
case R.id.theme3:
if (checked)
themeId = 3;
break;
}
themeStorageEditor.putInt("themeId",themeId);
themeStorageEditor.apply();
}
<RadioGroup
android:id="@+id/themeRadio"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:checkedButton="@+id/theme1"
android:orientation="horizontal">
<RadioButton
android:id="@+id/theme1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="onThemeRadio"
android:text="Default Theme" />
<RadioButton
android:id="@+id/theme2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="onThemeRadio"
android:text="Alternate Theme" />
<RadioButton
android:id="@+id/theme3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="onThemeRadio"
android:text="Combined Theme" />
</RadioGroup>