【问题标题】:How to change Button app:icon property programitically如何以编程方式更改 Button app:icon 属性
【发布时间】:2021-05-06 17:30:27
【问题描述】:

我有一个带有集中图标+文本的按钮,当某些事件发生时,我需要更改 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 是所需的可绘制对象和字符串的 id:

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

【问题讨论】:

    标签: java android android-button


    【解决方案1】:

    您可以使用以下方法:

    setIcon
    setIconResource
    

    例子:

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

    这里是doc

    【讨论】:

    • 谢谢。错误是button 变量的类型。使用setIcon 方法应该是MaterialButton 而不仅仅是Button
    【解决方案2】:

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

    查看此链接:enter link description here 搜索 drawableLeft 显示:

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

    【讨论】:

    • 我需要集中图标。 drawableLeft 会将图标放在按钮的左边框。
    • 您可以设置属性,例如:重力,这将在任何您想要的地方调整图标和文本,如果这没有帮助,您可以使用 Relativelayout 并添加 ImageView 和 TextView 组合。
    猜你喜欢
    • 1970-01-01
    • 2017-02-27
    • 2021-09-03
    • 2016-05-22
    • 1970-01-01
    • 2010-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多