programmer
programmer

Reputation: 101

How to change Button app:icon property programitically

I have a button with centralized icon+text, and I need to change the app:icon and android:text properties when some event occurred. I know that there is setText() method to change the text, but is there a way to change the icon?

XML:

<Button
    android:id="@+id/bottom_button"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginHorizontal="@dimen/default_margin"
    android:layout_marginVertical="@dimen/bottom_bar_content_vertical_margin"
    android:backgroundTint="@color/light_green"
    android:text="@string/next"
    android:textAllCaps="false"
    app:icon="@drawable/ic_baseline_next_plan_24"
    app:iconGravity="textStart" />

This is a function that is called after appropriate event, and I need to change icon in that function. icon and text are ids of desirable drawable and string:

private void setBottomButton(int icon, int text) {
    button.setText(getString(text));
}

Upvotes: 1

Views: 733

Answers (2)

Prakash Reddy
Prakash Reddy

Reputation: 1002

If you check the docs, you'll see the code equivalent for each XML attribute.

Check this link : enter link description here Searching for drawableLeft shows:

android:drawableLeft:
setCompoundDrawablesWithIntrinsicBounds(Drawable,Drawable,Drawable,Drawable)

Upvotes: 1

Gabriele Mariotti
Gabriele Mariotti

Reputation: 363557

You can use the methods:

setIcon
setIconResource

Example:

button.setIcon(drawable)
button.setIconResource(iconId)

Here the doc.

Upvotes: 1

Related Questions