线性布局 (LinearLayout)
(我的学习方式:先敲再看,先动再想)
我们直接创建几个文件,然后解释一下是什么意思:
- res/layout 下创建一个XML的布局文件 activity_line.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="match_parent">
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="right">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="搜索"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="重置"/>
</LinearLayout>
</LinearLayout>
- 创建 java 代码,应用我们编写XML文件,main/java/com.panyong.helloworld (包名自定义,无需跟我一样)下创建 LineActivity.java
package com.panyong.helloworld;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
public class LineActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_line);
}
}
完成上面步骤之后呢,我们还需要将我们的 LineActivity 加入到 AndroidManifest.xml 中:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.panyong.helloworld">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
</activity>
<activity android:name=".LineActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
然后大家用模拟机运行下可以看到效果如下:
完成以上内容,我们来解释下什么是线性布局,参考下图:
- 最外层使用的是垂直(vertical)的 线性布局(LinearLayout ),宽度满屏(fill_parent),高度自适应,根据子控件大小调整(wrap_content)
- 其次是可编辑的文本控件 (EditText )
- 接下来是一个水平(horizontal)的 线性布局(LinearLayout ),宽度满屏(fill_parent),高度自适应,根据子控件大小调整(wrap_content),内容靠右对齐(right)
- 最后是两个按钮(Button)
最后语法总结
android:orientation=“vertical”,确定线性布局的方向,有两个值:
- vertical 垂直布局
- horizontal 水平布局
android:layout_width=“fill_parent”, android:layout_height=“wrap_content”,分别指明了当前控件的宽高,常用用法:
- fill_parent 填满父控件的空白
- wrap_content 表示大小刚好能够显示当前控件里的内容
- 确定的大小值
android:gravity=“right”,对齐方式,可以指定以下值,如果需要指定多个值的话,需要用 “|” 隔开:
- top 不改变大小,位置位于容器的顶部
- bottom 不改变大小,位置位于容器的底部
- left 不改变大小,位置位于容器的左侧
- right 不改变大小,位置位于容器的右侧
- center_vertical 不改变大小,位置位于容器的纵向中央部分
- center_horizontal 不改变大小,位置位于容器的横向中央部分
- center 不改变大小,位置位于容器的横向和纵向的中央部分
- fill_vertical 可能的话,纵向延伸以填满容器
- fill_horizontal 可能的话,横向延伸以填满容器
- fill 可能的话,横向和纵向延伸以填满容器
android:text=“搜索”,用来显示文本