Android开发:如何让TextView先显示First再延迟显示Second?
Hey, I’ve dealt with this exact problem before—let me walk you through what’s going on and how to fix it quickly.
The core issue here is that you’re blocking the Android UI Thread with Thread.sleep(1000). When you call textTT.setText("First"), Android doesn’t immediately redraw the screen—it just queues up the UI update request. But since the main thread is stuck sleeping, that update never gets processed until the sleep finishes. By then, you’ve already called setText("Second"), so the UI skips straight to showing the final value.
Fix 1: Use Handler.postDelayed() (Java Standard)
This is the go-to way to run delayed UI operations without blocking the main thread:
private void applicationTest() { // Immediately set "First"—the main thread is free, so the UI updates right away textTT.setText("First"); // Queue up the "Second" update to run 1 second later new Handler(Looper.getMainLooper()).postDelayed(new Runnable() { @Override public void run() { textTT.setText("Second"); } }, 1000); // Delay in milliseconds (1000ms = 1s) }
Here’s how it works: We first set "First" while the main thread is unblocked, so the screen refreshes immediately. Then we use postDelayed to add the "Second" update to the main thread’s message queue, which executes after the 1-second delay. No blocking, no skipped UI updates.
Fix 2: Use View.postDelayed() (More Concise)
Since we’re working directly with the TextView, we can skip creating a Handler entirely—Views have their own postDelayed method that uses the main thread’s Looper under the hood:
private void applicationTest() { textTT.setText("First"); textTT.postDelayed(new Runnable() { @Override public void run() { textTT.setText("Second"); } }, 1000); }
This does the exact same thing as the Handler approach, but with less code.
Quick Note
Never call Thread.sleep(), do network calls, or run any slow operations on the main thread—it can cause your app to freeze and trigger an ANR (Application Not Responding) error, which might get your app force-closed by Android.
If you’re using Kotlin instead, coroutines make this even cleaner:
private fun applicationTest() { textTT.text = "First" lifecycleScope.launch { delay(1000) textTT.text = "Second" } }
内容的提问来源于stack exchange,提问作者OmerK

