How to set ImageButton property of app:srcCompat="@drawable/pic" programmatically?

AndroidAndroid AppcompatAndroid Imagebutton

Android Problem Overview


How to set the ImageButton property of

app:srcCompat="@drawable/pic"

programmatically?

Something like myImageButton.setBackgroundResource(R.drawable.eng2); but the property of app:srcCompat.

Android Solutions


Solution 1 - Android

You need to use setImageResource() method.

imageButton.setImageResource(R.drawable.eng2);

Solution 2 - Android

First, ensure you are dealing with AppCompatImageView, not regular ImageView:

AppCompatImageView iv = (AppCompatImageView)findViewById(....);

and then you can do:

iv.setImageResource(R.drawable.pic);

See other public methods in docs.

Solution 3 - Android

Using setImageResource() should fetch its resource in a backwards-compatible manner without any further effort required.

However if you are using setImageDrawable(), the ImageView/ImageButton will not help with any backwards compat and it's up to you to supply a backward-compat drawable, which is important for eg. if using VectorDrawables. The following will load and set a drawable in such a way:

val drawable = AppCompatResources.getDrawable(context, resourceId)
image.setImageDrawable(drawable)

Solution 4 - Android

I guess other methods are outdated and wouldn't work at the time of writing this,

iv_yourImageView.setImageDrawable(getResources().getDrawable(R.drawable.your_drawable));

This will work.

Solution 5 - Android

None, of the provided solutions worked for me. I was using an ImageView. Finally, I found out that using setBackgroundResource() works for me.

view.setBackgroundResource(R.drawable.ic_star_black_18dp)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIsaac DarlongView Question on Stackoverflow
Solution 1 - AndroidPrerak SolaView Answer on Stackoverflow
Solution 2 - AndroidMarcin OrlowskiView Answer on Stackoverflow
Solution 3 - AndroidTomView Answer on Stackoverflow
Solution 4 - AndroidmiPlodderView Answer on Stackoverflow
Solution 5 - AndroidMachineLearnerView Answer on Stackoverflow