Android 2-1 线性布局和相对布局

本文介绍了Android中的两种布局方式:线性布局和相对布局。线性布局讲解了如何设置垂直方向排列,并通过实例展示了如何创建内外盒子的布局。相对布局部分则阐述了如何设置元素的对齐方式,以及如何在一个线性布局内放置相对位置的子元素。
摘要由CSDN通过智能技术生成

线性布局和相对布局

线性布局

🔧常用属性

名称 解释
android:id 索引
android:layout_width 宽度
android:layout_height 高度
android:background 背景色
android:layout_margin 外边距
android:layout_padding 内填充
android:orentation 线性布局排列方向
android:gravity (设置在父元素)重心
android:layout_gravity (设置此元素)重心

打开activity_main.xml,这里提供了一个默认的线性布局,包含一个文本框控件TextView

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

🌲例子:
首先将默认的布局改为线性布局(LinearLayout),删除TextView,设置线性布局的方向orientation属性为垂直方向排列(vertical):
1:在上方放置一个200x200dp的黑色盒子,在内部加入相同大小的红色盒子,为外部的盒子设置填充20dp,最后为红色盒子设置重力(gravity),使得内部的小盒子(黑色)上下左右居中排列;
2:在下方放置一个等同于屏幕宽度的盒子,与上方的盒子设置有10dp的外间距,在该,盒子中放入3个小盒子,高度自适应,宽度分别为1:2:1

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值