1.自定义View
@SuppressLint("AppCompatCustomView") public class Random extends TextView{ public Random(Context context) { super(context); init(); }
public Random(Context context, 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); } } 2.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.random_num.Random android:layout_width="200dp" android:layout_height="100dp" android:gravity="center" android:layout_centerInParent="true" android:background="#000" android:textSize="40sp" android:textColor="#fcc" />
</RelativeLayout>
|
|