如何检查其他类的复选框?

问题描述 投票:0回答:1

我在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它将执行复选框的功能!谢谢你提问! (对不起,如果我错了英语语法)

android checkbox sharedpreferences imagebutton
1个回答
0
投票

boolean checked =((CheckBox)view).isChecked(); //错误在这里

在这一行中,您将向ImageButton投射复选框。

您尝试从checkBox Flash视图中获取选中的值

boolean checked = checkBoxFlash.isChecked();

© www.soinside.com 2019 - 2024. All rights reserved.