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

5

91

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.

Rash answered 5/7, 2016 at 21:13 Comment(0)
U
172

You need to use setImageResource() method.

imageButton.setImageResource(R.drawable.eng2);

Uplift answered 5/7, 2016 at 21:21 Comment(2)
Same for KotlinJusticz
does that mean that we dont use srcCompat changes on xml?Deodorant
H
26

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.

Heaton answered 5/7, 2016 at 21:19 Comment(6)
I'm using 'ImageButton' with 'app:srcCompat="@drawable/pic"' but setting to 'setImageResource(R.drawable.pic);' works fine. Thank youRash
build tools are probably replacing classes "in fly"Wilkes
hey Marcin, do you know why we need to programmatically change the image instead of giving the path between app:srcCompa="drawable/"Bastogne
I want to add to this answer, I had to use AppCompatImageButton instead of ImageButton.Concoct
@Concoct That probably because you the activity where the view was inflated didn't extend AppCompatActivityHominoid
@AndreRomano no, my subview was created inside a class which extends relative layout.Concoct
D
3

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)
Dative answered 13/12, 2018 at 0:43 Comment(1)
For ImageButtons, its workingRaptorial
S
1

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)
Scornful answered 4/5, 2020 at 20:0 Comment(0)
W
0

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.

Winfrid answered 8/6, 2018 at 17:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.