1. 添加依赖包
在app下的build.gradle里添加Google Material Button的依赖包
implementation ‘com.google.android.material:material:1.7.0’
添加后要sync gradle。
2. 修改Theme
在res文件夹下的theme.xml里,把App的主题的父主题改为“Theme.MaterialComponents.Light.NoActionBar”
3. MaterialButton的继承关系
java.lang.Object
↳android.view.View
↳android.widget.TextView
↳android.widget.Button
↳androidx.appcompat.widget.AppCompatButton
↳com.google.android.material.button.MaterialButton
4. 常用属性
属性 | 说明 |
---|---|
app:backgroundTint | 背景颜色 |
app:backgroundTintMode | 颜色模式 |
app:strokeColor | 描边颜色 |
app:strokeWidth | 描边宽度 |
app:cornerRadius | 圆角大小 |
app:icon | 在按钮中设置图标 |
app:iconSize | 图标大小 |
app:iconGravity | 图标显示重心(位置) |
app:iconTint | 图标颜色 |
app:iconPadding | 图标和文本之间的间距 |
style=“@style/Widget.MaterialComponents.Button.UnelevatedButton” | 去掉按钮的阴影效果 |
5. 实例
<?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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.google.android.material.button.MaterialButton
android:layout_width="150dp"
android:layout_height="50dp"