欢迎光临散文网 会员登陆 & 注册

Android开发学习教程(12)- Android布局之线性布局LinearLayout

2023-01-27 16:04 作者:考研保研直通车  | 我要投稿


—— 当下的生活或许疲惫又难熬,但你要相信,始终没有放弃过的你,一定会过上想要的生活。

上一篇我们讲了对话框AlertDialog的基本用法,这里来学习常用布局之线性布局的基本用法。

线性布局是什么

线性布局中的控件按照横向或竖向排列,并且线性布局不会换行,当控件超出屏幕边缘,后面的控件就被隐藏,不会被显示出来。

线性布局有什么用

控制其中的控件只能横向或竖向排列。

线性布局怎么用

继续基于上一篇的项目,我们新建一个LinearLayoutActivity:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<?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:gravity="center"
    android:orientation="horizontal">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello 我是第一个子控件" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello 我是第二个子控件" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello 我是第三个子控件" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello 我是第四个子控件" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello 我是第五个子控件" />
</LinearLayout>

上图横向排列了五个控件,并且线性布局不会自动换行,当控件超出屏幕边缘,后面的控件就被隐藏,不会被显示出来。

LinearLayout基本属性

android:gravity:用来控制子控件的位置,值有top,left,right,bottom,center,分别表示子控件在顶部、左部、右部、下部、垂直方向居中并且水平方向居中,值得注意的是,还可以组合取值,如right|center_vertical表示子控件在右部并且垂直方向居中;

android:orientation:用来控制子控件的排列方式,值为horizontal时表示所有子控件横向排列,为vertical时表示所有子控件竖向排列,上面的例子是横向排列,我们来试试竖向排列;

把android:orientation改为vertical,为了使效果更明显,我们去掉android:gravity设置,使用默认值(top|left),运行如下:

源码链接:https://yunjunet.cn/876750.html

Android开发学习教程(12)- Android布局之线性布局LinearLayout的评论 (共 条)

分享到微博请遵守国家法律