動態設定TextView邊框顏色
阿新 • • 發佈:2018-12-04
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 int3.佈局裡使用: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(); }
<?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()賦值。