首页 > Android布局中FrameLayout和fragment中的使用。

Android布局中FrameLayout和fragment中的使用。

我在看《第一行代码》中的碎片部分,对其中的这部分代码没有办法理解

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <fragment
        android:id="@+id/left_fragment"
        android:name="com.example.qiao.fragmenttest.LeftFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="2" />

    <FrameLayout
        android:id="@+id/right_layout"
        android:layout_width="10dp"
        android:layout_weight="1"
        android:layout_height="match_parent">

    <fragment
        android:id="@+id/right_fragment"
        android:name="com.example.qiao.fragmenttest.RightFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"/>

    </FrameLayout><!--相对布局-->
</LinearLayout>

我的主要困惑是不理解这里为什么要添加FrameLayout,作用是覆盖在fragment上,类似于浮动的效果吗?
同时

    <FrameLayout
        android:id="@+id/right_layout"
        android:layout_width="10dp"
        android:layout_weight="1"
        android:layout_height="match_parent">

这部分属性到底作用在哪里又该怎么理解,如何确定他们的大小。


FrameLayout 的作用

在 Activity 中托管一个 UI Fragment 有两种方式:(1)添加 fragment 到 activity 布局中;(2)在 activity 代码中添加 fragment。

left_fragmentright_fragment 都是采用了第1种方式。
对于第2种方式,需要在布局文件中为 Fragment 添加一个容器,以安排 Fragment 在 activity 视图中的位置。实践中常选用 FrameLayout 作为容器。

至于你贴出来的right_layout的作用,要看代码的意图。我猜作者是想演示如何通过代码添加一个Fragment(也就是第2种方式),用来与第1种方式作对比。也可能没有任何用意,因为布局文件是错误的!

需要纠正第1个错误,在FrameLayout视图的子组件中,layout_weight属性是无效的,你会得到如下的黄色感叹号警告:

Invalid layout param in a FrameLayout: layout_weight

按你贴出来的布局文件,right_fragment 由于layout_width 为0dp,根本就不会显示。

需要纠正第2个错误, 是注释的错误,FrameLayout 并不是相对布局,它就是一个容器,向其中添加的任何子组件,需要通过 layout_gravity 属性值决定在父视图中的位置,而各个子组件并不能像 RelativeLayout 一样,定义相对位置。

android:layout_weight 属性的工作原理

该属性告知 LinearLayout 如何安排子组件的布局。对于水平方向的 LinearLayout,查看 layou_widthlayout_weight 以决定子组件的宽度。

你贴出来的布局中,LinearLayout 有2个子组件,下文称 left_fragment 为 child1,称 right_layout 为 child2:
第1步,查看 layout_width 属性值,为 child1 分配0dp,为 child2 分配10dp;
第2步,依据 layout_weight 属性值分配剩余的宽度,child1 将分配到 2/3, child2 将分配到 1/3.


你看到最外面LinearLayout的orientation了没,然后FrameLayout的宽只有10dp。 :D

【热门文章】
【热门文章】