Android初试--LinearLayout(线性布局)

来源:互联网 发布:海军知耻陆军马鹿 编辑:程序博客网 时间:2024/04/28 02:37

Linearlayout(线性布局)

       LinearLayout以给它设置的垂直或水平的属性值,来排列所有的子元素。所有的子元素都被堆放在其它元素之后,因此一个垂直列表的每一行只会有一个元素,而不管他们有多宽,而一个水平列表将会只有一个行高(高度为最高子元素的高度加上边框高度)。LinearLayout保持子元素之间的间隔以及互相对齐(相对一个元素的右对齐、中间对齐或者左对齐)。它还支持为单独的子元素指定weight。好处就是允许子元素可以填充屏幕上的剩余空间。这也避免了在一个大屏幕中,一串小对象挤成一堆的情况,而是允许他们放大填充空白。子元素指定一个weight值,剩余的空间就会按这些子元素指定的weight比例分配给这些子元素,默认的weight值为0。例如,如果有三个文本框,其中两个指定了weight值为1,那么,这两个文本框将等比例地放大,并填满剩余的空间,而第三个文本框不会放大。fill_parent或者match_parent(Android2.2开始使用match_parent),强制性让一个顶部布局或控件布满整个屏幕。wrap_content即包裹内容,此时布局元素将根据内容更改大小。

    下面我们举例说明:

    工程的res文件的layout文件夹中的主布局文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent" 

    android:orientation="vertical">

   <TextView 

       android:id="@+id/lable"

       android:layout_width="match_parent"

       android:layout_height="wrap_content"

       android:text="用户名"

       />

   <EditText 

       android:id="@+id/input"

       android:layout_width="match_parent"

       android:layout_height="wrap_content"

       android:text="请输入用户名"

       />

   <Button 

       android:id="@+id/button"

       android:layout_width="match_parent"

       android:layout_height="wrap_content"

       android:text="登录"

       />

</LinearLayout>

 

代码说明:

android:orientation="vertical"  指定线性布局的方向为垂直方向

android:layout_width="match_parent" 指定组件的宽度为匹配父容器

android:layout_height="wrap_content" 指定组件的高度为包裹内容

效果如图:

        工程的res文件夹中values文件夹中的strings.xml文件中键入:

<string name="name">用户名</string>

<string name="input">请输入</string>

<string name="login">登录</string>

        工程的res文件的layout文件夹中的主布局文件:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="horizontal" >

    <TextView 

         android:id="@+id/lable"

         android:layout_width="50dp"

         android:layout_height="wrap_content"

         android:text="@string/name"

        />

     <EditText 

          android:id="@+id/input"

          android:inputType="text"

          android:layout_width="200dp"

          android:layout_height="wrap_content"

          android:text="@string/input"

         />

     <Button 

           android:id="@+id/butotn"

           android:layout_width="70dp"

           android:layout_height="wrap_content"

           android:text="@string/login"

         />

</LinearLayout>

代码说明:

android:orientation="horizontal" 指定线性布局的方向为水平方向

        用途实例:线性布局是android布局中使用最广的。可以说在任何一种布局文件中都有它的身影

0 0
原创粉丝点击