在Tabbed Activity(ViewPager)中切换Fragment

  我用Android Studio的向导新建了一个Tabbed Activity,里面是ViewPager样式的,有三个tabs。如下:

  

  但是我尝试在第一个tab中设置一个按钮,打开其他tab的时候,却提示错误:

  java.lang.IllegalArgumentException: No view found for id 0x7f0c0068 (com.drunkpiano.fragmentlast:id/container) for fragment BlankFragment3{2a5d6e3b #0 id=0x7f0c0068}

  在寻找错误的过程中我首先怀疑的是因为某种原因把position的位置颠倒了,因为我发现,如果在每个fragment(tab)的onCreate()里面加上println,会出现打开第一个fragment却提示第二个fragment的onCreate方法这样错位的情况。。于是我去StackOverFlow上提问了,描述如下:

However when the App runs and the view is in the first tab, I found it actually goes through the onCreateView() function in both Fragment and Fragment2(known from println() in onCreate() & onCreateView()), and when I swipe to Fragment2, it prints Fragment3. and when swipe to Fragment3, it prints nothing.. and after that I swipe back to Fragment2, It prints Fragment1. What's wrong with it?

  结果别人说这是正常的:

Thats is how a FragmentPagerAdapter is supposed to work. It created the Fragment in selected position and also the previous position and next position. 

  不过我觉得只有next position,没有previous position。

  并且评论里有人问我,你不读文档的吗。。。好惭愧,同时好想说文档英文看起来好累。。而且其实我是读了文档的,里面似乎并没有提到预先加载view这一点。http://developer.android.com/referenceh/android/support/v4/app/FragmentPagerAdapter.html

  然后我怀疑是container的问题了,还是搞不懂,就又去提了个问题,链接

  评论里有人让我参考另一个问题,这个问题里题主也遇到类似情况,不过我的问题从他的题干中就能找到答案,也就是container不应该是整个ViewPager的container,而应该是当前fragment的container。我试了一下,确实可以跳转。但是跟普通fragment之间跳转不同的是,下一个fragment的界面只是覆盖在了当前界面上,我又使用了setVisibility(View.GONE)才将当前fragment的控件隐藏,我觉得这应该也是跟viewPager预读next position有关。

  我的问题似乎是解决了,但是http://stackoverflow.com/questions/7723964/replace-fragment-inside-a-viewpager中的问题我还没有完全理解。明天看看。

  View里面细节真多。

  03/22/2015

  

原文地址:https://www.cnblogs.com/larrylawrence/p/5304075.html