在非 UI 线程中做一些 Android UI 的东西 [英] Do some Android UI stuff in non-UI thread
本文介绍了在非 UI 线程中做一些 Android UI 的东西的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法在非 UI 线程中进行 UI 更改?简短的问题.
Is there a way to do UI changes in a non-UI thread? Short question.
推荐答案
如果您不想使用 AsyncTask,请在您的主要活动中尝试带有内部类 (ResponseHandler) 的观察者模式,抱歉我无法正确设置格式,但是我确定你明白了
If you dont want to use an AsyncTask, try the observer pattern with an inner class (ResponseHandler) in your main activity, sorry I couldnt get the formatting right but im sure you get the idea
public class WorkerThread extends Observable implements Runnable {
public void run() {
try {
DoSomething();
String response = "Doing something";
setChanged();
notifyObservers( response );
DoSomethingElse();
String response = "Doing something else";
setChanged();
notifyObservers( response );
}
catch (IOException e) {
e.printStackTrace();
}
}
private void DoSomething(){
}
private void DoSomethingElse(){
}
public class MainActivity{
public class ResponseHandler implements Observer {
private String resp;
public void update (Observable obj, Object arg) {
if (arg instanceof String) {
resp = (String) arg;
//Write message to UI here ie System.out.println("
Received Response: "+ resp );
//or EditText et = (EditText)findViewById(R.id.blah);
// blah.SetText(resp);
}
}
}
private void doStuffAndReportToUI(){
final WorkerThread wt = new WorkerThread();
final ResponseHandler respHandler = new ResponseHandler();
wt.addObserver( respHandler );
Thread thread = new Thread(wt);
thread.start();
}
这篇关于在非 UI 线程中做一些 Android UI 的东西的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文