如何以编程方式设置 app 的 ImageButton 属性: srcCompat = “@draable/pic”?

如何设置的 ImageButton属性

app:srcCompat="@drawable/pic"

程序化?

类似 myImageButton.setBackgroundResource(R.drawable.eng2);的东西,但属于 app:srcCompat

51724 次浏览

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.

You need to use setImageResource() method.

imageButton.setImageResource(R.drawable.eng2);

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.

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)

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)