开发者

TextViews become single-line instead of multi-line when populated in a thread

I have an Activity that retrieves information from a url. I have 2 textviews which are multi-line (txtTitle & txtContent). If I populate them without using thread, it displays as multi-line. However, when I use a thread, the text views become single-line.

Is there anything I'm missing? Is the UI not completely ready when I tried putting text in it?

My sample code is below:

package com.mysite.app;

import org.json.JSONException; import org.json.JSONObject;

import android.app.Activity; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.Html; import android.text.Spanned; import android.widget.TextView;

public class ViewNewsActivity extends Activity implements Runnable{

private ProgressDialog progressDialog = null; 
private String apiUrl = "";
private String title = "";
private String content = "";
private Runnable viewNews;
private TextView txtTitle = null;
private TextView txtContent = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.view_news);

    Intent myIntent = getIntent();
    apiUrl = "http://www.mysite.com" + myIntent.getStringExtra("api_url");



    Thread thread =  new Thread(this);
    thread.start();
    progressDialog = ProgressDialog.show(ViewNewsActivity.this,    
            "Please wait...", "Retrieving News ...", true);

}


public void run() {

    txtTitle = (TextView)findViewById(R.id.view_news_title)开发者_JS百科;
    txtContent = (TextView)findViewById(R.id.view_news_content);
    getNews(apiUrl);
    handler.sendEmptyMessage(0);

}


private Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        progressDialog.dismiss();
        txtTitle.setText(title);
        Spanned contentHtml = Html.fromHtml(content);
        txtContent.setText(contentHtml.toString());
    }
};

private void getNews(String apiUrl) {
    String result = JSONUtils.getJSONResponse(apiUrl);

    JSONObject jsonResponse;
    try {
        jsonResponse = new JSONObject(result);
        title = jsonResponse.getString("title");
        content = jsonResponse.getString("content");


    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜