【问题标题】:how to get checked of checkbox from other class?如何检查其他班级的复选框?
【发布时间】: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


【解决方案1】:

boolean check = ((CheckBox) view).isChecked(); //这里有错误

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

您尝试从 checkBoxFlash 视图中获取检查值,例如

布尔检查 = checkBoxFlash.isChecked();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-23
    • 1970-01-01
    相关资源
    最近更新 更多