[英]Android button: How to change icon programatically
I create a list of cards dinamically from XML data by inflating an XML layout.我通过扩充 XML 布局从 XML 数据动态地创建卡片列表。 This layout has a button with dummy values to supress the warnings by the IDE, and I want to set the label and the leading icon according to the data from that XML resource.这个布局有一个带有虚拟值的按钮来抑制 IDE 的警告,我想根据来自该 XML 资源的数据设置标签和前导图标。
I can set the label, but I can't find a method to change the app:icon
property.我可以设置标签,但找不到更改app:icon
属性的方法。
layout.xml:布局.xml:
...
<Button
android:id="@+id/listItemAction"
style="@style/Widget.MaterialComponents.Button.TextButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:text="@string/misc_load" <!-- dummy value -->
app:icon="@drawable/ic_round_help_24" <!-- dummy value --> />
...
Adapter.java:适配器.java:
...
viewHolder.action.setText(list.get(position).label); // it works
viewHolder.action.setIcon(list.get(position).icon); // there is no such method
...
Can you try the following two methods可以试试以下两种方法吗
// Using icon resource ID
textButton.setIconResource(R.drawable.ic_show_black_18dp)
// Using icon Drawable
val showDrawable = AppCompatResources.getDrawable(context, R.drawable.ic_show_black_18dp)
textButton.icon = showDrawable
Since your are using a Material Components theme your Button
is replaced ad runtime with a MaterialButton
.由于您使用的是 Material Components 主题,因此您的Button
被替换为MaterialButton
广告运行时。
To apply the method setIcon
you have to use a MaterialButton
:要应用setIcon
方法,您必须使用MaterialButton
:
(button as MaterialButton).icon = ContextCompat.getDrawable(this,R.drawable.xxx)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.