动态设置TextView边框颜色

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_23575795/article/details/78478394

1.在values文件下的attrs.xml中添加样式:

<declare-styleable name="TextViewBorder">
    <attr name="tvborderColor" format="color" />
    <attr name="tvBorderWidth" format="integer" />
</declare-styleable>
2.自定义TextView:

public class TextViewBorder extends android.support.v7.widget.AppCompatTextView {
    private int strokeWidth = 2; // 默认边框宽度
    private int borderCol;
    private Paint borderPaint;

    public TextViewBorder(Context context, AttributeSet attrs) {
        super(context, attrs);

        TypedArray a = context.getTheme().obtainStyledAttributes(attrs,
                R.styleable.TextViewBorder, 0, 0);
        try {
            borderCol = a.getInteger(R.styleable.TextViewBorder_tvborderColor, 0);//0 is default
            strokeWidth=a.getInteger(R.styleable.TextViewBorder_tvborderColor,2);
            
        } finally {
            a.recycle();
        }

        borderPaint = new Paint();
        borderPaint.setStyle(Paint.Style.STROKE);
        borderPaint.setStrokeWidth(strokeWidth);
        borderPaint.setAntiAlias(true);
    }

    @Override
    protected void onDraw(Canvas canvas) {

        if (0 == this.getText().toString().length()) {
            return;
        }
        borderPaint.setColor(borderCol);
        int w = this.getMeasuredWidth();
        int h = this.getMeasuredHeight();
        RectF r = new RectF(2, 2, w - 2, h - 2);
        canvas.drawRoundRect(r, 5, 5, borderPaint);

        super.onDraw(canvas);
    }

    public int getBordderColor() {
        return borderCol;
    }


    public void setBorderColor(int newColor) {
        borderCol = newColor;
        invalidate();
        requestLayout();
    }
    public void setBorderWidth(int width){
        strokeWidth=width;
        invalidate();
        requestLayout();
    }
3.布局里使用:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

  
  <TextViewBorder
    android:id="@+id/tv_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center"
    app:tvborderColor="@color/green"
    tools:text="中国武术" />
</LinearLayout> 4.在调用处可以直接通过TextViewBorder.setBorderColor()赋值。


猜你喜欢

转载自blog.csdn.net/qq_23575795/article/details/78478394