【发布时间】:2018-02-28 11:28:39
【问题描述】:
我在 Setting.class 中有一个复选框:
Checkbox checkBoxFlash = findViewById(R.id.checkBoxFlash);
if(checkBoxFlash.isChecked()) {
checkBoxFlash.setChecked(mPrefe.getBoolean(KEY_CHECKED_FLASH, true));
}else{
checkBoxFlash.setChecked(mPrefe.getBoolean(KEY_CHECKED_FLASH, false));
}
checkBoxFlash.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(compoundButton.isChecked()){
myEditor.putBoolean(KEY_CHECKED_FLASH, true);
myEditor.apply();
}else{
myEditor.putBoolean(KEY_CHECKED_FLASH, false);
myEditor.apply();
}
}
});
我在 Main.class 中有一个 ImageButton:
ImageButton imgStart = findViewById(R.id.imageButtonStart);
imgStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
boolean checked = ((CheckBox) view).isChecked(); //error in here
switch (view.getId()) {
case R.id.checkBoxFlash:
try {
mCameraId = mCameraManager.getCameraIdList()[0];
} catch (CameraAccessException e) {
e.printStackTrace();
}
if (checked) {
turnOnFlash();
} else {
turnOffFlash();
}
break;
我遇到了一个错误
boolean checked = ((CheckBox) view).isChecked();
// java.lang.ClassCastException: android.support.v7.widget.AppCompatImageButton cannot be cast to android.widget.CheckBox
为什么我不能声明呢?我可以知道如何在 Main.class 中检查它吗? 我的目的是单击 ImageButton 它将执行复选框的功能! 感谢您的提问! (对不起,如果我错了英语语法)
【问题讨论】:
-
请提及您的申请流程并提供两个类的正确代码,并提及哪个类是启动器类以及您想要什么?
-
错误显示正确,因为您尝试将 ImageButton 转换为 CheckBox。这就是显示此错误消息的原因。
-
view中的OnClickListener指的是视图imageButtonStart。
标签: android checkbox sharedpreferences imagebutton