1. 什麼是佈局
就是把界面中的控件按照某種規律擺放到指定的位置
2. 佈局的二種實現
代碼
xml配置文件:res/layout目錄下
注:也可以同時使用xml和代碼
3. 佈局的基本屬性
設置背景顏色 android:background="@color/green"
設置內間距 android:padding="50dp"
設置外間距 android:layout_margin="50dp"
設置佈置方式: vertical垂直佈置 horizontal水平佈置
android:orientation="vertical"
設置位置
多個位置用|區分 android:gravity="center" 匹配父類的屏幕大小 match_parent
<?xml version="1.0" encoding="utf-8"?>
<!--
設置背景顏色
android:background="@color/green"
設置內間距
android:padding="50dp"
設置外間距
android:layout_margin="50dp"-->
<LinearLayout(你要使用的佈局) xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:background="@color/green"
android:padding="50dp"
android:layout_margin="50dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Hello World!"
android:background="@color/red"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</LinearLayout>
android:gravity和android:layout_gravity
用一個TextView、文字、背景查看效果最方便
android:gravity:控件內部的元素
android:layout_gravity:控件所在父元素的位置
但父元素的水平和垂直設置的優先度更高
4、 常見佈局
線性佈局(重點) LinearLayout
表格佈局(幾乎不用) TableLayout
幀佈局 FrameLayout(就好象一張張卡片堆疊上去,後面會蓋出前面的
絕對佈局 AbsoluteLayout
相對佈局 RelativeLayout
網格佈局 GridLayout
RTL(幾乎不用)
5、LinearLayout佈局中Layout_weight屬性的作用與誤區
android:layout_weight 權重
誤區:
layout_weight理解成將activity整個手機屏幕按比例區劃分了,理解成反比了
正確理解
layout_weight劃分的不是整個手機屏幕,劃分的是屏幕剩餘空件