Change Menu with Fragment in android

Frequently used code samples and tutorials
vivekkalady
Site Admin
Posts: 35
Joined: Tue Nov 18, 2014 2:39 pm

Change Menu with Fragment in android

Postby vivekkalady » Sun Nov 23, 2014 9:08 am

This Post shows how to change Menu with each Fragment.We can show Common Menus like Settings,About,etc in Main Activity Menu and Fragment Menus in corresponding fragments

Main Activity

Code: Select all

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.main_menu) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
 


Main Menu (Activity Menu)

Code: Select all

<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:id="@+id/main_menu"
        android:title="Activity Menu"/>

</menu>


Fragment 1 Menu Code

in onCreate you have to provide setHasOptionsMenu(true);

Code: Select all

   @Override
   public void onCreate(Bundle savedInstanceState) {
      // TODO Auto-generated method stub
      super.onCreate(savedInstanceState);
      setHasOptionsMenu(true);
   }
   
   @Override
   public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
      // TODO Auto-generated method stub
      inflater.inflate(R.menu.menu_one, menu);
      super.onCreateOptionsMenu(menu, inflater);
      
   }

   @Override
   public boolean onOptionsItemSelected(MenuItem item) {
       switch (item.getItemId()) {
       case R.id.one:
          //Write your code
           break;

       case R.id.two:
                //Write your code
           break;
       }
       return true;

   }


Menu for Fragment

Code: Select all

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/one"
        android:title="Fragment 1 Menu 1"/>
    <item
        android:id="@+id/two"
        android:title="Fragment 1 Menu 2"/>

</menu>

Return to “Tutorials & Examples”

Who is online

Users browsing this forum: No registered users and 1 guest

cron