这个对齐问题可以通过CheckableImageViewView
来解决,这是一个直接扩展ImageView
或AppCompatImageView
实现的自定义Checkable
。它还有其他ImageView
属性。
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Checkable;
import android.widget.ImageView;
/**
* @author hendrawd on 6/23/16
*/
public class CheckableImageView extends ImageView implements Checkable {
public CheckableImageView(Context context) {
super(context);
}
public CheckableImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
private boolean mChecked = false;
private static final int[] CHECKED_STATE_SET = {android.R.attr.state_checked};
@Override
public int[] onCreateDrawableState(final int extraSpace) {
final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
if (isChecked())
mergeDrawableStates(drawableState, CHECKED_STATE_SET);
return drawableState;
}
@Override
public void setChecked(boolean checked) {
if (mChecked != checked) {
mChecked = checked;
refreshDrawableState();
}
}
@Override
public boolean isChecked() {
return mChecked;
}
@Override
public void toggle() {
setChecked(!mChecked);
}
@Override
public void setOnClickListener(final OnClickListener l) {
View.OnClickListener onClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
toggle();
l.onClick(v);
}
};
super.setOnClickListener(onClickListener);
}
}
只需在 XML 的 src 属性中设置您的选择器可绘制,并且可绘制的检查状态将自动跟随。
使用示例
<your.package.name.CheckableImageView
android:id="@+id/some_id"
android:layout_width="48dp"
android:layout_height="48dp"
android:src="@drawable/set_your_selector_here"
android:padding="14dp"
android:gravity="center" />
选择器示例(放在带有扩展名的可绘制文件夹中.xml
)
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/ic_cb_check" android:state_checked="true" android:state_focused="true" />
<item android:drawable="@drawable/ic_cb_uncheck" android:state_checked="false" android:state_focused="true" />
<item android:drawable="@drawable/ic_cb_uncheck" android:state_checked="false" />
<item android:drawable="@drawable/ic_cb_check" android:state_checked="true" />
</selector>
用您喜欢的图像更改ic_cb_check和ic_cb_uncheck 。
此代码也可在https://gist.github.com/hendrawd/661824a721c22b3244667379e9358b5f获得