单击按钮 10 秒后如何使 imageView 可见?

How to make an imageView visible after 10secs of a buttonclick?

我需要在按钮单击操作 10 秒后使图像视图可见。我已经让我的 imageview 不可见了。但是,每当我尝试在线程睡眠(10000)后将其设置为可见时,我的应用程序就会崩溃。我该如何解决这个问题?请帮忙!

我认为您在主线程上执行了 Thread.sleep(),这不是正确的方法。

相反,您可以使用 AsyncTask 或 Handlers 来延迟某些代码的执行。

button.setOnClickListener(new Button.OnClickListener(){ 
    @Override
    public void onClick(View v) {
        new AsyncTask<Void, Void, Void>() {

            @Override
            protected Void doInBackground(Void... params) {
                Thread.sleep(10000);
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                yourView.setVisibility(VISIBLE);
            }
        }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }         
});    

你不能阻塞你的主线程不超过 5 秒,你的线程也是如此。与其使用线程然后进入睡眠状态,不如使用更好的用户计时器。

class MyTimerTask extends TimerTask {

    @Override
    public void run() {

        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                Intent intent = new Intent(SplashScreen.this,
                        MainActivity.class);
                startActivity(intent);

                finish();

            }
        });
    }

}

更多请阅读here

这个很短,不会阻塞应用程序:

yourButton.setOnClickListener(new View.OnClickListener(){ 
    @Override
    public void onClick(View v) {
        yourImageView.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (yourImageView != null) {
                    yourImageView.setVisibility(View.VISIBLE);
                }
            }
        }, 10000);
    }         
});

一些上下文:postDelayed 向主线程发送一条消息,该消息将在 10000 毫秒内执行,即 10 秒。当 10 秒过去后,主线程将接收消息,并尝试执行可运行对象。该按钮可能不再存在,因为您离开了屏幕,这就是为什么需要进行空检查的原因。