你可能不知道的 MaterialButton

缘起

项目设计图中有类似下图的一个效果,圆角矩形 + Icon + 文字居中这样的一个效果。

图片描述

可实现方案

  • 圆角Shape + ViewGroup + ImageView + TextView
  • 圆角Shape + ViewGroup + TextView
  • 自定义 TextView
  • MaterialButton

缘灭

在 app.gradle 下添加依赖

1
implementation 'com.google.android.material:material:1.6.0'

在 xml 布局中使用

1
2
3
4
5
6
7
8
9
10
11
12
13
<com.google.android.material.button.MaterialButton
android:id="@+id/btn_like"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginHorizontal="16dp"
android:insetTop="0dp"
android:insetBottom="0dp"
android:text="点赞"
app:backgroundTint="#FF7029"
app:cornerRadius="25dp"
app:icon="@drawable/ic_like"
app:iconGravity="textStart"
app:iconSize="30dp" />

insetTop 和 insetBottom 这两个属性主要是为了解决默认情况下 MaterialButton 会自动添加上下各 6dp 的间距,导致看起来的实际效果会比现在矮 12dp。

backgroundTint 为 background 的着色。

cornerRadius 为圆角大小。

icon 为图标资源。

iconGravity 只有 start、top、end、textStart、textTop、textEnd 这六个取值。

iconSize 为图标的大小。

总结

有时候我们并不一定要用 View 堆叠来实现效果,官方可能早已为我们提供了现成的 View 控件~

又是一个安卓开发的布局优化小技巧,你学废了吗?

如果对你有帮助的话,欢迎一键三连+关注哦~


你可能不知道的 MaterialButton
https://blog.funkt.cn/2022/11/27/1594712045128966145/
作者
anjiemo
发布于
2022年11月27日
许可协议
未经作者授权,禁止转载