如何在 Kotlin 中更改按钮的颜色一秒钟然后再更改回来?

问题描述 投票:0回答:1

我试图在单击时更改 Android Studio 中按钮的背景颜色一秒钟,然后将其更改回原来的颜色。

我现在的代码是这样的

val button: Button = findViewById(R.id.button)
        button.setOnClickListener {
            button.setBackgroundColor(Color.RED)
            Thread.sleep(1_000)
            button.setBackgroundColor(Color.BLUE)
        }

根本不会改变颜色。从其他一些实验中,我发现它在执行第二个 setBackgroundColor 之前确实等待了一秒钟,但它并没有在第一次更改它。这有什么问题吗?

android kotlin
1个回答
0
投票

你可以看看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;
    }

 });
© www.soinside.com 2019 - 2024. All rights reserved.