标题翻译
Set a String to TextView and wait for a while and set another String to same TextView
问题
private void applicationTest() {
textTT.setText("First");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
textTT.setText("Second");
}
英文翻译
I want to set "First" word to TextView (textTT) and wait for a while set to "Second" to same TextView
but result is directly set "second" to TextView
but I need firstly set "First". How can I overcome this?
<>
private void applicationTest() {
textTT.setText("First");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
textTT.setText("Second");
}
答案1
得分: 2
Sure, here's the translated code snippet:
如果您调用Thread.sleep(1000),意味着UI线程将会被阻塞,UI不会先更新First。如果您想等待并设置Second,应该使用Handler。尝试这样做:
private void applicationTest() {
textTT.setText("First");
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
textTT.setText("Second");
}
}, 1000);
}
英文翻译
If you call Thread.sleep(1000) it means UI thread will be blocking and UI not update First. If you want to wait and set Second you should use Handler. Try this
private void applicationTest() {
textTT.setText("First");
new Handler().postDelayed({
textTT.setText("Second");
}, 1000)
}
答案2
得分: 0
使用 thred.sleep 是一个非常糟糕的实践,因为它会冻结整个应用程序!所以你基本上是说:设置文本为 first 但什么都不做,然后设置 second。所以你会看到 second。
相反,你应该使用 Handler。在这种情况下,你可以说:设置 first,然后创建一个并行任务,等待1秒后再执行。1秒后它会设置 second。
以下是此代码:
private void applicationTest() {
textTT.setText("First");
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
textTT.setText("Second");
}
}, 1000);
}
英文翻译
Using thred.sleep is a very bad practice since you freeze the whole app! So you basically say: set text first but do nothing, then set second. So you see second.
Instead you should use Handler. In that case you say: set first then create a parallel task that waits for 1sec before it executes. After 1 sec it sets second.
That is the code for this:
private void applicationTest() {
textTT.setText("First");
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
textTT.setText("Second");
}
}, 1000);
}
答案3
得分: 0
你应该使用 Handler 来实现这个功能:
private void applicationTest() {
textTT.setText("First");
new Handler().postDelayed(new Runnable{
@Override
public void run() {
textTT.setText("Second");
}
}, 1000);
}
英文翻译
You should use Handler to achieve that:
private void applicationTest() {
textTT.setText("First");
new Handler().postDelayed(new Runnable{
@Override
public void run() {
textTT.setText("Second");
}
},1000)
}
专注分享java语言的经验与见解,让所有开发者获益!

评论