【问题标题】:Change icon in button if (condition) [duplicate]如果(条件)更改按钮中的图标[重复]
【发布时间】:2019-11-27 09:35:51
【问题描述】:

我有一个带有图标和文本的按钮。

<Button
...
android:drawableStart="@drawable/my_button"
android:text="ABC"
...
/>

如果条件存在,我想从代码中更改图标。

if (condition)
   setIcon1()
else
   setIcon2()

它必须是一个按钮,否则布局会分裂。

【问题讨论】:

  • 问题到底是什么?如何在代码中的视图上设置可绘制对象?

标签: android kotlin android-button


【解决方案1】:

你可以试试这个方法:

Button.setCompoundDrawablesWithIntrinsicBounds(
        R.drawable.my_button,
        R.drawable.my_button,
        R.drawable.my_button,
        R.drawable.my_button
    )

我建议您查看this tutorial 了解更多详情。

【讨论】:

  • 谢谢 :) 这就是我要找的 :)
【解决方案2】:
    Drawable img = getResources().getDrawable( R.drawable.profile_aadhar );
    binding.btn.setCompoundDrawablesWithIntrinsicBounds( img, null, null, null);

     position to set
     Note setCompoundDrawablesWithIntrinsicBounds( left, top, right, bottom);

【讨论】:

    【解决方案3】:

    你可以这样使用它。

    <Button
        android:id="@+id/btn"
        android:drawableStart="@drawable/my_button"
        android:text="ABC"
        />
    
    
    
    if (condition)
        btn.setBackgroundResource(R.drawable.img1); 
    else
        btn.setBackgroundResource(R.drawable.img2);
    

    它会起作用的。

    【讨论】:

      猜你喜欢
      • 2015-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-25
      • 1970-01-01
      • 1970-01-01
      • 2020-06-13
      相关资源
      最近更新 更多