图形用户界面(GUI)是Android应用程序开发不可或缺的一部分。其不仅能为用户提供输入,还能够根据(用户)执行的动作,提供相应的反馈。因此,作为开发人员,能够理解UI(用户界面)是如何创建以及跟新的,就显得尤为重要。
ViewTree
View 和 ViewGroup 是Android UI的基本组件, 而ViewGroup作为容器,可以包含一组View, 并且ViewGroup其本身就是View的扩展。看源码:
public abstract class ViewGroup extends View implements ViewParent, ViewManager{}
而各种不同的Widgets 像TextView, Button 等等 也是View的扩展,只不过是放在各种Layout里,比如LinearLayout, RelativeLayout。而Layout却是ViewGroup的子类。所以说一个ViewTree只不过是各种Views和ViewGroups放在一个Layout里组成的树形结构。
有例子才有真相。通过Eclipse的Outline窗口,我们可以看下下面这个树状布局。
XML Code:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/RelativeLayout1" android:layout_width="fill_parent" android:layout_height="fill_parent" > <View android:id="@+id/WhiteView" android:layout_width="200dp" android:layout_height="300dp" android:layout_marginLeft="20dp" android:background="#ffffff" /> <TextView android:id="@+id/RedText" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="@string/hello" android:textColor="#ff0000" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@+id/GrayView" android:layout_alignLeft="@+id/GrayView" android:layout_marginBottom="25dp" android:background="#0000ff" android:orientation="vertical" > <TextView android:id="@+id/GreenText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TextView" android:textColor="#00ff00" android:textStyle="bold" /> <Button android:id="@+id/Button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button in LinearLayout" /> </LinearLayout> <View android:id="@+id/RedView" android:layout_width="100dp" android:layout_height="100dp" android:layout_alignParentRight="true" android:layout_above="@+id/GrayView" android:layout_marginRight="10dp" android:layout_marginBottom="-10dp" android:background="#ff0000" /> <View android:id="@+id/GrayView" android:layout_width="200dp" android:layout_height="300dp" android:layout_alignParentBottom="true" android:layout_alignParentRight="true" android:layout_marginRight="20dp" android:background="#cccccc" /> </RelativeLayout>