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 显示操作栏菜单项
基础教程推荐
- Xcode UIView.init(frame:) 只能在主线程中使用 2022-01-01
- navigationItem.backBarButtonItem 不工作?为什么上一个菜单仍然显示为按钮? 2022-01-01
- 如何比较两个 NSDate:哪个是最近的? 2022-01-01
- Play 商店的设备兼容性问题 2022-01-01
- 为什么姜饼模拟器方向卡在应用程序中? 2022-01-01
- 如何将图像从一项活动发送到另一项活动? 2022-01-01
- UIImage 在开始时不适合 UIScrollView 2022-01-01
- SwiftUI-ScrollViewReader的ScrollTo不滚动 2022-01-01
- Android Volley - 如何动画图像加载? 2022-01-01
- iOS - UINavigationController 添加多个正确的项目? 2022-01-01
