RelativeLayout
接着上一篇,本篇我將介紹RelativeLayout(相對布局)的一些知識點。
RelativeLayout
這是一個非常常用的布局,相比於上節所學到的LinearLayout布局,它更加的隨意,可以通過相對定位的方式讓控件出現在布局的任何位置。新建UILayoutTestTwo工程,修改activity_main.xml中的代碼:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button_one"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="button 1"/>
<Button
android:id="@+id/button_two"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="button 2"/>
<Button
android:id="@+id/button_three"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="button 3"/>
<Button
android:id="@+id/button_four"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentBottom="true"
android:text="button 4"/>
<Button
android:id="@+id/button_five"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:text="button 5"/>
</RelativeLayout>
運行程序,效果如下圖:
以上代碼不做過多解釋。上面的控件定位是依靠父布局的,其實RelativeLayout中還可以依靠控件進行定位。修改activity_main.xml中的代碼:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button_three"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="button 3"/>
<Button
android:id="@+id/button_one"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/button_three"
android:layout_toLeftOf="@+id/button_three"
android:text="button 1"/>
<Button
android:id="@+id/button_two"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/button_three"
android:layout_toRightOf="@+id/button_three"
android:text="button 2"/>
<Button
android:id="@+id/button_four"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button_three"
android:layout_toLeftOf="@+id/button_three"
android:text="button 4"/>
<Button
android:id="@+id/button_five"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button_three"
android:layout_toRightOf="@+id/button_three"
android:text="button 5"/>
</RelativeLayout>
運行程序,效果如圖所示:
RelativeLayout的屬性除了上面提到的,還有很多其他的,以后的學習中遇到了,可以多積累。下面是一些屬性的簡要說明: