效果图为
CustomRandomTextView继承至TextView
package com.example.customrandom.view;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;
@SuppressLint("AppCompatCustomView")
public class CustomRandomTextView extends TextView {
public CustomRandomTextView(Context context) {
super(context);
init();
}
public CustomRandomTextView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
ChangeText();
setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
ChangeText();
}
});
}
int i=0;
private void ChangeText() {
setText(String.valueOf(getRandom()));
if (i%2==0){
setBackgroundColor(Color.BLACK);
}else {
setBackgroundColor(Color.RED);
}
i++;
}
private int getRandom() {
return (int) (Math.random()*9000+1000);
}
}
xml布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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">
<com.example.customrandom.view.CustomRandomTextView
android:layout_width="100dp"
android:layout_height="50dp"
android:layout_centerInParent="true"
android:gravity="center"
android:textSize="30sp"
android:textColor="#ff0"
/>
</RelativeLayout>