簡體   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