Android-自定义View-带边框TextView

2021-09-24 12:01:59 浏览数 (1)

实际效果:

代码实现:

新建 MyTextView 类,使其继承 TextView 类

代码语言:javascript复制
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();
    }
}

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

代码语言:javascript复制

0 人点赞