安卓:显示根据ViewPager操作栏菜单项 [英] Android: Showing Action Bar menu items depending on ViewPager
问题描述
我有麻烦了下面这段code打工了。我有一个 viewpager
有3个片段,我想只有一个搜索图标显示于一体。我开始试图通过该片段添加的搜索功能,但刷到该网页时,菜单项的呈现是缓慢的。我现在在零件上的搜索图标添加到活动中,然后就隐藏或显示,这取决于 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();
}
}
尽管上面并移动到
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
使系统调用在prepareOptionsMenu方法
,所以你可以重写此方法如下:
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();
}
这篇关于安卓:显示根据ViewPager操作栏菜单项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!