Android系统。 LazyAdapter正在加载图片不正确

时间:2015-09-06 09:46:27

标签: android listview android-lazyadapter

我是Android开发的新手。我正在尝试使用LazyAdapter将多个图像加载到ListView。我将图像存储在drawable文件夹中。我有四个图像:image1.jpg,image2.jpg,image3.jpg和image4.jpg。但是在ListView中,它们按以下顺序排列:image1.jpg,image2.jpg,image1.jpg,image2.jpg。我试图改变方法getItemId()和getItem(),但它没有帮助加载ListView中的所有图像,我仍然只看到其中两个。我无法理解我做错了什么。请参阅我的代码

public class MainActivityFragment extends Fragment {

CustomAdapter imagesAdapter;

public MainActivityFragment() {
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    int[] images = {R.drawable.image1,
            R.drawable.image2,
            R.drawable.image3,
            R.drawable.image4};

    imagesAdapter = new CustomAdapter(getActivity(), images);

    View rootView =  inflater.inflate(R.layout.fragment_main, container, false);
    ListView listView = (ListView) rootView.findViewById(R.id.listView);
    listView.setAdapter(imagesAdapter);

    return rootView;
}
}

这是我的LazyAdapter:

public class CustomAdapter extends BaseAdapter {

LayoutInflater inflater;
int[] imagePaths;

public CustomAdapter(Activity activity, int[] data) {
    imagePaths = data;
    inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

@Override
public int getCount() {
    return imagePaths.length;
}

@Override
public Object getItem(int position) {
    return position;
}

@Override
public long getItemId(int position) {
    return position;
}

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

    View view = convertView;

    if(view == null) {

        view = inflater.inflate(R.layout.list_view_item, parent, false);
        ImageView imageView = (ImageView) view.findViewById(R.id.imageView);
        imageView.setImageResource(imagePaths[position]);
    }

    return view;
}

}

请指教。如何使我的代码正常工作(即显示ListView中的所有图像,而不仅仅是其中两个)?

1 个答案:

答案 0 :(得分:0)

您收到此行为是因为listview的设计方式是重用项目。

@Override

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

View view = convertView;

if(view == null) {

    view = inflater.inflate(R.layout.list_view_item, parent, false);
    ImageView imageView = (ImageView) view.findViewById(R.id.imageView);
    imageView.setImageResource(imagePaths[position]);
}

return view;

}

此代码解释了这一点。只有在视图为null时才创建视图,否则它将重新使用已创建的视图。

在您的情况下,对于项目1和2,视图为null,因此适配器创建了新视图并正确设置了图像资源,但是当您向下滚动到项目3和4时,适配器正在使用已创建的视图,因此它将显示以前的图像。正如LuksProg建议的那样,你需要在if子句之外移动setImageResource方法,这样即使它重用了视图,它也会用新的正确图像更新它。

@Override

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

View view = convertView;

if(view == null) {

    view = inflater.inflate(R.layout.list_view_item, parent, false);
    ImageView imageView = (ImageView) view.findViewById(R.id.imageView);
}

    imageView.setImageResource(imagePaths[position]);

return view;

}