Android: Showing Action Bar menu items depending on ViewPager(Android:根据 ViewPager 显示操作栏菜单项)
问题描述
我无法运行以下代码.我有一个带有 3 个片段的 viewpager
,我希望一个搜索图标只显示在一个片段上.我开始尝试通过片段添加搜索功能,但是滑动到该页面时菜单项的呈现速度很慢.我现在正在将搜索图标添加到活动中,然后根据哪个 viewpager
页面处于活动状态来隐藏或显示,但以下内容不起作用:
I am having trouble getting the following piece of code to work out. I have a viewpager
with 3 fragments, and I want a search icon to only show up on one. I started off trying to add the search function by the fragment, but the rendering of the menu item was slow when swiping to that page. I am now on the part to add the search icon to the activity, and then just hide or show depending on which viewpager
page is active, but the following is not working:
public class MyApp extends FragmentActivity implements
FragmentTeams.FragmentNotification,ViewPager.OnPageChangeListener,
OnNavigationListener{
...
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
menuSearch = menu.findItem(R.id.menu_search);
mSearchView = new SearchView(this);
menuSearch.setActionView(mSearchView);
menuSearch.setVisible(false);
return true;
}
@Override
public void onPageSelected(int pageNum) {
if(pageNum== 1){
ActionBar actionBar = MyApp.this.getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
menuSearch.setVisible(true);
invalidateOptionsMenu();
}else{
ActionBar actionBar = MyApp.this.getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
menuSearch.setVisible(false);
invalidateOptionsMenu();
}
}
虽然上面确实(似乎)在 onCreateOptionsMenu
处创建并隐藏了图标,但在移动到时它不会重新启用
While the above does (appear to) create and hide the icon at onCreateOptionsMenu
, it is not reenabled when moving to
pageNum ==1
谁能告诉我为什么会发生这种情况?
Can anyone give me some insight as to why this may be happening?
推荐答案
invalidateOptionsMenu
使系统调用方法onPrepareOptionsMenu
,所以你可以重写这个方法如下:
invalidateOptionsMenu
make the system calls the method onPrepareOptionsMenu
, so you can override this method as follows:
public boolean onPrepareOptionsMenu(Menu menu) {
int pageNum = getCurrentPage();
if (pageNum == 1) {
menu.findItem(R.id.menu_search).setVisible(true);
}
else {
menu.findItem(R.id.menu_search).setVisible(false);
}
}
public void onPageSelected(int pageNum) {
invalidateOptionsMenu();
}
这篇关于Android:根据 ViewPager 显示操作栏菜单项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Android:根据 ViewPager 显示操作栏菜单项


基础教程推荐
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01