【发布时间】:2013-02-26 19:42:50
【问题描述】:
我想做这样的事情。图片比文字更容易:
当用户点击 Fragment B 上的按钮时,Fragment 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();
这部分效果很好。
我现在有两个问题:
这两种方式如何在主Activity中改变内容?我的意思是,在主要活动中,片段应该调用第二种方式,但在正常活动中,我需要调用第一种。
如果我单击片段 A 中的一个项目,然后单击片段 B 中的按钮,该按钮会将片段更改为 NextFragment。如果我点击另一个项目,我也会这样做。我可以回到第一个用户。点击新项目时有没有办法转储堆栈?
感谢您的帮助。
Ps:我使用的是原生片段库而不是支持 v4。
【问题讨论】:
标签: android android-fragments fragment