自定义ListView android

时间:2016-01-13 13:37:03

标签: android listview android-custom-view

我正面临一个问题,也看到了这一点 this链接但没有帮助。

项目是{a.b,c,d,e,f,g},但显示{a,b,c,d,a,b,c,d}。

@Override
public View getView(int i, View view, ViewGroup parent) {
    final ImageHolder imageHolder = new ImageHolder();
    ViewHolder viewHolder = new ViewHolder();

    if (view == null){
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(android.app.Service.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(R.layout.feeds_list_facebook, null);
        //viewHolder = new ViewHolder();
        viewHolder.message = (TextView) view.findViewById(R.id.message);
        viewHolder.imageView = (ImageView) view.findViewById(R.id.image);
        Event event = events.get(i);
        Log.i("SIZE",events.size() + "");
        Log.i("MESSAGE", event.getMessage());
        Log.i("IMAGE__URL", event.getPicture());
        viewHolder.message.setText("");
        viewHolder.imageView.setImageBitmap(null);

        viewHolder.message.setText(event.getMessage());

        mImageLoader.DisplayImage(event.getPicture(), viewHolder.imageView);
        view.setTag(viewHolder);

    }
    viewHolder = (ViewHolder) view.getTag();

    return view;
}

和我的viewHolder

class ViewHolder {
    TextView message;
    ImageView imageView;
}

1 个答案:

答案 0 :(得分:1)

在行return view;

之前移动这些行
    viewHolder.message = (TextView) view.findViewById(R.id.message);
    viewHolder.imageView = (ImageView) view.findViewById(R.id.image);
    Event event = events.get(i);
    Log.i("SIZE",events.size() + "");
    Log.i("MESSAGE", event.getMessage());
    Log.i("IMAGE__URL", event.getPicture());
    viewHolder.message.setText("");
    viewHolder.imageView.setImageBitmap(null);
    viewHolder.message.setText(event.getMessage());

您正在重复使用该视图,这很好,因为现在您只在没有可重复使用的视图时对视图进行充气,所以基本上在开头填充列表时。

但是,当您进行充气时,您也只是在列表项上设置自定义数据,这并不好。您始终可以设置自定义数据,无论是可重用视图还是新视图。