package com.testasyntextview;
/**
* 把获取的线程写到方法中(比较好)
*/
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.Spanned;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class TestAsynTextViewActivity extends Activity {
private TextView textView1;
private Button button1;
private Context context;
private ProgressDialog progressDialog;
private Spanned html;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
context = this;
textView1 = (TextView) findViewById(R.id.textView1);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(l);
}
private OnClickListener l = new OnClickListener() {
@Override
public void onClick(View v) {
progressDialog = ProgressDialog.show(context, "获取数据中", "等待");
getHtmlDate();
}
};
private void getHtmlDate() {// 获取数据,把线程写入了其中
new Thread() {
public void run() {
Message msg = myHandler.obtainMessage();
try {
html = HttpUtil.fromHtml(HttpUtil
.getHtml("http://wap.sina.com"));
msg.what = 0;
} catch (Exception e) {
e.printStackTrace();
msg.what = 1;
}
myHandler.sendMessage(msg);
}
}.start();
}
Handler myHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
textView1.setText(html);
progressDialog.dismiss();
break;
case 1:
textView1.setText("当前无数据");
progressDialog.dismiss();
break;
}
super.handleMessage(msg);
}
};
}
关于异步加载数据的又一种实现
最新推荐文章于 2022-04-05 14:50:12 发布