Android GridView非同期ロード画像


ネット上の資源は一般的にListViewの非同期ロード画像であり、GirdViewの非同期ロード画像は比較的少なく、ListViewの非同期ロード画像のやり方を参考にGridViewの非同期ロード画像機能を作り出し、方法と思想は大きく異なり、本文はGridViewの非同期ロードメモリカードとネット画像をみんなに役に立つことを望んでいる.効果図は以下の通りです.
一、メインインタフェースコード:
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.widget.GridView;

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        GridView gridView=(GridView)findViewById(R.id.gridview);
        List<ImageAndText> list = new ArrayList<ImageAndText>();
        String[] paths=new String[15];
        for(int i=0;i<15;i++){
        	int index=i;
        	paths[i]="/sdcard/"+String.valueOf(index+1)+".jpg";//     SD   15   , :1.jpg
        }
        for(int i=0;i<15;i++){
        	list.add(new ImageAndText(paths[i], String.valueOf(i)));
        }
        gridView.setAdapter(new ImageAndTextListAdapter(this, list, gridView));
    }
}

二、以下のコードは非同期でピクチャを取得する主な方法であり、SoftReferenceはソフトリファレンスであり、システムが変数を回収するために、重複したURLが既存のリソースに直接戻り、コールバック関数を実現し、データを成功させた後、UIスレッドに更新するためである. 
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;

import android.R.drawable;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ImageView;

public class AsyncImageLoader {

     private HashMap<String, SoftReference<Drawable>> imageCache;
     public AsyncImageLoader() {
             imageCache = new HashMap<String, SoftReference<Drawable>>();
         }
      
     public Drawable loadDrawable(final String imageUrl, final ImageCallback imageCallback) {
             if (imageCache.containsKey(imageUrl)) {
                 SoftReference<Drawable> softReference = imageCache.get(imageUrl);
                 Drawable drawable = softReference.get();
                 if (drawable != null) {
                     return drawable;
                 }
             }
             final Handler handler = new Handler() {
                 public void handleMessage(Message message) {
                     imageCallback.imageLoaded((Drawable) message.obj, imageUrl);
                 }
             };
             new Thread() {
                 @Override
                 public void run() {
                     Drawable drawable = loadImageFromUrl(imageUrl);
                     imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
                     Message message = handler.obtainMessage(0, drawable);
                     handler.sendMessage(message);
                 }
             }.start();
             return null;
         }
       
    public static Drawable loadImageFromUrl(String url) {
//    	/**
//    	 *       
//    	 */
//            URL m;
//            InputStream i = null;
//            try {
//                m = new URL(url);
//                i = (InputStream) m.getContent();
//            } catch (MalformedURLException e1) {
//                e1.printStackTrace();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//            Drawable d = Drawable.createFromStream(i, "src");
    	
    	/**
    	 *        
    	 */
    	    Options options=new Options();
    	    options.inSampleSize=2;
    	    Bitmap bitmap=BitmapFactory.decodeFile(url, options);
    	    Drawable drawable=new BitmapDrawable(bitmap);
            return drawable;
        }
      
    public interface ImageCallback {
             public void imageLoaded(Drawable imageDrawable, String imageUrl);
             
         }
}

三、ImageAndTextListAdapterはListViewを実現するAdapterで、中にはimageViewというテクニックがある.setTag(imageUrl)、setTagはデータを格納します.これは、コールバック関数のときにlistviewが自分の対応するitemを更新することを保証するためです.
import java.util.List;

import cn.wangmeng.test.AsyncImageLoader.ImageCallback;

import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class ImageAndTextListAdapter extends ArrayAdapter<ImageAndText> {

        private GridView gridView;
        private AsyncImageLoader asyncImageLoader;
        public ImageAndTextListAdapter(Activity activity, List<ImageAndText> imageAndTexts, GridView gridView1) {
            super(activity, 0, imageAndTexts);
            this.gridView = gridView1;
            asyncImageLoader = new AsyncImageLoader();
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            Activity activity = (Activity) getContext();

            // Inflate the views from XML
            View rowView = convertView;
            ViewCache viewCache;
            if (rowView == null) {
                LayoutInflater inflater = activity.getLayoutInflater();
                rowView = inflater.inflate(R.layout.griditem, null);
                viewCache = new ViewCache(rowView);
                rowView.setTag(viewCache);
            } else {
                viewCache = (ViewCache) rowView.getTag();
            }
            ImageAndText imageAndText = getItem(position);

            // Load the image and set it on the ImageView
            String imageUrl = imageAndText.getImageUrl();
            ImageView imageView = viewCache.getImageView();
            imageView.setTag(imageUrl);
            Drawable cachedImage = asyncImageLoader.loadDrawable(imageUrl, new ImageCallback() {
                public void imageLoaded(Drawable imageDrawable, String imageUrl) {
                    ImageView imageViewByTag = (ImageView) gridView.findViewWithTag(imageUrl);
                    if (imageViewByTag != null) {
                        imageViewByTag.setImageDrawable(imageDrawable);
                    }
                }
            });
            if (cachedImage == null) {
                imageView.setImageResource(R.drawable.icon);
            }else{
                imageView.setImageDrawable(cachedImage);
            }
            // Set the text on the TextView
            TextView textView = viewCache.getTextView();
            textView.setText(imageAndText.getText());
            return rowView;
        }

}

四、二つの補助類:
public class ImageAndText {
	    private String imageUrl;
	    private String text;

	    public ImageAndText(String imageUrl, String text) {
	        this.imageUrl = imageUrl;
	        this.text = text;
	    }
	    public String getImageUrl() {
	        return imageUrl;
	    }
	    public String getText() {
	        return text;
	    }
}
public class ViewCache {

	    private View baseView;
	    private TextView textView;
	    private ImageView imageView;

	    public ViewCache(View baseView) {
	        this.baseView = baseView;
	    }

	    public TextView getTextView() {
	        if (textView == null) {
	            textView = (TextView) baseView.findViewById(R.id.text);
	        }
	        return textView;
	    }

	    public ImageView getImageView() {
	        if (imageView == null) {
	            imageView = (ImageView) baseView.findViewById(R.id.image);
	        }
	        return imageView;
	    }

}

五、Xmlプロファイル、griditemとmainを含む:
1griditem:
<?xml version="1.0" encoding="UTF-8"?>    
<RelativeLayout    
         xmlns:android="http://schemas.android.com/apk/res/android"  
         android:layout_height="100dip"    
         android:paddingBottom="4dip" android:layout_width="fill_parent">
         <ImageView 
               android:id="@+id/image"
               android:layout_height="80dip"
               android:layout_width="80dip"
               android:layout_centerHorizontal="true"
               android:scaleType="centerCrop">
         </ImageView>
         <TextView
               android:id="@+id/text"   
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:layout_below="@+id/image"
               android:layout_centerHorizontal="true"
               >
         </TextView>
</RelativeLayout>

2main: 
<div class="dp-highlighter bg_html"><div class="bar"><div class="tools"><b>[html]</b> <a href="#" class="ViewSource" title="view plain" onclick="dp.sh.Toolbar.Command('ViewSource',this);return false;">view plain</a><a href="#" class="CopyToClipboard" title="copy" onclick="dp.sh.Toolbar.Command('CopyToClipboard',this);return false;">copy</a><a href="#" class="PrintSource" title="print" onclick="dp.sh.Toolbar.Command('PrintSource',this);return false;">print</a><a href="#" class="About" title="?" onclick="dp.sh.Toolbar.Command('About',this);return false;">?</a><div style="position: absolute; left: 0px; top: 0px; width: 0px; height: 0px; z-index: 99;"><embed id="ZeroClipboardMovie_10" src="http://static.blog.csdn.net/scripts/ZeroClipboard/ZeroClipboard.swf" loop="false" menu="false" quality="best" bgcolor="#ffffff" name="ZeroClipboardMovie_10" allowscriptaccess="always" allowfullscreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="id=10&width=0&height=0" wmode="transparent" align="middle" height="0" width="0"></div></div></div><ol class="dp-xml" start="1"><li class="alt"><span><span class="tag"><?</span><span class="tag-name">xml</span><span> </span><span class="attribute">version</span><span>=</span><span class="attribute-value">"1.0"</span><span> </span><span class="attribute">encoding</span><span>=</span><span class="attribute-value">"utf-8"</span><span class="tag">?></span><span>  </span></span></li><li class=""><span><span class="tag"><</span><span class="tag-name">LinearLayout</span><span> </span><span class="attribute">xmlns:android</span><span>=</span><span class="attribute-value">"http://schemas.android.com/apk/res/android"</span><span>  </span></span></li><li class="alt"><span>    <span class="attribute">android:orientation</span><span>=</span><span class="attribute-value">"vertical"</span><span> </span><span class="attribute">android:layout_width</span><span>=</span><span class="attribute-value">"fill_parent"</span><span>  </span></span></li><li class=""><span>    <span class="attribute">android:layout_height</span><span>=</span><span class="attribute-value">"fill_parent"</span><span class="tag">></span><span>  </span></span></li><li class="alt"><span>      </span></li><li class=""><span>    <span class="tag"><</span><span class="tag-name">GridView</span><span> </span><span class="attribute">xmlns:android</span><span>=</span><span class="attribute-value">"http://schemas.android.com/apk/res/android"</span><span>      </span></span></li><li class="alt"><span>    <span class="attribute">android:id</span><span>=</span><span class="attribute-value">"@+id/gridview"</span><span>     </span></span></li><li class=""><span>    <span class="attribute">android:layout_width</span><span>=</span><span class="attribute-value">"fill_parent"</span><span>      </span></span></li><li class="alt"><span>    <span class="attribute">android:layout_height</span><span>=</span><span class="attribute-value">"fill_parent"</span><span>     </span></span></li><li class=""><span>    <span class="attribute">android:numColumns</span><span>=</span><span class="attribute-value">"4"</span><span>     </span></span></li><li class="alt"><span>    <span class="attribute">android:verticalSpacing</span><span>=</span><span class="attribute-value">"10dp"</span><span>     </span></span></li><li class=""><span>    <span class="attribute">android:horizontalSpacing</span><span>=</span><span class="attribute-value">"10dp"</span><span>     </span></span></li><li class="alt"><span>    <span class="attribute">android:columnWidth</span><span>=</span><span class="attribute-value">"80dp"</span><span>  </span></span></li><li class=""><span>    <span class="attribute">android:stretchMode</span><span>=</span><span class="attribute-value">"columnWidth"</span><span>     </span></span></li><li class="alt"><span>    <span class="attribute">android:gravity</span><span>=</span><span class="attribute-value">"center"</span><span>   </span></span></li><li class=""><span>    <span class="attribute">android:background</span><span>=</span><span class="attribute-value">"#ffffff"</span><span>   </span></span></li><li class="alt"><span><span class="tag">/></span><span>   </span></span></li><li class=""><span><span class="tag"></</span><span class="tag-name">LinearLayout</span><span class="tag">></span><span>  </span></span></li></ol></div><pre style="display: none;" name="code" class="html"><?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 xmlns:android="http://schemas.android.com/apk/res/android"    
    android:id="@+id/gridview"   
    android:layout_width="fill_parent"    
    android:layout_height="fill_parent"   
    android:numColumns="4"   
    android:verticalSpacing="10dp"   
    android:horizontalSpacing="10dp"   
    android:columnWidth="80dp"
    android:stretchMode="columnWidth"   
    android:gravity="center" 
    android:background="#ffffff" 
/> 
</LinearLayout></pre><br>
<br>
<pre></pre>
<p></p>
<pre></pre>
<div class="dp-highlighter bg_html"><div class="bar"><div class="tools"><b>[html]</b> <a href="#" class="ViewSource" title="view plain" onclick="dp.sh.Toolbar.Command('ViewSource',this);return false;">view plain</a><a href="#" class="CopyToClipboard" title="copy" onclick="dp.sh.Toolbar.Command('CopyToClipboard',this);return false;">copy</a><a href="#" class="PrintSource" title="print" onclick="dp.sh.Toolbar.Command('PrintSource',this);return false;">print</a><a href="#" class="About" title="?" onclick="dp.sh.Toolbar.Command('About',this);return false;">?</a><div style="position: absolute; left: 0px; top: 0px; width: 0px; height: 0px; z-index: 99;"><embed id="ZeroClipboardMovie_11" src="http://static.blog.csdn.net/scripts/ZeroClipboard/ZeroClipboard.swf" loop="false" menu="false" quality="best" bgcolor="#ffffff" name="ZeroClipboardMovie_11" allowscriptaccess="always" allowfullscreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="id=11&width=0&height=0" wmode="transparent" align="middle" height="0" width="0"></div></div></div><ol class="dp-xml" start="1"><li class="alt"><span><span> 、    ,    。  </span></span></li></ol></div><pre style="display: none;" name="code" class="html"> 、    ,    。</pre><br>
<br>
<p></p>
<p style="text-align:left"><br>
</p>
<p><br>
</p>