69

I'm trying to change the image of the ImageButton programmatically.

I'm trying to copy this code, but the setBackgroundDrawable is already deprecated.

public void giveClue(View view) {
    Drawable replacer = getResources().getDrawable(R.drawable.icon2);
    ((ImageButton) view).setEnabled(false);
    ((ImageButton) view).setBackgroundDrawable(replacer);
    gameAdapter.giveClue(game);
}

My button was created using xml as follows:

   <ImageButton
        android:id="@+id/ImageButton2"
        android:layout_width="24dp"
        android:layout_height="22dp"
        android:layout_alignTop="@+id/imageButton1"
        android:layout_toLeftOf="@+id/ImageButton3"
        android:src="@drawable/icon" 
        android:onClick="giveClue"/>
Dharman
  • 30,962
  • 25
  • 85
  • 135
newbie
  • 14,582
  • 31
  • 104
  • 146

8 Answers8

157

your code is trying to change the background of the button. not its image. Those are two different things

  ((ImageButton) view).setImageResource(R.drawable.icon2);
meda
  • 45,103
  • 14
  • 92
  • 122
Budius
  • 39,391
  • 16
  • 102
  • 144
  • It doesn't work, the xml always override what you changed to the previous state specified in xml attribute (app:srcCompat). – Salah Jun 12 '22 at 16:52
19

Try this its working for me,Change the background image programmatically,

 image.setBackgroundResource(R.drawable.ico);
MuraliGanesan
  • 3,233
  • 2
  • 16
  • 22
  • 2
    You should use [setImageResource](https://developer.android.com/reference/android/widget/ImageView.html#setImageResource(int)) instead. – StupidFox Jun 01 '16 at 10:35
3

Hi you can use the following code

if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN ) 
{
    ((ImageButton) view).setImageResource(getResources().getIdentifier("icon2", "drawable", getPackageName()));
}
else 
{
    ((ImageButton) view).setImageDrawable(getDrawable(getResources().getIdentifier("icon2", "drawable", getPackageName())));
}

Hope this will help you.

ziniestro
  • 686
  • 1
  • 11
  • 24
2

In Kotlin you can use this code:

val myImageButton = findViewById<ImageButton>(R.id.myImageButton)  

myImageButton.setOnClickListener {

     (myImageButton as ImageButton).setImageResource(R.drawable.myIcon) 

}
jtate
  • 2,612
  • 7
  • 25
  • 35
GoldCat
  • 81
  • 1
  • 6
1

Just try out this way:

((ImageButton) view).setImageDrawable(replacer);

GrIsHu
  • 29,068
  • 10
  • 64
  • 102
0

Using Kotlin, you can do this:

val myImageButton = ImageButton(context).apply({
    background = null
    setImageDrawable(ContextCompat.getDrawable(context, 
                         R.drawable.ic_save_black_24px))
})
Hasan A Yousef
  • 22,789
  • 24
  • 132
  • 203
0

For kotlin this works for me

yourimagebuttonID.setImageResource(R.drawable.ic_check_black_24dp)
Jimale Abdi
  • 2,574
  • 5
  • 26
  • 33
-4

Try ((ImageButton) view).setImageDrawable(replacer);

f.old
  • 343
  • 3
  • 15