詳解Android Widget組件RelativeLayout實(shí)例
以前很少用RelativeLayout,但是這次筆者的項(xiàng)目用到了RelativeLayout。用起來(lái)才發(fā)現(xiàn)RelativeLayout太靈活了。很容易給人造成一些錯(cuò)誤。
51CTO推薦專(zhuān)題:Mobile Widget
下面談?wù)劰P者的看法。
引用
- From Tutorials:
- If you find yourself using several nested LinearLayout groups, you may be able toreplace them with a single RelativeLayout
以上來(lái)自Tutorials,筆者理解的觀(guān)點(diǎn)是,當(dāng)有過(guò)個(gè)ViewGroup嵌套的時(shí)候,再去考慮用RelativeLayout,筆者覺(jué)得既然官方這么寫(xiě),很程度是因?yàn)?,RelativeLayout太靈活了,它的靈活性給我們對(duì)UI的控制多少回造成一定影響。
曾經(jīng)有人跟筆者說(shuō)過(guò),RelativeLayout跟FrameLayout有一些相似,給人的感覺(jué)是分層的。有層的這個(gè)概念。
筆者覺(jué)得不是這樣的,是沒(méi)有層的概念的。從官方的解釋上可以看出這東西就是可以設(shè)置相對(duì)布局的一個(gè)布局而已。沒(méi)有層的概念。
先上段代碼,更直觀(guān)的看看。
Java代碼
- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:background="#CCFFFF">
- <LinearLayout
- android:id="@+id/linearLayout"
- android:layout_width="fill_parent"
- android:layout_height="200dp"
- android:background="#32000033"
- android:orientation="vertical">
- <Button
- android:id="@+id/button1"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:background="#FF3300"
- android:text="Button" />
- <TextView
- android:id="@+id/textView"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:layout_weight="1"
- android:text="Base"
- android:textColor="#6633FF"
- android:gravity="center" />
- <Button
- android:id="@+id/button2"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:background="#FF3300"
- android:text="Button" />
- </LinearLayout>
- <Button
- android:id="@+id/button3"
- android:layout_width="100dp"
- android:layout_height="50dp"
- android:layout_centerInParent="true"
- android:layout_alignBottom="@id/linearLayout"
- android:text="button" />
- </RelativeLayout>
只貼xml,activity沒(méi)什么東西,就顯示一下罷了。
運(yùn)行效果圖

很明顯可以看出button3的下邊緣是跟lineLayout的下邊緣在一條水平線(xiàn)上的。
Java代碼
- android:layout_alignBottom="@id/button1"
但是當(dāng)像上面一樣設(shè)置的時(shí)候,我們可能會(huì)是想讓button3的下邊緣跟button1的下邊緣在一個(gè)水平線(xiàn),但是這些寫(xiě)的效果卻不是按我們所想的顯示,如此設(shè)置根本不起作用。

這其中的原因,筆者是這樣認(rèn)為的,首先,linearLayout,Button這些組件都是在android.widget這個(gè)包中的。他們是同一級(jí)別的。只是說(shuō)linearLayout是一個(gè)ViewGroup可以再包含其他的View而已。不存在其他的優(yōu)先級(jí)關(guān)系。
所以,筆者的理解是,如果Button3這個(gè)控件要同其他控件產(chǎn)生相互關(guān)系的話(huà),首先他們是要位于同一級(jí)別的。(此處說(shuō)的級(jí)別不是說(shuō)組件級(jí)別,而是在xml文件里面設(shè)置的級(jí)別,如:linearLayout和button3是一級(jí)的話(huà),那button2,textView,button3既是二級(jí))
只有同一級(jí)別的才能設(shè)置關(guān)系,否則的話(huà)設(shè)置相互之間的位置關(guān)系就不會(huì)起作用。
這就是筆者的理解,根本不存在層的概念。
【編輯推薦】


















