Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to handle onContextItemSelected in a multi fragment activity?
    text
    copied!<p>I'm currently trying to adapt my application to use the "Compatibility Libraries for Android v4" to provide the benefits of the usage of fragments even to Android 1.6 users.</p> <p>The implementation of a context menu seems to be tricky:</p> <ul> <li>The main activity of the application is extending the <strong>FragmentActivity</strong> class.</li> <li>The fragments are all based on one class which extends the Fragment class.</li> <li>The fragment class is calling <strong>registerForContextMenu()</strong> in its <strong>onCreateView()</strong> method and overrides the methods <strong>onCreateContextMenu()</strong> and <strong>onContextItemSelected()</strong>.</li> </ul> <p>For <strong>onCreateContextMenu()</strong> this works pretty well. The context menu is inflated from a resource file and slightly modified based on the selected item (which is based on a listView... even if the fragment is not an ListFragment).</p> <p>The problem occurs when a context menu entry is selected. <strong>onContextItemSelected()</strong> is called for all currently existing fragments starting with the first added one.</p> <p>In my case the fragments are used to show the content of a folder structure. When the context menu of a subfolder fragment is opened and a menu item is selected, <strong>onContextItemSelected()</strong> is first called on the upper levels (depending on how many fragments are allowed/visible in this moment).</p> <p>Right now, I use a workaround by a field on activity level which holds the tag of last fragment calling its <strong>onCreateContextMenu()</strong>. This way I can call "return super.onContextItemSelected(item)" in the begin of <strong>onContextItemSelected()</strong> when the stored tag is not the same as getTag(). But this approach looks a bit dirty to me.</p> <p>Why is onContextItemSelected() called on all fragments? and not just one the one that was calling <strong>onCreateContextMenu()</strong>?</p> <p>What is the most elegant way to handle this?</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