我是 Android 开发的新手。我正在尝试使用 LazyAdapter 将多个图像加载到 ListView。我将图像存储在可绘制文件夹中。我有四个图像: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;
}
}
这是我的懒惰适配器:
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 中的所有图像,而不仅仅是其中两个)?