简体   繁体   English

在Android中,如何更改按钮的颜色,暂停几秒钟,然后再次更改?

[英]In Android, how do I change the color of a button, pause for a few seconds, then change it again?

Here is my code: 这是我的代码:

public class TestActivity extends Activity {    

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        start();
    }

    private void start() {
        setContentView(R.layout.main);

        LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout);

        Button button = new Button(this);

        layout.addView(button);

        button.getBackground().setColorFilter(new LightingColorFilter(0x00000000, 0x0000FF00));  // green
        button.invalidate(); 

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        button.getBackground().setColorFilter(new LightingColorFilter(0x00000000, 0x000000FF));  // blue
        button.invalidate(); 
    }
}

This just displays a blue button after 3 seconds; 这只是在3秒后显示一个蓝色按钮; it never shows it as green. 它从未表现为绿色。

I think that if my brain worked properly, I could figure out the answer from one of these posts: 我认为,如果我的大脑正常工作,我可以从其中一个帖子中找出答案:

Why isn't view.invalidate immediately redrawing the screen in my android game 为什么view.invalidate不能立即重绘我的安卓游戏中的屏幕

How to force a view to redraw immediately before the next line of code is executed 如何在执行下一行代码之前强制视图重绘

How to force an entire layout View refresh? 如何强制整个布局查看刷新?

You should not sleep on the UI thread, as this will hang your interface. 你不应该睡在UI线程上,因为这会挂起你的界面。 Instead, after initially setting the colour to green, you could create a Handler (on the UI thread, so it will use that thread to handle messages), then use Handler.postDelayed to send a message that will be handled in 3 seconds. 相反,在最初将颜色设置为绿色之后,您可以创建一个Handler(在UI线程上,因此它将使用该线程来处理消息),然后使用Handler.postDelayed发送将在3秒内处理的消息。 In the Runnable you pass to postDelayed you can set the colour to blue. Runnable您传递给postDelayed您可以将颜色设置为蓝色。

You're sleeping the main UI thread virtually instantly after setting the colour. 设置颜色后,您几乎可以立即睡眠主UI线程。 This means that the thread is locked up before it gets a chance to do redrawing. 这意味着线程在有机会重绘之前被锁定。

One solution to this is to use threads. 对此的一个解决方案是使用线程。 Set the background colour, then use another thread to sleep which on completion calls the main (UI) thread to change the colour again. 设置背景颜色,然后使用另一个线程进入睡眠状态,在完成时调用主(UI)线程再次更改颜色。

You can try looking up AsyncTask or Threading . 您可以尝试查找AsyncTaskThreading

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM