首页 > 解决方案 > 如何在 AndroidStudio 上设置已检查的 ImageView

问题描述

我正在使用 Texas Instruments 的 CC2640 和我的自定义应用程序。一切正常,但我发现了一个错误。在实践中,我可以从应用程序中读取设备输入的状态,因此如果它们是空闲的(绿灯),如果它们是忙碌的(红灯)。此时设置为 Settogglebutton,但我不想在布局中作为按钮,而是作为更改为 true/False 值的图像。我怎样才能做到这一点?这是我的部分代码:

                        if (intent.hasExtra(MainActivity.EXTRA_INPUT1)) {
                        setToggleButtonState(R.id.ingresso, intent.getIntExtra(MainActivity.EXTRA_INPUT1, 0));
                    } else if (intent.hasExtra(MainActivity.EXTRA_INPUT2)) {
                        setToggleButtonState(R.id.ingresso2, intent.getIntExtra(MainActivity.EXTRA_INPUT2, 0));
                    }

    private void setToggleButtonState(int id, int value) {
    if (id != -1) {
        final ToggleButton b = (ToggleButton) findViewById(id);
        if(value == 1){
            b.setChecked(true);
        }
        else{
            b.setChecked(false);

        }
    }
}

标签: androidbluetooth-lowenergy

解决方案


让我看看我是否理解正确。您想根据值更改 ImageView 资源吗?

private void setImageResource(int id, int value) {
if (id != -1) {
    final ImageView myImageView = (ImageView)findViewById(id); // i assume you wont use this imageview anywhere else, you just want to change the resource.
    if(value == 1){
        myImgView.setImageResource(R.drawable.true);
    }
    else{
       myImgView.setImageResource(R.drawable.false);

    }
}

如果您希望 imageview 保存该值,您可以将其定义为属性并将其保存在 image 标记中。


推荐阅读