如何将片段声明为隐藏在XML布局中

Jay*_*ske 14 xml android fragment

我的活动在单个XML布局中声明其所有GUI片段.它只需要在发布时显示一些片段; 当用户与应用程序交互时,其余部分会显示.布局的一部分如下:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <fragment
        android:id="@+id/map_panel"
        android:name="com.example.MapPanel"
        android:layout_width="match_parent"
        android:layout_height="@dimen/map_panel_height" />
    <fragment
        android:id="@+id/list_panel"
        android:name="com.example.ListPanel"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/map_panel" />
    <fragment
        android:id="@+id/detail_panel"
        android:name="com.example.DetailPanel"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/map_panel"
        android:visibility="gone" />
Run Code Online (Sandbox Code Playgroud)

我的意图是list_panel片段在启动时可见,并且detail_panel片段被隐藏,直到用户从列表中选择某些内容.

默认情况下,片段以isHidden属性false 开头.这意味着我的活动必须遍历加载的片段并在启动时手动调用isHidden(true)片段detail_panel.

我更愿意isHidden在XML布局中声明状态.但是,设置android:visibility="gone"在一个<fragment>声明中不改变isHidden现状,我无法找到上会做的伎俩另一个属性的任何文件.

是否可以在a上设置XML属性<fragment>以使其隐藏?

注意:我不关心视图可见性,我关心的是fragment.isHidden()值.这会影响FragmentManager如何操纵后台堆栈并执行动画.如果调用transaction.show(fragment)视图不可见或不存在的片段,但fragment.isHidden()值为false,则FragmentManager不会使视图可见.请参阅http://developer.android.com/reference/android/app/Fragment.html#isHidden()以供参考.

Vik*_*kas 12

我遇到了类似的情况,我不得不隐藏片段.

我只是将片段包含在LinearLayout中,并将布局标记为可见/消失.

<LinearLayout
    android:id="@+id/map_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:visibility="visible" >

    <fragment
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.MapFragment" />
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)


Nei*_*eil 8

根据Jyo的帖子,使用这个:

FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.hide(mFragment);
fragmentTransaction.commit();
Run Code Online (Sandbox Code Playgroud)

这在API级别23上对我有用.mFragment是您要隐藏的片段.

  • 这是正确答案。您不应该使用视图可见性隐藏片段。 (2认同)

SHA*_*NDA -1

我们有 isVisible 方法,用于将片段的可见性设置为 Gone 不占用任何空间,而 Invisble 则占用实际的视图空间。