自定義View---隨機顯示TextView並更換背景顏色
阿新 • • 發佈:2018-12-11
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>