I create a list of cards dinamically from XML data by inflating an XML layout. 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.
I can set the label, but I can't find a method to change the app:icon
property.
layout.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:
...
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
.
To apply the method setIcon
you have to use a MaterialButton
:
(button as MaterialButton).icon = ContextCompat.getDrawable(this,R.drawable.xxx)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.