XML中的代码中
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<bawei.com.day3_4.CustomView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.559"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.498" />
</android.support.constraint.ConstraintLayout>
自定义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<Integer> 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);
}
}