Different menu for different tabs in tab+swipe application for android project

15,780

Solution 1

create a menu xml file for menu_a.xml and menu_b.xml in the res/menu folder.

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/menu_item_search"
        android:icon="@drawable/ic_action_search"
        android:title="@string/description_search"
        android:orderInCategory="1"
        android:showAsAction="ifRoom" />
    <item android:id="@+id/menu_item_share"
        android:icon="@drawable/ic_action_share"
        android:title="@string/description_share"
        android:orderInCategory="1"
        android:showAsAction="ifRoom" />
</menu>

To create a option menu for the current Fragment displayed, add setHasOptionsMenu(true); to the Fragment onCreate() method.

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

    setHasOptionsMenu(true);

}

Then you must inflate the corresponding option menu (menu_a.xml or menu_b.xml) by override the onCreateOptionsMenu() method.

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_a, menu);
    super.onCreateOptionsMenu(menu, inflater);
}

For handling menu selections override the onOptionsItemSelected()

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
        case R.id.menu_item_search:                
              //do something
            return true;

        case R.id.menu_item_share:
              //do something
            return true;
    }
    return super.onOptionsItemSelected(item);
} 

see Creating an Options Menu: http://developer.android.com/guide/topics/ui/menus.html for more details.

Solution 2

Yes, I got the output with these codes ,

In TabOne.java and TabTwo.java I've added

   setHasOptionsMenu(true);

In onCreateView() function and after that menu function with different menu,removed menu function from main class.

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                    Bundle savedInstanceState)
    {
            View view = inflater.inflate(R.layout.tab_a, container, false);
            setHasOptionsMenu(true);
            return view;
    }
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        // TODO Auto-generated method stub
        //super.onCreateOptionsMenu(menu, inflater);
         inflater.inflate(R.menu.menu_b, menu);
    }
Share:
15,780
Anshad Vattapoyil
Author by

Anshad Vattapoyil

Works with Krews Limited, Abu Dhabi

Updated on June 05, 2022

Comments

  • Anshad Vattapoyil
    Anshad Vattapoyil almost 2 years

    I am a beginner to android applications and java, basically I am a PHP developer.

    I've a project for a tab+swipe application,

    Reseller.java

    package com.idevoc.onsitereseller;
    
    import java.util.ArrayList;
    import android.app.ActionBar;
    import android.app.ActionBar.Tab;
    import android.app.Activity;
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.support.v4.app.FragmentActivity;
    import android.support.v4.app.FragmentManager;
    import android.support.v4.app.FragmentPagerAdapter;
    import android.support.v4.app.FragmentTransaction;
    import android.support.v4.view.ViewPager;
    import android.view.Menu;
    import android.view.MenuInflater;
    
    public class Reseller extends FragmentActivity {
    
        FragmentTransaction transaction;
        static ViewPager mViewPager;
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reseller);
    
        Fragment tabOneFragment = new TabOne();
        Fragment tabTwoFragment = new TabTwo();
    
        PagerAdapter mPagerAdapter = new PagerAdapter(getSupportFragmentManager());
        mPagerAdapter.addFragment(tabOneFragment);
        mPagerAdapter.addFragment(tabTwoFragment);
    
        //transaction = getSupportFragmentManager().beginTransaction();
    
        mViewPager = (ViewPager) findViewById(R.id.pager);
                mViewPager.setAdapter(mPagerAdapter);
                mViewPager.setOffscreenPageLimit(2);
            mViewPager.setCurrentItem(0);
    
                mViewPager.setOnPageChangeListener(
                    new ViewPager.SimpleOnPageChangeListener() {
                        @Override
                        public void onPageSelected(int position) {
                            // When swiping between pages, select the
                            // corresponding tab.
                            getActionBar().setSelectedNavigationItem(position);
                        }
                    });
    
        ActionBar ab = getActionBar();
        ab.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        Tab tab1 = ab.newTab().setText("Tab One")
                        .setTabListener(new TabListener<TabOne>(
                        this, "tabone", TabOne.class));
    
                Tab tab2 = ab.newTab().setText("Tab Two")
                                .setTabListener(new TabListener<TabTwo>(
                        this, "tabtwo", TabTwo.class));
    
                ab.addTab(tab1);
                ab.addTab(tab2);         
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.menu.menu, menu);
        return true;
    }
    
    public static class TabListener<T extends Fragment> implements ActionBar.TabListener {
        private Fragment mFragment;
        private final Activity mActivity;
        private final String mTag;
        private final Class<T> mClass;
    
        /** Constructor used each time a new tab is created.
          * @param activity  The host Activity, used to instantiate the fragment
          * @param tag  The identifier tag for the fragment
          * @param clz  The fragment's Class, used to instantiate the fragment
          */
        public TabListener(Activity activity, String tag, Class<T> clz) {
            mActivity = activity;
            mTag = tag;
            mClass = clz;
        }
    
        /* The following are each of the ActionBar.TabListener callbacks */
    
        public void onTabSelected(Tab tab, FragmentTransaction ft) {
            // Check if the fragment is already initialized
            if (mFragment == null) {
                // If not, instantiate and add it to the activity
                mFragment = Fragment.instantiate(mActivity, mClass.getName());
                ft.add(android.R.id.content, mFragment, mTag);
            } else {
                // If it exists, simply attach it in order to show it
                ft.attach(mFragment);
            }
        }
    
        public void onTabUnselected(Tab tab, FragmentTransaction ft) {
            if (mFragment != null) {
                // Detach the fragment, because another one is being attached
                ft.detach(mFragment);
            }
        }
    
        public void onTabReselected(Tab tab, FragmentTransaction ft) {
            // User selected the already selected tab. Usually do nothing.
        }
    
                public void onTabReselected(Tab arg0,
                                android.app.FragmentTransaction arg1)
                {
    
    
                }
    
                public void onTabSelected(Tab arg0, android.app.FragmentTransaction arg1)
                {
    
                        mViewPager.setCurrentItem(arg0.getPosition());
                }
    
                public void onTabUnselected(Tab arg0,
                                android.app.FragmentTransaction arg1)
                {
    
    
                }
    }
    
    public class PagerAdapter extends FragmentPagerAdapter{
    
        private final ArrayList<Fragment> mFragments = new ArrayList<Fragment>();
    
        public PagerAdapter(FragmentManager manager){
            super(manager);
        }
    
        public void addFragment(Fragment fragment){
            mFragments.add(fragment);
            notifyDataSetChanged();
        }
    
        @Override
        public int getCount() {
            return mFragments.size();
        }
    
        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }
      }
    
     }
    

    TabOne.java

     package com.idevoc.onsitereseller;
    
     import android.os.Bundle;
     import android.support.v4.app.Fragment;
     import android.view.LayoutInflater;
     import android.view.View;
     import android.view.ViewGroup;
    
    public class TabOne extends Fragment
    {
    public static final String ARG_SECTION_NUMBER = "section_number";
         @Override
        public void onActivityCreated(Bundle savedInstanceState) {
           super.onActivityCreated(savedInstanceState);
        }
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                        Bundle savedInstanceState)
        {
                View view = inflater.inflate(R.layout.tab_a, container, false);
                return view;
        }
    
    }
    

    TabTwo.java

     package com.idevoc.onsitereseller;
    
     import android.os.Bundle;
     import android.support.v4.app.Fragment;
     import android.view.LayoutInflater;
     import android.view.View;
     import android.view.ViewGroup;
    
     public class TabTwo extends Fragment
     {
    
         @Override
            public void onActivityCreated(Bundle savedInstanceState){
            super.onActivityCreated(savedInstanceState);
            }
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                        Bundle savedInstanceState)
        {
                View view = inflater.inflate(R.layout.tab_a, container, false);
    
                return view;
        }
      }
    

    Here I am loading two tabs for the application and loading a common menu, but I need to load a different menu for different tabs like:

    if the tab is TabOne then load menu_a, if tab is TabTwo then load menu_b with different options. I don't want to load the common menu. How can I do this?

  • bernzkie
    bernzkie over 8 years
    how to do this with effects?
  • TouchBoarder
    TouchBoarder over 8 years
    @bernzkie what kind of effects?
  • bernzkie
    bernzkie over 8 years
    like the first menu icon will fadeOut then the second will fadeIn? maybe if only possible?
  • TouchBoarder
    TouchBoarder over 8 years
    @bernzkie if so I would have tried adding the menu items in the parent activity, kept a reference to the menu item and programatically switched the menu icon in a tab or page change listener. This could help stackoverflow.com/a/34295265/546054
  • sarfarazsajjad
    sarfarazsajjad over 8 years
    doing this append items in the menu. is it possible to completely replace the items
  • TouchBoarder
    TouchBoarder over 8 years
    @Saifee make sure you only inflate the Fragment specific menu.xml. and do not inflate any menu in the parent Activity. If you do that the Fragment menu will be added to you Activity menu.
  • Aliton Oliveira
    Aliton Oliveira over 5 years
    The items are shown, but the onOptionsItemSelected(MenuItem item) does nothing in FragmentTwo. Why? I have a menu implemented in MainActivity and another menu implemented in FragmentTwo. The onCreateOptionsMenu(Menu menu, MenuInflater inflater) in FragmentTwo has menu.clear() and only the options for FragmentTwo are shown.
  • Aliton Oliveira
    Aliton Oliveira over 5 years
    I fond the answer here stackoverflow.com/a/19449914/4300670. The magic happens in the onOptionsItemSelected(MenuItem item) in MainActivity. It must return false.