Android-自定义View-带边框TextView

实际效果:

代码实现:

新建 MyTextView 类,使其继承 TextView 类

public class MyTextView extends android.support.v7.widget.AppCompatTextView {

    private Paint mPaint1 = null, mPaint2 = null;

    public MyTextView(Context context) {
        super(context);
    }

    public MyTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        mPaint1 = new Paint();
        mPaint1.setColor(getResources().getColor(android.R.color.holo_blue_light));
        mPaint1.setStyle(Paint.Style.FILL);

        mPaint2 = new Paint();
        mPaint2.setColor(Color.YELLOW);
        mPaint2.setStyle(Paint.Style.FILL);

        // 绘制外层矩形
        canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), mPaint1);

        // 绘制内层矩形
        canvas.drawRect(10, 10, getMeasuredWidth() - 10, getMeasuredHeight() - 10, mPaint2);

        canvas.save();
        // 绘制前文字向前平移 10dp
        canvas.translate(10, 0);
        super.onDraw(canvas);
        canvas.restore();
    }
}

然后再布局文件中引用即可:

<com.example.desighviewtext.views.MyTextView
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:layout_margin="10dp"
    android:gravity="center"
    android:textSize="35dp"
    android:text="My android TextView"/>

猜你喜欢

转载自blog.csdn.net/qq_43377749/article/details/88853138