自定义TextView 灵活使用Shape实现边框

xiaoxiao2021-02-28  146

效果: 一般写法,使用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); } “`

使用 可以再扩展。

转载请注明原文地址: https://www.6miu.com/read-19602.html

最新回复(0)