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

来源:互联网 发布:保益读屏软件苹果下载 编辑:程序博客网 时间:2024/05/21 14:59

效果:
这里写图片描述
一般写法,使用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>

灵活写法:

  1. 在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>
  1. 自定义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);
    }
    “`

  2. 使用
    这里写图片描述
    这里写图片描述
    可以再扩展。

0 0
原创粉丝点击