Подтвердить что ты не робот

Picasso + convertView: что я делаю неправильно здесь?

Это мой getView().

Я, очевидно, делаю что-то не так, потому что элемент FIRST моего списка всегда не показывает изображение.

Проблема здесь в the convertview, потому что, если я не перерабатываю ее, проблем нет.

Пожалуйста, что я делаю неправильно?

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if(convertView==null) //IF I DELETE THIS IF EVERYTHING OK!!!
    convertView = inflater.inflate(R.layout.square, null);
    ImageView image = (ImageView) convertView.findViewById(R.id.background_image);
    if (data.get(position).isFollowed()) {
        int approprieteimage = getApproppreiateImage(data.get(position));
        Picasso.with(context).load(approprieteimage).centerCrop().error(R.drawable.no_image_available).transform(new TealTransformation(context)).fit().into(image);
    } else {
        int approprieteimage = getApproppreiateImage(data.get(position));
        Picasso.with(context).load(approprieteimage).centerCrop().error(R.drawable.no_image_available).fit().into(image);

    }
    AbsListView.LayoutParams layoutParams = new AbsListView.LayoutParams(width / 2, width / 2);
    convertView.setLayoutParams(layoutParams);
    return convertView;
}
4b9b3361

Ответ 1

Привет, Лиза Энн, пожалуйста, попробуйте это

ViewHolder h; //declare viewholder global

Получите просмотр с помощью зрителя

@Override
public View getView(int position, View convertView, ViewGroup parent) {

        if (convertView == null) {
            convertView = inflater.inflate(R.layout.square, parent, false);
            h = new ViewHolder();
            h.image = (ImageView) convertView.findViewById(R.id.background_image);
            convertView.setTag(h);
        }else{
            h = (ViewHolder)convertView.getTag();
        }
        //display in log and check if the the url of image is here and live.
        Log.e("checking","image file name"+data.get(position))
    if (data.get(position).isFollowed()) {
        int approprieteimage = getApproppreiateImage(data.get(position));
        Picasso.with(context).load(approprieteimage).centerCrop().error(R.drawable.no_image_available).transform(new TealTransformation(context)).fit().into(h.image);
    } else {
        int approprieteimage = getApproppreiateImage(data.get(position));
        Picasso.with(context).load(approprieteimage).centerCrop().error(R.drawable.no_image_available).fit().into(h.image);

    }
    AbsListView.LayoutParams layoutParams = new AbsListView.LayoutParams(width / 2, width / 2);
    convertView.setLayoutParams(layoutParams);

    return convertView;
}

Класс владельца

static class ViewHolder {
     ImageView  image;
  }

Ваш код может часто вызвать findViewById() во время прокрутки ListView, что может замедлить производительность. Даже когда адаптер возвращает завышенный вид для повторного использования, вам все равно нужно искать элементы и обновлять их. Способ многократного использования findViewById() заключается в использовании шаблона дизайна "держатель вида".

Объект ViewHolder хранит каждый из представлений компонентов внутри поля тега макета, поэтому вы можете сразу же получить к ним доступ, не пересматривая их повторно.

View holder - очень полезная техника, особенно при отображении изображений. Документация разработчика Android

после этого, пожалуйста, покажите мне свою ошибку в журнале.

Ответ 2

Почему бы вам просто не использовать шаблон держателя в вашем адаптере?

if (convertView == null) {
   convertView = inflater.inflate(R.layout.square, null, false);
   holder = new Holder(convertView);
   convertView.setTag(holder);
}
else {
   holder = (Holder) convertView.getTag();
}

Создайте свой держатель таким образом (замените его своими представлениями)

public static class Holder {
    private View row;
    private TextView title;

    public Holder(View row) {
       this.row = row;
    }

    public TextView getTitle() {
       if (title == null) {
          title = (TextView) row.findViewById(R.id.title);
       }
       return title;
    }
 }

Вы должны быть в порядке.

Ответ 3

Как я нашел в этой ссылке: проблема с picasso При повторной обработке представления вы должны вызвать cancelRequest перед загрузкой нового запроса. Поэтому код должен быть:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if(convertView==null) //IF I DELETE THIS IF EVERYTHING OK!!!
    convertView = inflater.inflate(R.layout.square, null);
    ImageView image = (ImageView) convertView.findViewById(R.id.background_image);
    Picasso.with(context).cancelRequest(image); // cancel old request
    if (data.get(position).isFollowed()) {
        int approprieteimage = getApproppreiateImage(data.get(position));
        Picasso.with(context).load(approprieteimage).centerCrop().error(R.drawable.no_image_available).transform(new TealTransformation(context)).fit().into(image);
    } else {
        int approprieteimage = getApproppreiateImage(data.get(position));
        Picasso.with(context).load(approprieteimage).centerCrop().error(R.drawable.no_image_available).fit().into(image);

    }
    AbsListView.LayoutParams layoutParams = new AbsListView.LayoutParams(width / 2, width / 2);
    convertView.setLayoutParams(layoutParams);
    return convertView;
}

Ответ 4

convertView = inflater.inflate(R.layout.square, parent, false);

Передайте parentView в ваш конвертированный файл.

Ответ 5

    try this one:
    It is working smoothly for me:

    @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.row_events, null);
                holder = new ViewHolder();
                holder.txtdName = (TextView) convertView
                        .findViewById(R.id.txtTitle);
                holder.txtdate = (TextView) convertView.findViewById(R.id.txtDate);

                holder.txtSubTitle = (TextView) convertView
                        .findViewById(R.id.txtSubtitle);
                holder.imgEvent = (ImageView) convertView
                        .findViewById(R.id.imgEvents);
                holder.imgArrow = (ImageView) convertView
                        .findViewById(R.id.imgArrow);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            try {
                holder.txtdName.setText(listd.get(position).getName());
                holder.txtdate.setText(Constants.dateFormat(listd.get(position)
                        .getStart_date()));
                holder.txtSubTitle.setText(listd.get(position).getDescription());
                holder.txtSubTitle.setTextColor(Color.GRAY);
                String imgUrl = listd.get(position).getImageUrl();
                // imageLoader.displayImage(imgUrl, holder.imgEvent, options);
                Picasso.with(context).load(imgUrl).into(holder.imgEvent);

return convertView;

Ответ 6

Попробуйте

convertView = inflater.inflate(R.layout.square, parent, false);