Universal-Image-Loader 示例 工具
Base
public class MyApplication extends Application {@Overridepublic void onCreate() {super.onCreate();//在Application中创建默认的ImageLoaderConfiguration配置参数,并初始化到ImageLoader中ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(this));}}
/*** 基类,提供共用的ImageLoader,共用的菜单* @author 白乾涛*/public abstract class BaseActivity extends Activity {protected ImageLoader imageLoader = ImageLoader.getInstance();@Overridepublic boolean onCreateOptionsMenu(Menu menu) {getMenuInflater().inflate(R.menu.main_menu, menu);return true;}@Overridepublic boolean onOptionsItemSelected(MenuItem item) {switch (item.getItemId()) {case R.id.item_clear_memory_cache:imageLoader.clearMemoryCache();//清除内存缓存return true;case R.id.item_clear_disc_cache:imageLoader.clearDiskCache();//清除磁盘缓存。建议使用clearDiskCache()。经查源码clearDiscCache中就一行代码,那就是调用clearDiskCache方法。return true;default:return false;}}@Overridepublic void onBackPressed() {imageLoader.stop();super.onBackPressed();}}/*** 带有两个滑动控制菜单的基类,设置是否在滑动过程中、在猛的滑动界面的时候停止加载图片。适用于ListView或GridView* @author 白乾涛*/public class AbsListViewBaseActivity extends BaseActivity {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;@Overridepublic void onResume() {super.onResume();//设置是否在滑动过程中、在猛的滑动界面的时候停止加载图片。listView.setOnScrollListener(new PauseOnScrollListener(imageLoader, pauseOnScroll, pauseOnFling));}@Overridepublic void onSaveInstanceState(Bundle outState) {outState.putBoolean(STATE_PAUSE_ON_SCROLL, pauseOnScroll);outState.putBoolean(STATE_PAUSE_ON_FLING, pauseOnFling);}@Overridepublic void onRestoreInstanceState(Bundle savedInstanceState) {pauseOnScroll = savedInstanceState.getBoolean(STATE_PAUSE_ON_SCROLL, false);pauseOnFling = savedInstanceState.getBoolean(STATE_PAUSE_ON_FLING, true);}@Override//onCreateOptionsMenu只会在Menu显示之前去调用一次,之后就不会再去调用。//onPrepareOptionsMenu是每次在显示Menu之前都会去调用,只要按一次Menu按鍵,就会调用一次。所以可以在这里动态的改变menu。public boolean onPrepareOptionsMenu(Menu menu) {//menu.clear(); //如果没有clear而直接add的话,那么菜单中菜单项是会“追加”的MenuItem pauseOnScrollItem = menu.findItem(R.id.item_pause_on_scroll);pauseOnScrollItem.setVisible(true);pauseOnScrollItem.setChecked(pauseOnScroll);MenuItem pauseOnFlingItem = menu.findItem(R.id.item_pause_on_fling);pauseOnFlingItem.setVisible(true);pauseOnFlingItem.setChecked(pauseOnFling);return true;}@Overridepublic boolean onOptionsItemSelected(MenuItem item) {switch (item.getItemId()) {case R.id.item_pause_on_scroll:pauseOnScroll = !pauseOnScroll;item.setChecked(pauseOnScroll);listView.setOnScrollListener(new PauseOnScrollListener(imageLoader, pauseOnScroll, pauseOnFling));return true;case R.id.item_pause_on_fling:pauseOnFling = !pauseOnFling;item.setChecked(pauseOnFling);listView.setOnScrollListener(new PauseOnScrollListener(imageLoader, pauseOnScroll, pauseOnFling));return true;default://默认调用父类的方法return super.onOptionsItemSelected(item);}}}
ListView
public class ListViewActivity extends AbsListViewBaseActivity {private ViewHolder holder;private DisplayImageOptions options;private SimpleImageLoadingListener loadingListener;/**图片的地址*/private String[] imageUrls;/**记录所有已加载的URL*/private static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);imageUrls = getIntent().getExtras().getStringArray(Extra.IMAGES);options = new DisplayImageOptions.Builder()//.showImageOnLoading(R.drawable.ic_stub).showImageForEmptyUri(R.drawable.ic_empty).showImageOnFail(R.drawable.ic_error)//.cacheInMemory(true).cacheOnDisk(true).considerExifParams(true).displayer(new CircleBitmapDisplayer(0xffff0000, 2)).build();//圆形描边loadingListener = new SimpleImageLoadingListener() {@Overridepublic void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {//加载完图片后append图片宽高信息!注意:只能在回调中获取,在其他地方获取都是不靠谱的!if (loadedImage != null) {//加载失败时loadedImage可能为nullholder.text.append(loadedImage.getWidth() + " * " + loadedImage.getHeight());//Bitmap会被压缩后加载仅内存,然后ImageView会对其进行缩放((BaseAdapter) ((ListView) listView).getAdapter()).notifyDataSetChanged();//必须调用//第一次加载时显示渐变动画boolean firstDisplay = !displayedImages.contains(imageUri);if (firstDisplay) {FadeInBitmapDisplayer.animate((ImageView) view, 500);displayedImages.add(imageUri);}}}};//******************************************************************************************listView = new ListView(this);((ListView) listView).setAdapter(new ItemAdapter());listView.setOnItemClickListener(new OnItemClickListener() {@Overridepublic void onItemClick(AdapterView<?> parent, View view, int position, long id) {Intent intent = new Intent(ListViewActivity.this, ViewPagerActivity.class);intent.putExtra(Extra.IMAGES, imageUrls);intent.putExtra(Extra.IMAGE_POSITION, position);startActivity(intent);}});setContentView(listView);}@Overridepublic void onBackPressed() {displayedImages.clear();super.onBackPressed();}//***********************************************************************************************************************************************private class ItemAdapter extends BaseAdapter {@Overridepublic int getCount() {return imageUrls.length;}@Overridepublic Object getItem(int position) {return position;}@Overridepublic long getItemId(int position) {return position;}@Overridepublic View getView(final int position, View convertView, ViewGroup parent) {if (convertView == null) {convertView = getLayoutInflater().inflate(R.layout.item_list_image, parent, false);holder = new ViewHolder();holder.text = (TextView) convertView.findViewById(R.id.text);holder.image = (ImageView) convertView.findViewById(R.id.image);convertView.setTag(holder);} else {holder = (ViewHolder) convertView.getTag();}holder.text.setText(position + ":");//必须放在displayImage之前,否则会产生线程安全问题(直接导致loadingListener中无法append图片宽高信息)imageLoader.displayImage(imageUrls[position], holder.image, options, loadingListener);return convertView;}}//*********************************************************************************************************************************************private class ViewHolder {public TextView text;public ImageView image;}}
ViewPage
public class ViewPagerActivity extends BaseActivity {private static final String STATE_POSITION = "STATE_POSITION";//初始位置private DisplayImageOptions options;private ViewPager pager;private String[] imageUrls;public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);Bundle bundle = getIntent().getExtras();if (getIntent() == null || getIntent().getExtras() == null) {finish();}imageUrls = bundle.getStringArray(Extra.IMAGES);int pagerPosition = bundle.getInt(Extra.IMAGE_POSITION, 0);if (savedInstanceState != null) {pagerPosition = savedInstanceState.getInt(STATE_POSITION);}options = new DisplayImageOptions.Builder().showImageForEmptyUri(R.drawable.ic_empty).showImageOnFail(R.drawable.ic_error).resetViewBeforeLoading(true).cacheOnDisk(true).imageScaleType(ImageScaleType.EXACTLY).bitmapConfig(Bitmap.Config.RGB_565).considerExifParams(true).displayer(new FadeInBitmapDisplayer(300)).build();pager = new ViewPager(this);pager.setAdapter(new ImagePagerAdapter());pager.setCurrentItem(pagerPosition);setContentView(pager);}@Overridepublic void onSaveInstanceState(Bundle outState) {outState.putInt(STATE_POSITION, pager.getCurrentItem());}//******************************************************************************************private class ImagePagerAdapter extends PagerAdapter {@Overridepublic void destroyItem(ViewGroup container, int position, Object object) {container.removeView((View) object);}@Overridepublic int getCount() {return imageUrls.length;}@Overridepublic boolean isViewFromObject(View view, Object object) {return view.equals(object);}@Overridepublic Object instantiateItem(ViewGroup view, int position) {View imageLayout = LayoutInflater.from(ViewPagerActivity.this).inflate(R.layout.item_pager_image, view, false);ImageView imageView = (ImageView) imageLayout.findViewById(R.id.image);final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.loading);imageLoader.displayImage(imageUrls[position], imageView, options, new SimpleImageLoadingListener() {@Overridepublic void onLoadingStarted(String imageUri, View view) {spinner.setVisibility(View.VISIBLE);}@Overridepublic void onLoadingFailed(String imageUri, View view, FailReason failReason) {String message = null;switch (failReason.getType()) {//加载失败原因case IO_ERROR:message = "Input/Output error";break;case DECODING_ERROR:message = "Image can't be decoded";break;case NETWORK_DENIED:message = "Downloads are denied";break;case OUT_OF_MEMORY:message = "Out Of Memory error";break;case UNKNOWN:message = "Unknown error";break;}Toast.makeText(ViewPagerActivity.this, message, Toast.LENGTH_SHORT).show();spinner.setVisibility(View.GONE);}@Overridepublic void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {spinner.setVisibility(View.GONE);}});view.addView(imageLayout, 0);return imageLayout;}}}
公司封装的工具类
import java.util.ArrayList;import java.util.List;import android.app.Activity;import android.content.ContentResolver;import android.content.Context;import android.database.Cursor;import android.graphics.Bitmap;import android.graphics.Bitmap.Config;import android.graphics.BitmapFactory;import android.provider.MediaStore;import android.text.TextUtils;import android.widget.ImageView;import com.lokinfo.m95xiu.application.LokApp;import com.lokinfo.m95xiu.util.M95Log;import com.nostra13.universalimageloader.core.DisplayImageOptions;import com.nostra13.universalimageloader.core.ImageLoader;import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;import com.nostra13.universalimageloader.core.assist.ImageScaleType;import com.nostra13.universalimageloader.core.assist.QueueProcessingType;import com.nostra13.universalimageloader.core.display.CircleBitmapDisplayer;import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;public class ImageHelper {public static void init(Context context){DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)//设置下载的图片是否缓存在内存中.cacheOnDisk(true)//设置下载的图片是否缓存在SD卡中.considerExifParams(true) //是否考虑JPEG图像EXIF参数(旋转,翻转).imageScaleType(ImageScaleType.EXACTLY_STRETCHED)//设置图片以如何的编码方式显示.bitmapConfig(Config.RGB_565)//设置图片的解码类型//.build();//构建完成ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context.getApplicationContext()).memoryCacheExtraOptions(480, 800).threadPoolSize(3)//线程池内加载的数量.threadPriority(Thread.NORM_PRIORITY).denyCacheImageMultipleSizesInMemory().tasksProcessingOrder(QueueProcessingType.FIFO).defaultDisplayImageOptions(options).writeDebugLogs().build();//开始构建ImageLoader.getInstance().init(config);//全局初始化此配置}public static void loadImage(String urlString , ImageView imageView , int defaultRes){DisplayImageOptions options = new DisplayImageOptions.Builder().showImageOnLoading(defaultRes) //设置图片在下载期间显示的图片.showImageForEmptyUri(defaultRes)//设置图片Uri为空或是错误的时候显示的图片.showImageOnFail(defaultRes) //设置图片加载/解码过程中错误时候显示的图片.cacheInMemory(true)//设置下载的图片是否缓存在内存中.cacheOnDisk(true)//设置下载的图片是否缓存在SD卡中.considerExifParams(true) //是否考虑JPEG图像EXIF参数(旋转,翻转).imageScaleType(ImageScaleType.EXACTLY_STRETCHED)//设置图片以如何的编码方式显示.bitmapConfig(Config.RGB_565)//设置图片的解码类型//.resetViewBeforeLoading(true)//设置图片在下载前是否重置,复位.build();//构建完成ImageLoader.getInstance().displayImage(urlString, imageView, options);}/*** 加载圆角图片* @param urlString* @param imageView* @param cornerRadius 圆角大小* @param defaultRes*/public static void LoadRoundImage(String urlString , ImageView imageView , int cornerRadius , int defaultRes){DisplayImageOptions options = new DisplayImageOptions.Builder().showImageOnLoading(defaultRes) //设置图片在下载期间显示的图片.showImageForEmptyUri(defaultRes)//设置图片Uri为空或是错误的时候显示的图片.showImageOnFail(defaultRes) //设置图片加载/解码过程中错误时候显示的图片.cacheInMemory(true)//设置下载的图片是否缓存在内存中.cacheOnDisk(true)//设置下载的图片是否缓存在SD卡中.considerExifParams(true) //是否考虑JPEG图像EXIF参数(旋转,翻转).imageScaleType(ImageScaleType.EXACTLY_STRETCHED)//设置图片以如何的编码方式显示.bitmapConfig(Config.RGB_565)//设置图片的解码类型//.resetViewBeforeLoading(true)//设置图片在下载前是否重置,复位.displayer(new RoundedBitmapDisplayer(cornerRadius))//是否设置为圆角,弧度为多少.build();//构建完成ImageLoader.getInstance().displayImage(urlString, imageView, options);}/*** 加载圆形图片* @param urlString* @param imageView* @param defaultRes*/public static void LoadCircleImage(String urlString , ImageView imageView, int defaultRes){Bitmap circleBitmap = BitmapFactory.decodeResource(LokApp.app().getApplicationContext().getResources(), defaultRes);CircleImageDrawable circleImageDrawable = new CircleImageDrawable(circleBitmap);DisplayImageOptions options = new DisplayImageOptions.Builder().showImageOnLoading(circleImageDrawable) //设置图片在下载期间显示的图片.showImageForEmptyUri(circleImageDrawable)//设置图片Uri为空或是错误的时候显示的图片.showImageOnFail(circleImageDrawable) //设置图片加载/解码过程中错误时候显示的图片.cacheInMemory(true)//设置下载的图片是否缓存在内存中.cacheOnDisk(true)//设置下载的图片是否缓存在SD卡中.considerExifParams(true) //是否考虑JPEG图像EXIF参数(旋转,翻转).imageScaleType(ImageScaleType.EXACTLY_STRETCHED)//设置图片以如何的编码方式显示.bitmapConfig(Config.RGB_565)//设置图片的解码类型//.resetViewBeforeLoading(true)//设置图片在下载前是否重置,复位.displayer(new CircleBitmapDisplayer()).build();//构建完成ImageLoader.getInstance().displayImage(urlString, imageView, options);}/*** 获取手机上所有图片的地址* @param context* @return*/public static List<String> getAllImageFlilPath(Activity context){List<String> paths = new ArrayList<String>();ContentResolver cr = context.getContentResolver();Cursor cursor = null;try{cursor = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null, null, MediaStore.Images.Media.DEFAULT_SORT_ORDER);while(cursor.moveToNext()){String imgPath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));if (!TextUtils.isEmpty(imgPath)){paths.add(imgPath);}}}catch(Exception e){M95Log.e("Exception", "getAllImageFlilPath" + e.getMessage());e.printStackTrace();}finally{if(cursor != null) cursor.close();}return paths;}}
附件列表
Universal-Image-Loader 示例 工具的更多相关文章
- 【Android应用开发】 Universal Image Loader ( 使用简介 | 示例代码解析 )
作者 : 韩曙亮 转载请注明出处 : http://blog.csdn.net/shulianghan/article/details/50824912 相关地址介绍 : -- Universal I ...
- android universal image loader 缓冲原理详解
1. 功能介绍 1.1 Android Universal Image Loader Android Universal Image Loader 是一个强大的.可高度定制的图片缓存,本文简称为UIL ...
- universal image loader自己使用的一些感受
1.全局入口的Application定义初始化: ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Build ...
- 【译】UNIVERSAL IMAGE LOADER. PART 3---ImageLoader详解
在之前的文章,我们重点讲了Android-Universal-Image-Loader的三个主要组件,现在我们终于可以开始使用它了. Android-Universal-Image-Loader有四个 ...
- Android中Universal Image Loader开源框架的简单使用
UIL (Universal Image Loader)aims to provide a powerful, flexible and highly customizable instrument ...
- universal image loader在listview/gridview中滚动时重复加载图片的问题及解决方法
在listview/gridview中使用UIL来display每个item的图片,当图片数量较多需要滑动滚动时会出现卡顿,而且加载过的图片再次上翻后依然会重复加载(显示设置好的加载中图片) 最近在使 ...
- 开源项目Universal Image Loader for Android 说明文档 (1) 简介
When developing applications for Android, one often facesthe problem of displaying some graphical ...
- 开源项目Universal Image Loader for Android 说明文档 (1) 简单介绍
When developing applications for Android, one often facesthe problem of displaying some graphical ...
- Android开源库--Universal Image Loader通用图片加载器
如果说我比别人看得更远些,那是因为我站在了巨人的肩上. github地址:https://github.com/nostra13/Android-Universal-Image-Loader 介绍 ...
随机推荐
- myeclipse插件安装
MyEclipse插件安装 安装1: HELP->MuEclipse Configuration Center.切换到SoftWare选项卡. 点击 add site 打开对话框,在对话框中na ...
- [转]《深度探索C++对象模型》读书笔记[一]
前 言 Stanley B.Lippman1. 任何对象模型都需要的三种转换风味: ü 与编译器息息相关的转换 ü 语言语义转换 ü 程序代码和对象模型的 ...
- telnet简单操作 模拟请求
telnet简单操作 模拟请求 一: 二: 三: 按照以上操作即可!
- mysql版本问题sql_mode=only_full_group_by
set @@sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_ ...
- 关于GestureDetector.OnGestureListener的onScroll参数distance问题
关于GestureDetector.OnGestureListener类的onScroll方法参数distanceX和distanceY问题 看到有文章上说onScroll方法中distanceX和d ...
- PHP常用字符串函数
1:访问子字符串:strpos()2:提取子字符串:substr()3:逐字节处理字符串:strstr()4:计算字符串长度:strlen()5:替换子字符串:substr_replace()6:按字 ...
- Android中的一些小知识
android中开发常用快捷键alt+/ 自动补全ctrl+1 有问题提示生成接收的参数 ctrl+L 在按2 注释// 注释 ctrl+//**/ 多行注释 ctrl+shift+/ android ...
- BZOJ3412: [Usaco2009 Dec]Music Notes乐谱
3412: [Usaco2009 Dec]Music Notes乐谱 Time Limit: 3 Sec Memory Limit: 128 MBSubmit: 35 Solved: 30[Sub ...
- HDOJ 1397 Goldbach's Conjecture(快速筛选素数法)
Problem Description Goldbach's Conjecture: For any even number n greater than or equal to 4, there e ...
- android TextView 添加下划线
android Textview加下划线 由于新做的一个项目要求有字体带下划线效果,当时看了下其实可以通过图片伪造出那种视觉效果.但是为了体现点技术含量,于是我想用Textview带下划线的效果.方法 ...