Reputation: 301
I'm using BottomNavigationView in android to make a application just like Instagram. I'm using fragments with the navigationTabs. App have 5 tabs initialy I've set the middle tab as active tab and loads it once the app start. when i click on any other tab a network call is made and data is loaded. Now when i press on back button or click on the last tab again(which was loaded on startup) the fragment is recreated and the network call is made to load the same data. I want to show the previous fragments with same data without recreating.
I've tried using
transaction.add(container,fragment);
but to no avail.
my code on tab click
if (item.getItemId() == R.id.nav_OverView && _current != R.id.nav_OverView) {
Overview _overView = new Overview();
_fragmentTransaction.hide(_currentFragment);
_fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE);
_fragmentTransaction.add(R.id.content_base_drawer, _overView);
_fragmentTransaction.commit();
_current = R.id.nav_OverView;
viewIsAtHome = true;
}
I know using remove and add is same as using replace.
Any help is appreciated.
Upvotes: 0
Views: 1932
Reputation: 275
Before creating the view you can check if the view is already created or not, the below code helps fragment recreating problem.
View view;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
if (view == null)
{
view = inflater.inflate(R.layout.frag_layout, container, false);
init(view);
}
return view;
}
Upvotes: 1
Reputation: 28239
Make _overview
into a class field (instead of a local variable), and change your listener code to this:
Also, use replace
instead of hide
+add
, this will prevent Fragment already added
errors.
Replace an existing fragment that was added to a container. This is essentially the same as calling remove(Fragment) for all currently added fragments that were added with the same containerViewId and then add(int, Fragment, String) with the same arguments given here.
See example:
if (item.getItemId() == R.id.nav_OverView && _current != R.id.nav_OverView) {
if (_overView == null) {
_overView = new Overview();
}
_fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE);
_fragmentTransaction.replace(R.id.content_base_drawer, _overView);
_fragmentTransaction.commit();
_current = R.id.nav_OverView;
viewIsAtHome = true;
}
Upvotes: 0