简体   繁体   English

在 Android 中隐藏/显示 ViewPager

[英]Hide/show ViewPager in Android

I have this app structure:我有这个应用程序结构:

  1. MainActivity with a global menu and Fragment container. MainActivity 带有全局菜单和Fragment容器。
  2. First Fragment : a ViewPager with three pages.第一个Fragment :一个包含三页的ViewPager
  3. Second Fragment : a list第二个Fragment :一个列表

I insert the Fragment s on the OnCreate() in the MainActivity and change their visibility with show and hide (using the FragmentTransaction ).我在 MainActivity 的OnCreate()上插入Fragment并使用 show 和 hide (使用FragmentTransaction )更改它们的可见性。

When I launch the app the first Fragment appear in the screen without problem, when change to the second Fragment also work like a charm but when I come back to the first Fragment the app doesn't show anything inside the ViewPager .当我启动应用程序时,第一个Fragment毫无问题地出现在屏幕上,当更改为第二个Fragment也像魅力一样工作,但是当我回到第一个Fragment ,应用程序在ViewPager中没有显示任何ViewPager

Are there any particular option that I have to change in the ViewPager to solve this?我必须在ViewPager更改任何特定选项来解决此问题吗?

The problem seems due to that android does not allow to have nested fragments.问题似乎是由于 android 不允许嵌套片段。 In my case I can manage the situation using simple views instead of fragments inside the ViewPager.就我而言,我可以使用简单的视图而不是 ViewPager 中的片段来管理这种情况。

I used ViewStub to show/hide ViewPager.我使用ViewStub来显示/隐藏 ViewPager。

The basic idea was you created ViewStub in layout file, and inflate/setVisible while necessary.基本思想是您在布局文件中创建了 ViewStub,并在必要时膨胀/setVisible。

The only trick was, I had to setAdatper to null otherwise it crashed while re-createView when off and on screen.唯一的技巧是,我必须将Adatper 设置为null 否则它会在关闭和在屏幕上重新创建视图时崩溃。

@Override
public void onDestroyView() {
    super.onDestroyView();

    viewPager.setAdatper(null);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM