xml - Android布局中FrameLayout和fragment中的使用。
大家讲道理
大家讲道理 2017-04-17 14:54:43
0
2
281

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

<?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">

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

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

全部回覆(2)
刘奇

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

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!