我想做那样的事情。图片比文字更容易:
当用户点击片段B上的按钮时,片段B已更改但不是A. 我做了两种不同的布局(一幅肖像和一幅土地)。第一个具有类似
的布局<?xml version="1.0" encoding="utf-8"?>
<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
android:name="com.my.app.ContactsFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/contacts_fragment" />
我的片段布局中有一个按钮,只有一个简单的活动调用:
Intent intent = new Intent(getActivity(), NextActivity.class);
startActivity(intent);
土地就像那样:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
android:name="com.my.app.ContactsFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/contacts_fragment" />
<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
android:name="com.my.app.HomeFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/fragment_container" />
</LinearLayout>
我使用以下代码更改内部片段:
FragmentTransaction ft = getActivity().getFragmentManager().beginTransaction();
NextFragment nextFrag = new NextFragment();
ft.replace(R.id.fragment_container, nextFrag);
ft.addToBackStack(null);
ft.commit();
这部分效果很好。
我现在有两个问题:
如何通过这两种方式更改主要活动中的内容?我的意思是,在主要活动中,一个片段应该调用第二种方式,但在正常活动中,我需要调用第一种方式。
如果我单击片段A中的项目,然后单击片段B中将片段更改为NextFragment的按钮。如果我点击另一个项目,我也会这样做。我可以回到第一个用户。有没有办法在点击新项目时转储堆栈?
感谢您的帮助。
Ps:我使用的是本机片段lib而不是支持v4。
答案 0 :(得分:3)
我很难理解你的两个问题的细节,因为它们含糊不清,并没有提供足够的细节。
但是,由于您希望在运行时更改Fragment
,因此不应将<fragment/>
放入布局文件中。您当前的体系结构使您无法更改布局中的Fragment
,这不是您想要的。
注意:通过在布局XML文件中定义片段将片段添加到活动布局时,无法在运行时删除片段。如果您计划在用户交互期间将片段交换进出,则必须在活动首次开始时将片段添加到活动中。
您应该在布局文件中使用FrameLayout
个容器作为Fragment
个容器,并且单个 Activity
添加Fragment
到那些FrameLayout
容器取决于它们是否在那里。这将允许应用在纵向中创建1 Fragment
,在横向中创建2 Fragment
(假设您有每个方向的布局)。这样您也可以根据需要更换Fragment
,并将它们添加到后台。
可以找到{strong> Google推荐方法的示例here。
答案 1 :(得分:1)
您可以从here找到一个好的解决方案。