如何以编程方式更改按钮 app:icon 属性

How to change Button app:icon property programitically

我有一个带有集中图标+文本的按钮,我需要在发生某些事件时更改 app:iconandroid:text 属性。我知道有 setText() 方法可以更改文本,但是有没有办法更改图标?

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" />

这是一个在适当事件后调用的函数,我需要更改该函数中的图标。 icontext 是理想的 drawable 和字符串的 ids:

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

您可以使用以下方法:

setIcon
setIconResource

示例:

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

这里是doc.

如果您查看文档,您会看到每个 XML 属性的等效代码。

检查此 link:enter link description here 搜索 drawableLeft 显示:

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