您的位置:首页 > 其它

关于异步加载数据的又一种实现

2012-10-07 16:40 543 查看
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);
}
};

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: