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.