0

I have a button with icon and text inside.

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

I would like to change icon from code if condition exists.

if (condition)
   setIcon1()
else
   setIcon2()

It has to be a button otherwise the layouts will split up.

Jawad Malik
  • 608
  • 5
  • 21
CallMePedro
  • 51
  • 3
  • 19

3 Answers3

3

You can try this way:

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

I recommend you to have a look on this tutorial for more detail.

John Le
  • 1,116
  • 9
  • 12
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);
Peter Alwin
  • 239
  • 1
  • 6
0

you can use it like this.

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

It will work.

Sergey Glotov
  • 20,200
  • 11
  • 84
  • 98