我正在應用程序中有一個SearchActivity
;搜索活動只是「SearchFragment」的一個容器,而「SearchFragment」在ActionBar中包含SearchView
,其主要佈局的RecyclerView
用於顯示搜索結果。假設用戶執行搜索,結果顯示在RecyclerView
內,然後用戶旋轉屏幕......在這種情況下,我使用setRetainInstance(true)
方法。我認爲我的自定義ArrayAdapter數據將被保存,但事實並非如此。我知道我可以保存ArrayAdapter數據Bundle
爲onSaveInstanceState()
方法。但我想知道爲什麼setRetainInstance()
方法不起作用。setRetainInstance()方法是否保留ArrayAdapter數據?
public class SearchFragment extends Fragment
implements SearchView.OnQueryTextListener,
ResultsListAdapter.ItemClickListener {
private ResultsListAdapter mListAdapter;
private CustomRecyclerView resultsList;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_search, container, false);
RecyclerView.LayoutManager linearManager = new LinearLayoutManager(getActivity());
mListAdapter = new ResultsListAdapter(new ArrayList<Kiosk>(), this);
resultsList.setAdapter(mListAdapter);
resultsList.setLayoutManager(linearManager);
resultsList.setSetEmptyView(rootView.findViewById(R.id.empty_view));
if (savedInstanceState == null){
setRetainInstance(true);
}
return rootView;
}
@Override
public boolean onQueryTextSubmit(String s) {
if(s.isEmpty()) {
//Set an empty array, to set an empty view
mListAdapter.changeData(new ArrayList<Kiosk>());
mListAdapter.notifyDataSetChanged();
}
ArrayList<Kiosk> kiosksFound = performSearch(s);
mListAdapter.changeData(kiosksFound);
mListAdapter.notifyDataSetChanged();
return false;
}
@Override
public boolean onQueryTextChange(String s) {
if(s.isEmpty()) {
//Set an empty array, to set an empty view
mListAdapter.changeData(new ArrayList<Kiosk>());
mListAdapter.notifyDataSetChanged();
return false;
}
ArrayList<Kiosk> kiosksFound = performSearch(s);
mListAdapter.changeData(kiosksFound);
mListAdapter.notifyDataSetChanged();
return false;
}
}
我想知道是否在'Fragment'的生命週期早期調用方法會產生影響。你有沒有嘗試在'onCreate()'中調用'setRetainInstance(true)'? – Emmanuel 2015-02-23 05:20:28
嗨@Emmanuel,是的,我嘗試過,但結果是一樣的。 – Silmood 2015-02-23 06:01:36