【发布时间】:2016-07-05 21:13:22
【问题描述】:
如何设置ImageButton的属性
app:srcCompat="@drawable/pic"
以编程方式?
类似于myImageButton.setBackgroundResource(R.drawable.eng2); 但属于app:srcCompat 的属性。
【问题讨论】:
标签: android android-appcompat android-imagebutton
如何设置ImageButton的属性
app:srcCompat="@drawable/pic"
以编程方式?
类似于myImageButton.setBackgroundResource(R.drawable.eng2); 但属于app:srcCompat 的属性。
【问题讨论】:
标签: android android-appcompat android-imagebutton
你需要使用setImageResource()方法。
imageButton.setImageResource(R.drawable.eng2);
【讨论】:
首先,确保您处理的是AppCompatImageView,而不是普通的ImageView:
AppCompatImageView iv = (AppCompatImageView)findViewById(....);
然后你可以这样做:
iv.setImageResource(R.drawable.pic);
查看其他公共方法in docs。
【讨论】:
AppCompatImageButton 而不是ImageButton。
使用setImageResource() 应该以向后兼容的方式获取其资源,而无需任何进一步的努力。
但是,如果您使用setImageDrawable(),则 ImageView/ImageButton 不会帮助任何向后兼容,并且由您来提供向后兼容的可绘制对象,这对于例如。如果使用VectorDrawables。以下将以这种方式加载和设置可绘制对象:
val drawable = AppCompatResources.getDrawable(context, resourceId)
image.setImageDrawable(drawable)
【讨论】:
我猜其他方法已经过时,在写这篇文章时不起作用,
iv_yourImageView.setImageDrawable(getResources().getDrawable(R.drawable.your_drawable));
这会起作用。
【讨论】:
没有,提供的解决方案对我有用。我使用的是 ImageView。最后,我发现使用setBackgroundResource() 对我有用。
view.setBackgroundResource(R.drawable.ic_star_black_18dp)
【讨论】: