使用路径从可绘制的毕加索加载图像

问题描述

我想要做的是从 drawable 加载一些图像。事实上,我想加载像 R.drawable."string" 这样的图像,但不幸的是找不到将字符串放入其中的方法。此外,该字符串是从 MysqL 数据库加载的。

在这里你可以看到代码

public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ProductViewHolder> {

    private Context mContext;
    private ArrayList<Product> mProducts;
    private OnItemClickListener mListener;

    public interface OnItemClickListener {
        void onItemClick(int position);
    }

    public void setonItemClickListener(OnItemClickListener listener) {
        mListener = listener;
    }

    public ProductAdapter(Context context,ArrayList<Product> products) {
        mContext = context;
        mProducts = products;
    }

    @NonNull
    @Override
    public ProductViewHolder onCreateViewHolder(@NonNull ViewGroup parent,int viewType) {
        View v = LayoutInflater.from(mContext).inflate(R.layout.product,parent,false);
        return new ProductViewHolder(v);
    }

    @Override
    public void onBindViewHolder(@NonNull ProductViewHolder holder,int position) {
        Product currentProduct = mProducts.get(position);
        String name = currentProduct.getName();
        String photo = currentProduct.getPhoto();
        double price = currentProduct.getPrice();

        holder.textViewName.setText(name);
        holder.textViewPrice.setText(price + "€");

        int id = mContext.getResources().getIdentifier(photo,"drawable",mContext.getPackageName());



        Picasso.get().load(id).into(holder.imageView);
    }

    @Override
    public int getItemCount() {
        return mProducts.size();
    }

    public class ProductViewHolder extends RecyclerView.ViewHolder {

        public ImageView imageView;
        public TextView textViewName;
        public TextView textViewPrice;

        public ProductViewHolder(@NonNull View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.image_view);
            textViewName = itemView.findViewById(R.id.textViewName);
            textViewPrice = itemView.findViewById(R.id.textViewPrice);

            itemView.setonClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (mListener != null) {
                        int position = getAdapterPosition();
                        if (position != RecyclerView.NO_POSITION) {
                            mListener.onItemClick(position);
                        }
                    }
                }
            });

        }
    }
}

如您所见,我尝试了在谷歌搜索中发现的 int id = mContext.getResources().getIdentifier(photo,mContext.getPackageName());,但似乎不起作用...

非常感谢您能提供的任何帮助。

解决方法

我建议使用另一种方法而不是您需要使用的方法:您可以对从 MySQL 数据库返回的内容设置条件,并相应地返回 id (R.drawable.xx),如下所示:

int id;

if(photo.equals("foo")) {
    id = R.drawable.foo;

} else if(photo.equals("bla")) {
    id = R.drawable.bla;

} else {
    id = // default id
}

Picasso.get().load(id).into(holder.imageView);

这样,每个 drawable 在数据库中都有一个特定的映射。