android - 如何实现drawable局部变色?

标签 android drawable material-components-android

我正在将我的应用程序的设计基础架构更改为 Material Design 组件,并希望实现如下目标:

enter image description here

这是来自 toggle button它表明可以对可绘制对象进行部分着色,但是没有实现示例如何实现这一点。在我的应用程序中,我有一个带有前景色的文本格式工具栏,我需要以这种方式准确显示选定的文本颜色。

最佳答案

您可以将图标分成两部分(相同大小),例如我们可以从 material icons 中获取“格式颜色文本”图标

2

然后使用 <layer-list> 将两个可绘制对象合并为一个( LayerDrawable )

ic_format_color_text.xml

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/ic_format_color_text_black_part1_24dp" />
    <item android:drawable="@drawable/ic_format_color_text_black_part2_24dp" />
</layer-list>

现在,这个可绘制对象可以用作按钮的图标 ( MaterialButtonToggleGroup + MaterialButton )。仅对“底部形状”部分着色:

val dr = (colorTextBtn.icon as? LayerDrawable)?.getDrawable(0 /* colored shape layer index*/)
dr?.let { DrawableCompat.setTint(dr, /* color */) }

enter image description here

关于android - 如何实现drawable局部变色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65994410/

相关文章:

android - 无法使用 android.material :1. 1.x 渲染 MaterialButton

android - 如何在 "TextInputLayout"的右端动态添加一个 drawable?

java - 在 Canvas 上画一条线,旁边再画一条虚线

Android AlertDialog.Builder 和软键盘

Android - 将compileSdkVersion更改为16会导致编译错误(gradle)

Android:如何从其他 Activity 更改项目列表中的可绘制对象

java - native C++ 方法是否计入 dex 文件方法计数?

android - Android 的高级动画

android - 如何检查整数数组中的android资源类型

android - 提示的字体系列在 TextInputLayout 中无法正常工作