android-fragments MenuProvider不会在ViewPager内自动切换

bvn4nwqk  于 2022-11-13  发布在  Android
关注(0)|答案(2)|浏览(257)

我有一个带有2个片段的ViewPager。每个片段都包含一个MenuProvider,添加如下:

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    requireActivity().addMenuProvider(new MyMenuProvider1(), getViewLifecycleOwner());
}

但是在打开包含ViewPager的Activity之后,我总是看到第二个片段的菜单,切换片段并没有改变任何东西。看起来第二个片段的MenuProvider总是覆盖第一个片段。如果我用旧的和不赞成的方式管理菜单,菜单就能正确切换。
我做错了什么?有没有一种自动的方式在ViewPager内部切换MenuProviders?

3b6akqbq

3b6akqbq1#

正如前面的评论所建议的,您的pager通过最初创建它的两个子片段,然后将它们持久化在内存中来进行优化。我建议在ViewPager回调中添加/删除MenuProvider示例,而不是在子片段onViewCreated中添加/删除x1m0 n1,示例。当ViewPager更改页面时,您可以添加/删除示例。它看起来如下所示:

class MyContainerFragment extends Fragment {

    private ViewPager2 pager;

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        pager.registerOnPageChangeCallback(new UpdateMenuProviderOnPageChangeCallback());
    }

    class UpdateMenuProviderOnPageChangeCallback extends ViewPager2.OnPageChangeCallback {
        private MenuProvider provider1 = new MyMenuProvider1();
        private MenuProvider provider2 = new MyMenuProvider2();

        @Override
        public void onPageSelected(int position) {
            switch(position) {
            case 1:
                requireActivity().removeMenuProvider(provider2);
                requireActivity().addMenuProvider(provider1, getLifecycleOwner());
                break;
            case 2:
                requireActivity().removeMenuProvider(provider1);
                requireActivity().addMenuProvider(provider2, getLifecycleOwner());
                break;
            }
        }
    }
bhmjp9jg

bhmjp9jg2#

Activity中定义MenuProvider是最简单的方法:

abstract public class BaseActivity extends AppCompatActivity {

    /** Menu Provider */
    BaseMenuProvider mMenuProvider = null;

    /** It removes & adds {@link BaseMenuProvider} */
    public void setMenuProvider(BaseMenuProvider menuProvider) {
        if (mMenuProvider != null) {removeMenuProvider(mMenuProvider);}
        addMenuProvider(menuProvider, this, Lifecycle.State.RESUMED);
        mMenuProvider = menuProvider;
    }
    ...
}

然后在Fragment内更改MenuProvider

BaseActivity activity = ((BaseActivity) this.requireActivity());
activity.setMenuProvider(new SettingsMenuProvider(activity));

相关问题