同一个 android Activity 中的两个 Thread.sleep()

Two Thread.sleep() in the same android Activity

也许有人可以告诉我我做错了什么我正在编写一个 Android 应用程序,它将按时间间隔显示 3 个视图,所以基本思想是;

    ViewOne.setVisibility(View.INVISIBLE); //This is redundant but I put here for clarity
    ViewTwo.setVisibility(View.INVISIBLE);
    ViewThree.setVisibility(View.INVISIBLE);

    ViewOne.setVisibility(View.VISIBLE);
    //This supposed to make a 1 second stop.
    try {
      Thread.sleep(1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    ViewTwo.setVisibility(View.VISIBLE);
    //This supposed to make another 1 second stop.
    try {
      Thread.sleep(1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    ViewThree.setVisibility(View.VISIBLE);

但 activity 不是单独停止 1000 毫秒,而是等待 2000 毫秒开始,然后同时显示所有视图。我是 android 和 java 开发人员的新手,如果我做了一件愚蠢的事情,我深表歉意。在此先感谢大家。

根本原因: 您的代码阻塞了 UI 线程,因此它不会更新 UI 直到线程空闲(或未阻塞)。

解决方案:我给你这个解决方案,让你做你想做的事

final Handler handler = new Handler();

ViewOne.setVisibility(View.INVISIBLE); //This is redundant but I put here for clarity
ViewTwo.setVisibility(View.INVISIBLE);
ViewThree.setVisibility(View.INVISIBLE);

ViewOne.setVisibility(View.VISIBLE);
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        ViewTwo.setVisibility(View.VISIBLE);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                ViewThree.setVisibility(View.VISIBLE);
            }
        }, 1000);
    }
}, 1000);

确保在 ViewTwoViewThree 变量之前添加 final 关键字。

更新:我不知道你背后的逻辑代码或你的意图,但如果你想重复N次。

int secondsForEachStep = 3;
for (int i = 0; i < 3; i++) {
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            wordText.setVisibility(View.INVISIBLE);
            myImageView.setVisibility(View.INVISIBLE);
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    wordText.setVisibility(View.VISIBLE);
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            myImageView.setVisibility(View.VISIBLE);
                        }
                    }, 1000);
                }
            }, 1000);

        }
    }, (i * secondsForEachStep + 1) * 1000);
}

解释上面的代码:

i = 0: After 1 seconds hide 2 views, after 2 seconds show view one, after 3 seconds show view 2.
i = 1: After 4 seconds hide 2 views, after 5 seconds show view one, after 6 seconds show view 2.
i = 2: After 7 seconds hide 2 views, after 8 seconds show view one, after 9 seconds show view 2.

每一步我们需要3秒来完成,从中我们可以发现规则是

i * secondsForEachStep + 1