2011-06-13 109 views
2

我有一個存在一些圖像的URL。我想從該URL中檢索所有圖像,並在GridView中顯示這​​些圖像。現在,當我點擊網格視圖中的任何拇指預覽時,它應該放大或加載到全屏。從URL下載圖像並將其顯示在GridView中

把花絮更好地理解你將如何從一個鏈接,我相信這是有點難下載所有圖像的方式enter image description here

+1

你到底需要什麼幫助?製作gridview?加載圖像?加載圖像時禁止鎖定UI?顯示詳細圖像? – 2011-06-13 04:26:46

回答

5

首先要弄清楚。

然後把所有的鏈接位置放到一個字符串數組中。現在使用下面的代碼來下載圖像。

public Drawable LoadImage(String url) { 

    Drawable d; 
    try { 
     InputStream is = (InputStream) new URL(url).getContent(); 
     d = Drawable.createFromStream(is, "src name"); 
     return d; 
    } catch (NullPointerException e) { 
     d = getResources().getDrawable(R.drawable.icon); 
     return d; 
    } catch (Exception e) { 
     d = getResources().getDrawable(R.drawable.icon); 
     return d; 
    } 
} 

獲取已存儲鏈接位置的字符串數組的長度。在for循環中嘗試執行上面的代碼。這將返回一個可繪製的對象,您可以將其轉換爲資源或位圖並將其添加到GridView。

+0

您應該使用後臺線程進行連接。否則,您的程序將在大約5秒後阻止並顯示「應用程序未響應」對話框。 – 2011-06-13 06:11:52

+0

如果Android SDK版本<2.2,在2.2之前,此解決方案將失敗,它應使用httpconnection。 – Cheung 2012-07-12 15:53:57

6

您可以嘗試下面的代碼。延遲加載圖像是加載圖像的一個很好的解決方案,您可以嘗試從以下鏈接進行延遲加載:Lazy load of images in ListView。在這一點,他們已經用在佈局一個ListView,因此圖像和相應的文字顯示爲列表項,您可以在ListView控件更改爲一個GridView是這樣的:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"> 
    <GridView 
     android:id="@+id/gridv" 
     android:layout_width="wrap_content" 
     android:layout_height="fill_parent" 
     android:numColumns="auto_fit" 
     android:verticalSpacing="10dp" 
     android:horizontalSpacing="10dp" 
     android:columnWidth="90dp" 
     android:stretchMode="columnWidth" 
     android:gravity="center"/> 
    <Button 
     android:id="@+id/button1" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:text="Clear Cache"/> 
</LinearLayout> 

我認爲這將解決這一問題。

相關問題