如何以编程方式更改 Outlined Button 图标?

How can I change Outlined Button icon programmatically?

https://material.io/develop/android/components/buttons#text-button 从这个参考有一个 setIcon 方法,但我怎样才能达到它?

如果您没有使用 material 主题作为您的应用主题,您需要在 xml:

中像这样声明 Material 按钮
 <com.google.android.material.button.MaterialButton
                android:id="@+id/outlinedButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Outlined button"
                app:icon="@drawable/ic_launcher_background"
                style="@style/Widget.MaterialComponents.Button.OutlinedButton.Icon"
                />

并以编程方式更改图标:

findViewById<MaterialButton>(R.id.outlinedButton).setIcon(ContextCompat.getDrawable(this,R.drawable.ic_launcher_foreground))

在 Android 中,每个 UI 小部件组件都是 View, or derives from the View, and according to the documentation, the Button 派生自 TextView

关于 Android 中的文本,现在有一些重要的信息需要了解。该框架允许您为每个文本定义 Compound Drawables - 看看 this method。有了它,您可以以编程方式设置复合可绘制对象,但还要注意文档的 Related XML Attributes 部分 - 可绘制对象可以在 XML 中定义,这通常是最简单的方法(如果适用于给定的情况)当然)。

您附加的按钮图像看起来像 MaterialButton,这也是标准的 Button,因此 'plus' 图标应该只是一个复合可绘制对象,因此应该可以轻松更改,如上所述。

编辑:转念一想,Google 的 material 设计库 Android 的事情通常并不那么简单。查看我上面链接的 MaterialButton 文档 - 那里有一个 setIcon() 方法,它可能会回答您的问题。您还可以使用 app:icon 属性在 XML 中定义可绘制图标。