我怎么能在AsyncTask中更改ListView?

时间:2012-10-06 09:05:31

标签: java android android-listview android-asynctask listadapter

我有一些从服务执行的AsyncTask类:

public class DownloadTask extends AsyncTask<Void, Integer, Boolean {

    @Override
    protected Boolean doInBackground(Void... arg0) {
        // do something
        publishProgress(i);
    }

    @Override
    protected void onProgressUpdate(Integer ... progress) {
        if(textView()!=null) getTextView().setText(i + "%");
    }

    public void setTextView(TextView textView) {
        this.textView = textView;
    }

}

ListAdapter,在方法getView()中我使用AsyncTask的方法setTextView()在AsyncTask中设置TextView:

public class DownloadTasksAdapter extends BaseAdapter {
    private final Activity context;
    private DownloadTask[] downloadTasks;

    public DownloadTasksAdapter(Activity context, DownloadTask[] downloadTasks) {
        this.context = context;
        this.downloadTasks = downloadTasks;
    }

    public int getCount() {
        return downloadTasks.length;
    }

    public DownloadTask getItem(int position) {
        return downloadTasks[position];
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(final int position, View convertView, ViewGroup parent) {       
        LayoutInflater inflater = (LayoutInflater) context.getLayoutInflater();
        final View rowView = inflater.inflate(R.layout.downloads_listview_row, parent, false);


        final TextView progressTxt = (TextView) rowView.findViewById(R.id.downloads_listview_row_progress);


        switch (downloadTasks[position].getStatus()) {
        case RUNNING:
            downloadTasks[position].setTextView(progressTxt);

            break;
        }

        return rowView;
    }
}

AsyncTask从服务执行,但是当我打开包含ListView的Activity时,AsyncTask应该更新一些字段,我该怎么做? :(

1 个答案:

答案 0 :(得分:1)

完成任务调用后

mAdapter.notifyDataSetChanged();