有没有办法在非UI线程中进行UI更改?简短的问题。
答案 0 :(得分:9)
使用Handler或使用以下代码
runOnUiThread(new Runnable()
{
@Override
public void run()
{
// Ui Stuff here
}
});
答案 1 :(得分:5)
有很多方法可以做到这一点,使用AsyncTask or Threads。简短的回答。
提示:UI内容可以在pre-postExecute / runOnUiThread / Handler类中完成
答案 2 :(得分:5)
如果您不想使用AsyncTask,请在主活动中尝试使用内部类(ResponseHandler)的观察者模式,抱歉我无法正确设置格式,但我确定您明白了这一点
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("\nReceived 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();
}
答案 3 :(得分:1)
查看Handler课程。或者看看这些类似的问题:
答案 4 :(得分:0)
尝试探索runOnUIThread()
http://developer.android.com/reference/android/app/Activity.html#runOnUiThread(java.lang.Runnable)
答案 5 :(得分:0)
我试过+ tmho回答,但它仍然给出了这个错误:
E / AndroidRuntime(****):android.view.ViewRootImpl $ CalledFromWrongThreadException:只有创建视图层次结构的原始线程才能触及其视图。
我终于用+ ingsaurabh方式将它组合起来,就像那样:
private class ResponseHandler implements Observer, Runnable {
Activity act;
public ResponseHandler(Activity caller) {
act = caller;
}
@Override
public void update (Observable obj, Object arg) {
act.runOnUiThread(this);
}
@Override
public void run() {
//update UI here
}
}
谢谢你们两位。