Android 如何为不同的选项卡添加多个菜单

标签 android android-tabhost android-tabs android-tabactivity

我有很多这样的标签:

TabHost th;
TabSpec spec;
th = (TabHost) findViewById(R.id.tabhost_template_two_tabs);
th.setup();
// all tab
spec = th.newTabSpec("All");
spec.setIndicator("All");
spec.setContent(R.id.tab_template_two_tabs_all);
th.addTab(spec);
// favorite tab
spec = th.newTabSpec("Favorite");
spec.setIndicator("Favorite");
spec.setContent(R.id.tab_template_two_tabs_favorite);
th.addTab(spec);

我想为每个选项卡添加一个菜单,怎么样?

最佳答案

TabHost 中的每个Tab 都有一个从 0 开始的数字,因此您必须通过使用 int currentTab = th 知道您现在在哪个选项卡中。 getCurrentTab();,然后使用 menu.clear() 清除之前的菜单,然后使用 inflater.inflater(menuID, menu) 添加新菜单

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

注意事项:

onCreateOptionsMenu 对您的情况没有帮助

关于Android 如何为不同的选项卡添加多个菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14529926/

相关文章:

java - 安卓文件关联

android - 无法从android studio上的github导入项目

android - 我如何将变量从我的适配器传递到我在 Kotlin 中实例化的 fragment

android - 如何在 Espresso 中打开标签页

android - 删除 Android 中的操作栏标签填充

android - "Developer error: this application is misconfigured"Google 使用列入白名单的客户端 ID 在 firebase 上登录

android - HttpClient 在执行方法时失败

java - Tabhost 不更新选项卡

android - 在 TabHost 中有小写标题

屏幕中间的android导航选项卡