I'm facing two problems with fragments in Android.
I have an app with a Navigation Drawer Fragment inside my MainActivity. When I click in an item on this Navigation Drawer, a new fragment is load on the "fragment_placeholder" inside the Main Activity. Pretty simple.
When the MainActivity is created, I'm loading "homeFragment" inside fragment_placeholder. This fragment has a SlidingTabLayout with two tabs, each one loading it´s corresponding fragment. This Home Fragment is my "main" part of the app.
When I click on another item in Navigation Drawer, the Home Fragment is replaced with the another Fragment, for example, when I click on "My account", the "My account fragment" is loaded on fragment_placeholder. I have 3 itens in the Navigation Drawer.
I want to keep the Home Fragment (and the two tabs/fragments inside it) on back stack, so I can navigate on any fragment (my account, config, and so on) and when I press back button, I'm getting back to Home Fragment.
I tried to addToBackStack the Home Fragment inside onCreate of MainActivity (before I commit it), but is not working properly. If I press the "My account" item on navigation drawer, and then press back, the app load "My account" fragment again, and if I press back again, app is closed. Another case: if I press the "Home" item, and then press back, the app back to the same home fragment but without any tab (it´s not loading the two fragments belonging to him).
Here is my app:
Here is my code: MainActivity
public class MainActivity extends ActionBarActivity {
private Toolbar mToolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupDrawer();
// Loading home fragment
if (findViewById(R.id.fragment_placeholder) != null) {
if (savedInstanceState != null) {
return;
}
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
HomeFragment homeFragment = new HomeFragment();
homeFragment.setArguments(getIntent().getExtras());
fragmentTransaction.replace(R.id.fragment_placeholder, homeFragment);
fragmentTransaction.addToBackStack(null); // This is not working properly
fragmentTransaction.commit();
}
}
Navigation Drawer: itemClicked method
@Override
public void itemClicked(View view, int position) {
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
switch(position)
{
// Home
case 0:
HomeFragment homeFragment = new HomeFragment();
fragmentTransaction.replace(R.id.fragment_placeholder, homeFragment);
break;
// My account
case 1:
MyAccountFragment myAccountFragment = new MyAccountFragment();
fragmentTransaction.replace(R.id.fragment_placeholder, myAccountFragment);
break;
// Config
case 2:
ConfigFragment configFragment = new ConfigFragment();
fragmentTransaction.replace(R.id.fragment_placeholder, configFragment );
break;
}
fragmentTransaction.commit();
mDrawerLayout.closeDrawer(mDrawerListView);
}
Thank you and sorry about my english.