如何更新在Android的后台线程的UI中的文本 [英] How to update the text in the UI from the background thread in Android

查看:313
本文介绍了如何更新在Android的后台线程的UI中的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序需要更新取决于我使用从network.For数据在UI中的文本的AsyncTask 做的工作在Android的后台。我的code是如下:

In my application I need to update the text in the UI depending upon the data from the network.For that I am using a AsyncTask to do work in background in Android. My code is as follows.

public class DefaultActivity extends Activity{

  TextView textView;
  public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    textView=(TextView)findViewById(R.id.textId);
    new networkFileAccess().execute("background","Progress","result");
  }

  private class networkFileAccess extends AsyncTask<String,String,String>{

    protected String doInBackground(String... background){
       return changeText();
    }

    private String changeText(){
     //Code to Access data from the Network.
     //Parsing the data.
     //Retrieving the boolean Value.
     if(booleanistrue){
      //Displaying some text on the UI.
      publishProgress("someTextOnUI");
      //Send request till we get get boolean value as false.
      changeText();
     }else{
       return "success";
     }
      return "";
    }

    protected void onProgressUpdate(String... progress){
      textView.setText("Wait background work is going on");
    }

    protected void onPostExecute(String result){
      if(result.equals("success")){
       //Code to finish the activity.
      }
    }
  }

}

在上面的code,我能够运行后台线程,直到我得到布尔值false.But文本没有更新的用户界面。我可以通过调用 publishProgress method.?Any suggesstions更新使用 onProgressUpdate ()方法在用户界面上的文字。

In the above code I am able to run the background thread till I get boolean value as false.But the text is not updating on the UI. Can I update the text on the UI using onProgressUpdate() method by calling publishProgress method.?Any suggesstions.

推荐答案

把你的UI方法内部runonUiTHREAD这样

Put your Ui method inside runonUiTHREAD like this

runOnUiThread(new Runnable() {
public void run() {
    tv.setText("ABC");
}
 });

这篇关于如何更新在Android的后台线程的UI中的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆