Android GridView显示图片

package com.example.dynamicimage;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.http.AndroidHttpClient;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

public class MainActivity extends Activity
{
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

setTitle("用图片填充GridView");
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this));

}

public class ImageAdapter extends BaseAdapter
{
private Context mContext;

// references to our images
// 地址自己去选择,可以尝试多个网站的,我试过百度的图片,不知为啥不可以?
private String[] myImageURL =
{
"http://pic3.nipic.com/20090520/2595280_225552071_2.jpg",
"http://pic9.nipic.com/20100831/4164977_115736793120_2.jpg",
"http://pic9.nipic.com/20100831/4164977_115736793120_3.jpg",
"http://pic9.nipic.com/20100831/4164977_115736793120_4.jpg",
"http://pic9.nipic.com/20100831/4164977_115736793120_5.jpg",
"http://pic9.nipic.com/20100831/4164977_115736793120_6.jpg"
};

public ImageAdapter(Context c)
{
mContext = c;
}

public int getCount()
{
return myImageURL.length;
}

public Object getItem(int position)
{
return myImageURL[position];
}

public long getItemId(int position)
{
return position;
}

public View getView(int position, View convertView, ViewGroup parent)
{
/*
* ImageView
*/
ImageView imageView = new ImageView(this.mContext);

try
{
// // 在网络条件好的情况下使用已注释的方法
// URL aryURI = new URL(myImageURL[position]);
// // 打开连接
// URLConnection conn = aryURI.openConnection();
// conn.connect();
// // 转变为 InputStream
// InputStream is = conn.getInputStream();
// // 将InputStream转变为Bitmap
// Bitmap bm = BitmapFactory.decodeStream(is);

// Bitmap bm = getBitMap(mContext, myImageURL[position]);
Bitmap bm = downloadBitmap(myImageURL[position]);
if (bm == null)
{
bm = BitmapFactory.decodeResource(mContext.getResources(),R.drawable.ic_launcher);
Log.i("BitmapPicture", "picture is null!!");
}
/* 关闭InputStream */
// is.close();
/* 添加图片 */
imageView.setImageBitmap(bm);
}
catch (Exception e)
{
e.printStackTrace();
}

// 填充ImageView
imageView.setLayoutParams(new GridView.LayoutParams(150, 133));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(4, 2, 2, 2);
return imageView;
}

/**
* 即使在网速不好的时候也能加载图片. 扩展:因为联网比较慢,为了用户的友好,可以使用线程Handle,进度条
*
* @param c
* @param url
* @return
*/
public synchronized Bitmap getBitMap(Context c, String url)
{
URL myFileUrl = null;
Bitmap bitmap = null;
try
{
myFileUrl = new URL(url);

// 打开网络连接
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream(); // 把得到的内容转换成流
int length = (int) conn.getContentLength(); // 获取文件的长度
if (length != -1)
{
byte[] imgData = new byte[length];
byte[] temp = new byte[512];
int readLen = 0;
int destPos = 0;
while ((readLen = is.read(temp)) > 0)
{
System.arraycopy(temp, 0, imgData, destPos, readLen);
destPos += readLen;
}

bitmap = BitmapFactory.decodeByteArray(imgData, 0,imgData.length);
}
}
catch (MalformedURLException e)
{
bitmap = BitmapFactory.decodeResource(c.getResources(),R.drawable.ic_launcher); // 当网络连接异常后,给个默认图片
return bitmap;
}
catch (IOException e)
{
bitmap = BitmapFactory.decodeResource(c.getResources(),R.drawable.ic_launcher);
return bitmap;
}

return bitmap;
}

public synchronized Bitmap downloadBitmap(String url)
{
final AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
final HttpGet getRequest = new HttpGet(url);

try
{
HttpResponse response = client.execute(getRequest);
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK)
{
Log.w("ImageDownloader", "Error " + statusCode + " while retrieving bitmap from " + url);
return null;
}

final HttpEntity entity = response.getEntity();
if (entity != null)
{
InputStream inputStream = null;
try
{
inputStream = entity.getContent();
final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
} finally
{
if (inputStream != null)
{
inputStream.close();
}
entity.consumeContent();
}
}
}
catch (Exception e)
{
// Could provide a more explicit error message for IOException or IllegalStateException
getRequest.abort();
}
finally
{
if (client != null)
{
client.close();
}
}
return null;
}
}
}

你可能感兴趣的:(andriod)