继续在方向更改上填充ListView

时间:2012-12-20 00:20:08

标签: android listview service android-asynctask

AsyncTask正在做背景工作,并在其ListView中填充onProgressUpdate并在适配器上调用notifyDataSetChanged()。问题是当方向发生变化时,AsyncTask会停止。如何使AsyncTask继续开展工作并将ListView填入结果,无论如何?我无法使用android:configChanges="keyboardHidden|orientation",因为我的横向模式布局不同。我也尝试使用Service类,但我无法访问我的UI组件。实现我追求目标的最简单方法是什么?

1 个答案:

答案 0 :(得分:1)

您可以使用回调方法更新listView。您需要在AsyncTask中实现它,并直接从您的doInBackground或onProgressUpdate调用:

private updateListViewListener mListener;


public interface updateListViewListener{
    void updateListView(List<String> rowsData);     
}

public void setUpdateListViewListener(updateListViewListener listener) {
    mListener = listener;
}

然后在doInBackGround(或onPogressUpdate)中:

@Override
    protected Object doInBackground(Object... arg0) {
    //Code that downloads data or executes time consumming code that calls the following interface when the data of a row is ready
     mListener.updateListView(listOfStrings); 
}

然后在您的活动中,您可以将AsyncTask的引用保存在另一个类中:

RandomClass.saveAsyncTask(yourAsynctask);

这样你就可以获得对AsyncTask的引用,即使重新创建了活动,在oncreateView()上添加了类似的内容:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        YourAsyncTask task = RandomClass.getAsyncTask();
        if(task != null){
            newAsyncTask =  task;
            newAsyncTask .setUpdateListViewListener(this); // you set again the listener
        }
    }

最后,您可以将此添加到您将覆盖您的活动的updateListView方法中:

@Override
    public void updateListView(List<String> newDataFromAT) {
        adapter.setData(newDataFromAT);
            // You need to do this since you can't change anything in the UI from doInBakcground
        getActivity().runOnUiThread(new Runnable() {
                public void run() {
          adapter.notifyDataSetChanged();
                }
            });
    }

这只是我认为适合你的一些代码,因为你没有发布任何代码,但是你知道当你旋转你的设备时,AsyncTask无法更新像listView一样被破坏的东西所以它是最好保持对asyncTask的引用。