在Android中更改标签时更改菜单

时间:2014-01-14 11:14:28

标签: android menu tabs listener

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

我在这里做了什么

  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

现在,当用户点击照片标签时,我想显示一个用于编辑图片的菜单,当用户点击歌曲标签时,我想显示一个控制歌曲顺序的菜单。我希望每次用户点击任何标签时都这样做。

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

1 个答案:

答案 0 :(得分:7)

您可以使用以下代码:

@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处理项目点击