Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You're not missing anything (or I'm missing it too). </p> <p>I searched long and hard for a way to do this "properly" but I couldn't find anything. What I ended up doing is writing my own backstack logic. Unfortunately my employer owns my code so I can't share any of that verbatim, but here was my approach:</p> <p>Create an <code>enum</code> with one entry for each of your tabs. Let's call it <code>TabType</code>. Now create an instance variable <code>tabStacks</code> of type <code>HashMap&lt;TabType, Stack&lt;String&gt;&gt;</code>. Now you can instantiate one stack for each tab - each stack is a list of tags, as specified by <code>Fragment.getTag()</code>. This way you don't have to worry about storing references to <code>Fragments</code> and whether they're going to disappear on you when you rotate the device. Any time you need a reference to a <code>Fragment</code>, grab the right tag off the stack and use <code>FragmentManager.findFragmentByTag()</code>.</p> <p>Now whenever you want to push a <code>Fragment</code> onto a tab, generate a new tag (I used <code>UUID.randomUUID().toString()</code>) and use it in your call to <code>FragmentTransaction.add()</code>. Then push the tag on top of the stack for the currently displayed tab.</p> <p><strong>Be careful:</strong> when you want to push a new fragment on top of an old one, don't <code>remove()</code> the old one, since the <code>FragmentManager</code> will consider it gone and it will be cleaned up. Be sure to <code>detach()</code> it, and then <code>attach()</code> it later. Only use <code>remove()</code> when you're permanently popping a <code>Fragment</code>, and only use <code>add()</code> the first time you want to show it.</p> <p>Then, you'll have to add some relatively simple logic to your <code>TabListener</code>. When a tab is unselected, simply <code>peek()</code> at its stack and <code>detatch()</code> the associated Fragment. When a tab is selected, <code>peek()</code> at the top of <em>that</em> stack and <code>attach()</code> that fragment.</p> <p>Lastly, you'll have to deal with Activity lifecycle quirks (like orientation changes). Persist your <code>Map</code> of <code>Stacks</code> as well as the currently selected tab, and unpack it again in your <code>onCreate()</code>. (You don't get this packing and unpacking for free, but it's pretty easy to do.) Luckily your <code>TabType</code> enum is <code>Serializable</code> so it should be trivial to put into a <code>Bundle</code>.</p>
 

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