Search code examples
androidandroid-buttonmaterial-components-android

Android button: How to change icon programatically


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
...

Solution

  • 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)