你这个是想按递增计数之后,按钮颜色发生改变,数字从0到20递增吗?你可以试试计时器结合handler刷新你的数字
private TimerTask timerTask = new TimerTask() {
@Override
public void run() {
Message message = Message.obtain();
message.what = 1;
handler.sendMessage(message);
}
};
private Timer timer = new Timer();
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == 1) {
在这里刷新数字
}
}
};
在oncreate方法中启动计时器timer.schedule(timerTask, 1000, 1000);
//创建一个 黄色 shape,名字 yellow_shape_4 ,原角度 4dp
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#FF6533" />
<corners android:radius="4dp" />
</shape>
//创建一个 红色 shape ,名字 red_shape_4,原角度 4dp
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#F44336" />
<corners android:radius="4dp" />
</shape>
//当前 数值
var num = 0
//点击 num 在 0-20内自增
btn.setOnClickListener {
if (num>=20){
//达到上限
return@setOnClickListener
}
++num
changeUiColor()
}
//根据数值改变按钮颜色
fun changeUiColor(){
when(num){
0->btn.setBackgroundResource(R.drawable.yellow_shape_4)
1->btn.setBackgroundResource(R.drawable.red_shape_4)
2->btn.setBackgroundResource(R.drawable.yellow_shape_4)
3->btn.setBackgroundResource(R.drawable.red_shape_4)
4->btn.setBackgroundResource(R.drawable.yellow_shape_4)
5->btn.setBackgroundResource(R.drawable.red_shape_4)
//一次类推 6-20 也写上
else ->btn.setTextColor(Color.RED)
}
}