自定义View---随机显示TextView并更换背景颜色

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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值