Android 所有常用控件详解 —— 属性、用法一篇通关

继上一篇 ViewGroup 容器详解之后,这篇带你系统掌握 Android 所有常用 UI 控件。每个控件都包含:核心属性、XML 示例、适用场景、常见坑。


前言:Android 控件体系概览

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
View(所有控件的基类)
├── TextView(文本类)
│ ├── EditText(输入框)
│ └── CheckedTextView
├── Button(按钮类)
│ ├── CompoundButton
│ │ ├── CheckBox(复选框)
│ │ ├── RadioButton(单选按钮)
│ │ ├── ToggleButton(开关按钮)
│ │ └── Switch(滑动开关)
│ └── ImageButton
├── ImageView(图片控件)
├── ProgressBar(进度条)
│ └── SeekBar(拖动条)
│ └── RatingBar(评分条)
├── WebView(网页容器)
├── Chronometer(计时器)
└── ViewGroup(容器)→ 详见上一篇

最佳实践:读完这篇,再结合上一篇容器篇,你就具备了画任何 Android 页面的能力。


一、TextView —— 文本控件

作用

显示文字。Android 里 最基础、最常用 的控件,没有之一。

核心属性

属性值/说明
android:text显示的文本内容
android:textSize字号,单位 sp(推荐),如 16sp
android:textColor文字颜色,如 #333@color/primary
android:textStylenormal / bold / italic
android:gravity文字在控件内的对齐方式(center、left、right 等)
android:maxLines最大行数,超出显示 ...
android:ellipsize省略号位置:end / middle / start / marquee(跑马灯)
android:lineSpacingExtra行间距(dp)
android:drawableLeft文字左侧图标(另有 Top/Right/Bottom)
android:drawablePadding文字与图标的间距
android:autoLink自动识别链接:web / phone / email / all
android:singleLine单行模式(已废弃,用 maxLines=”1” 替代)

示例

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
<!-- 基础文本 -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World"
android:textSize="18sp"
android:textColor="#333"
android:textStyle="bold" />

<!-- 带左侧图标,最多两行,超出省略 -->
<TextView
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="这是一段很长的文字,超过两行就会显示省略号"
android:maxLines="2"
android:ellipsize="end"
android:drawableLeft="@drawable/ic_info"
android:drawablePadding="8dp" />

<!-- 跑马灯效果 -->
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="滚动文字效果 —— 适合标题新闻展示"
android:singleLine="true"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
android:focusable="true"
android:focusableInTouchMode="true" />

适用场景

  • 页面标题、正文、标签、提示信息等一切需要显示文字的地方

⚠️ 注意

  • textSize 默认单位是 sp,不要用 px
  • 跑马灯需要控件获得焦点才能滚动,代码中需设 focusable=true

二、EditText —— 输入框

作用

用户输入文字,继承自 TextView,拥有 TextView 的所有属性 + 输入相关属性。

核心属性

属性说明
android:hint占位提示文字,用户输入后消失
android:textColorHint占位文字颜色
android:inputType⭐ 输入类型,极其重要(见下表)
android:maxLength最大字符数
android:lines固定行数
android:imeOptions键盘右下角按钮:actionDone / actionSearch / actionGo / actionNext
android:drawableEnd输入框右侧图标(常用于清除按钮)
android:password密码模式(已废弃,用 inputType="textPassword" 替代)

inputType 常用值速查

场景
text普通文本
textPassword密码(显示圆点)
textVisiblePassword密码(可见明文)
number纯数字
numberDecimal带小数点的数字
phone电话号码
textEmailAddress邮箱地址
textMultiLine多行文本
textCapWords每个单词首字母大写
textNoSuggestions关闭拼写建议

可以组合使用,如 android:inputType="textPassword|number"

示例

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
<!-- 普通输入框 -->
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入用户名"
android:maxLength="20"
android:inputType="text" />

<!-- 密码输入框 -->
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入密码"
android:inputType="textPassword"
android:imeOptions="actionDone" />

<!-- 搜索输入框 -->
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="搜索..."
android:inputType="textNoSuggestions"
android:imeOptions="actionSearch"
android:drawableEnd="@drawable/ic_search" />

<!-- 数字输入框 -->
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入金额"
android:inputType="numberDecimal"
android:maxLength="10" />

适用场景

  • 登录/注册表单、搜索框、评论输入、聊天输入、任何需要用户输入的地方

⚠️ 注意

  • 获取和设置文本用 getText().toString()setText()
  • 密码框建议加上 android:textIsSelectable="false" 防止复制粘贴
  • 监听输入变化:addTextChangedListener()

三、Button —— 按钮

作用

用户点击触发操作。Android 中最核心的交互控件。

核心属性

属性说明
android:text按钮文字
android:textAllCaps是否全大写(默认 true,英文注意)
android:onClick绑定点击方法(XML 方式,不推荐)
android:enabled是否可点击(false 变灰)
style="?android:attr/borderlessButtonStyle"无边框按钮样式
android:background自定义背景(shape / selector)
android:stateListAnimator按下抬起动画(Material Design)

示例

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
<!-- 标准按钮 -->
<Button
android:layout_width="match_parent"
android:layout_height="48dp"
android:text="登录"
android:textSize="16sp" />

<!-- 小写文字按钮 -->
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="取消"
android:textAllCaps="false" />

<!-- 无边框文字按钮 -->
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="跳过"
style="?android:attr/borderlessButtonStyle" />

<!-- 禁用按钮 -->
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="提交"
android:enabled="false" />

适用场景

  • 任何需要用户点击确认/提交/跳转的操作

⚠️ 注意

  • 英文按钮默认全大写,中文不影响
  • 设置点击事件:button.setOnClickListener { }(推荐)或 XML 中用 onClick 属性
  • Material Design 风格建议用 com.google.android.material.button.MaterialButton

四、ImageButton —— 图片按钮

作用

用图片替代文字的按钮。常用于工具栏、操作栏上的图标按钮。

核心属性

属性说明
android:src显示的图片
android:background设定为 ?attr/selectableItemBackgroundBorderless 实现涟漪点击效果
android:scaleType图片缩放方式(同 ImageView)
android:contentDescription无障碍描述(必填,帮助视障用户)

示例

1
2
3
4
5
6
7
8
<!-- 带涟漪效果的图片按钮 -->
<ImageButton
android:layout_width="48dp"
android:layout_height="48dp"
android:src="@drawable/ic_back"
android:background="?attr/selectableItemBackgroundBorderless"
android:contentDescription="返回"
android:scaleType="centerInside" />

适用场景

  • 顶部导航栏返回按钮、搜索按钮、更多按钮
  • 底部操作栏图标

⚠️ 注意

  • **必须设置 android:contentDescription**,否则无障碍检测会报警告
  • 如果需要同时显示文字和图片,请用 Button + drawableLeftMaterialButton

五、ImageView —— 图片控件

作用

显示图片,支持本地资源、网络图片(需配合 Glide/Picasso 等框架)。

核心属性

属性说明
android:src显示的图片资源
android:scaleType⭐ 缩放类型(最关键属性)
android:tint图片着色(Material Design 图标染色)
android:adjustViewBounds是否保持宽高比(配合 maxWidth/maxHeight 使用)
android:alpha透明度(0~1,1 为不透明)
android:cropToPadding是否裁剪到 padding 区域

scaleType 详解(⭐ 这张图说不清,用表)

scaleType效果
center不缩放,居中显示,超出部分裁剪
centerCrop等比缩放,填满控件,超出裁剪 → 头像常用
centerInside等比缩放,完整显示在控件内
fitCenter等比缩放,居中完整显示(默认值)
fitXY拉伸填满,不保持比例,会变形
fitStart / fitEnd同 fitCenter,但对齐在顶部/底部
matrix使用 Matrix 自定义变换

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!-- 普通图片 -->
<ImageView
android:layout_width="200dp"
android:layout_height="200dp"
android:src="@drawable/sample"
android:scaleType="centerCrop" />

<!-- 圆形头像(配合 shape 或第三方库) -->
<ImageView
android:id="@+id/iv_avatar"
android:layout_width="64dp"
android:layout_height="64dp"
android:src="@drawable/ic_avatar"
android:scaleType="centerCrop" />

<!-- 图标染色 -->
<ImageView
android:layout_width="24dp"
android:layout_height="24dp"
android:src="@drawable/ic_home"
android:tint="@color/primary" />

适用场景

  • 头像、Banner、产品图、图标、引导页插图等各种图片展示

⚠️ 注意

  • 加载网络图片不要手动处理,用 GlideCoilPicasso 等图片加载库
  • 大图需要压缩,否则 OOM
  • 非必要不要让 ImageView 的宽高都是 wrap_content(无法确定展示大小)

六、CheckBox —— 复选框

作用

多选控件,允许用户选中/取消选中一个或多个选项。

核心属性

属性说明
android:text选项文字
android:checked默认是否选中
android:button自定义勾选框图形(@null 去掉默认图标)
android:buttonTint勾选框颜色

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!-- 基础复选框 -->
<CheckBox
android:id="@+id/cb_agree"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="我已阅读并同意《用户协议》"
android:textSize="14sp" />

<!-- 多选组 -->
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<CheckBox android:text="篮球" android:checked="true" />
<CheckBox android:text="足球" />
<CheckBox android:text="乒乓球" android:checked="true" />
<CheckBox android:text="羽毛球" />
</LinearLayout>

适用场景

  • 协议确认、兴趣爱好多选、筛选条件多选

⚠️ 注意

  • 获取选中状态:checkBox.isChecked
  • 监听变化:checkBox.setOnCheckedChangeListener { _, isChecked -> }
  • CheckBox 不属于 RadioGroup,多个 CheckBox 互不影响

七、RadioButton / RadioGroup —— 单选按钮

作用

互斥单选。RadioGroup 包裹的多个 RadioButton 中,只能选中一个。

核心属性

RadioGroup

属性说明
android:orientation排列方向(horizontal / vertical)
android:checkedButton默认选中的 RadioButton 的 id

RadioButton

属性说明
android:text选项文字
android:checked是否选中

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<RadioGroup
android:id="@+id/rg_gender"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">

<RadioButton
android:id="@+id/rb_male"
android:text="男"
android:checked="true" />

<RadioButton
android:id="@+id/rb_female"
android:text="女" />

<RadioButton
android:id="@+id/rb_secret"
android:text="保密" />
</RadioGroup>

适用场景

  • 性别选择、支付方式切换、选项互斥的单选场景

⚠️ 注意

  • 获取选中项:
1
2
val selectedId = radioGroup.checkedRadioButtonId
val radioButton: RadioButton = findViewById(selectedId)
  • RadioButton 必须放在 RadioGroup 里才能互斥
  • RadioButton 默认不带内边距,必要时加 android:padding

八、Switch / SwitchCompat —— 开关控件

作用

二元切换控件(开/关),比 CheckBox 更直观。

核心属性

属性说明
android:text开关旁的描述文字
android:checked默认开关状态
android:thumb滑块图标
android:track滑轨背景
android:thumbTint滑块颜色
android:trackTint滑轨颜色
app:showText是否在滑块上显示 ON/OFF 文字(SwitchCompat)

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!-- 原生 Switch -->
<Switch
android:id="@+id/sw_notification"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="通知开关"
android:checked="true" />

<!-- Material 风格 SwitchCompat -->
<com.google.android.material.switchmaterial.SwitchMaterial
android:id="@+id/sw_wifi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Wi-Fi" />

适用场景

  • 设置页面(通知开关、Wi-Fi、蓝牙、夜间模式等)
  • 二元状态切换

⚠️ 注意

  • 推荐使用 SwitchCompatSwitchMaterial(Material Design 风格)
  • 监听:switchView.setOnCheckedChangeListener { _, isChecked -> }
  • 代码切换状态:switchView.isChecked = true

九、ToggleButton —— 切换按钮

作用

带文字标签的开关按钮,比 Switch 更传统,显示”开/关”文字。

核心属性

属性说明
android:textOn开启时显示的文字
android:textOff关闭时显示的文字
android:checked默认状态
android:background自定义背景(可用 selector 实现状态切换)

示例

1
2
3
4
5
6
<ToggleButton
android:id="@+id/tb_mode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="免打扰"
android:textOff="正常" />

适用场景

  • 老式风格的开关场景(现代开发中多数被 Switch 替代)

十、SeekBar —— 拖动条

作用

通过拖动滑块选择一个范围内的数值,直观展示进度。

核心属性

属性说明
android:max最大值(默认 100)
android:progress当前值
android:thumb滑块图标
android:progressDrawable进度条颜色(自定义 layer-list)
android:thumbTint滑块颜色
android:progressTint进度颜色
android:secondaryProgress二级进度(如缓冲进度)
android:min最小值(API 26+)

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!-- 音量调节 -->
<SeekBar
android:id="@+id/sb_volume"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="100"
android:progress="50"
android:progressTint="@color/primary"
android:thumbTint="@color/primary" />

<!-- 带二级进度的播放器进度条 -->
<SeekBar
android:id="@+id/sb_play"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="100"
android:progress="30"
android:secondaryProgress="60" />

适用场景

  • 播放器进度调节、音量/亮度调节、设置中的范围选择

⚠️ 注意

  • 监听拖动:seekBar.setOnSeekBarChangeListener,需重写三个方法(onProgressChanged、onStartTrackingTouch、onStopTrackingTouch)
  • Kotlin 中更推荐用 Kotlin 扩展,或在代码块中处理
  • 非拖动结束时频繁回调可能造成性能开销,通常只在 onStopTrackingTouch 里做网络请求

十一、RatingBar —— 评分条

作用

星级评分控件,用户可以用星星打分。

核心属性

属性说明
android:numStars星星总数(默认 5)
android:rating默认评分
android:stepSize步长(0.5 表示支持半星,1 表示只能整数)
android:isIndicator是否仅作为指示器(true = 不可交互)
style="?attr/ratingBarStyleSmall"小号星星样式(不可交互)

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!-- 可交互评分 -->
<RatingBar
android:id="@+id/rb_score"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:numStars="5"
android:rating="4.0"
android:stepSize="0.5" />

<!-- 仅展示评分,不可操作 -->
<RatingBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="?attr/ratingBarStyleSmall"
android:numStars="5"
android:rating="3.5"
android:isIndicator="true" />

适用场景

  • 商品评分、电影评分、用户评价

⚠️ 注意

  • 监听:ratingBar.onRatingBarChangeListener { _, rating, _ -> }
  • 小星星样式默认不可操作(适合列表展示),大星星样式默认可操作
  • Android 原生 RatingBar 样式有限,追求美观建议自绘或使用第三方

十二、ProgressBar —— 进度条

作用

展示操作进度,让用户知道”正在加载”。

核心属性

属性说明
style?attr/progressBarStyleHorizontal(水平)或不写(圆形)
android:max最大值
android:progress当前进度
android:indeterminate是否不确定模式(无限转圈)
android:indeterminateTint圆形进度条颜色
android:progressTint水平进度条颜色
android:secondaryProgress二级进度(如缓冲)

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!-- 圆形菊花(不确定) -->
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:indeterminateTint="@color/primary" />

<!-- 水平进度条 -->
<ProgressBar
android:id="@+id/pb_download"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="8dp"
android:max="100"
android:progress="45"
android:progressTint="@color/primary" />

适用场景

  • 页面加载中(菊花转圈)、文件下载进度、上传进度、播放缓冲

⚠️ 注意

  • 不确定模式显示旋转菊花,确定模式显示实际进度
  • progressBar.visibility = View.GONE 来隐藏
  • 在 RecycleView 等列表中频繁切换可见性可能导致布局抖动

十三、Spinner —— 下拉选择框

作用

点击后弹出下拉列表供用户选择一项。

核心属性

属性说明
android:entries直接指定数组资源(@array/xxx
android:spinnerModedropdown(下拉)/ dialog(弹窗)
android:dropDownVerticalOffset下拉列表垂直偏移
android:popupBackground下拉列表背景

基础用法

方式一:静态数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!-- res/values/arrays.xml -->
<resources>
<string-array name="city_list">
<item>北京</item>
<item>上海</item>
<item>广州</item>
<item>深圳</item>
</string-array>
</resources>

<Spinner
android:id="@+id/sp_city"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:entries="@array/city_list" />

方式二:Adapter 动态绑定

1
2
3
4
5
6
7
8
9
10
11
val cities = listOf("北京", "上海", "广州", "深圳")
val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, cities)
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spinner.adapter = adapter

spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
val selected = cities[position]
}
override fun onNothingSelected(parent: AdapterView<*>?) {}
}

适用场景

  • 省份选择、年份选择、分类筛选等单值从多个候选项中选取的场景

⚠️ 注意

  • onItemSelectedListener 在初始化时也会回调一次,注意处理
  • 如果数据是动态的,必须用 Adapter 方式
  • Material Design 推荐使用 MaterialAutoCompleteTextView + TextInputLayoutExposedDropdownMenu 样式

十四、AutoCompleteTextView —— 自动补全输入框

作用

输入时自动联想匹配,显示下拉建议列表。

核心属性

属性说明
android:completionThreshold输入几个字符后开始联想(默认 2)
android:completionHint下拉列表提示文字
android:dropDownHeight下拉列表最大高度

示例

1
2
3
4
val suggestions = listOf("Android", "Android Studio", "Kotlin", "Java", "JavaScript")
val adapter = ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, suggestions)
autoCompleteTextView.setAdapter(adapter)
autoCompleteTextView.threshold = 1 // 输入 1 个字符就提示
1
2
3
4
5
6
<AutoCompleteTextView
android:id="@+id/actv_search"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="输入编程语言"
android:completionThreshold="1" />

适用场景

  • 搜索框自动联想、输入标签、邮箱地址联想

十五、WebView —— 网页容器

作用

在 App 内显示网页,相当于一个内置浏览器。

核心方法(代码配置为主)

方法 / 设置说明
webView.loadUrl("https://...")加载网页
webView.settings.javaScriptEnabled = true启用 JavaScript
webView.settings.domStorageEnabled = true启用 DOM 存储
webView.settings.mixedContentMode允许混合内容(HTTP + HTTPS)
webView.webViewClient = WebViewClient()在 App 内打开链接(不跳浏览器)
webView.webChromeClient = WebChromeClient()处理 JS 弹窗、进度条等
webView.addJavascriptInterface(obj, "name")JS 与原生交互

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
webView.settings.apply {
javaScriptEnabled = true
domStorageEnabled = true
useWideViewPort = true // 适配屏幕宽度
loadWithOverviewMode = true
mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
}

webView.webViewClient = WebViewClient()
webView.webChromeClient = object : WebChromeClient() {
override fun onProgressChanged(view: WebView, newProgress: Int) {
// 加载进度
}
}

webView.loadUrl("https://www.example.com")

适用场景

  • 网页内容展示(H5 页面、协议页面、活动页)、Hybrid App

⚠️ 注意

  • Android 9+ 默认禁止明文流量(HTTP),需要配置 network_security_config.xml
  • WebView 有内存泄漏风险,Activity onDestroy 时要移除并销毁
  • 不要忘记处理返回键(webView.canGoBack()webView.goBack()
  • 加载本地 H5 用 file:///android_asset/xxx.html

十六、Chronometer —— 计时器

作用

简单计时器,显示已过去的时间。

核心方法

方法说明
chronometer.base设置起始时间戳
chronometer.start()开始计时
chronometer.stop()停止计时
chronometer.format设置显示格式

示例

1
2
3
4
5
6
// 从 0 开始计时
chronometer.base = SystemClock.elapsedRealtime()
chronometer.start()

// 停止
chronometer.stop()
1
2
3
4
5
<Chronometer
android:id="@+id/chronometer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24sp" />

适用场景

  • 通话计时、录音计时、秒表

十七、ListView —— 传统列表(已不推荐)

作用

早期的列表控件,现在已被 RecyclerView 取代,但旧项目常见。

核心属性

属性说明
android:divider分割线
android:dividerHeight分割线高度

⚠️

新项目请直接使用 RecyclerView。 ListView 没有强制使用 ViewHolder 模式,性能不如 RecyclerView,扩展性也差。这里只做了解,不展开。


十八、Material Design 常用控件

18.1 CardView —— 卡片容器

让内容以卡片形式展示(圆角 + 阴影 + 边距)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<com.google.android.material.card.MaterialCardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardCornerRadius="12dp"
app:cardElevation="4dp"
app:cardBackgroundColor="#FFF"
app:strokeColor="#EEE"
app:strokeWidth="1dp"
android:layout_margin="16dp">

<!-- 卡片内容 -->
<LinearLayout ...>
<TextView ... />
<ImageView ... />
</LinearLayout>
</com.google.android.material.card.MaterialCardView>

核心属性

属性说明
app:cardCornerRadius圆角大小
app:cardElevation阴影高度(Z 轴)
app:cardBackgroundColor卡片背景色
app:strokeColor描边颜色
app:strokeWidth描边宽度
app:cardUseCompatPadding兼容 padding(阴影不裁剪)

适用场景

  • 列表卡片(商品卡片、文章卡片)、信息面板

18.2 Chip / ChipGroup —— 标签/芯片

标签式控件,常用于筛选、标签展示。

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
<com.google.android.material.chip.ChipGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:singleSelection="false"
app:chipSpacing="8dp">

<com.google.android.material.chip.Chip
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Android"
app:chipIcon="@drawable/ic_android"
app:closeIconEnabled="true"
style="@style/Widget.MaterialComponents.Chip.Filter" />

<com.google.android.material.chip.Chip
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Kotlin"
app:chipIcon="@drawable/ic_kotlin"
style="@style/Widget.MaterialComponents.Chip.Filter" />

<com.google.android.material.chip.Chip
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Flutter"
style="@style/Widget.MaterialComponents.Chip.Filter" />
</com.google.android.material.chip.ChipGroup>

Chip 常用属性

属性说明
app:chipIcon左侧图标
app:closeIconEnabled是否显示关闭图标
app:closeIcon关闭图标
app:chipBackgroundColor背景色
app:chipStrokeColor描边色
android:checkable是否可选中
android:checked默认选中状态

样式风格

  • Widget.MaterialComponents.Chip.Action – 操作型芯片
  • Widget.MaterialComponents.Chip.Filter – 筛选型芯片(可选中高亮)
  • Widget.MaterialComponents.Chip.Entry – 输入型芯片(可删除)
  • Widget.MaterialComponents.Chip.Choice – 选择型芯片

适用场景

  • 标签筛选(Filter 模式)、输入标签(Entry 模式,如邮件收件人)

18.3 FloatingActionButton —— 悬浮按钮

1
2
3
4
5
6
7
8
9
10
11
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_add"
android:contentDescription="新建"
app:fabSize="normal"
app:backgroundTint="@color/primary"
app:tint="@color/white"
android:layout_margin="16dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintBottom_toBottomOf="parent" />
属性说明
app:fabSizenormal(56dp)/ mini(40dp)/ auto
app:backgroundTint背景色
app:tint图标颜色
app:elevation阴影高度

适用场景

  • 页面主操作入口(新建邮件、发布动态、添加联系人)

18.4 BottomNavigationView —— 底部导航栏

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/bottom_nav"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:menu="@menu/bottom_nav_menu"
app:labelVisibilityMode="labeled" />

<!-- res/menu/bottom_nav_menu.xml -->
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/nav_home"
android:icon="@drawable/ic_home"
android:title="首页" />
<item
android:id="@+id/nav_discover"
android:icon="@drawable/ic_discover"
android:title="发现" />
<item
android:id="@+id/nav_mine"
android:icon="@drawable/ic_mine"
android:title="我的" />
</menu>

核心属性

属性说明
app:menu菜单资源
app:labelVisibilityModeauto / labeled / unlabeled / selected
app:itemIconTint图标选中/未选中颜色(ColorStateList)
app:itemTextColor文字选中/未选中颜色

⚠️ 注意

  • 官方建议 3~5 个选项,不要超过 5 个
  • 监听切换:bottomNav.setOnItemSelectedListener { item -> ... }
  • 不建议在代码中手动设置 selectedItemId,可能导致无限回调

18.5 Snackbar —— 轻量提示条

1
2
3
4
5
6
Snackbar.make(rootView, "删除成功", Snackbar.LENGTH_SHORT)
.setAction("撤销") {
// 点击撤销
}
.setActionTextColor(resources.getColor(R.color.accent))
.show()

特点

  • 比 Toast 更强大(支持交互操作)
  • 从底部弹出,会自动向上推 FAB
  • 一次只能显示一个 Snackbar

18.6 TextInputLayout —— 增强输入框

让 EditText 支持 Material Design 风格的浮动标签、错误提示、字符计数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:counterEnabled="true"
app:counterMaxLength="20"
app:errorEnabled="true"
android:hint="用户名"
style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox">

<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text" />
</com.google.android.material.textfield.TextInputLayout>

核心属性

属性说明
app:hint浮动标签文字
app:errorEnabled错误提示开关
app:counterEnabled字符计数器开关
app:counterMaxLength最大字符数
app:endIconMode尾部图标模式:password_toggle / clear_text
style样式:OutlinedBox(描边)/ FilledBox(填充)

代码设置错误提示:

1
2
textInputLayout.error = "用户名不能为空"  // 设置错误
textInputLayout.error = null // 清除错误

18.7 Toolbar —— 顶部工具栏

1
2
3
4
5
6
7
8
<com.google.android.material.appbar.MaterialToolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:title="标题"
app:titleTextColor="#FFF"
app:navigationIcon="@drawable/ic_back"
app:menu="@menu/toolbar_menu" />

使用方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// Activity 中
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
}

// 点击返回按钮
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
onBackPressedDispatcher.onBackPressed()
return true
}
return super.onOptionsItemSelected(item)
}

⚠️ 注意

  • 使用 Toolbar 时,需要把主题设为 NoActionBarTheme.MaterialComponents.Light.NoActionBar
  • Toolbar 功能比旧 ActionBar 强很多(自定义布局、动画、伸缩)

十九、通用属性速查(适用于所有 View)

以下属性几乎所有控件都能用

属性说明
android:id控件唯一标识(@+id/xxx
android:layout_width宽度:match_parent / wrap_content / 具体值
android:layout_height高度
android:layout_margin外边距(另有 Left/Top/Right/Bottom/Start/End)
android:padding内边距(另有 Left/Top/Right/Bottom/Start/End)
android:background背景(颜色/drawable/shape)
android:visibility可见性:visible / invisible / gone
android:alpha透明度(0~1)
android:elevation阴影高度(Z 轴,API 21+)
android:clickable是否可点击
android:focusable是否可获取焦点
android:contentDescription无障碍辅助描述
android:minWidth / minHeight最小宽高
android:translationX / translationY平移偏移量
android:rotation旋转角度
android:scaleX / scaleY缩放比例

二十、控件选择速查表

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
我需要...

显示一段文字 → TextView
用户输入文字 → EditText
用户点击文字按钮 → Button
用户点击图标按钮 → ImageButton
显示图片/头像 → ImageView
多选(如兴趣爱好) → CheckBox
单选题(如性别) → RadioGroup + RadioButton
开关设置 → Switch / SwitchCompat
滑块调节(音量/亮度) → SeekBar
星级评分 → RatingBar
显示加载状态 → ProgressBar
下拉选择(如省份) → Spinner
输入时自动联想 → AutoCompleteTextView
显示网页 → WebView
计时器 → Chronometer
卡片展示内容 → MaterialCardView
标签/筛选标签 → Chip / ChipGroup
浮动操作按钮 → FloatingActionButton
底部导航栏 → BottomNavigationView
轻量操作提示 → Snackbar
增强输入框(浮动标签+错误提示) → TextInputLayout
顶部工具栏 → MaterialToolbar
列表(大量数据) → RecyclerView

📊 最终总结

分类控件学习难度使用频率
文本TextView★☆☆☆☆⭐⭐⭐⭐⭐
文本EditText★★☆☆☆⭐⭐⭐⭐⭐
按钮Button★☆☆☆☆⭐⭐⭐⭐⭐
按钮ImageButton★☆☆☆☆⭐⭐⭐⭐
图片ImageView★★☆☆☆⭐⭐⭐⭐⭐
选择CheckBox★☆☆☆☆⭐⭐⭐⭐
选择RadioButton/RadioGroup★★☆☆☆⭐⭐⭐⭐
选择Switch★☆☆☆☆⭐⭐⭐⭐
选择ToggleButton★☆☆☆☆⭐⭐
选择Spinner★★☆☆☆⭐⭐⭐
进度ProgressBar★☆☆☆☆⭐⭐⭐⭐⭐
进度SeekBar★★☆☆☆⭐⭐⭐
进度RatingBar★☆☆☆☆⭐⭐⭐
输入AutoCompleteTextView★★☆☆☆⭐⭐⭐
容器WebView★★★☆☆⭐⭐⭐⭐
计时Chronometer★☆☆☆☆⭐⭐
MaterialCardView★★☆☆☆⭐⭐⭐⭐⭐
MaterialChip/ChipGroup★★☆☆☆⭐⭐⭐
MaterialFloatingActionButton★☆☆☆☆⭐⭐⭐⭐⭐
MaterialBottomNavigationView★★☆☆☆⭐⭐⭐⭐
MaterialTextInputLayout★★☆☆☆⭐⭐⭐⭐⭐
MaterialToolbar★★☆☆☆⭐⭐⭐⭐⭐

🎯 学习路线建议

1
2
3
4
5
6
 1 天:TextView + EditText + Button + ImageView → 能画基础页面
2 天:CheckBox + RadioButton + Switch + Spinner → 能画表单页面
3 天:ProgressBar + SeekBar + RatingBar → 能画设置/播放器页
4 天:CardView + Chip + FAB + Snackbar → 拥抱 Material Design
5 天:Toolbar + BottomNavigationView + TextInputLayout → 构建完整页面框架
进阶:WebView + AutoCompleteTextView + 自定义 View

动手写,比看十遍记得牢。
建议每天 2~3 个控件,打开 Android Studio 新建一个 Activity,把每个属性都试试。

配合上一篇 Android 常用容器详解 一起看,容器 + 控件 = 完整的 Android UI 能力。


💡 延伸阅读