您的位置:首页 > 其它

自定义TextView设置边框与背景颜色添加点击事件,点击更改随机数与背景

2017-09-28 14:55 1366 查看
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();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐