我有一个页面查看器,在API 21上发生了一些非常奇怪的事情(它适用于API 17)。
在查看器的第一页上,有一个链接可以加载第二页并替换它中的一个片段。我第一次点击链接并加载第二页它工作正常,但如果我在加载第三页后点击链接,片段替换不起作用,我最终得到第二个屏幕没有片段在其中
以下是设置第二页的代码的简化版本:
ScreenSlidePagerAdapter adapter = (ScreenSlidePagerAdapter) sPager.getAdapter();
// Set second page in the viewer
if (adapter.getCount() != 2) {
adapter.setCount(2);
adapter.notifyDataSetChanged();
}
SecondPageFragment frag2 = new SecondPageFragment();
sFragmentManager.beginTransaction().replace(R.id.container_page2, frag2, “Frag2TAG”).commit();
sPager.setCurrentItem(1);
如果与API 17相比,为什么替换API 21的工作方式不同?以前有人有类似的问题吗?这似乎是相关的,但没有解决方案:fragments-transaction-replace-on-api-21-is-staying-behind
编辑:SecondPageFragment的代码只是一个片段:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle saved_instance_state) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_page2, container, false);
return rootView;
}
这是布局fragment_page2:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/container_page2">
答案 0 :(得分:1)
新的相关性!在我看来, FragmentPagerAdapter 类中存在一个错误。查看SO链接@ Replace Fragment inside a ViewPager。由于你的评论&#34;我第一次点击链接并加载第二页它工作正常...&#34;,我认为它与getItemId
()有关,可能必须覆盖它
就我个人而言,我在片段中使用了 PagerAdapter ,将来可能会使用FragmentPagerAdapter,因为它结合了两个类并且应该更容易。
修改强>:
您的ID container_page2
可能正在使用正确的表单和布局文件。但是,如果要将其与replace()一起使用,则应使用相同的一致UI元素ID。否则, FragmentManager 将根据容器视图ID管理片段,这让我很困惑。
我有一个片段的布局示例。它是sample_content_fragment
, FrameLayout ,嵌套在LinearLayout中。
片段的示例布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/sample_main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<FrameLayout
android:id="@+id/sample_content_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
让我们发布。我想知道。
答案 1 :(得分:0)
方法getSupportFragmentManager
()引用目录 android / support / v4 / ...
由于sFragmentManager
是使用getSupportFragmentManager
()创建的,因此您应检查对 Fragment 的所有引用,并查看它们是否引用了相同的support / v4目录。一种快速方法是检查android.support.v4的导入。您还可以通过单击片段的所有引用进行检查。
另一个选择是不使用&#34;支持&#34;包。
答案 2 :(得分:0)
为了进行调试,我建议使用 FragmentTransaction 的addToBackStack
()。这样可以保存堆栈中活动的数据和片段状态。这对于代码检查很有用,并且由于保存状态可能会产生积极的影响。
您也可以在代码getBackStackEntryCount
()之后调用 FragmentManager 的commit
()。为此,您必须分解代码sFragmentManager.beginTransaction().replace(R.id.container_page2, frag2, “Frag2TAG”).commit()
。但它不应该太难。