当前位置:操作系统 > 安卓/Android >>

Android学习笔记之布局

我们对Android应用程序运行原理及布局文件可谓有了比较深刻的认识和理解,并且用“Hello World!”程序来实践证明了。在继续深入Android开发之旅之前,有必要解决前两篇中没有介绍的遗留问题:View的几种布局显示方法,以后就不会在针对布局方面做过多的介绍。View的布局显示方式有下面几种:线性布局(Linear Layout)、相对布局(Relative Layout)、表格布局(Table Layout)、网格视图(Grid View)、标签布局(Tab Layout)、列表视图(List View)、绝对布局(AbsoluteLayout)。本文虽然是介绍View的布局方式,但不仅仅是这样,其中涉及了很多小的知识点,绝对能给你带来Android大餐!

本文的主要内容就是分别介绍以上视图的七种布局显示方式效果及实现,大纲如下:

  • 1、View布局概述
  • 2、线性布局(Linear Layout)   
    • 2.1、Tips:android:layout_weight="1"
  • 3、相对布局(Relative Layout)
  • 4、表格布局(Table Layout)
  • 5、列表视图(List View)   
    • 5.1、一个小的改进
    • 5.2、补充说明
  • 6、网格视图(Grid View)
  • 7 、绝对布局()
  • 8、标签布局(Tab Layout)

1、view的布局显示概述

通过前面的学习我们知道:在一个Android应用程序中,用户界面通过View和ViewGroup对象构建。Android中有很多种View和ViewGroup,他们都继承自View类。View对象是Android平台上表示用户界面的基本单元。

View的布局显示方式直接影响用户界面,View的布局方式是指一组View元素如何布局,准确的说是一个ViewGroup中包含的一些View怎么样布局。ViewGroup类是布局(layout)和视图容器(View container)的基类,此类也定义了ViewGroup.LayoutParams类,它作为布局参数的基类,此类告诉父视图其中的子视图想如何显示。例如,XML布局文件中名为layout_something的属性(参加上篇的4.2节)。我们要介绍的View的布局方式的类,都是直接或间接继承自ViewGroup类,如下图所示:

ViewGroup的继承

图1、继承自ViewGroup的一些布局类

其实,所有的布局方式都可以归类为ViewGroup的5个类别,即ViewGroup的5个直接子类。其它的一些布局都扩展自这5个类。下面分小节分别介绍View的七种布局显示方式。

2、线性布局(Linear Layout)

线性布局:是一个ViewGroup以线性方向显示它的子视图(view)元素,即垂直地或水平地。之前我们的Hello World!程序中view的布局方式就是线性布局的,一定不陌生!如下所示res/layour/main.xml:     

<?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="horizontal"><!-- have an eye on ! -->
    <Button android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"            
            android:text="Hello, I am a Button1"
            android:layout_weight="1"
            />
    <Button android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello, I am a Button2"
    android:layout_weight="1"
    />
    <Button android:id="@+id/button3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello, I am a Button3"
    android:layout_weight="1"
    />
    <Button android:id="@+id/button4"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello, I am a Button4"
    android:layout_weight="1"
    />
    <Button android:id="@+id/button5"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello, I am a Button5"
    android:layout_weight="1"
    />
</LinearLayout>

从上面可以看出根LinearLayout视图组(ViewGroup)包含5个Button,它的子元素是以线性方式(horizontal,水平的)布局,运行效果如下图所示:

linearlayout1

CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,