Android - 一段时间后显示和隐藏文字?

时间:2013-10-27 11:44:19

标签: java android

我正在尝试显示错误消息并在3秒后隐藏它们。这就是我所写的,但似乎它不会那样工作。

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

2 个答案:

答案 0 :(得分:6)

您可以将Handler及其postDelayed方法用于您的目的:

//Show your view
yazi.setVisibility(View.VISIBLE);

Handler handler = new Handler();
handler.postDelayed(new Runnable() {

    @Override
    public void run() {
        // Hide your View after 3 seconds
        yazi.setVisibility(View.GONE);
    }
}, 3000);

答案 1 :(得分:0)

像这样更新您的代码

在onCreate()方法中

  yazi.setVisibility(View.VISIBLE);
    Thread thread=new Thread(runnable);
     thread.start();

在你的onCreate()方法之外,做这个

Runnable runnable=new Runnable() {

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


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


            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    yazi.setVisibility(View.GONE);
                }
            });
    }
};
};

始终使用 runOnUiThread 进行用户界面操作。