ลองมัน -
package com;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
public class CheckBoxImageView extends ImageView implements View.OnClickListener {
boolean checked;
int defImageRes;
int checkedImageRes;
OnCheckedChangeListener onCheckedChangeListener;
public CheckBoxImageView(Context context, AttributeSet attr, int defStyle) {
super(context, attr, defStyle);
init(attr, defStyle);
}
public CheckBoxImageView(Context context, AttributeSet attr) {
super(context, attr);
init(attr, -1);
}
public CheckBoxImageView(Context context) {
super(context);
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
setImageResource(checked ? checkedImageRes : defImageRes);
}
private void init(AttributeSet attributeSet, int defStyle) {
TypedArray a = null;
if (defStyle != -1)
a = getContext().obtainStyledAttributes(attributeSet, R.styleable.CheckBoxImageView, defStyle, 0);
else
a = getContext().obtainStyledAttributes(attributeSet, R.styleable.CheckBoxImageView);
defImageRes = a.getResourceId(0, 0);
checkedImageRes = a.getResourceId(1, 0);
checked = a.getBoolean(2, false);
a.recycle();
setImageResource(checked ? checkedImageRes : defImageRes);
setOnClickListener(this);
}
@Override
public void onClick(View v) {
checked = !checked;
setImageResource(checked ? checkedImageRes : defImageRes);
onCheckedChangeListener.onCheckedChanged(this, checked);
}
public void setOnCheckedChangeListener(OnCheckedChangeListener onCheckedChangeListener) {
this.onCheckedChangeListener = onCheckedChangeListener;
}
public static interface OnCheckedChangeListener {
void onCheckedChanged(View buttonView, boolean isChecked);
}
}
เพิ่มผู้ช่วยนี้ -
<declare-styleable name="CheckBoxImageView">
<attr name="default_img" format="integer"/>
<attr name="checked_img" format="integer"/>
<attr name="checked" format="boolean"/>
</declare-styleable>
ใช้เช่น -
<com.adonta.ziva.consumer.wrapper.CheckBoxImageView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/checkBox"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:clickable="true"
android:padding="5dp"
app:checked_img="@drawable/check_box_checked"
app:default_img="@drawable/check_box" />
มันจะแก้ไข porblems ของคุณทั้งหมด