选中复选框后如何更改图像

时间:2017-03-29 12:00:34

标签: java android android-checkbox

我在我的服务中回调了这个浮动图像的一张MyService.java

    back = new ImageView(this);
    back.setBackgroundResource(R.drawable.quick_launch_pressed_pink);
    back.setImageResource(R.drawable.back);

我想通过在另一个类上调用MyService来更改ImageResource,但我的应用程序强制关闭了。这是我在MainActivity.java上的代码

    public void addListenerOnCb() {

    chb = (CheckBox) findViewById(R.id.cb);
    final MyService ms = new MyService();
    chb.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            //is chkIos checked?
            if (((CheckBox) v).isChecked()) {
                ms.back.setImageResource(R.drawable.home);
            }

        }
    });

}

2 个答案:

答案 0 :(得分:0)

为check&添加两个不同的图像在drawable中未选中 在drawable文件夹中创建xml文件checkbox_selected.xml

<强> checkbox_selected.xml

<?xml version="1.0" encoding="utf-8"?>
<selector
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@drawable/remember_me_selected" />
    <item android:state_selected="true" android:drawable="@drawable/remember_me_selected" />
    <item android:state_activated="true" android:drawable="@drawable/remember_me_selected" />
    <item android:drawable="@drawable/remember_me" />
</selector>

url xml代码中的ImageView

       <ImageView
            android:id="@+id/remember_checkbox_img"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_weight="0.3"
            android:clickable="true"
            android:src="@drawable/checkbox_selected" />

答案 1 :(得分:0)

将此用于CheckBox

    checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                        @Override
                        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                            if(b)
                           {
              // do something
                            }
                            else
                             {
                          // do another something
                               }
                        }
                    });