效果图
-
在values下创建attrs.xml
-
自定义属性
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MySelectorTextView">
<attr name="pressColor" format="color" />
<attr name="pressAlpha" format="float" />
</declare-styleable>
</resources>
- 自定义View
public class MySelectorTextView extends AppCompatTextView {
public MySelectorTextView(Context context) {
super(context);
}
public MySelectorTextView(Context context, AttributeSet attrs) {
super(context, attrs, android.R.attr.textViewStyle);
//当前设置字体颜色
int currentTextColor = getCurrentTextColor();
//转rgb值
int red = Color.red(currentTextColor);
int green = Color.green(currentTextColor);
int blue = Color.blue(currentTextColor);
//自定义属性
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MySelectorTextView);
//透明度
float aFloat = typedArray.getFloat(R.styleable.MySelectorTextView_pressAlpha, 0.3f);
//按压的颜色值
int pressedColor = typedArray.getColor(R.styleable.MySelectorTextView_pressColor, Color.argb((int) (aFloat * 255), red, green, blue));
typedArray.recycle();
//设置点击效果
int[][] stateList = new int[][]{
new int[]{android.R.attr.state_pressed},
new int[]{}
};
int[] stateColorList = new int[]{
pressedColor,
getCurrentTextColor(),
};
ColorStateList colorStateList = new ColorStateList(stateList, stateColorList);
setTextColor(colorStateList);
//设置可点击
setClickable(true);
setFocusable(true);
}
}
- 使用
<com.weiou.medical.view.MySelectorTextView
android:id="@+id/tvCheck"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/string_read_agree" />