从 getView 内的线程内更新视图?
Update a view from within a thread inside getView?
我有一个 activity class 调用我的自定义适配器 class 来扩展基本适配器。在我的 getView
方法中,我有一个 button.setOnClickListener
,其中有一个线程可以下载数据。我想在用户点击时将按钮文本设置为"downloading",然后在下载完成后,将按钮文本设置为"finished"。我该怎么做?
public class MyActivity extends Activity {
//some code here
private void setAdapter(ArrayList arrayList) {
listView.setAdapter(new UserAdapter(context,arrayList));
}
}
public class UserAdapter extends BaseAdapter {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Holder holder = new Holder();
holder.button = (Button) view.findViewById(R.id.button);
holder.button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
try{
//set button text to "downloading"
//establish an http connection and download data
//after download done, if successfull set button text to downloaded
//if download failed, set button text to failed.
} catch (Exception exception) {
}
}
}
).start();
}
});
return view;
}
private class Holder {
private Button button;
}
}
为了更新线程内的视图,请像这样在 getView 方法内使用 runOnUithread。在 activity 中你可以直接使用,但在 activity 之外你必须使用上下文。
context.runOnUiThread(new Runnable(){
public void run() {
//If there are stories, add them to the table
try{
}
} catch (final Exception ex) {
Log.i("---","Exception in thread");
}
}
});
对于 http 请求,您可以使用 asyncTask。
我有一个 activity class 调用我的自定义适配器 class 来扩展基本适配器。在我的 getView
方法中,我有一个 button.setOnClickListener
,其中有一个线程可以下载数据。我想在用户点击时将按钮文本设置为"downloading",然后在下载完成后,将按钮文本设置为"finished"。我该怎么做?
public class MyActivity extends Activity {
//some code here
private void setAdapter(ArrayList arrayList) {
listView.setAdapter(new UserAdapter(context,arrayList));
}
}
public class UserAdapter extends BaseAdapter {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Holder holder = new Holder();
holder.button = (Button) view.findViewById(R.id.button);
holder.button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
try{
//set button text to "downloading"
//establish an http connection and download data
//after download done, if successfull set button text to downloaded
//if download failed, set button text to failed.
} catch (Exception exception) {
}
}
}
).start();
}
});
return view;
}
private class Holder {
private Button button;
}
}
为了更新线程内的视图,请像这样在 getView 方法内使用 runOnUithread。在 activity 中你可以直接使用,但在 activity 之外你必须使用上下文。
context.runOnUiThread(new Runnable(){
public void run() {
//If there are stories, add them to the table
try{
}
} catch (final Exception ex) {
Log.i("---","Exception in thread");
}
}
});
对于 http 请求,您可以使用 asyncTask。