Android 基礎:常用佈局 介紹 & 使用(附 屬性查詢)
阿新 • • 發佈:2018-12-23
前言
- 在
Android
開發中,繪製UI
時常需各種佈局 - 今天,我將全面介紹
Android
開發中最常用的五大布局
含
Android Studio 2.2
中新增的佈局:約束佈局(ConstraintLayout
)介紹目錄
1. 佈局型別
在Android
中,共有2類、6種佈局方式,分別是:
2. 佈局介紹
- 具體介紹
本文主要介紹傳統的5大布局,關於約束佈局(ConstraintLayout)
具體點選檢視文章
3. 佈局屬性
-
Android
的佈局屬性通過XML
配置 - 下面,主要講解佈局公有屬性 & 特有屬性
3.1 公有屬性
即 5種佈局都具備下述屬性
-
layout_width
layout_height
-
layout_margin
+方位 -
padding
+方位 layout_gravity
gravity
3.2 特有屬性
- 具體介紹如下
3.3 特別注意
- 5個佈局元素可相互巢狀使用,從而實現各種不同的效果
- 關於 線性佈局(LinearLayout)的權重屬性layout_weight請看文章
4. 選擇器(Selector)
4.1 作用
通過設定選擇器(selector
)可使控制元件 在不同操作下(預設、點選等) 顯示不同樣式
通過
xml
編寫 =selector.xml
4.2 屬性
XML屬性 說明 android:drawable 放一個drawable資源 android:state_pressed 按下狀態,如一個按鈕觸控或者點選。 android:state_focused 取得焦點狀態,比如使用者選擇了一個文字框。 android:state_hovered 游標懸停狀態,通常與focused state相同,它是4.0的新特性 android:state_selected 選中狀態 android:state_enabled 能夠接受觸控或者點選事件 android:state_checked 被checked了,如:一個RadioButton可以被check了。 android:state_enabled 能夠接受觸控或者點選事件注:上述所有屬性的取值 = boolean
true
、false
4.3 例項說明
在drawable
新增 selector.xml
資原始檔
button_selector.xml:
<?xml version="1.0" encoding="UTF-8"?>
< selector xmlns:android="http://schemas.android.com/apk/res/android">
< !-- 指定按鈕按下時的圖片 -->
<item android:state_pressed="true"
android:drawable="@drawable/start_down"
/>
< !-- 指定按鈕鬆開時的圖片 -->
<item android:state_pressed="false"
android:drawable="@drawable/start"
/>
< /selector>
在佈局檔案main.xml中控制元件的屬性設定:
<Button
android:id="@+id/startButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/button_selector"
/>
5. 佈局形狀(Shape)
- 作用:設定佈局的顏色、邊框線
- 使用:通過
xml
編寫 =shape.xml
- 具體使用
<shape xmlns:android="http://schemas.android.com/apk/res/android">
//預設顏色
<solid android:color="#876543"/>
//哪個方向有邊框線
<padding
android:bottom="0dp"
android:left="1dp"
android:right="1dp"
android:top="1dp" />
//邊框線顏色、大小
<stroke
android:width="1dp"
android:color="#000000" />
在佈局檔案main.xml中控制元件的屬性設定:
<Button
android:id="@+id/startButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/layout_shape"
/>
6. 總結
- 本文全面介紹了
Android
常用佈局 - 下面我將繼續對
Android
中的知識進行深入講解 ,有興趣可以繼續關注Carson_Ho的安卓開發筆記
作者:Carson_Ho 連結:https://www.jianshu.com/p/4fac6304d872 來源:簡書 著作權歸作者所有。商業轉載請聯絡作者獲得授權,非商業轉載請註明出處。