Reputation: 377
I'm trying to keep the recyclerview filled even after switching tabs. I've been going at it of a while now, and tried several methods but none work.
MainActivity.java
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
initTab
}
private void initTab(){
//tab setup
mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
mTabHost.setup(MainActivity.this,getSupportFragmentManager(),android.R.id.tabcontent);
...
mTabHost.addTab(mTabHost.newTabSpec("tab1").setIndicator(createTabView(icon_search, "search")),
searchFragment.class, null);
...more tabs added...
return;
Fragment
private RecyclerView results;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
final Bundle savedInstanceState){
View v = inflater.inflate(R.layout.tab_search, container, false);
results = (RecyclerView) v.findViewById(R.id.search_results);
results.setHasFixedSize(true);
LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
results.setLayoutManager(mLayoutManager);
ScrollListener mScrollListener = new ScrollListener(mLayoutManager);
results.setAdapter(searchResultsAdapter);
results.addOnScrollListener(mScrollListener);
return v;
I cant make mLayoutManager a singleton either otherwise I get an error from recyclerview something like
"LayoutManager is already attatched to a RecyclerView"
Portrait mode is locked and MainActivity doesn't switch to other activities
Upvotes: 0
Views: 930
Reputation: 1781
When you're swapping away from your fragment, it's getting unloaded to preserve memory. Then, when you swap back to it, it needs to be reloaded from scratch. That's why your RecyclerView is losing its items. You could try and find a way to stop it from getting unloaded but since Android has limited memory we don't really want to enthusiastically throw away nice memory management features.
You want your RecyclerView to persist its items. The answer to this lies in how the RecyclerView gets its items in the first place. The RecyclerView just manages loading a subset of whatever its RecyclerView.Adapter
says are its items. If RecyclerView.Adapter.getItemCount()
returns 0, then the RecyclerView is going to load nothing. So, the RecyclerView.Adapter
is the real culprit.
If you make it so that your RecyclerView.Adapter
remembers the list of items it last had when it's created, rather than always starting with an empty list, then your RecyclerView will render that list.
Now your problem is about persisting a list of objects (relatively straight forward), rather than trying to get some views to stay inflated in the background (relatively complicated and somewhat unwanted due to the memory stuff).
Hope this helps.
Upvotes: 1