片段的OptionsMenu在Viewpager显示对方的按钮 [英] OptionsMenu of Fragments in Viewpager showing each other's Buttons

查看:222
本文介绍了片段的OptionsMenu在Viewpager显示对方的按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个片段在viewpager。

I've got three fragments in a viewpager.

二,这些碎片有其自己版本的onCreateOptionsMenu方法:

Two of these fragments have their own version of the onCreateOptionsMenu method:

 @Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);

    // Set up 1 action button
    inflater.inflate(R.menu.home_snapshot_add, menu);
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);

    // Set up 2 action buttons
    inflater.inflate(R.menu.home_snapshot_send, menu);
}

家庭活动有一个基本的onCreateOptionsMenu方法:

The home activity has a basic onCreateOptionsMenu method:

    @Override
public boolean onCreateOptionsMenu(Menu menu) {
    return false;
}

在onCreate方法,每个片段调用方法:

In the onCreate method, each fragment calls the method:

setHasOptionsMenu(true);

每个菜单项有标签

android:showAsAction="always"

好像为我打开了活动,这三个按钮出现。 然而,当我通过他们滚动,错的人奇迹般地消失了。 这感觉就像该活动呼吁每一个片段的期权活动创作的菜单,然后更改菜单适当的时候我刷卡左,右。 我检查了菜单,但不知道什么是错的。 任何你想我需要检查?我有点没了主意。

Seems like as I open the Activity, all three buttons appear. However, when I scroll through them, the wrong ones magically disappear. It feels like the activity is calling every Fragment's options menu on Activity creation and then changes the menu appropriately when I swipe left and right. I've checked the menus but not sure what's wrong. Anything you reckon I need to check? I'm a little out of ideas.

谢谢!

推荐答案

在你的 ViewPager OnPageChangeListener 和适配器设置之后, ViewPager ,有这样的:

In your ViewPager's OnPageChangeListener and after setting the adapter to the ViewPager, have this:

@Override
public void onPageSelected(int position){
   invalidateFragmentMenus(position);
}


private void invalidateFragmentMenus(int position){
   for(int i = 0; i < mViewPagerFragentAdapter.getCount(); i++){
      mViewPagerAdapter.getItem(i).setHasOptionsMenu(i == position);
   }
   invalidateOptionsMenu(); //or respectively its support method.
}

与下面的参数设置你的片段适配器调用相同的方法后:

After setting your fragment adapter call the same method with following argument:

invalidateFragmentMenus(mViewPager.getCurrentItem());

以上语句将prevent所有其他的碎片不会收到关于 onCreateOptionsMenu调用()方法时, invalidateOptionsMenu()被调用,仅当前可见的片段将接收并能够填充选项菜单。

The above statements will prevent all other fragments not to receive call on onCreateOptionsMenu() method when invalidateOptionsMenu() is called, only the currently visible fragment will receive and be able to populate the options menu.

这篇关于片段的OptionsMenu在Viewpager显示对方的按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆