我正在开发一个使用 fragment 的 Android 应用程序,它更像是一种主/细节形式。我希望主要 Activity 由左侧的列表 fragment 组成,根据左侧选择的项目,我想在右侧显示具有不同布局的 fragment 。 (注意:右边的每个 fragment 需要不同的布局/ View )
我遇到的所有示例都通过更改其中的一些值或交换/替换具有相同布局的新 fragment 来仅使用右侧的一个公共(public) fragment 。
如果有人能阐明这个问题,那将对我有很大帮助。谢谢!
最佳答案
如果您使用框架布局来保存您的 fragment ,则它与您提到的其他 fragment 相同。您只需实例化您的 fragment (无论布局如何)并将其交换到框架布局中以代替另一个。
如果您已将您的 fragment 硬编码到 XML 中,您将无法做到这一点(据我所知)。
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/frames"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="@id/hline1"
android:layout_below="@id/horizontalline"
android:orientation="horizontal" >
<FrameLayout
android:id="@+id/leftpane"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight=".4" />
<TextView
android:id="@+id/verticalline"
android:layout_width="2dp"
android:layout_height="match_parent"
android:background="@color/bar_background"
android:gravity="center_horizontal"
android:paddingLeft="5dip"
android:paddingRight="5dip" />
<FrameLayout
android:id="@+id/rightpane"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="1" >
</FrameLayout>
</LinearLayout>
然后使用框架布局的 id 和实例化 fragment 的名称将 fragment 放入框架布局中。
EventListFragment eventlist = new EventListFragment();
getFragmentManager().beginTransaction().replace(R.id.leftpane, eventlist).commit();
EventDetailFragment eventadd = new EventDetailFragment();
getFragmentManager().beginTransaction().replace(R.id.rightpane, eventadd).commit();
当你想改变内容时,你再次做同样的事情(下面将用一个新的/不同的 fragment 替换右 Pane 中的 fragment ,它可以有它自己的,不同的,与之相关的布局):
EventSuperDetailFragment eventsuper = new EventSuperDetailFragment();
getFragmentManager().beginTransaction().replace(R.id.rightpane, eventsuper).commit();
关于android - 如何在android中交换具有不同布局的 fragment ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11787229/