我正在将Android Image Slider与Glide一起使用,制作图像轮播,并且尝试测试是否可以在将URL添加到适配器时实现ArrayList,但是当我将URL添加到ArrayList时,其他数据不显示,仅显示数组中的最后一个。看来我无法将URL存储到SliderItem的值。为什么其他图像没有显示在Slider上?
我使用了Android Image Slider的默认适配器:SliderAdapterExample.java。
Home.java
SliderItem sliderItem = new SliderItem();
ArrayList<String> urls = new ArrayList<>();
urls.add("https://lh3.googleusercontent.com/proxy/xdswuBCXXazoCcJ9t9c0y1DqcEU8Ixog4B6Q2MJaE3Iy84VV7g8GOS8C5b9JgTlFRGg23q_Rjw61Tr68A0mJ9ZnoqJdxPLLvCCZteQBOcaW61KEOQA");
urls.add("https://www.luxuryproperty.com/uploads/images/6-bedroom-villa-for-sale-dubai_hills_mansions-LP0542-9ea75fa49452780.jpg");
urls.add("https://www.luxuryproperty.com/uploads/images/7-bedroom-villa-for-sale-dubai_hills_mansions-LP0514-261aafdf24310c00.jpg");
for(int i = 0; i < urls.size(); i++){
sliderItem.setDescription("Slider Item Added Manually");
sliderItem.setImageUrl(urls.get(i));
}
adapter.addItem(sliderItem);
SliderItem.java
public class SliderItem {
private String description;
private String imageUrl;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}}
这就是我现在得到的。仅最后一个链接有效。参见下图:
答案 0 :(得分:1)
您需要在adapter.addItem(sliderItem);
循环内移动for
。
SliderItem sliderItem = new SliderItem();
ArrayList<String> urls = new ArrayList<>();
urls.add("https://lh3.googleusercontent.com/proxy/xdswuBCXXazoCcJ9t9c0y1DqcEU8Ixog4B6Q2MJaE3Iy84VV7g8GOS8C5b9JgTlFRGg23q_Rjw61Tr68A0mJ9ZnoqJdxPLLvCCZteQBOcaW61KEOQA");
urls.add("https://www.luxuryproperty.com/uploads/images/6-bedroom-villa-for-sale-dubai_hills_mansions-LP0542-9ea75fa49452780.jpg");
urls.add("https://www.luxuryproperty.com/uploads/images/7-bedroom-villa-for-sale-dubai_hills_mansions-LP0514-261aafdf24310c00.jpg");
for(int i = 0; i < urls.size(); i++){
sliderItem.setDescription("Slider Item Added Manually");
sliderItem.setImageUrl(urls.get(i));
// here
adapter.addItem(sliderItem);
}
或
ArrayList<String> urls = new ArrayList<>();
urls.add("https://lh3.googleusercontent.com/proxy/xdswuBCXXazoCcJ9t9c0y1DqcEU8Ixog4B6Q2MJaE3Iy84VV7g8GOS8C5b9JgTlFRGg23q_Rjw61Tr68A0mJ9ZnoqJdxPLLvCCZteQBOcaW61KEOQA");
urls.add("https://www.luxuryproperty.com/uploads/images/6-bedroom-villa-for-sale-dubai_hills_mansions-LP0542-9ea75fa49452780.jpg");
urls.add("https://www.luxuryproperty.com/uploads/images/7-bedroom-villa-for-sale-dubai_hills_mansions-LP0514-261aafdf24310c00.jpg");
for(int i = 0; i < urls.size(); i++){
SliderItem sliderItem = new SliderItem();
sliderItem.setDescription("Slider Item Added Manually");
sliderItem.setImageUrl(urls.get(i));
// here
adapter.addItem(sliderItem);
}
根据您的代码,您有3个网址,因此需要3个SliderItem
。但是,如果将adapter.addItem(sliderItem);
放在for
循环之外,则只能获得最后一个SliderItem
此外,每次将项目添加到适配器时,都需要将adapter.notifyDataSetChanged()
设置为addItem()
。
如果我的解决方案有任何问题,请让我知道。