我正在使用具有SearchActivity的应用程序;搜索活动只是“ SearchFragment”的容器,“ SearchFragment”在ActionBar中包含SearchView,并且其主布局具有RecyclerView来显示搜索结果。假设用户执行搜索,结果显示在RecyclerView中,然后用户旋转屏幕...在这种情况下,我使用setRetainInstance(true)方法。我以为我的自定义ArrayAdapter数据将被保存,但事实并非如此。我知道我可以将ArrayAdapter数据保存在Bundle中用于onSaveInstanceState()方法。但是我想知道为什么setRetainInstance()方法不起作用。

 

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;
            }

  }

最佳答案

即使保留状态,仍会调用onCreateView。由于您在此处重新创建列表视图,因此将清除数据。

10-01 05:23
查看更多