一:创建一个activity的基类初始化imageloder
package com.xxx.clouddialer;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.AbsListView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
/**
* Created 5/3/13.
*/
public class BaseActivity extends FragmentActivity {
protected static final String STATE_PAUSE_ON_SCROLL = "STATE_PAUSE_ON_SCROLL";
protected static final String STATE_PAUSE_ON_FLING = "STATE_PAUSE_ON_FLING";
protected AbsListView listView;
protected boolean pauseOnScroll = false;
protected boolean pauseOnFling = true;
//ImageLoader
protected ImageLoader imageLoader = ImageLoader.getInstance();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ImageLoaderConfiguration configuration = ImageLoaderConfiguration.createDefault(this);
imageLoader.init(configuration);
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
pauseOnScroll = savedInstanceState.getBoolean(STATE_PAUSE_ON_SCROLL, false);
pauseOnFling = savedInstanceState.getBoolean(STATE_PAUSE_ON_FLING, true);
}
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putBoolean(STATE_PAUSE_ON_SCROLL, pauseOnScroll);
outState.putBoolean(STATE_PAUSE_ON_FLING, pauseOnFling);
}
}
二:在需要使用的activity中,做一些处理,较好的控制图片的加载过程,例如暂停图片加载,重新开始加载图片,一般使用在ListView,GridView中,滑动过程中暂停加载图片,停止滑动的时候去加载图片
@Override
protected void onResume() {
super.onResume();
applyScrollListener();
}
// 这段代码是对
private void applyScrollListener() {
mGridView.setOnScrollListener(new PauseOnScrollListener(imageLoader, pauseOnScroll, pauseOnFling));
}
三:在adapter中
public CloudGroupAdapter(CloudDialerActivity c, ImageLoader imageLoader) {
mContext = c;
mLayoutInflater = LayoutInflater.from(c);
options = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.default_image)
.showImageForEmptyUri(R.drawable.default_image)
.showImageOnFail(R.drawable.default_image)
.cacheInMemory(true)
.cacheOnDisc(true)
.imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
animateFirstListener = new AnimateFirstDisplayListener();
this.imageLoader = imageLoader;
}
// 图片加载监听器在这里吧可以设置加载时的动画或者进度条之类的东西这里,一般可以不用
private static class AnimateFirstDisplayListener extends
SimpleImageLoadingListener {
static final List<String> displayedImages = Collections
.synchronizedList(new LinkedList<String>());
@Override
public void onLoadingComplete(String imageUri, View view,
Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 500);
displayedImages.add(imageUri);
}
}
}
}
四:在设置图片的时候
imageLoader.displayImage(imageUrl, hodler.groupType, options, animateFirstListener);
如果不需要进度之类的东西也可是使用三个参数的:
imageLoader.displayImage(imageUrl, hodler.groupType, options);
注意:这个类库适合listview gridview 等加载大量的图片,如果是就一张图片可以用异步任务去加载图片;
downloadImageTask = new DownloadImageTask(mIvContactPhoto,mCloudImage);
downloadImageTask.execute(imageUrl);
private class DownloadImageTask extends AsyncTask<String, Void, Drawable> {
ImageView mImageView;
String mUrl;
public DownloadImageTask(ImageView imageView, String url) {
mImageView = imageView;
mUrl = url;
}
protected Drawable doInBackground(String... urls) {
return loadImageFromNetwork(urls[0]);
}
protected void onPostExecute(Drawable result) {
if (result != null) {
BitmapDrawable bd = (BitmapDrawable) result;
Bitmap bm = bd.getBitmap();
mImageView.setImageBitmap(bm);
}
}
}
private Drawable loadImageFromNetwork(String imageUrl) {
Drawable drawable = null;
try {
// 可以在这里通过文件名来判断,是否本地有此图片
try {
drawable = Drawable.createFromStream(
new URL(imageUrl).openStream(), "image.jpg");
}catch (OutOfMemoryError e){
}
} catch (IOException e) {
Log.d("test", e.getMessage());
}
if (drawable == null) {
Log.d("test", "null drawable");
} else {
Log.d("test", "not null drawable");
}
return drawable;
}
image loader 显示本地图片
这两个方法是将一个bitmap对象生成一个文件保存到本地,这个文件的名字是根据时间设置的,没有后缀,默认打不开
/**
* 保存图片到sd卡
* @param bm
* @param mContext
* @return
*/
public static String saveBitmaptoSdCard(Bitmap bm,Activity mContext) {
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
File sdCardDir = Environment.getExternalStorageDirectory();
File yaoYanDir = new File(sdCardDir.getPath()+"/Yun/Images");
if(!yaoYanDir.exists()){
yaoYanDir.mkdirs();
}
String filename = getRandomFileName();
FileOutputStream fos;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 90, baos);
byte[] buffer = baos.toByteArray();
File f = new File(yaoYanDir,filename);
if (!f.exists()) {
try {
f.createNewFile();
fos = new FileOutputStream(f);
fos.write(buffer,0,buffer.length);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return filename;
}else{
Toast.makeText(mContext,"sd卡不存在",Toast.LENGTH_SHORT).show();
return null;
}
}
/**
* 生成一个随机的文件名
* @return
*/
public static String getRandomFileName() {
String rel="";
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
Date curDate = new Date(System.currentTimeMillis());
rel = formatter.format(curDate);
rel = rel+new Random().nextInt(1000);
return rel;
}
在adapter中显示图片
// 有两种方式 chatMsg.getImageContent()的值就是上面保存的图片的文件名
// 1:
// imagePath = "file://mnt/sdcard/Yun/Images/"+chatMsg.getImageContent();
// mImageLoader.displayImage(imagePath,viewHolder.imageContent,options);
// 2:
imagePath = Environment.getExternalStorageDirectory().getAbsolutePath()+"/Yun/Images/"+chatMsg.getImageContent();
// 这个地方不加 file:// 出不来
mImageLoader.displayImage("file://"+imagePath,viewHolder.imageContent,options);