Lily
Lily

Reputation: 846

Change Menu when Tab changed in Android

I have two tabs in my application and I want the menu to change depending on the Tab.

Here what I did

  TabHost tabHost = tabHost = getTabHost();

    TabSpec photospec = tabHost.newTabSpec("Photos");
    photospec.setIndicator("Photos", getResources().getDrawable(R.drawable.photo));
    Intent photosIntent = new Intent(this, Photos.class);
    photospec.setContent(photosIntent);



    TabSpec songspec = tabHost.newTabSpec("Songs");       
    songspec.setIndicator("Songs", getResources().getDrawable(R.drawable.songs));
    Intent songsIntent = new Intent(this, Songs.class);
    songspec.setContent(songsIntent);

    tabHost.addTab(photospec); // Adding photos tab
    tabHost.addTab(songspec); // Adding songs tab

Now When the user clicks on the photos tab, I would like to display a menu for editing pictures and when the user clicks on songs tab I want to display a menu of controlling the order of the songs. I want to do this each time the user click on any of the tabs.

 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
    int currentTab = tabHost.getCurrentTab();
    if (currentTab == 0)
        startActivity(new Intent(this, Photosoptions.class));
    if (currentTab == 1)
        {
           startActivity(new Intent(this, Songsoptions.class));
                      } 
            return true;
        }



      @Override
    public boolean onPrepareOptionsMenu(Menu menu) {

        MenuInflater inflater = getMenuInflater();
        int currentTab = tabHost.getCurrentTab();

        if (currentTab == 0){
            menu.clear();
            inflater.inflate(R.menu.first, menu);
           closeOptionsMenu();

           }
       if (currentTab ==1){
            menu.clear();
            inflater.inflate(R.menu.second, menu);
        closeOptionsMenu();

       }
        return super.onPrepareOptionsMenu(menu);
    }

Upvotes: 2

Views: 3322

Answers (1)

Shayan Pourvatan
Shayan Pourvatan

Reputation: 11948

you can use following code:

@Override
 public boolean onPrepareOptionsMenu(Menu menu) {
        // TODO Auto-generated method stub
        MenuInflater inflater = getMenuInflater();
        int currentTab = tabHost.getCurrentTab();
        Toast.makeText(getApplicationContext(), currentTab+"", Toast.LENGTH_SHORT);
        menu.clear();
        if (currentTab == 0) {
            inflater.inflate(R.menu.first, menu);  //  menu for photospec.
        } else {
            inflater.inflate(R.menu.second, menu);  // menu for songspec
        }
        return super.onPrepareOptionsMenu(menu);
    }

you don't needed onCreateOptionsMenu and you must handle item click with onOptionsItemSelected

Upvotes: 7

Related Questions