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

时间:2016-07-05 21:13:23

标签: android android-appcompat android-imagebutton

如何设置

ImageButton属性
app:srcCompat="@drawable/pic"

编程?

myImageButton.setBackgroundResource(R.drawable.eng2);之类的内容,但app:srcCompat的属性。

5 个答案:

答案 0 :(得分:101)

您需要使用setImageResource()方法。

imageButton.setImageResource(R.drawable.eng2);

答案 1 :(得分:19)

首先,确保您正在处理[super prepareForReuse];,而不是“正常”AppCompatImageView

ImageView

然后你可以使用

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

请参阅其他公开方法in docs

答案 2 :(得分:0)

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

但是,如果您使用的是setImageDrawable(),则ImageView / ImageButton将无助于任何向后兼容,由您来提供向后兼容的drawable,例如,这很重要。如果使用VectorDrawables。下面将以这种方式加载和设置一个drawable:

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

答案 3 :(得分:0)

没有一个提供的解决方案对我有用。我正在使用ImageView。最终,我发现使用setBackgroundResource()对我有效。

view.setBackgroundResource(R.drawable.ic_star_black_18dp)

答案 4 :(得分:-1)

我猜其他方法已经过时,在撰写本文时也不会有效,

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

这样可行。