Note that there are some explanatory texts on larger screens.

plurals
  1. POImplementing up navigation with fragments without Support library
    primarykey
    data
    text
    <p>Suppose we have activity with dynamic fragments. There is some "root" fragment, and it is added like this:</p> <pre><code>@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (savedInstanceState == null) { getFragmentManager().beginTransaction() .replace(R.id.container, new RootFragment()) .addToBackStack("root") .commit(); } } </code></pre> <p>There are also some other fragments, which replaces this root fragment according to some logic. And we want to implement home button on <code>ActionBar</code>, which allows us to go from any fragment to the root. So, we call anywhere <code>getActionBar().setDisplayHomeAsUpEnabled(true);</code> and override <code>onOptionsItemSelected</code> in our activity:</p> <pre><code>@Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); FragmentManager fm = getFragmentManager(); switch (id) { case android.R.id.home: fm.popBackStack("root", 0); return true; … } return super.onOptionsItemSelected(item); } </code></pre> <p>This code works. But an issue appeared. When we press Back on root fragment, it just disappears from activity, we see empty screen and need to press Back once again to close application. I understand that it is correct behaviour according to the code I wrote and I need to remove <code>addToBackStack</code> to fix it. But in that case the home button implementation will not work.</p> <p>The fix I see is overriding <code>onBackPressed</code> as following:</p> <pre><code>@Override public void onBackPressed() { if (getFragmentManager().getBackStackEntryCount() &gt; 1) { super.onBackPressed(); } else { finish(); } } </code></pre> <p>But it seems unnaturally. Fragments should make code cleaner, not like this.</p> <p>So, how to do it correct? I think that it is typical task and probably it is a silly question. But in official documentation I've found only <a href="http://developer.android.com/training/implementing-navigation/ancestral.html" rel="nofollow">one solution</a>, and it is about Support library, which I don't want to use.</p> <p>Or my dirty hack is OK?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload