【发布时间】:2012-08-02 23:23:39
【问题描述】:
我正在开发一个使用 Fragment 的 Android 应用程序,它更像是 Master/Detail 表单。我希望主要活动由左侧的列表片段组成,基于左侧选择的项目我想在右侧显示具有不同布局的片段。 (注意:右边的每个片段需要不同的布局/视图)
我遇到的所有示例都通过更改其中的某些值或交换/替换具有相同布局的新片段来仅使用右侧的一个公共片段。
如果有人能对这个问题有所了解,那么它将极大地帮助我。谢谢!
【问题讨论】:
我正在开发一个使用 Fragment 的 Android 应用程序,它更像是 Master/Detail 表单。我希望主要活动由左侧的列表片段组成,基于左侧选择的项目我想在右侧显示具有不同布局的片段。 (注意:右边的每个片段需要不同的布局/视图)
我遇到的所有示例都通过更改其中的某些值或交换/替换具有相同布局的新片段来仅使用右侧的一个公共片段。
如果有人能对这个问题有所了解,那么它将极大地帮助我。谢谢!
【问题讨论】:
如果您使用框架布局来保存片段,则与您提到的其他那些相同。您只需实例化您的片段(无论布局如何)并将其交换到框架布局中来代替另一个。
如果您已将片段硬编码到 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 和实例化片段的名称将您的片段放入框架布局中。
EventListFragment eventlist = new EventListFragment();
getFragmentManager().beginTransaction().replace(R.id.leftpane, eventlist).commit();
EventDetailFragment eventadd = new EventDetailFragment();
getFragmentManager().beginTransaction().replace(R.id.rightpane, eventadd).commit();
当你想改变内容时,你再次做同样的事情(下面会用一个新的/不同的片段替换右窗格中的片段,它可以有它自己的、不同的、与之关联的布局):
EventSuperDetailFragment eventsuper = new EventSuperDetailFragment();
getFragmentManager().beginTransaction().replace(R.id.rightpane, eventsuper).commit();
【讨论】: