也许有人可以告诉我我在做什么错,我正在编写一个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);
但不是停止单个1000毫秒,而是活动等待2000开始,然后同时显示所有视图。我是android和Java开发人员中的新手,如果我做的是愚蠢的事情,对不起。预先感谢大家。
答案 0 :(得分:0)
根本原因::您的代码阻止了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);
确保在final
和ViewTwo
变量之前添加ViewThree
关键字。
更新:我不知道您背后的逻辑代码或预期的逻辑代码,但是如果您想重复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