詳解Android Widget組件RelativeLayout實例
以前很少用RelativeLayout,但是這次筆者的項目用到了RelativeLayout。用起來才發(fā)現(xiàn)RelativeLayout太靈活了。很容易給人造成一些錯誤。
51CTO推薦專題: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
以上來自Tutorials,筆者理解的觀點是,當(dāng)有過個ViewGroup嵌套的時候,再去考慮用RelativeLayout,筆者覺得既然官方這么寫,很程度是因為,RelativeLayout太靈活了,它的靈活性給我們對UI的控制多少回造成一定影響。
曾經(jīng)有人跟筆者說過,RelativeLayout跟FrameLayout有一些相似,給人的感覺是分層的。有層的這個概念。
筆者覺得不是這樣的,是沒有層的概念的。從官方的解釋上可以看出這東西就是可以設(shè)置相對布局的一個布局而已。沒有層的概念。
先上段代碼,更直觀的看看。
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沒什么東西,就顯示一下罷了。
運行效果圖
很明顯可以看出button3的下邊緣是跟lineLayout的下邊緣在一條水平線上的。
Java代碼
- android:layout_alignBottom="@id/button1"
但是當(dāng)像上面一樣設(shè)置的時候,我們可能會是想讓button3的下邊緣跟button1的下邊緣在一個水平線,但是這些寫的效果卻不是按我們所想的顯示,如此設(shè)置根本不起作用。
這其中的原因,筆者是這樣認(rèn)為的,首先,linearLayout,Button這些組件都是在android.widget這個包中的。他們是同一級別的。只是說linearLayout是一個ViewGroup可以再包含其他的View而已。不存在其他的優(yōu)先級關(guān)系。
所以,筆者的理解是,如果Button3這個控件要同其他控件產(chǎn)生相互關(guān)系的話,首先他們是要位于同一級別的。(此處說的級別不是說組件級別,而是在xml文件里面設(shè)置的級別,如:linearLayout和button3是一級的話,那button2,textView,button3既是二級)
只有同一級別的才能設(shè)置關(guān)系,否則的話設(shè)置相互之間的位置關(guān)系就不會起作用。
這就是筆者的理解,根本不存在層的概念。
【編輯推薦】