线性布局和相对布局
线性布局
🔧常用属性
名称 | 解释 |
---|---|
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"