public class ColorFulButton2 extends TextView {
public ColorFulButton2(Context context) {
super(context);
}
//
public ColorFulButton2(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RoundCornerTextView);
float dp = typedArray.getDimension(R.styleable.RoundCornerTextView_rc_corner_radius, 0.0f);
// 最终绘图的单位是像素
int cornerRadius = dp2px(context, dp);
typedArray.recycle();
final int textColor = getCurrentTextColor();
GradientDrawable unpressed = new GradientDrawable();
unpressed.setCornerRadius(cornerRadius);
unpressed.setColor(Color.WHITE);
unpressed.setStroke(2, textColor);
GradientDrawable pressed = new GradientDrawable();
pressed.setCornerRadius(cornerRadius);
pressed.setColor(getCurrentTextColor());
StateListDrawable newBackground = new StateListDrawable();
newBackground.addState(new int[]{-android.R.attr.state_pressed}, unpressed);
newBackground.addState(new int[]{android.R.attr.state_pressed}, pressed);
setBackground(newBackground);
//
ColorStateList colorStateList = new ColorStateList(
new int[][]{{-android.R.attr.state_pressed}, {android.R.attr.state_pressed}},
new int[]{textColor, Color.WHITE}
);
setTextColor(colorStateList);
setClickable(true);
}
//
protected int dp2px(Context context, float dp) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dp * scale + 0.5f);
}
}
ColorFulButton2
最新推荐文章于 2024-07-24 16:58:33 发布