[英]recycler view with different images from serverdata
我在服務器請求中從recyclerview中獲取了一個字符串,該字符串為PDF Word或圖像。 現在,我想在每個字符串的recyclerviewitem中顯示不同的圖像。 這是我的代碼:
@Override
public void onBindViewHolder(ScriptViewHolder holder, int position) {
final ItemObject currentScript = scriptObjects.get(position);
holder.scriptName.setText(currentScript.getScriptName());
holder.scriptDate.setText(currentScript.getScriptDate());
holder.scriptUser.setText(currentScript.getScriptUser());
String whichformat = currentScript.getScriptFormat();
switch (whichformat) {
case "PDF":
imagename = "ic_picture_as_pdf_black_24dp.png";
case "Word":
imagename = "ic_insert_drive_file_black_24dp.png";
case "Image":
imagename = "ic_photo_library_black_24dp.png";
}
int resourceId = context.getResources().getIdentifier(imagename, null , null );
holder.scriptIcon.setImageDrawable(ContextCompat.getDrawable(context, resourceId));
我收到一個錯誤:
致命異常:主進程:com.ndlp.socialstudy,PID:3481 android.content.res.Resources $ NotFoundException:資源ID#0x0
它指向我的回收站適配器類,並指向:
holder.scriptIcon.setImageDrawable(ContextCompat.getDrawable(context, resourceId));
你知道我做錯了嗎? 像開關中的圖像名稱是正確的,我已經檢查了它們。
我也已經嘗試過:
int resourceId = context.getResources().getIdentifier(imageName, "drawable" , context.getPackageName() );
親切的問候
hellownero
您應該通過以下方式獲取resourceId:
switch (whichformat) {
case "PDF":
imagename = "ic_picture_as_pdf_black_24dp";
case "Word":
imagename = "ic_insert_drive_file_black_24dp";
case "Image":
imagename = "ic_photo_library_black_24dp";
}
int resourceId = context.getResources().getIdentifier(imagename, "drawable", context.getPackageName());
之所以出現此異常,是因為您將null
作為defType
和packageName
傳遞了。 您無需傳遞文件類型作為圖像名稱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.