如果有条件则在按钮中更改图标

问题描述 投票:0回答:3

在我的应用中,我有一个带有图标和文本的按钮。

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

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

if (condition)
setIcon1()
else
setIcon2()

有什么想法吗?是的,它必须是一个按钮,否则布局将拆分。

问候

android kotlin android-button
3个回答
3
投票

您可以尝试这种方式:

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

0
投票

您可以这样使用它。

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

它将起作用..

© www.soinside.com 2019 - 2024. All rights reserved.