【发布时间】:2015-11-15 22:36:29
【问题描述】:
我的学校作业有一个包含 ListFragment 和 Fragment 的活动。 MainActivity 创建 ListFragment,然后列表上的每个项目都应该打开只包含图片的常规 Fragment,然后当我点击图片时它应该返回 ListFragment。
在所有情况下,我都使用以下代码调用片段(当然针对特定情况进行了编辑):
Fragment fragTwo = new FragmentTwo();
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragment_place, fragTwo);
ft.addToBackStack(null);
ft.commit();
它调用片段 OK,除了第二个片段将出现在 ListFragment 上方,当第二个片段打开时,我仍然可以从列表中选择内容。每次导航时都需要创建一个新的片段对象吗?以及如何从它自己的 onclick 侦听器中禁用/启用片段?
main_activity.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<fragment
android:name="com.example.w0068332.fragmentstest.FragmentOne"
android:id="@+id/fragment_place"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
【问题讨论】:
-
Activity如何插入ListFragment?它是在活动的布局 xml 中,还是您使用 FragmentTransaction 以编程方式添加它?发布您的活动和 xml 布局代码可能会有所帮助。
-
@Benstrom 我已经添加了 main_activity.xml,你可以看到有一个片段被放入其中。在 mainActivity 的 onCreate 中,我(基本上)使用第一段代码将片段 (fragOne) 放置到位。
标签: java android listview android-fragments fragment