演示APK
CircleColorButton.java
演示工程项目
与任何一种类型的控件的使用方式完全相同。
<club.andnext.widget.CircleColorButton
android:id="@+id/iv_color"
android:layout_width="12dp"
android:layout_height="12dp"/>
为神马笔记的标签提供颜色选择功能,要求有选中标识。
组合2个ImageView
实现CircleColorButton
。anc_iv_color
显示圆形颜色,and_iv_check
显示选中标识。
<merge xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/anc_iv_color"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"/>
<ImageView
android:id="@+id/anc_iv_check"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:src="@drawable/anc_ic_check_white_24dp"/>
merge>
CircleColorButton
继承自FrameLayout
,并实现了Checkable
接口用于设置选中状态。
public class CircleColorButton extends FrameLayout implements Checkable {
}
ImageView colorView;
ImageView checkView;
int replaceColor; // color for transparent
int color;
onMeasure
保证为圆形protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width = colorView.getMeasuredWidth();
int height = colorView.getMeasuredHeight();
if (width > 0 && height > 0 && width != height) {
int size = (width > height)? height: width;
width = MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY);
height = MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY);
colorView.measure(width, height);
}
}
setColor
使用tint
进行着色public void setColor(int color) {
this.color = color;
if (color == Color.TRANSPARENT) {
int c = this.getReplaceColor();
int resId = R.drawable.anc_ic_circle_color_stroke;
colorView.setImageResource(resId);
colorView.setImageTintList(ColorStateList.valueOf(c));
checkView.setImageTintList(ColorStateList.valueOf(c));
} else {
int c = color;
int resId = R.drawable.anc_ic_circle_color_solid;
colorView.setImageResource(resId);
colorView.setImageTintList(ColorStateList.valueOf(c));
checkView.setImageTintList(null);
}
}
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<stroke android:color="#ffffff" android:width="1dp"/>
<solid android:color="#00000000"/>
shape>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid android:color="#ffffff"/>
shape>