【发布时间】:2021-03-24 05:31:39
【问题描述】:
https://material.io/develop/android/components/buttons#text-button 从这个参考有一个 setIcon 方法,但我怎样才能达到它?
【问题讨论】:
标签: android button material-design
https://material.io/develop/android/components/buttons#text-button 从这个参考有一个 setIcon 方法,但我怎样才能达到它?
【问题讨论】:
标签: android button material-design
如果你没有使用 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,要么派生自 View,根据文档,Button 派生自 TextView。
现在有一些关于 Android 文本的重要知识。该框架允许您为每个文本定义Compound Drawables - 看看this method。有了它,您可以以编程方式设置复合可绘制对象,但还要注意文档的 Related XML Attributes 部分 - 可绘制对象可以在 XML 中定义,这通常是最简单的方法(当然,如果适用于给定情况)。
您附加的按钮图像看起来像MaterialButton,这也是一个标准的Button,因此“加号”图标应该只是一个复合可绘制图标,因此应该很容易更改,如上所述。
编辑:转念一想,使用 Google 的 Android 材料设计库,事情通常不会那么简单。看看我上面链接的MaterialButton 文档——那里有一个setIcon() 方法,它可能会回答你的问题。您还可以使用app:icon 属性在 XML 中定义您的可绘制图标。
【讨论】: