繁体   English   中英

Android - 问题 getResources() 和 getPackageName()

[英]Android - Problem getResources() and getPackageName()

我尝试使用setImageResources()来设置 R.drawable。 variable_image_file 我不知道怎么做,所以我搜索了一下,我在很多论坛上都找到了这个:

int resID = getResources().getIdentifier(character.getBmppath(), "drawable", getPackageName());
holder.pictureView.setImageResource(resID);

但这是我的问题,Android Studio 似乎无法识别getResources()getPackageName()

在此处输入图片说明

(在此代码中,'domas.png' 存储在 drawable 文件夹中)

网上没找到解决办法,能帮忙解决一下吗?

Context传递给您的类,然后在其上使用getResources

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文件夹中,你不需要做任何花哨的事情,这应该在提供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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM