Android学习笔记16:布局管理器的嵌套

    接上文
    布局管理器的嵌套就是将多种布局管理器混合使用,以达到复杂布局的排版效果。如果一个布局页面效果复杂,可能使用一种布局管理器无法完成,那么我们就需要将多种布局管理器嵌套起来以达到显示效果。在Web开发中,编写的CSS基本都是设置嵌套元素的样式的,这个理念是类似的。
    几种布局管理器都已经介绍过了,我们直接在Eclipse中建立新的项目来说明:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <TextView
        android:id="@+id/txt"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="文字提示信息" />
    <LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="horizontal" >
        <ImageView
            android:id="@+id/img1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_launcher" />
        <ImageView
            android:id="@+id/img2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_launcher" />
        <ImageView
            android:id="@+id/img3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_launcher" />
    </LinearLayout>
</LinearLayout>

    相对以前的代码,这个有些复杂,我们一层一层来看,首先外部是个线性布局(该布局管理器垂直放置各个元素),放置了一个文本显示组件TextView,并且设置这个组件为居中显示。之后嵌套了一个线性布局管理器(该布局管理器设置水平放置各个元素),嵌套的布局管理器中放置了三幅图片,那么运行该布局管理器来看看显示效果:



    下面我们继续嵌套,在内部线性布局管理器之下,我们平行放置一个表格布局管理器:
    <TableLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="horizontal" >
        <TableRow>
            <EditText
                android:id="@+id/edit"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="输入关键字进行搜索" />
            <Button
                android:id="@+id/btn"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="搜索" />
        </TableRow>
    </TableLayout>

    这里面也没有什么可多说的,直接运行程序,我们可以看到:



    只是在嵌套布局管理器时我们要注意设置各个布局管理器的layout_height为包裹高度,而不能设置成为填充屏幕,否则该布局管理器就会占据剩余屏幕整个内容,而其它的布局管理器将无法显示。
    在嵌套布局管理器时,页面的排版已经非常的复杂了,而若想使用Java代码对其进行控制,这个难度就已经很大了,所以在复杂布局管理器下不建议再编写Java代码来控制了,使用XML文件来布局是比较简单的方式。
    代码请参考附件
    接下文

猜你喜欢

转载自sarin.iteye.com/blog/1757401