如何在Android Studio项目中通过Material依赖使用Material图标?
在Android项目中便捷使用Material图标(无需手动下载)
你已经添加了com.google.android.material:material:1.8.0依赖,直接引用com.google.android.material.R.drawable.chat找不到是因为Material图标在库中的引用方式并非简单名称,以下是两种类似iOS SFSymbols的便捷使用方法:
方法一:使用MaterialIconView组件(推荐,支持动态调整样式)
这是最接近SFSymbols的使用方式,支持修改图标填充度、粗细、大小等参数:
- XML布局中添加组件:
<com.google.android.material.icon.MaterialIconView android:layout_width="48dp" android:layout_height="48dp" <!-- 引用聊天图标(Outlined空心样式) --> app:icon="@string/material_symbols_chat_outlined" <!-- 设置图标颜色 --> app:iconTint="@color/your_icon_color" <!-- 可选:调整填充度(0=空心,1=实心) --> app:iconFill="0" <!-- 可选:调整图标粗细 --> app:iconWeight="400" <!-- 可选:调整图标尺寸 --> app:iconSize="24dp" />
- 代码中动态设置图标:
val iconView = findViewById<MaterialIconView>(R.id.icon_view) iconView.setIconResource(R.string.material_symbols_chat_outlined) iconView.setIconTintResource(R.color.your_icon_color)
方法二:作为Drawable资源使用(适配传统控件)
如果需要将图标作为Drawable给Button、ImageView等控件使用,可调用库中内置的VectorDrawable资源:
- XML布局示例:
<ImageView android:layout_width="24dp" android:layout_height="24dp" android:src="@drawable/ic_baseline_chat_24" android:tint="@color/your_icon_color" />
- 代码中获取Drawable:
val chatDrawable = AppCompatResources.getDrawable(this, R.drawable.ic_baseline_chat_24) // 给MaterialButton设置图标 val button = findViewById<MaterialButton>(R.id.btn_chat) button.icon = chatDrawable
注意事项
- 图标资源命名规则:Material Icons分为Baseline(常规)、Outlined(空心)、Round(圆角)等样式,命名格式为
ic_<样式>_<图标名称>_<尺寸>,比如ic_baseline_chat_24、ic_outlined_chat_24。 - Material Symbols的字符串资源命名为
material_symbols_<图标名称>_<样式>,比如material_symbols_chat_outlined,这类资源支持更多样式调整(填充、粗细、渐变等)。
内容的提问来源于stack exchange,提问作者NoKey
相关产品推荐
相关产品推荐

