Как я могу добавить изображение в RecyclerView в AdapterClass? - PullRequest
0 голосов
/ 13 сентября 2018

Вот класс компонента продукта введите описание изображения здесь

Итак, мое представление Recycle работает, но эта строка кода не работает. Это из моего класса адаптера.

holder.imageView.setImageDrawable(mCtx.getResources().getDrawable(product.getImage()));

КЛАСС

@NonNull
@Override
public productViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
    LayoutInflater inflater = LayoutInflater.from(mCtx);
    View view = inflater.inflate(R.layout.list_layout,null);
    productViewHolder holder = new productViewHolder(view);
    return holder;
    //  return new productViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull productViewHolder holder, int position) {

    Product product = productList.get(position);
    holder.textViewTitle.setText(product.getTitle());
    holder.textViewDescription.setText(product.getShort_description());
    holder.textViewRating.setText(String.valueOf(product.getRating()));
    holder.textViewPrice.setText(String.valueOf(product.getPrice()));

//    holder.imageView.setImageDrawable(mCtx.getResources().getDrawable(product.getImage()));

}

@Override
public int getItemCount() {
    //returns number of elements within the list
    return productList.size();
}

class productViewHolder extends RecyclerView.ViewHolder{

    ImageView imageView;
    TextView textViewTitle, textViewDescription, textViewRating, textViewPrice;


    public productViewHolder(@NonNull View itemView) {
        super(itemView);

        imageView = itemView.findViewById(R.id.imageView);
        textViewTitle = itemView.findViewById(R.id.textViewTitle);
        textViewDescription = itemView.findViewById(R.id.textViewShortDesc);
        textViewRating = itemView.findViewById(R.id.textViewRating);
        textViewPrice = itemView.findViewById(R.id.textViewPrice);
    }

Ответы [ 7 ]

0 голосов
/ 13 сентября 2018
// Object class for Product

class Product{

        public Product(String title, String short_description, double rating, double price, int image) {
            this.title = title;
            this.short_description = short_description;
            this.rating = rating;
            this.price = price;
            this.image = image;
        }

        String title;
        String short_description;
        double rating;
        double price;
        int image;
    }


    //Array List of products
    List<Product> productList = new ArrayList<>();
          productList.add(new Product("Title1", "Short Description1", 4, 50, R.drawable.ic_thumb_down));
        productList.add(new Product("Title2", "Short Description2", 3, 100, R.drawable.ic_thumb_down));
        productList.add(new Product("Title3", "Short Description3", 4, 150, R.drawable.ic_thumb_down));




    //Adapter

        public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ImageViewHolder>{

            List<Integer> resourceList;

            public ImageAdapter(List<Integer> resourceList) {
                this.resourceList = resourceList;
            }

            @NonNull
            @Override
            public ImageViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
                return new ImageViewHolder(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_image, viewGroup, false));
            }

            @Override
            public void onBindViewHolder(@NonNull ImageViewHolder imageViewHolder, int i) {


              Product product = productList.get(i);
              imageViewHolder.imageView.setImageResource(product.image);
              // Here you can also use other field like title, description, etc... 

            }

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

            class ImageViewHolder extends RecyclerView.ViewHolder{

                ImageView imageView;

                public ImageViewHolder(@NonNull View itemView) {
                    super(itemView);
                    imageView = itemView.findViewById(R.id.imageView3);
                }
            }

        }
0 голосов
/ 13 сентября 2018

попробуйте использовать:

holder.imageView.setImageDrawable(ContextCompact.getDrawable(ctxt, R.drawable.YOUR_RESOURCE_IMAGE));

, если ваш product.getimage () возвращает идентификатор ресурса R.drwable.YOUR_RESOURCE_IMAGE попробуйте использовать:

  holder.imageView.setImageDrawable(ContextCompact.getDrawable(ctxt, product.getimage()));
0 голосов
/ 13 сентября 2018

При чтении комментариев выглядит, как будто ваш объект продукта хранит изображение в виде строки.Метод getImage () должен возвращать int.

Объявите изображение (с некоторым изображением по умолчанию) в Product следующим образом:

private int image = R.drawable.default_image;

И получатель будет выглядеть следующим образом

public int getImage() {
  return image;
}
0 голосов
/ 13 сентября 2018

Есть метод, который я использую для загрузки прорисовываемых файлов, это вектор isset

 public static BitmapDescriptor getBitmapFromVector(@NonNull Context context,
                                                   @DrawableRes int vectorResourceId,
                                                   @ColorInt int tintColor) {

    Drawable vectorDrawable = ResourcesCompat.getDrawable(
            context.getResources(), vectorResourceId, null);
    if (vectorDrawable == null) {
        String TAG = "tag";
        Log.e(TAG, "Requested vector resource was not found");
        return BitmapDescriptorFactory.defaultMarker();
    }
    Bitmap bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(),
            vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    vectorDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    DrawableCompat.setTint(vectorDrawable, tintColor);
    vectorDrawable.draw(canvas);
    return BitmapDescriptorFactory.fromBitmap(bitmap);
}

после этого остается только imageview.setImageBitmap (Bitmapdescriptor (параметры);

0 голосов
/ 13 сентября 2018

Я думаю, что вы получите строку вашего продукта, вы должны попытаться преобразовать эту estring в Uri или растровое изображение, чтобы при создании набора в просмотре изображений вы могли показать, что это очень поможет, если вы покажете свой продукткласс, чтобы узнать, какой тип значения возвращает product.getimage ();Uri.parse(product.getImage());

0 голосов
/ 13 сентября 2018

Попробуйте:

если вы получаете данные формы API, установите изображение следующим образом

 RequestOptions options = new RequestOptions()
            .centerCrop()
            .placeholder(R.drawable.avatar1)
            .error(R.drawable.avatar1)
            .diskCacheStrategy(DiskCacheStrategy.ALL)
            .priority(Priority.HIGH)
            .dontAnimate()
            .dontTransform();

 Glide.with(context)
            .load(UpcomingHistoryList.get(position).getPhotoUrl())
            .apply(options)
            .into(holder.img);

вы можете использовать glide и picasso

, если вы получаете рисованную форму изображения, установите изображение следующим образом

  ImageView imageView = (ImageView) findViewById(R.id.image);
  imageView.setImageResource(R.drawable.hello);
0 голосов
/ 13 сентября 2018

Если ваше изображение в объекте продукта содержит ресурс изображения из вашего отрисовываемого пакета, вам нужно использовать

holder.imageView.setImageResource(product.getImage());
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...