Java Android-getResources()和getPackageName()问题
我尝试使用Java Android-getResources()和getPackageName()问题,java,android,android-studio,Java,Android,Android Studio,我尝试使用setImageResources()来设置R.drawable.variable\u image\u文件。 我不知道怎么做,所以我搜索了一下,在很多论坛上都找到了: int resID = getResources().getIdentifier(character.getBmppath(), "drawable", getPackageName()); holder.pictureView.setImageResource(resID); 但我的问题是,Android Studi
setImageResources()
来设置R.drawable.variable\u image\u文件。
我不知道怎么做,所以我搜索了一下,在很多论坛上都找到了:
int resID = getResources().getIdentifier(character.getBmppath(), "drawable", getPackageName());
holder.pictureView.setImageResource(resID);
但我的问题是,Android Studio似乎无法识别getResources()
和getPackageName()
:
(在此代码中,'domas.png'存储在drawable文件夹中)
我在网上找不到解决方案,你能帮我解决这个问题吗?将
上下文
传递给你的班级,然后使用获取资源
context.getResources().getIdentifier("domas", "drawable", context.getPackageName());
我建议你这样设置图像
holder.pictureView.setImageDrawable(
ContextCompat.getDrawable(
context,
R.drawable.domas
)
)
如果适配器中没有上下文,请尝试此操作
int resId =holder.firstNameView.getContext().getResources().getIdentifier("domas", "drawable", holder.firstNameView.getContext().getPackageName());
如果它在您的
drawable
文件夹中,您不需要做任何花哨的事情,这应该在提供上下文
(我假设您可以轻松地从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)
}