MyTextView
public class MyTextView extends android.support.v7.widget.AppCompatTextView { /** * 需要绘制的文字 */ private String mText; /** * 文本的颜色 */ private int mTextColor; /** * 文本的大小 */ private int mTextSize = 10; /** * 绘制时控制文本绘制的范围 */ private Paint mPaint; private Paint mPaintIn; public MyTextView(Context context) { super(context); init(); } public MyTextView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(); } public MyTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //边框颜色 canvas.drawRect(new Rect(0, 0, getMeasuredWidth(), getMeasuredHeight()), mPaintIn); //绘画文本 canvas.drawText(mText, 0, 100, mPaint); } private void init() { //初始化 mText = "4546"; mTextSize = 100; mTextColor = Color.BLACK; //文本的画笔 mPaint = new Paint(); mPaint.setColor(mTextColor); mPaint.setAntiAlias(true); mPaint.setTextSize(mTextSize); this.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mText = randomText(); String color = randomColor(); mPaintIn.setColor(Color.parseColor("#F"+color)); invalidate(); } }); //边框背景颜色的画笔 mPaintIn = new Paint(); mPaintIn.setAntiAlias(true); mPaintIn.setDither(true); mPaintIn.setStyle(Paint.Style.FILL); mPaintIn.setColor(getResources().getColor(R.color.colorPrimary)); } //随机数 private String randomText() { Random random = new Random(); Set<Integer> set = new HashSet<Integer>(); while (set.size() < 4) { int randomInt = random.nextInt(10); set.add(randomInt); } StringBuffer sb = new StringBuffer(); for (Integer i : set) { sb.append("" + i); } return sb.toString(); } //设置颜色的随机数 private String randomColor() { Random random = new Random(); Set<Integer> set = new HashSet<Integer>(); while (set.size() < 5) { int randomInt = random.nextInt(10); set.add(randomInt); } StringBuffer sb = new StringBuffer(); for (Integer i : set) { sb.append("" + i); } return sb.toString(); } }