gpt4 book ai didi

android - 异步更新 ListFragment

转载 作者:行者123 更新时间:2023-11-30 02:55:01 25 4
gpt4 key购买 nike

我检查了有关 ListFragments 异步更新的其他答案,发现 notifyDataSetChanged() 方法不起作用的最常见问题是,开发人员倾向于覆盖初始适配器源,导致适配器丢失引用,因此不更新 View 。我有一个要异步更新的 ListFragment。我决定做的是在 AsyncTask 中解析列表数据,最后在 onPostExecute() 中更新 fragment 。我希望 UI 尽可能流畅,所以我想避免在主线程上进行繁重的处理。我在创建 View 后调用 AsyncTask 以避免 null 指针。

public class CategoryFragment extends ListFragment {

ArrayList<Category> categoriesArray = new ArrayList<Category>();
CategoryAdapter adapter;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_category, container, false);
adapter = new CategoryAdapter(getActivity(), R.layout.category_list_item, categoriesArray);
setListAdapter(adapter);
return rootView;
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
new UpdateUITask().execute(categories);
}

...

// The async task to update the UI.
class UpdateUITask extends AsyncTask<String, String, ArrayList<Category>>{

@Override
protected ArrayList<Category> doInBackground(String... input) {

// Do some data processing, to fill the categoriesArray.
// categoriesArray.add(...); -- loop
return categoriesArray;
}

@Override
protected void onPostExecute(ArrayList<Category> result) {
super.onPostExecute(result);
adapter.notifyDataSetChanged();
}
}
}

刷新方法触发,但没有产生任何结果。我还缺少什么?我应该选择一种完全不同的方法吗?

最佳答案

看起来您的 categoriesArray 实例丢失了。 adapter.notifyDataSetChanged(); 仅在您刚刚传递给适配器的 listArray 引用丢失或更改时才起作用。因此,我建议您确保这一点。

此外,如果您要填充自定义数组,请使用 AsyncTaskonProgressUpdate() 方法。它也会减少加载时间。你可以这样做:

class UpdateUITask extends AsyncTask<String, Category, ArrayList<Category>>
{

@Override
protected ArrayList<Category> doInBackground(String... input)
{

// Do some data processing, to fill the categoriesArray.
// and get the category objects one by one and call
//publishprogress till data is there
publishProgress(Category);

// and finallly just return somthing to get in onpostexecute

}

@Override
protected void onProgressUpdate(Category... values)
{
// TODO Auto-generated method stub
super.onProgressUpdate(values);
categoriesArray.add(...);
adapter.notifyDataSetChanged();
}

@Override
protected void onPostExecute(ArrayList<Category> result)
{
super.onPostExecute(result);
adapter.notifyDataSetChanged();
}
}

关于android - 异步更新 ListFragment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23426178/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com