AND4011002849
AND4011002849

Reputation: 2001

How to change the menu according to the fragment using navigation drawer

I'm using NavigationDrawer as the main activity, but when I go to another fragment I want to modify the menu, putting an arrow to back to the home and hide the search icon of the navbar, so I'm having two problems here, I can hide the search icon when I change the fragment, but when I'm back to the navigationMain it should be visible again, which is not happening, and if I am in another fragment the navigation bar must be removed and an arrow back must appear so I can get back to home, this is what I've tried so far:

public class NavigationMain extends ActionBarActivity{

    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private android.support.v7.app.ActionBarDrawerToggle mDrawerToggle;

    private CharSequence mDrawerTitle;
    private CharSequence mTitle;
    private String[] mPlanetTitles;
    static Toolbar toolbar;
    TextView toolbartitle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.navigation_main);


        mPlanetTitles = getResources().getStringArray(R.array.planets_array);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);
        toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
        toolbartitle = (TextView) findViewById(R.id.titletool);


        mDrawerList.setAdapter(new ArrayAdapter<String>(this,
                R.layout.drawer_list_item, mPlanetTitles));
        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());


        mDrawerToggle = new android.support.v7.app.ActionBarDrawerToggle(
                this,                  /* host Activity */
                mDrawerLayout,         /* DrawerLayout object */
                toolbar,  /* nav drawer image to replace 'Up' caret */
                R.string.drawer_open,  /* "open drawer" description for accessibility */
                R.string.drawer_close  /* "close drawer" description for accessibility */
        ) {
            public void onDrawerClosed(View view) {
                //getSupportActionBar().setTitle(mTitle);
                toolbartitle.setText(mTitle);
                getSupportActionBar().setDisplayShowTitleEnabled(false);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }

            public void onDrawerOpened(View drawerView) {
                //getSupportActionBar().setTitle(mDrawerTitle);
                toolbartitle.setText(mDrawerTitle);
                getSupportActionBar().setDisplayShowTitleEnabled(false);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }
        };

        setSupportActionBar(toolbar);
        mDrawerLayout.setDrawerListener(mDrawerToggle);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbartitle.setText("Nav");
        toolbar.inflateMenu(R.menu.main);

        mDrawerToggle.syncState();

        if (savedInstanceState == null) {
            selectItem(0);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        return super.onCreateOptionsMenu(menu);
    }

    /* Called whenever we call invalidateOptionsMenu() */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // If the nav drawer is open, hide action items related to the content view
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // The action bar home/up action should open or close the drawer.
        // ActionBarDrawerToggle will take care of this.
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        // Handle action buttons
        switch (item.getItemId()) {
            case R.id.action_websearch:
                // create intent to perform web search for this planet
                Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
                intent.putExtra(SearchManager.QUERY, toolbartitle.getText());
                // catch event that there's no activity to handle intent
                if (intent.resolveActivity(getPackageManager()) != null) {
                    startActivity(intent);
                } else {
                    Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show();
                }
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    /* The click listner for ListView in the navigation drawer */
    private class DrawerItemClickListener implements ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            selectItem(position);
        }
    }

    private void selectItem(int position) {

        FragmentManager fragmentManager = getSupportFragmentManager();
        Fragment fragment = new InstituicoesFragment();

        switch (position) {

            case 0:
                fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
                break;
        }
        // Load your conten here
        Toast.makeText(NavigationMain.this, "Position" + position, Toast.LENGTH_LONG).show();

        // update selected item and title, then close the drawer
        mDrawerList.setItemChecked(position, true);
        mDrawerLayout.closeDrawer(mDrawerList);
    }

    @Override
    public void setTitle(CharSequence title) {
        mTitle = title;
        //getSupportActionBar().setTitle(mTitle);
        toolbartitle.setText(mTitle);
    }


    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggls
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    @Override
    public void onBackPressed() {

        super.onBackPressed();

    }


}

In my Fragment I add the following:

 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

   @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.main, menu);
        menu.removeItem(R.id.action_websearch);
        super.onCreateOptionsMenu(menu, inflater);
    }

Upvotes: 4

Views: 2612

Answers (1)

Ivano Donadi
Ivano Donadi

Reputation: 377

i used this method : i inflate the menu for the actionbar with all the items already in. then in the Activity onCreateOptionsMenu() i check wich fragment is displayed and i set the visibility of the items accordingly. then in the onSectionAttached method i call invalidateOptionsMenu(); that will reload the onCreateOptionsMenu so i can have different menu items on each fragment selected

for checking i use boolean flags and if the flag is true it means that the fragment is n view, like:

viewing the first fragment:

ft.replace(R.id.container, firstFragment);
firstfragmentIsOn=true;
secondFragmentIsOn=false;

viewing the second fragment:

ft.replace(R.id.container, secondFragment);
firstfragmentIsOn=false;
secondFragmentIsOn=true;

and in the onCreateOptionsMenu:

MenuItem item1=menu.findItem(R.id.item1);
MenuItem item2=menu.findItem)(R.id.item2);
if(firstfragmentIsOn)
{
  item1.setVisible(true);
   item2.setVisible(false);
}
if(secondFragmentIsOn)
{
  item1.setVisible(false);
   item2.setVisible(true);
}

Upvotes: 1

Related Questions