Search code examples
androidandroid-fragmentsandroid-navigationview

Handling NavigationViewer Menu Items click


I have a NavigationViewer activity which has 3 fragments. I want that every time the user selects an item from NavigationViewersliding menu items the app will transact a new fragment object of the selected kind.

for Example I have a NavigationViewer menu item Called "MyFragment" So I am trying this Code on that item:

MyFragment myFragment = new MyFragment();
fragmentTransaction.replace(R.id.RR, myFragment , "nav_MyFragment ").commit();

But this causes a problem that if user selected "MyFragment" from menu while it is active [seen to user] it will create a new object. and I want to create that new object only if transacting from some fragment to another.

Any Suggestions?

Edit: retrieving the fragment by tag and then checking if isVisble() or if isAdded() gives null exception


Solution

  • You can keep a Fragment variable and assign your active fragment there, and then check the getClassName() and if it's the clicked one is the same as the one you are currently displaying, you don't load a new one.

    I'm going to use the code from this app I have in github.

    Then in your Activity declare a Fragment variable like this:

    Fragment active;
    

    In your onOptionsItemSelected() method, you have to do the checking for the item pressed.

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        //noinspection SimplifiableIfStatement
        if (id == R.id.nav_item1) {
            if (active.getClass().getSimpleName().equals("FragmentA")) {
                // then this fragment is already being shown, therefore do nothing
            } else {
                FragmentA fragtoadd = new FragmentA();
                getFragmentManager().beginTransaction()
                                    .remove(fragtoadd)
                                    .commit();
                active = fragtoadd; // the magic is here, everytime you add a new fragment, keep the reference to it to know what fragment is being shown
            }
            return true;
        } else if (id == R.id.nav_item2) {
            // do the same as above but for FragmentB, and so on
            return true;
        } 
        // ... check all your items
        return super.onOptionsItemSelected(item);
    }
    

    If you have your code in Github so that I can have a look it would be better. Hope it helps!