Does the image change programmatically?

I am trying to modify an ImageButton image programmatically.

I am trying to copy this code, but 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"/> 

Please, help.

Thank.

+54
android imagebutton
Jan 09 '13 at 10:24
source share
7 answers

your code is trying to change the button background. not his image. These are two different things.

  ((ImageButton) view).setImageResource(R.drawable.icon2); 
+109
Jan 09 '13 at
source share

Try this for me, change the background image programmatically,

  image.setBackgroundResource(R.drawable.ico); 
+14
Jan 09 '13 at
source share

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 helps you.

+2
Apr 08 '15 at 1:08
source share

Just try it like this:

((ImageButton)). SetImageDrawable (replacer);

+1
Jan 09 '13 at 10:27
source share

Using Kotlin, you can do this:

 val myImageButton = ImageButton(context).apply({ background = null setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_save_black_24px)) }) 
0
Apr 20 '18 at 10:20
source share

For kotlin it works for me

 yourimagebuttonID.setImageResource(R.drawable.ic_check_black_24dp) 
0
Jul 16 '19 at 15:01
source share

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

-four
Jan 09 '13 at 10:26
source share



All Articles