2016-06-29 102 views
0

我在我的應用程序中使用AndroidImageSlider庫作爲圖像滑塊。我加載使用Hashmap像這樣的圖片:動態圖像滑塊Android

HashMap<String,String> url_maps = new HashMap<String, String>(); 
url_maps.put("Image 1", "http://example.com/./project_image/example.jpg"); 
url_maps.put("Image 2", "http://example.com/./project_image/example.jpg"); 
url_maps.put("Image 3", "http://example.com/./project_image/example.jpg"); 


for(String name : url_maps.keySet()){ 
    TextSliderView textSliderView = new TextSliderView(this); 
    // initialize a SliderLayout 
    textSliderView 
      .description(name) 
      .image(url_maps.get(name)) 
      .setScaleType(BaseSliderView.ScaleType.Fit); 

    //add your extra information 
    textSliderView.bundle(new Bundle()); 
    textSliderView.getBundle() 
      .putString("extra",name); 

    mDemoSlider.addSlider(textSliderView); 
} 

注:我設置HashMap的爲每個圖像描述的關鍵。

如何使此滑塊動態?

我想從一個JSON提要看起來像這樣動態加載圖片:它採用了一塊HashMap

{ 
    "Images": [ 
    { 
     "title": "title", 
     "Image": "http://example.com/./project_image/example.jpg" 
    }, 
    { 
     "title": "Distribution", 
     "Image": "http://example.com/./project_image/example.jpg" 
    }, 
    { 
     "title": "Distribution", 
     "Image": "http://example.com/./project_image/example.jpg" 
    } 
    ] 
} 

能做些什麼或做我需要使用一個替代?如果是,請提出建議。或者我使用不同的圖書館?如果是,請給予參考。 謝謝。

回答

0

創建一個類來作爲你的數據

class ImageUrls{ 
    String imageTitle,imageUrl; 
    ImageUrls(String imageTitle, String imageUrl){ 
     this.imageTitle = imageTitle; 
     this.imageUrl = imageUrl; 
    } 
} 

現在結構做出ArrayList<ImageUrls> url_maps

ArrayList中

url_maps.add("Image 1", "http://example.com/./project_image/example.jpg"); 
    url_maps.add("Image 2", "http://example.com/./project_image/example.jpg"); 
    url_maps.add("Image 3", "http://example.com/./project_image/example.jpg"); 

添加數據,並將這些數據添加到您的ImageSlider

For(int count : ArrayList.size()){ 
    //here you can get your data from arraylist using 
    arraylist.get(postion).imageTitle 
    arraylist.get(postion).imageUrl 

    } 
+0

我不能使用哈希映射來做這個嗎? –

+0

這種方法在製作ImageSlider時適用於我,我認爲它也可以使用哈希映射,但從未嘗試過。 –

1

使用Gson

Gson gson = new Gson(); 
Type type= new TypeToken<List<ImageData>>(){}.getType(); 
List<ImageData> imageDataList = gson.fromJson(jsonString, type); 

其中jsonString是代表你的JSON數組的字符串

ImageData類是這樣的

public class ImageData { 
    String title; 
    String Image; 
    public ImageData(){}; 
} 

然後在列表上迭代如下

for(ImageData data : imageDataList){ 
    TextSliderView textSliderView = new TextSliderView(this); 
    // initialize a SliderLayout 
    textSliderView 
      .description(data.title) 
      .image(data.Image) 
      .setScaleType(BaseSliderView.ScaleType.Fit); 

    //add your extra information 
    textSliderView.bundle(new Bundle()); 
    textSliderView.getBundle() 
      .putString("extra",data.title); 

    mDemoSlider.addSlider(textSliderView); 
}