ToggleImageButton
它实现Checkable
接口,并支持OnCheckedChangeListener
和android:checked
XML属性:
public class ToggleImageButton extends ImageButton implements Checkable {
private OnCheckedChangeListener onCheckedChangeListener;
public ToggleImageButton(Context context) {
super(context);
}
public ToggleImageButton(Context context, AttributeSet attrs) {
super(context, attrs);
setChecked(attrs);
}
public ToggleImageButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setChecked(attrs);
}
private void setChecked(AttributeSet attrs) {
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.ToggleImageButton);
setChecked(a.getBoolean(R.styleable.ToggleImageButton_android_checked, false));
a.recycle();
}
@Override
public boolean isChecked() {
return isSelected();
}
@Override
public void setChecked(boolean checked) {
setSelected(checked);
if (onCheckedChangeListener != null) {
onCheckedChangeListener.onCheckedChanged(this, checked);
}
}
@Override
public void toggle() {
setChecked(!isChecked());
}
@Override
public boolean performClick() {
toggle();
return super.performClick();
}
public OnCheckedChangeListener getOnCheckedChangeListener() {
return onCheckedChangeListener;
}
public void setOnCheckedChangeListener(OnCheckedChangeListener onCheckedChangeListener) {
this.onCheckedChangeListener = onCheckedChangeListener;
}
public static interface OnCheckedChangeListener {
public void onCheckedChanged(ToggleImageButton buttonView, boolean isChecked);
}
}
res / values / attrs.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="ToggleImageButton">
<attr name="android:checked" />
</declare-styleable>
</resources>