在 Android 中更改选项卡时更改菜单 [英] Change Menu when Tab changed in Android

查看:24
本文介绍了在 Android 中更改选项卡时更改菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序中有两个选项卡,我希望根据选项卡更改菜单.

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

我做了什么

  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);
    }

推荐答案

你可以使用以下代码:

@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);
    }

您不需要 onCreateOptionsMenu 并且您必须使用 onOptionsItemSelected

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

这篇关于在 Android 中更改选项卡时更改菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆