Android常用ViewGroup之FrameLayout
阿新 • • 發佈:2018-11-09
簡介
幀佈局或叫層佈局,從螢幕左上角按照層次堆疊方式佈局,後面的控制元件覆蓋前面的控制元件,核心就是檢視的層疊。類似於圖層,這種檢視的疊加思路在開發中處處可見。
重要屬性
- 子View使用的屬性
- android:layout_gravity 調整子View是父佈局中的顯示位置。常用屬性值有center、center_vertical、center_horizontal、top、bottom、left、right等,可以同時取多個,通過"|"進行拼接 FrameLayout預設都是檢視在左上角進行疊加,通過這個引數我們可以調整特定子view的在父佈局中的顯示位置
示例
- 預設的疊加效果
xml
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#00FF78"> <TextView android:layout_width="200dp" android:layout_height="200dp" android:background="#aaaaaa" /> <TextView android:layout_width="150dp" android:layout_height="150dp" android:background="#FF0000" /> <TextView android:layout_width="100dp" android:layout_height="100dp" android:background="#00FF00" /> <TextView android:layout_width="49dp" android:layout_height="54dp" android:background="#0000FF" /> </FrameLayout>
- 效果2
使用layout_gravity實現相對佈局的效果
xml
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#00FF78"> <TextView android:layout_width="49dp" android:layout_height="54dp" android:layout_gravity="top"//對齊父控制元件頂部 android:background="#0000FF" /> <TextView android:layout_width="49dp" android:layout_height="54dp" android:layout_gravity="right"//對齊父控制元件右邊 android:background="#0000FF" /> <TextView android:layout_width="49dp" android:layout_height="54dp" android:layout_gravity="center"//父控制元件中居中 android:background="#0000FF" /> <TextView android:layout_width="49dp" android:layout_height="54dp" android:layout_gravity="bottom"//對齊父控制元件底部 android:background="#0000FF" /> <TextView android:layout_width="49dp" android:layout_height="54dp" android:layout_gravity="right|bottom"//對齊父控制元件底部和右邊 android:background="#0000FF" /> </FrameLayout>
拓展
FrameLayout中某個子View顯示到最上面
FrameLayout提供了一個方法
public void bringChildToFront(View child)
只要指定子View就可以將子View顯示在FrameLayout最上面,比如層疊了5個View,想把第三個顯示出來就可以使用這個方法