我试图在单击时更改 Android Studio 中按钮的背景颜色一秒钟,然后将其更改回原来的颜色。
我现在的代码是这样的
val button: Button = findViewById(R.id.button)
button.setOnClickListener {
button.setBackgroundColor(Color.RED)
Thread.sleep(1_000)
button.setBackgroundColor(Color.BLUE)
}
根本不会改变颜色。从其他一些实验中,我发现它在执行第二个 setBackgroundColor 之前确实等待了一秒钟,但它并没有在第一次更改它。这有什么问题吗?
你可以看看https://developer.android.com/reference/android/view/MotionEvent 有关运动事件的文档。您可以使用 Motion 事件来解决这个问题,这里是示例代码
final Button btn = (Button) findViewById(R.id.button_id);
btn.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_UP) {
button.setBackgroundColor(Color.GREEN);
} else if(event.getAction() == MotionEvent.ACTION_DOWN) {
button.setBackgroundColor(Color.RED);
}
return false;
}
});