Android布局之線性布局LinearLayout(一) ----四角顯示TextView
Android中有六大布局,分別是:
英文 | 中文 |
---|---|
LinearLayout | 線性布局 |
RelativeLayout | 相對布局 |
TableLayout | 表格布局 |
FrameLayout | 幀布局 |
AbsoluteLayout | 絕對布局 |
GridLayout | 網格布局 |
今天我學習的第一個布局就是LinearLayout(線性布局),LinearLayout中用的比較多的是weight(權重屬性),主要用法如下:
第一個實驗要求只允許用LinearLayout布局和TextView控件,填充背景色,分別放置在屏幕的四個角上。
思路:LinearLayout有水平布局和豎直布局,則讓整體為水平布局,左邊兩個TextView,右邊兩個TextView,左右兩邊的容器分別設置為豎直布局,並調整相應的位置即可。
activity_main.xml代碼如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<!--orientation="vertical"豎直排列-->
<!--horizontal水平排列-->
<!--gravity居中-->
<!--layout_width="wrap_content"自適應-->
<!--match_parent充滿父容器-->
<!--整體采用左右布局-->
<!--左-->
<!--左邊內部采用上下布局,寬度自適應,高度充滿-->
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical">
<!--紅色塊在上方,高度寬度自適應-->
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:layout_width="50dp"
android:layout_height="50dp"
android:background="#F44336" />
</LinearLayout>
<!--綠色在下方,高度充滿,寬度自適應,bottom底部對齊-->
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent">
<TextView
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_gravity="bottom"
android:background="#4CAF50" />
</LinearLayout>
</LinearLayout>
<!--右-->
<!--右邊內部采用上下布局,寬度充滿,高度充滿(即充滿剩余所有的空間)-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!--黃色塊在上方,高度寬度自適應,右對齊-->
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right">
<TextView
android:layout_width="50dp"
android:layout_height="50dp"
android:background="#FFEB3B" />
</LinearLayout>
<!--藍色塊在下方,高度充滿,寬度自適應,右對齊,底部對齊-->
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="right">
<TextView
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_gravity="bottom"
android:background="#2196F3" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
運行截圖如下: