温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Android UI布局-1.1线性布局(一)-线性布局基础

发布时间:2020-07-06 11:37:33 来源:网络 阅读:729 作者:BrightKoala 栏目:移动开发

LinearLayout,中文意思就是线性布局,是一种最简单、最常用的布局方式,它将其中的组件以线性方式进行排列。其中有垂直和水平两种布局方向,可以使用orientation属性来对它的方向进行设定。使用方法如下:

android:orientation="vertical"属性将其指定为垂直线性排列;
android:orientation="vertical"属性将其指定为水平线性排列;

当指定了方向后,线性布局中的组件就会自动垂直或者水平成一条线,一个挨一个的排列。下面我们先来看一个简单的例子,并通过这个示例,学习线性布局的基本属性。

示例1:
\Android Project\app\src\main\res\layout\activity_main.xml

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

    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:layout_width="match_parent"
            android:layout_height="match_parent" 
            android:text="按钮1"
            android:id="@+id/button1"/>

        <Button
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="按钮2"
            android:id="@+id/button2"/>

        <Button
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="按钮3"
            android:id="@+id/button3"/>

    </LinearLayout>

以上代码,就是一个使用线性布局对组件进行布局的例子,该示例的线性布局中,摆放了三个按钮(Button)组件。下面就以它为例对LinearLayout布局方式做简单的介绍。该示例的运行效果如下图所示:
Android UI布局-1.1线性布局(一)-线性布局基础

首先我们来看根节点LinearLayout,它有一个属性“xmlns:android”,用于指定命名空间,根元素必须指定命名空间。

它还有其他的属性,像orientation、layout_width以及layout_height,这些都是定义在该命名空间中,因此需要在这些属性前面加上前缀“android:”,表示这个属性定义在“android”所定义的命名空间,即“http://schemas.android.com/apk/res/android” 。

每个组件都具有android:layout_width和android:layout_height属性,他们的值可以设置为数字,可选单位有dp、dip和px等,前两者是一样的,px是绝对像素,而dip是设备独立像素(Device Independent Pixels)。

px不利于不同屏幕分辨率的适配,因此Google推荐大家使用dp或者dip为单位。除了数值以外,还有三种常用的取值,分别是wrap_content、match_parent和fill_parent。其中,后两者是一样的,以前的老版本使用fill_parent,而后来的版本使用match_parent,他们都表示该组件将尽可能把父控件占满,与此相对应,而wrap_content则表示只占有足够自己内容的空间。

LinearLayout的属性“android:orientation”是指定其中的子组件的排列方式,若指定为“vertical”,则表示子组件垂直排列,每个子组件会占独立的一行;而指定另一个“horizontal”,它表示子组件水平排列,即每个子组件会占独立的一列,我们上面示例的代码中,就是使用的水平排列。大家可以将上面的方向修改哼垂直方向(即vertical),就可以看到下面这个图的效果。
Android UI布局-1.1线性布局(一)-线性布局基础

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI