简体   繁体   English

将Android按钮设置为在一段时间后可见?

[英]Setting an Android Button visible after a certain period of time?

I have a button that I don't want to be clickable until a certain amount of time has run (say, 5 seconds?) I tried creating a thread like this 我有一个按钮,在经过一定时间(例如5秒?)之前,我不希望它被单击。

    continueButtonThread =  new Thread()
    {
        @Override
        public void run()
        {
            try {
                synchronized(this){
                    wait(5000);
                }
            }
            catch(InterruptedException ex){                    
            }

            continueButton.setVisibility(0);                
        }
    };

    continueButtonThread.start();

But I can't modify the setVisibility property of the button within a different thread. 但是我无法在其他线程中修改按钮的setVisibility属性。 This is the error from the LogCat: 这是来自LogCat的错误:

10-02 14:35:05.908: ERROR/AndroidRuntime(14400): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. 10-02 14:35:05.908:错误/ AndroidRuntime(14400):android.view.ViewRoot $ CalledFromWrongThreadException:只有创建视图层次结构的原始线程才能触摸其视图。

Any other way to get around this? 还有其他解决方法吗?

The problem is that you can touch views of your activity only in UI thread. 问题是您只能在UI线程中触摸活动的视图。 you can do it by using runOnUiThread function. 您可以使用runOnUiThread函数来实现。 I would like to suggest you to use 我建议您使用

handler.postDelayed(runnable, 5000)`

You must update your view from UI-thread. 您必须从UI线程更新视图。 What you are doing is you are updating from non-ui-thread. 您正在做的是从非ui线程进行更新。

Use 采用

contextrunOnUiThread(new Runnable(){

        @Override
        public void run() {
            // TODO Auto-generated method stub

        }});

or use handler and signalize hand.sendMessage(msg) when you think is right time to update the view visibility 或在认为适当时机更新视图可见性时使用处理程序并信号化hand.sendMessage(msg)

 Handler hand = new Handler()        
        {

            @Override
            public void handleMessage(Message msg) {
                /// here change the visibility
                super.handleMessage(msg);
            }

        };

您可以使用View类中的postDelayed方法(一个ButtonView的子级)

here is simple answer i found 这是我找到的简单答案

Button button = (Button)findViewBYId(R.id.button);
button .setVisibility(View.INVISIBLE);
button .postDelayed(new Runnable() {
    public void run() {
        button .setVisibility(View.VISIBLE);
    }
}, 7000);

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

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