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;}}