Mr Robot
Mr Robot

Reputation: 1747

Android fragment addToBackStack not working with Navigation drawer

I had Created a Home activity which includes a Navigation Drawer onclick with fragment. I had included fragmentTransaction.addToBackStack(null).commit(); with the fragment transaction code. But it doesn't go back to previous page,instead it is closing the app.

In My MainActivity

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    // Handle navigation view item clicks here.
    int id = item.getItemId();
    RelativeLayout mainLayout=(RelativeLayout)findViewById(R.id.mainlayout);

  if (id == R.id.nav_project) {
        ProjectFragment fragment = new ProjectFragment();
        mainLayout.removeAllViews();
        fragmentTransaction.replace(R.id.mainlayout, fragment);
        fragmentTransaction.addToBackStack(null).commit();

    } 

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}
 @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

My Default Fragment

public class ProjectFragment extends Fragment {

       @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
           View v =  inflater.inflate(R.layout.fragment_project, container, false);

            return v;
        }



}

Can anyone help me to figure out this problem.

Upvotes: 1

Views: 1770

Answers (1)

The Original Android
The Original Android

Reputation: 6215

Thanks for your response, it helps. Basically you need to add a fragment to the stack.

Instead of using replace(), use the add method of fragmentTransaction. This will give you the desired effect.

Easy sample: fragmentTransaction.add(R.id.mainlayout, fragment);

Upvotes: 1

Related Questions