【问题标题】:How to swap fragments with different layouts in android?如何在android中交换具有不同布局的片段?
【发布时间】:2012-08-02 23:23:39
【问题描述】:

我正在开发一个使用 Fragment 的 Android 应用程序,它更像是 Master/Detail 表单。我希望主要活动由左侧的列表片段组成,基于左侧选择的项目我想在右侧显示具有不同布局的片段。 (注意:右边的每个片段需要不同的布局/视图)

我遇到的所有示例都通过更改其中的某些值或交换/替换具有相同布局的新片段来仅使用右侧的一个公共片段。

如果有人能对这个问题有所了解,那么它将极大地帮助我。谢谢!

【问题讨论】:

    标签: android android-fragments


    【解决方案1】:

    如果您使用框架布局来保存片段,则与您提到的其他那些相同。您只需实例化您的片段(无论布局如何)并将其交换到框架布局中来代替另一个。

    如果您已将片段硬编码到 XML 中,您将无法执行此操作(据我所知)。

    ma​​in.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();
    

    【讨论】:

    • 非常感谢您的帮助!片段概念对我来说很新。你能用一些简单的例子来说明你的观点吗?
    • 我已经更新了我的答案,希望它能为您指明正确的方向。告诉我!
    • 谢谢巴拉克!!!是的,它奏效了!另外我想知道是否可以在片段中创建片段。
    猜你喜欢
    • 2013-08-27
    • 1970-01-01
    • 1970-01-01
    • 2015-10-05
    • 1970-01-01
    • 1970-01-01
    • 2018-06-11
    • 1970-01-01
    • 2017-04-03
    相关资源
    最近更新 更多