[英]Android - Problem getResources() and getPackageName()
I try to use setImageResources()
with a way to set a R.drawable.我尝试使用
setImageResources()
来设置 R.drawable。 variable_image_file . variable_image_file 。 I have no idea how to do it, so I searched a little and i found this on many forums:
我不知道怎么做,所以我搜索了一下,我在很多论坛上都找到了这个:
int resID = getResources().getIdentifier(character.getBmppath(), "drawable", getPackageName());
holder.pictureView.setImageResource(resID);
But here is my problem, Android Studio seems to not recognize getResources()
and getPackageName()
:但这是我的问题,Android Studio 似乎无法识别
getResources()
和getPackageName()
:
(in this code, 'domas.png' is stored in the drawable folder) (在此代码中,'domas.png' 存储在 drawable 文件夹中)
I don't find a solution online, can you please help to figure this out ?网上没找到解决办法,能帮忙解决一下吗?
Pass a Context
to your class and then use getResources
on it.将
Context
传递给您的类,然后在其上使用getResources
。
context.getResources().getIdentifier("domas", "drawable", context.getPackageName());
I would suggest you setting image this way我建议你这样设置图像
holder.pictureView.setImageDrawable(
ContextCompat.getDrawable(
context,
R.drawable.domas
)
)
如果您的适配器中没有上下文,请尝试此操作。
int resId =holder.firstNameView.getContext().getResources().getIdentifier("domas", "drawable", holder.firstNameView.getContext().getPackageName());
If it is in your drawable
folder, you don't need to do anything fancy, this should work after providing a Context
(I assume you can easily convert the below to Java from Kotlin):如果它在你的
drawable
文件夹中,你不需要做任何花哨的事情,这应该在提供Context
之后工作(我假设你可以轻松地将下面的内容从 Kotlin 转换为 Java):
context?.let {
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.M) {
AppCompatResources.getDrawable(it, R.drawable.domas)
} else {
it.resources.getDrawable(R.drawable.domas, null)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.