我正在使用ViewPager與FragmentStatePagerAdapter包含5頁。如何避免重新創建片段到ViewPager中?
在第一頁我有一個ListView的項目。當我在ViewPager的最後一頁進行更改並返回第一頁時,我的ListView是空的,因爲適配器已被重新創建。 onAttach(),onCreate(),onCreateView(),onViewCreated(),onActivityCreated(),onStart()和onResume()方法總是調用下一個方法。
我想不要使用ViewPager.setOffscreenPageLimit()避免我的頁面被破壞的方法。有其他解決方案嗎?
我想要的行爲與使Facebook相同。
我做錯了什麼?我如何將數據保存在我的ListView中?
代碼我FragmentStatePageAdapter的:
public class AdapterMain extends FragmentStatePagerAdapter {
List<ChicfyFragment> fragments = new ArrayList<ChicfyFragment>();
public AdapterMain(FragmentManager fm) {
super(fm);
fragments.add(new FragmentShop());
fragments.add(new FragmentSearch());
fragments.add(new FragmentSell());
fragments.add(new FragmentNotification());
fragments.add(new FragmentProfile());
}
@Override
public Fragment getItem(int position) {
return fragments.get(position);
}
@Override
public int getCount() {
return fragments.size();
}
}
我ViewPager的第一頁的代碼:
public class FragmentShop extends ChicfyFragment implements SwipeRefreshLayout.OnRefreshListener {
ListView mListView;
AdapterProductList mAdapter;
SwipeRefreshLayout mSwipeRefreshLayout;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main_shop, container, false);
mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh);
mListView = (ListView) view.findViewById(R.id.fragment_main_shop_listview);
return view;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// setup adapter
mAdapter = new AdapterProductList((FragmentActivity) getActivity(), new ArrayList());
// setup listview
mListView.setAdapter(mAdapter);
mListView.setDivider(null);
// setup swipe
mSwipeRefreshLayout.setColorScheme(R.color.red, R.color.white, R.color.blue, R.color.white);
mSwipeRefreshLayout.setOnRefreshListener(this);
}
@Override
public void onRefresh() {
new AsyncTask<Void, Void, Void>() {
List<String> list = new ArrayList<String>();
@Override
protected Void doInBackground(Void... voids) {
try {
Thread.sleep(1000);
for(int i=0; i<10; i++) list.add("" + i);
} catch (Exception e) {}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
mAdapter.clear();
mAdapter.addAll(list);
mAdapter.notifyDataSetChanged();
mSwipeRefreshLayout.setRefreshing(false);
}
}.execute();
}
}
我這樣做的X計數。但mAdapter仍然爲空。所以它仍然在重新創建... – 2015-03-20 09:47:55
嘗試爲FragmentShop片段調用setRetainInstance(true)。你可以從它的構造函數中做到這一點。 – Grimmy 2016-06-06 12:21:57