回收站视图与来自serverdata的不同图像

时间:2017-10-23 16:43:20

标签: android android-recyclerview switch-statement android-drawable recycler-adapter

我的Recyclerview中的一个项目的服务器请求中有一个字符串,它为我提供了PDF Word或Image。现在我想在我的recyclerviewitem中为每个String显示不同的图像。这是我的代码:

@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

它指向我的Recycler适配器类并且:

holder.scriptIcon.setImageDrawable(ContextCompat.getDrawable(context, resourceId));

你知道我做错了什么吗?像开关中的图像名是正确的我已经检查了它们。

我也试过了:

 int resourceId = context.getResources().getIdentifier(imageName, "drawable" , context.getPackageName() );

亲切的问候

hellownero

1 个答案:

答案 0 :(得分:0)

你应该用这种方式获得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作为defTypepackageName传递。您不需要将文件类型作为图像名称传递。