我是Android開發新手。我試圖使用LazyAdapter將幾個圖像加載到ListView。我將圖像存儲在可繪製文件夾中。我有四個圖像:image1.jpg,image2.jpg,image3.jpg和image4.jpg。但在ListView中,它們按以下順序排列:image1.jpg,image2.jpg,image1.jpg,image2.jpg。我試圖改變方法getItemId()和getItem(),但它沒有幫助加載ListView中的所有圖像,我仍然只看到其中兩個。我無法理解我做錯了什麼。請參考我的代碼Android。 LazyAdapter加載圖像不正確
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中顯示所有圖像,而不僅是其中的兩個)?
移動線'imageView.setImageResource(imagePaths [位置]);的'外'if'子句將圖像正確設置到行中。 – Luksprog