从适配器中的字符串获取Android资源ID

时间:2017-03-24 23:06:05

标签: android json android-resources

我试图获取Android资源ID并将ImageView src设置为来自JSON数组的特定ID。

我使用以下代码

String str = mDataset.get(position).icon_res.substring(0, mDataset.get(position).icon_res.lastIndexOf('.'));
        int res = Resources.getSystem().getIdentifier("ic_" + str, "drawable", this.getClass().getPackage().getName());
        if(res == 0)
        {
            Log.d("is null", "null");
            Log.d("string = ", "ic_" + str);
            Log.d("package", this.getClass().getPackage().getName());
        }

但是由于某种原因,它将res int检测为0.包名称似乎正确,字符串是正确的但由于某种原因它没有找到正确的可绘制资源。我在这里做错了什么?

编辑:

Full adapter code

package com.xyz

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.media.Image;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Kreso on 23.3.2017..
 */

public class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.ViewHolder>{


    private List<Category> mDataset;
    private Context context;

    public CategoryAdapter(List<Category> categoriesList) {
        mDataset = categoriesList;
    }


    // Provide a reference to the views for each data item
    // Complex data items may need more than one view per item, and
    // you provide access to all the views for a data item in a view holder
    public class ViewHolder extends RecyclerView.ViewHolder {
        // each data item is just a string in this case
        public TextView txtHeader;
        public ConstraintLayout holderLayout;
        public ImageView icon;

        public ViewHolder(View v) {
            super(v);
            txtHeader = (TextView) v.findViewById(R.id.firstLine);
            holderLayout = (ConstraintLayout) v.findViewById(R.id.itemHolder);
            icon = (ImageView) v.findViewById(R.id.icon);
            context = v.getContext();
        }
    }

    /*public void add(int position, String item) {
        mDataset.add(position, item);
        notifyItemInserted(position);
    }*/

    public void remove(int position) {
        mDataset.remove(position);
        notifyItemRemoved(position);
        notifyItemRangeChanged(position, mDataset.size());
    }

    // Provide a suitable constructor (depends on the kind of dataset)
   /* public CategoryAdapter(ArrayList<String> myDataset) {
        mDataset = myDataset;
    }*/

    // Create new views (invoked by the layout manager)
    @Override
    public CategoryAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
                                                   int viewType) {
        // create a new view
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_item_row, parent, false);
        // set the view's size, margins, paddings and layout parameters
        ViewHolder vh = new ViewHolder(v);
        return vh;
    }

    // Replace the contents of a view (invoked by the layout manager)
    @Override
    public void onBindViewHolder(ViewHolder holder, final int position) {
        // - get element from your dataset at this position
        // - replace the contents of the view with that element
    final String name = mDataset.get(position).name;
        holder.txtHeader.setText(mDataset.get(position).name);
        //holder.icon.setImageResource(R.drawable.ic_beer);
        String str = mDataset.get(position).icon_res.substring(0, mDataset.get(position).icon_res.lastIndexOf('.'));
        int res = context.getResources().getSystem().getIdentifier("ic_" + str, "drawable", context.getPackageName());
        if(res == 0)
        {
            Log.d("is null", "null");
            Log.d("string = ", "ic_" + str);
            Log.d("package", this.getClass().getPackage().getName());
        }

        holder.icon.setImageResource(res);
        holder.holderLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            remove(position);
        }
    });

}

    // Return the size of your dataset (invoked by the layout manager)
    @Override
    public int getItemCount() {
        return mDataset.size();
    }

}

2 个答案:

答案 0 :(得分:2)

使用此代码从Resources获取图像:

int res = context.getResources().getIdentifier("ic_" + str, "drawable", context.getPackageName());

答案 1 :(得分:0)

我设法通过使用稍微不同的方法来解决它

// Remove file extension
        String str = mDataset.get(position).icon_res.substring(0, mDataset.get(position).icon_res.lastIndexOf('.'));
        // Replace - with underscore _
        str = str.replace("-", "_");

        int res = 0;
        // Try to find the resource with that name (icons in drawable folder)
        try {
            res = R.drawable.class.getField("ic_" + str).getInt(null);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            // if no icon is found
            holder.icon.setImageResource(R.drawable.ic_coffee);
        }
        // Set icon resource
        holder.icon.setImageResource(res);