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

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

如何设置ImageButton 属性 of

app:srcCompat="@drawable/pic"

以编程方式?

类似于 myImageButton.setBackgroundResource(R.drawable.eng2);app:srcCompat 的 属性。

首先,确保您处理的是 AppCompatImageView,而不是常规 ImageView:

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

然后你可以做:

iv.setImageResource(R.drawable.pic);

查看其他 public 方法 in docs

您需要使用setImageResource()方法。

imageButton.setImageResource(R.drawable.eng2);

我想其他方法已经过时并且在撰写本文时不起作用,

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

这会起作用。

使用 setImageResource() 应该以向后兼容的方式获取其资源,无需任何进一步的努力。

但是,如果您使用的是 setImageDrawable(),ImageView/ImageButton 将无助于任何向后兼容,您需要提供向后兼容的可绘制对象,这对于例如很重要。如果使用 VectorDrawables。以下将以这种方式加载和设置可绘制对象:

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

None,所提供的解决方案对我有用。我正在使用 ImageView。最后,我发现使用 setBackgroundResource() 对我有用。

view.setBackgroundResource(R.drawable.ic_star_black_18dp)