TextView 를 사용자 정의 하여 난수 와 랜 덤 색상 가 져 오기
2737 단어 사용자 정의 뷰
사용자 정의 View 의 코드
@SuppressLint("AppCompatCustomView")
public class CustomView extends TextView {
private Paint paint;
private RectF rectF;
private String result="1111";//
public CustomView(Context context) {
super(context);
initView();
}
public CustomView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
initView();
}
public void initView(){
paint=new Paint();
paint.setStrokeWidth(10);
paint.setColor(40);
paint.setColor(Color.RED);
paint.setTextSize(60);
this.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
result = setData();
int currColor = (int) -(Math.random() * (16777216 - 1) + 1);//
setBackgroundColor(currColor);
invalidate();//
}
});
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(300,200);
}
//
public String setData(){
Random random=new Random();
Set set=new HashSet<>();
for (int i=0;set.size()<4;i++){
int value = random.nextInt(10);
set.add(value);
}
StringBuilder builder=new StringBuilder();
for (Integer i:set){
builder.append(i);
}
return builder.toString();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//
canvas.drawText(result,80,100,paint);
}
}