runOnUiThread()实例
时间: 2024-03-27 11:36:56 浏览: 46
以下是一个简单的例子,演示了如何在 `Activity` 中使用 `runOnUiThread()` 方法更新 UI:
```
public class MainActivity extends AppCompatActivity {
private TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = findViewById(R.id.text_view);
new Thread(new Runnable() {
@Override
public void run() {
// 模拟一个耗时的操作
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 更新 UI
runOnUiThread(new Runnable() {
@Override
public void run() {
mTextView.setText("操作完成");
}
});
}
}).start();
}
}
```
在这个例子中,我们创建了一个新的线程,并在其中模拟了一个耗时的操作(这里使用了 `Thread.sleep()` 方法模拟)。然后,我们使用 `runOnUiThread()` 方法切换到 UI 线程,并在其中更新了一个 `TextView` 的文本内容。这样,当耗时操作完成后,用户界面上的文本内容就会被更新为“操作完成”。需要注意的是,这个更新必须在 `run()` 方法中执行,因为这是在 UI 线程中执行的。
阅读全文
相关推荐
















