Hello everybody! I am writing my phone book. I decided to divide the application into fragments. It is not possible to adjust the work of the "back" button in the toolbar. I want it to be able to go back through the stack of fragments.

In each of the fragments added addToBackStack (null). When using the hardware "Back" button, everything works without problems, if you remove the onBackPressed () method.

Main_activity code:

public class MainActivity extends AppCompatActivity { private Toolbar mainToolbar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mainToolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(mainToolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); Fragment listViewFragment = new ListViewFragment(); FragmentTransaction transaction = getFragmentManager().beginTransaction(); transaction.add(R.id.fragContainer, listViewFragment); transaction.commit(); } @Override public void onBackPressed() { FragmentManager fm = getSupportFragmentManager(); if (fm.getBackStackEntryCount() > 0) fm.popBackStack(); else finish(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.information: Fragment infoFragment = new InfomationFragment(); FragmentTransaction transaction = getFragmentManager().beginTransaction(); transaction.replace(R.id.fragContainer, infoFragment) .addToBackStack(null) .commit(); return true; case R.id.home: onBackPressed(); return true; default: return super.onOptionsItemSelected(item); } } } 

The onBackPressed () method does not work as it should. Help me find a solution, please.

    2 answers 2

    In onCreate add the toolbar setNavigationOnClickListener at the toolbar:

     mainToolbar = (Toolbar) findViewById(R.id.toolbar); mainToolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); 

    And remove its implementation of onBackPressed. Those. This should be removed:

     @Override public void onBackPressed() { FragmentManager fm = getSupportFragmentManager(); if (fm.getBackStackEntryCount() > 0) fm.popBackStack(); else finish(); } 

    In general, onBackPressed is just a click on the hardware button, and it already has the default handling, including unwinding the stack of fragments. But the arrow of the tulbard is often used to go to parental activity, and not as a duplicate hardware button.

    • Thank you so much, works - Krabs

    You use getSupportFragmentManager in one place, and getFragmentManager in another. Use one any