自定義TextView 靈活使用Shape實現邊框
效果:
一般寫法,使用shape:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke
android:width="1dp"
android:color="@color/google_lightYellow"></stroke>
<corners android:radius="5dp"></corners>
</shape>
靈活寫法:
- 在attrs.xml中自定義屬性
<declare-styleable name="CustomShapeTextView">
<attr name="default_ring_width" format="dimension" />
<attr name="default_ring_color" format="color" />
<attr name="default_ring_angle" format="dimension" />
</declare-styleable >
自定義TextView
private static final int DEFAULT_COLOR = R.color.google_lightGreen;
private static final int DEFAULT_RING_W = 2;
private static final int DEFAULT_RING_ANGLE = 5;
//邊線顏色
private int mRingColor = DEFAULT_COLOR;
//邊線寬度
private int mRingWidth = DEFAULT_RING_W;
//邊線圓角
private int mRingAngle = DEFAULT_RING_ANGLE;private Paint mPaint;
public CustomShapeTextView(Context context) {
super(context);
init();
}public CustomShapeTextView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}public CustomShapeTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomShapeTextView, defStyleAttr, 0);
mRingColor = a.getColor(R.styleable.CustomShapeTextView_default_ring_color, getResources().getColor(DEFAULT_COLOR));
mRingWidth = (int) a.getDimension(R.styleable.CustomShapeTextView_default_ring_width, DEFAULT_RING_W);
mRingAngle = (int) a.getDimension(R.styleable.CustomShapeTextView_default_ring_angle, DEFAULT_RING_ANGLE);
a.recycle();
init();
}private void init() {
GradientDrawable drawable = new GradientDrawable();
drawable.setCornerRadius(mRingAngle);
drawable.setStroke(mRingWidth, mRingColor);
setBackground(drawable);
}
“`使用
可以再擴充套件。