我主要活动只有ViewPager。第一个标签页片段包含:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/llEventsTabPage"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="@+id/lvEvents"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
我想在用户点击ListView中的项目时显示详细信息片段:
lvEvents.setAdapter(adapter);
lvEvents.setOnItemClickListener(
new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
Fragment eventFragment = new EventFragment();
FragmentTransaction fragmentTransaction = getChildFragmentManager().beginTransaction();
fragmentTransaction.addToBackStack(null);
fragmentTransaction.replace(R.id.llEventsTabPage, eventFragment);
fragmentTransaction.commit();
}
}
);
代码'fragmentTransaction.commit();'被调用,调用EventFragment的onCreateView,但在'fragmentTransaction.commit();'之后什么都没发生。没有错误,没有结果。只是列表视图仍在显示和工作。
我做错了什么?我找到了一些例子,我的代码看起来一样,但没有用,我也无能为力。
谢谢!
答案 0 :(得分:7)
当您执行replace
或add
时,它所要做的就是将Fragment
的视图添加到您指定的容器中。唯一的区别是:
replace
将删除容器中先存在的第一个现有片段that is handled by the FragmentManager specified
。
add
只会将Fragment添加到容器中。
在您的情况下,您有一个LinearLayout容器,其中包含一个大小为match_parent
的ListView。这意味着,当ChildFragmentManager将Fragment添加到容器时,它会将它添加到LinearLayout。该片段实际上位于视图范围之外的ListView之下。
将LinearLayout更改为FrameLayout,您的Fragment将显示在ListView上。
答案 1 :(得分:0)
我不确定。但我使用两种布局结构。
第一个布局结构
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</FrameLayout>
在这种情况下,你需要两个片段
一个是EventFragment,另一个是ListView的片段
所以你还应该为ListView创建片段。
第二种布局结构
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView android:id="@+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<FrameLayout android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</FrameLayout>
在这种情况下,您提交R.id.fragment_container而不是R.id.llEventsTabPage。
我认为它会运作....