Android UI-开源框架ImageLoader的完美例子

时间:2022-09-21 12:42:13

Android开源框架ImageLoader的完美例子

2013年8月19日开源框架之Universal_Image_Loader学习

很多人都在讨论如何让图片能在异步加载更加流畅,可以显示大量图片,在拖动ListView的时候不会出现卡的现象。关于ImageLoader这个开源框架的使用有很多网友都介绍过,不过还不够清楚,这里有一个关于这个开源项目的完美例子,ListView的图片加载、GridView的图片加载、ViewPager的图片加载、Gallery画廊的图片加载、Widget的使用。很完善的一个例子,在这里我把所有界面效果做出博客分享出来,需要源码的朋友到我的资源页下载

下载地址:http://download.csdn.net/detail/wwj_748/5975847

要使用ImageLoader就要到这里下载jar包:

https://github.com/nostra13/Android-Universal-Image-Loader

然后导入项目中去就行了

项目文档结构图:

Android UI-开源框架ImageLoader的完美例子

从界面说起,界面本身是没什么好说的,就是如何在xml当中进行定义罢了

有以下这么多个布局文件

Android UI-开源框架ImageLoader的完美例子

一个一个来看呗

首先是这样的效果

Android UI-开源框架ImageLoader的完美例子

这个在Android4.2.2比较好看,在Android2.3.3就显得比较挫。

/2013.8.19_Universal_Image_Loader_Demo/res/layout/ac_home.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="fill_parent"
  4. android:layout_height="fill_parent" >
  5. <LinearLayout
  6. android:layout_width="fill_parent"
  7. android:layout_height="fill_parent"
  8. android:orientation="vertical" >
  9. <TextView
  10. android:layout_width="fill_parent"
  11. android:layout_height="wrap_content"
  12. android:gravity="center"
  13. android:paddingBottom="10dip"
  14. android:paddingTop="20dip"
  15. android:text="@string/label_activity_examples"
  16. android:textSize="24sp" />
  17. <Button
  18. android:layout_width="fill_parent"
  19. android:layout_height="wrap_content"
  20. android:layout_margin="10dip"
  21. android:onClick="onImageListClick"
  22. android:text="@string/button_image_list" />
  23. <Button
  24. android:layout_width="fill_parent"
  25. android:layout_height="wrap_content"
  26. android:layout_margin="10dip"
  27. android:onClick="onImageGridClick"
  28. android:text="@string/button_image_grid" />
  29. <Button
  30. android:layout_width="fill_parent"
  31. android:layout_height="wrap_content"
  32. android:layout_margin="10dip"
  33. android:onClick="onImagePagerClick"
  34. android:text="@string/button_image_pager" />
  35. <Button
  36. android:layout_width="fill_parent"
  37. android:layout_height="wrap_content"
  38. android:layout_margin="10dip"
  39. android:onClick="onImageGalleryClick"
  40. android:text="@string/button_image_gallery" />
  41. </LinearLayout>
  42. </ScrollView>

列表异步加载图片效果

Android UI-开源框架ImageLoader的完美例子

/2013.8.19_Universal_Image_Loader_Demo/res/layout/ac_image_list.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <ListView xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:id="@android:id/list"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent" />

/2013.8.19_Universal_Image_Loader_Demo/res/layout/item_list_image.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="fill_parent"
  4. android:layout_height="wrap_content" >
  5. <ImageView
  6. android:id="@+id/image"
  7. android:layout_width="72dip"
  8. android:layout_height="72dip"
  9. android:layout_margin="3dip"
  10. android:adjustViewBounds="true"
  11. android:contentDescription="@string/descr_image"
  12. android:scaleType="centerCrop" />
  13. <TextView
  14. android:id="@+id/text"
  15. android:layout_width="fill_parent"
  16. android:layout_height="wrap_content"
  17. android:layout_gravity="left|center_vertical"
  18. android:layout_marginLeft="20dip"
  19. android:textSize="22sp" />
  20. </LinearLayout>

GridView异步加载图片显示

Android UI-开源框架ImageLoader的完美例子

/2013.8.19_Universal_Image_Loader_Demo/res/layout/ac_image_grid.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <GridView xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:id="@+id/gridview"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent"
  6. android:gravity="center"
  7. android:horizontalSpacing="4dip"
  8. android:numColumns="3"
  9. android:stretchMode="columnWidth"
  10. android:verticalSpacing="4dip"
  11. android:padding="4dip" />

/2013.8.19_Universal_Image_Loader_Demo/res/layout/item_grid_image.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <ImageView xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:id="@+id/image"
  4. android:layout_width="fill_parent"
  5. android:layout_height="120dip"
  6. android:adjustViewBounds="true"
  7. android:contentDescription="@string/descr_image"
  8. android:scaleType="centerCrop" />

ViewPager异步加载图片显示

Android UI-开源框架ImageLoader的完美例子

/2013.8.19_Universal_Image_Loader_Demo/res/layout/ac_image_pager.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:id="@+id/pager"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent" />

/2013.8.19_Universal_Image_Loader_Demo/res/layout/item_pager_image.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="fill_parent"
  4. android:layout_height="fill_parent"
  5. android:padding="1dip" >
  6. <ImageView
  7. android:id="@+id/image"
  8. android:layout_width="wrap_content"
  9. android:layout_height="wrap_content"
  10. android:layout_gravity="center"
  11. android:adjustViewBounds="true"
  12. android:contentDescription="@string/descr_image" />
  13. <ProgressBar
  14. android:id="@+id/loading"
  15. android:layout_width="wrap_content"
  16. android:layout_height="wrap_content"
  17. android:layout_gravity="center"
  18. android:visibility="gone" />
  19. </FrameLayout>

Gallery画廊异步加载图片显示

Android UI-开源框架ImageLoader的完美例子

/2013.8.19_Universal_Image_Loader_Demo/res/layout/ac_image_gallery.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <Gallery xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:id="@+id/gallery"
  4. android:layout_width="fill_parent"
  5. android:layout_height="wrap_content"
  6. android:layout_gravity="center_vertical"
  7. android:spacing="1dip" />

/2013.8.19_Universal_Image_Loader_Demo/res/layout/item_gallery_image.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <ImageView xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:id="@+id/image"
  4. android:layout_width="120dip"
  5. android:layout_height="120dip"
  6. android:layout_gravity="center"
  7. android:adjustViewBounds="true"
  8. android:contentDescription="@string/descr_image"
  9. android:scaleType="centerCrop" />

还有一个就是桌面小部件

Android UI-开源框架ImageLoader的完美例子Android UI-开源框架ImageLoader的完美例子

以上只是布局文件,没有什么可以说,具体Activity代码实现如下:

先是这个:

/2013.8.19_Universal_Image_Loader_Demo/src/com/nostra13/example/universalimageloader/HomeActivity.java

主界面Activity代码

  1. /*******************************************************************************
  2. * Copyright 2011-2013 Sergey Tarasevich
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. *******************************************************************************/
  16. package com.nostra13.example.universalimageloader;
  17. import static com.nostra13.example.universalimageloader.Constants.IMAGES;
  18. import java.io.File;
  19. import java.io.FileOutputStream;
  20. import java.io.IOException;
  21. import java.io.InputStream;
  22. import android.content.Intent;
  23. import android.os.Bundle;
  24. import android.view.View;
  25. import com.nostra13.example.universalimageloader.Constants.Extra;
  26. import com.nostra13.universalimageloader.utils.L;
  27. /**
  28. * @author Sergey Tarasevich (nostra13[at]gmail[dot]com)
  29. */
  30. public class HomeActivity extends BaseActivity {
  31. private static final String TEST_FILE_NAME = "Universal Image Loader @#&=+-_.,!()~'%20.png";
  32. @Override
  33. public void onCreate(Bundle savedInstanceState) {
  34. super.onCreate(savedInstanceState);
  35. setContentView(R.layout.ac_home);
  36. // 定义文件对象,目录:/mnt/sdcard, 文件名:TEST_FILE_NAME
  37. File testImageOnSdCard = new File("/mnt/sdcard", TEST_FILE_NAME);
  38. if (!testImageOnSdCard.exists()) {  // 如果文件不存在
  39. // 把文件复制到SD卡
  40. copyTestImageToSdCard(testImageOnSdCard);
  41. }
  42. }
  43. // 点击进入ListView展示界面
  44. public void onImageListClick(View view) {
  45. Intent intent = new Intent(this, ImageListActivity.class);
  46. intent.putExtra(Extra.IMAGES, IMAGES);
  47. startActivity(intent);
  48. }
  49. // 点击进入GridView展示界面
  50. public void onImageGridClick(View view) {
  51. Intent intent = new Intent(this, ImageGridActivity.class);
  52. intent.putExtra(Extra.IMAGES, IMAGES);
  53. startActivity(intent);
  54. }
  55. // 点击进入ViewPager展示界面
  56. public void onImagePagerClick(View view) {
  57. Intent intent = new Intent(this, ImagePagerActivity.class);
  58. intent.putExtra(Extra.IMAGES, IMAGES);
  59. startActivity(intent);
  60. }
  61. // 点击进入画廊展示界面
  62. public void onImageGalleryClick(View view) {
  63. Intent intent = new Intent(this, ImageGalleryActivity.class);
  64. intent.putExtra(Extra.IMAGES, IMAGES);
  65. startActivity(intent);
  66. }
  67. @Override
  68. public void onBackPressed() {
  69. imageLoader.stop();     // 停止加载图片
  70. super.onBackPressed();
  71. }
  72. /**
  73. * 开一个线程把assert目录下的图片复制到SD卡目录下
  74. * @param testImageOnSdCard
  75. */
  76. private void copyTestImageToSdCard(final File testImageOnSdCard) {
  77. new Thread(new Runnable() {
  78. @Override
  79. public void run() {
  80. try {
  81. InputStream is = getAssets().open(TEST_FILE_NAME);
  82. FileOutputStream fos = new FileOutputStream(testImageOnSdCard);
  83. byte[] buffer = new byte[8192];
  84. int read;
  85. try {
  86. while ((read = is.read(buffer)) != -1) {
  87. fos.write(buffer, 0, read); // 写入输出流
  88. }
  89. } finally {
  90. fos.flush();        // 写入SD卡
  91. fos.close();        // 关闭输出流
  92. is.close();         // 关闭输入流
  93. }
  94. } catch (IOException e) {
  95. L.w("Can't copy test image onto SD card");
  96. }
  97. }
  98. }).start();     // 启动线程
  99. }
  100. }

/2013.8.19_Universal_Image_Loader_Demo/src/com/nostra13/example/universalimageloader/BaseActivity.java

  1. /*******************************************************************************
  2. * Copyright 2011-2013 Sergey Tarasevich
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. *******************************************************************************/
  16. package com.nostra13.example.universalimageloader;
  17. import android.app.Activity;
  18. import android.view.Menu;
  19. import android.view.MenuItem;
  20. import com.nostra13.universalimageloader.core.ImageLoader;
  21. /**
  22. * @author Sergey Tarasevich (nostra13[at]gmail[dot]com)
  23. */
  24. public abstract class BaseActivity extends Activity {
  25. protected ImageLoader imageLoader = ImageLoader.getInstance();
  26. @Override
  27. public boolean onCreateOptionsMenu(Menu menu) {
  28. // 加载菜单
  29. getMenuInflater().inflate(R.menu.main_menu, menu);
  30. return true;
  31. }
  32. @Override
  33. public boolean onOptionsItemSelected(MenuItem item) {
  34. switch (item.getItemId()) {
  35. case R.id.item_clear_memory_cache:
  36. imageLoader.clearMemoryCache();     // 清除内存缓存
  37. return true;
  38. case R.id.item_clear_disc_cache:
  39. imageLoader.clearDiscCache();       // 清除SD卡中的缓存
  40. return true;
  41. default:
  42. return false;
  43. }
  44. }
  45. }

/2013.8.19_Universal_Image_Loader_Demo/src/com/nostra13/example/universalimageloader/AbsListViewBaseActivity.java

  1. /*******************************************************************************
  2. * Copyright 2011-2013 Sergey Tarasevich
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. *******************************************************************************/
  16. package com.nostra13.example.universalimageloader;
  17. import android.os.Bundle;
  18. import android.view.Menu;
  19. import android.view.MenuItem;
  20. import android.widget.AbsListView;
  21. import com.nostra13.universalimageloader.core.assist.PauseOnScrollListener;
  22. /**
  23. *
  24. *
  25. * @author Sergey Tarasevich (nostra13[at]gmail[dot]com)
  26. */
  27. public class AbsListViewBaseActivity extends BaseActivity {
  28. protected static final String STATE_PAUSE_ON_SCROLL = "STATE_PAUSE_ON_SCROLL";
  29. protected static final String STATE_PAUSE_ON_FLING = "STATE_PAUSE_ON_FLING";
  30. protected AbsListView listView;
  31. protected boolean pauseOnScroll = false;
  32. protected boolean pauseOnFling = true;
  33. @Override
  34. public void onRestoreInstanceState(Bundle savedInstanceState) {
  35. pauseOnScroll = savedInstanceState.getBoolean(STATE_PAUSE_ON_SCROLL, false);
  36. pauseOnFling = savedInstanceState.getBoolean(STATE_PAUSE_ON_FLING, true);
  37. }
  38. @Override
  39. public void onResume() {
  40. super.onResume();
  41. applyScrollListener();
  42. }
  43. private void applyScrollListener() {
  44. listView.setOnScrollListener(new PauseOnScrollListener(imageLoader, pauseOnScroll, pauseOnFling));
  45. }
  46. @Override
  47. public void onSaveInstanceState(Bundle outState) {
  48. outState.putBoolean(STATE_PAUSE_ON_SCROLL, pauseOnScroll);
  49. outState.putBoolean(STATE_PAUSE_ON_FLING, pauseOnFling);
  50. }
  51. @Override
  52. public boolean onPrepareOptionsMenu(Menu menu) {
  53. MenuItem pauseOnScrollItem = menu.findItem(R.id.item_pause_on_scroll);
  54. pauseOnScrollItem.setVisible(true);
  55. pauseOnScrollItem.setChecked(pauseOnScroll);
  56. MenuItem pauseOnFlingItem = menu.findItem(R.id.item_pause_on_fling);
  57. pauseOnFlingItem.setVisible(true);
  58. pauseOnFlingItem.setChecked(pauseOnFling);
  59. return true;
  60. }
  61. @Override
  62. public boolean onOptionsItemSelected(MenuItem item) {
  63. switch (item.getItemId()) {
  64. case R.id.item_pause_on_scroll:
  65. pauseOnScroll = !pauseOnScroll;
  66. item.setChecked(pauseOnScroll);
  67. applyScrollListener();
  68. return true;
  69. case R.id.item_pause_on_fling:
  70. pauseOnFling = !pauseOnFling;
  71. item.setChecked(pauseOnFling);
  72. applyScrollListener();
  73. return true;
  74. default:
  75. return super.onOptionsItemSelected(item);
  76. }
  77. }
  78. }

/2013.8.19_Universal_Image_Loader_Demo/src/com/nostra13/example/universalimageloader/Constants.java

常量类代码

  1. /*******************************************************************************
  2. * Copyright 2011-2013 Sergey Tarasevich
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. *******************************************************************************/
  16. package com.nostra13.example.universalimageloader;
  17. /**
  18. * @author Sergey Tarasevich (nostra13[at]gmail[dot]com)
  19. * 常量类
  20. */
  21. public final class Constants {
  22. // 一堆图片链接
  23. public static final String[] IMAGES = new String[] {
  24. // Heavy images
  25. "https://lh6.googleusercontent.com/-jZgveEqb6pg/T3R4kXScycI/AAAAAAAAAE0/xQ7CvpfXDzc/s1024/sample_image_01.jpg",
  26. "https://lh4.googleusercontent.com/-K2FMuOozxU0/T3R4lRAiBTI/AAAAAAAAAE8/a3Eh9JvnnzI/s1024/sample_image_02.jpg",
  27. "https://lh5.googleusercontent.com/-SCS5C646rxM/T3R4l7QB6xI/AAAAAAAAAFE/xLcuVv3CUyA/s1024/sample_image_03.jpg",
  28. "https://lh6.googleusercontent.com/-f0NJR6-_Thg/T3R4mNex2wI/AAAAAAAAAFI/45oug4VE8MI/s1024/sample_image_04.jpg",
  29. "https://lh3.googleusercontent.com/-n-xcJmiI0pg/T3R4mkSchHI/AAAAAAAAAFU/EoiNNb7kk3A/s1024/sample_image_05.jpg",
  30. "https://lh3.googleusercontent.com/-X43vAudm7f4/T3R4nGSChJI/AAAAAAAAAFk/3bna6D-2EE8/s1024/sample_image_06.jpg",
  31. "https://lh5.googleusercontent.com/-MpZneqIyjXU/T3R4nuGO1aI/AAAAAAAAAFg/r09OPjLx1ZY/s1024/sample_image_07.jpg",
  32. "https://lh6.googleusercontent.com/-ql3YNfdClJo/T3XvW9apmFI/AAAAAAAAAL4/_6HFDzbahc4/s1024/sample_image_08.jpg",
  33. "https://lh5.googleusercontent.com/-Pxa7eqF4cyc/T3R4oasvPEI/AAAAAAAAAF0/-uYDH92h8LA/s1024/sample_image_09.jpg",
  34. "https://lh4.googleusercontent.com/-Li-rjhFEuaI/T3R4o-VUl4I/AAAAAAAAAF8/5E5XdMnP1oE/s1024/sample_image_10.jpg",
  35. "https://lh5.googleusercontent.com/-_HU4fImgFhA/T3R4pPVIwWI/AAAAAAAAAGA/0RfK_Vkgth4/s1024/sample_image_11.jpg",
  36. "https://lh6.googleusercontent.com/-0gnNrVjwa0Y/T3R4peGYJwI/AAAAAAAAAGU/uX_9wvRPM9I/s1024/sample_image_12.jpg",
  37. "https://lh3.googleusercontent.com/-HBxuzALS_Zs/T3R4qERykaI/AAAAAAAAAGQ/_qQ16FaZ1q0/s1024/sample_image_13.jpg",
  38. "https://lh4.googleusercontent.com/-cKojDrARNjQ/T3R4qfWSGPI/AAAAAAAAAGY/MR5dnbNaPyY/s1024/sample_image_14.jpg",
  39. "https://lh3.googleusercontent.com/-WujkdYfcyZ8/T3R4qrIMGUI/AAAAAAAAAGk/277LIdgvnjg/s1024/sample_image_15.jpg",
  40. "https://lh6.googleusercontent.com/-FMHR7Vy3PgI/T3R4rOXlEKI/AAAAAAAAAGs/VeXrDNDBkaw/s1024/sample_image_16.jpg",
  41. "https://lh4.googleusercontent.com/-mrR0AJyNTH0/T3R4rZs6CuI/AAAAAAAAAG0/UE1wQqCOqLA/s1024/sample_image_17.jpg",
  42. "https://lh6.googleusercontent.com/-z77w0eh3cow/T3R4rnLn05I/AAAAAAAAAG4/BaerfWoNucU/s1024/sample_image_18.jpg",
  43. "https://lh5.googleusercontent.com/-aWVwh1OU5Bk/T3R4sAWw0yI/AAAAAAAAAHE/4_KAvJttFwA/s1024/sample_image_19.jpg",
  44. "https://lh6.googleusercontent.com/-q-js52DMnWQ/T3R4tZhY2sI/AAAAAAAAAHM/A8kjp2Ivdqg/s1024/sample_image_20.jpg",
  45. "https://lh5.googleusercontent.com/-_jIzvvzXKn4/T3R4t7xpdVI/AAAAAAAAAHU/7QC6eZ10jgs/s1024/sample_image_21.jpg",
  46. "https://lh3.googleusercontent.com/-lnGi4IMLpwU/T3R4uCMa7vI/AAAAAAAAAHc/1zgzzz6qTpk/s1024/sample_image_22.jpg",
  47. "https://lh5.googleusercontent.com/-fFCzKjFPsPc/T3R4u0SZPFI/AAAAAAAAAHk/sbgjzrktOK0/s1024/sample_image_23.jpg",
  48. "https://lh4.googleusercontent.com/-8TqoW5gBE_Y/T3R4vBS3NPI/AAAAAAAAAHs/EZYvpNsaNXk/s1024/sample_image_24.jpg",
  49. "https://lh6.googleusercontent.com/-gc4eQ3ySdzs/T3R4vafoA7I/AAAAAAAAAH4/yKii5P6tqDE/s1024/sample_image_25.jpg",
  50. "https://lh5.googleusercontent.com/--NYOPCylU7Q/T3R4vjAiWkI/AAAAAAAAAH8/IPNx5q3ptRA/s1024/sample_image_26.jpg",
  51. "https://lh6.googleusercontent.com/-9IJM8so4vCI/T3R4vwJO2yI/AAAAAAAAAIE/ljlr-cwuqZM/s1024/sample_image_27.jpg",
  52. "https://lh4.googleusercontent.com/-KW6QwOHfhBs/T3R4w0RsQiI/AAAAAAAAAIM/uEFLVgHPFCk/s1024/sample_image_28.jpg",
  53. "https://lh4.googleusercontent.com/-z2557Ec1ctY/T3R4x3QA2hI/AAAAAAAAAIk/9-GzPL1lTWE/s1024/sample_image_29.jpg",
  54. "https://lh5.googleusercontent.com/-LaKXAn4Kr1c/T3R4yc5b4lI/AAAAAAAAAIY/fMgcOVQfmD0/s1024/sample_image_30.jpg",
  55. "https://lh4.googleusercontent.com/-F9LRToJoQdo/T3R4yrLtyQI/AAAAAAAAAIg/ri9uUCWuRmo/s1024/sample_image_31.jpg",
  56. "https://lh4.googleusercontent.com/-6X-xBwP-QpI/T3R4zGVboII/AAAAAAAAAIs/zYH4PjjngY0/s1024/sample_image_32.jpg",
  57. "https://lh5.googleusercontent.com/-VdLRjbW4LAs/T3R4zXu3gUI/AAAAAAAAAIw/9aFp9t7mCPg/s1024/sample_image_33.jpg",
  58. "https://lh6.googleusercontent.com/-gL6R17_fDJU/T3R4zpIXGjI/AAAAAAAAAI8/Q2Vjx-L9X20/s1024/sample_image_34.jpg",
  59. "https://lh3.googleusercontent.com/-1fGH4YJXEzo/T3R40Y1B7KI/AAAAAAAAAJE/MnTsa77g-nk/s1024/sample_image_35.jpg",
  60. "https://lh4.googleusercontent.com/-Ql0jHSrea-A/T3R403mUfFI/AAAAAAAAAJM/qzI4SkcH9tY/s1024/sample_image_36.jpg",
  61. "https://lh5.googleusercontent.com/-BL5FIBR_tzI/T3R41DA0AKI/AAAAAAAAAJk/GZfeeb-SLM0/s1024/sample_image_37.jpg",
  62. "https://lh4.googleusercontent.com/-wF2Vc9YDutw/T3R41fR2BCI/AAAAAAAAAJc/JdU1sHdMRAk/s1024/sample_image_38.jpg",
  63. "https://lh6.googleusercontent.com/-ZWHiPehwjTI/T3R41zuaKCI/AAAAAAAAAJg/hR3QJ1v3REg/s1024/sample_image_39.jpg",
  64. // Light images
  65. "http://tabletpcssource.com/wp-content/uploads/2011/05/android-logo.png",
  66. "http://simpozia.com/pages/images/stories/windows-icon.png",
  67. "https://si0.twimg.com/profile_images/1135218951/gmail_profile_icon3_normal.png",
  68. "http://www.krify.net/wp-content/uploads/2011/09/Macromedia_Flash_dock_icon.png",
  69. "http://radiotray.sourceforge.net/radio.png",
  70. "http://www.bandwidthblog.com/wp-content/uploads/2011/11/twitter-logo.png",
  71. "http://weloveicons.s3.amazonaws.com/icons/100907_itunes1.png",
  72. "http://weloveicons.s3.amazonaws.com/icons/100929_applications.png",
  73. "http://www.idyllicmusic.com/index_files/get_apple-iphone.png",
  74. "http://www.frenchrevolutionfood.com/wp-content/uploads/2009/04/Twitter-Bird.png",
  75. "http://3.bp.blogspot.com/-ka5MiRGJ_S4/TdD9OoF6bmI/AAAAAAAAE8k/7ydKtptUtSg/s1600/Google_Sky%2BMaps_Android.png",
  76. "http://www.desiredsoft.com/images/icon_webhosting.png",
  77. "http://goodereader.com/apps/wp-content/uploads/downloads/thumbnails/2012/01/hi-256-0-99dda8c730196ab93c67f0659d5b8489abdeb977.png",
  78. "http://1.bp.blogspot.com/-mlaJ4p_3rBU/TdD9OWxN8II/AAAAAAAAE8U/xyynWwr3_4Q/s1600/antivitus_free.png",
  79. "http://cdn3.iconfinder.com/data/icons/transformers/computer.png",
  80. "http://cdn.geekwire.com/wp-content/uploads/2011/04/firefox.png?7794fe",
  81. "https://ssl.gstatic.com/android/market/com.rovio.angrybirdsseasons/hi-256-9-347dae230614238a639d21508ae492302340b2ba",
  82. "http://androidblaze.com/wp-content/uploads/2011/12/tablet-pc-256x256.jpg",
  83. "http://www.theblaze.com/wp-content/uploads/2011/08/Apple.png",
  84. "http://1.bp.blogspot.com/-y-HQwQ4Kuu0/TdD9_iKIY7I/AAAAAAAAE88/3G4xiclDZD0/s1600/Twitter_Android.png",
  85. "http://3.bp.blogspot.com/-nAf4IMJGpc8/TdD9OGNUHHI/AAAAAAAAE8E/VM9yU_lIgZ4/s1600/Adobe%2BReader_Android.png",
  86. "http://cdn.geekwire.com/wp-content/uploads/2011/05/oovoo-android.png?7794fe",
  87. "http://icons.iconarchive.com/icons/kocco/ndroid/128/android-market-2-icon.png",
  88. "http://thecustomizewindows.com/wp-content/uploads/2011/11/Nicest-Android-Live-Wallpapers.png",
  89. "http://c.wrzuta.pl/wm16596/a32f1a47002ab3a949afeb4f",
  90. "http://macprovid.vo.llnwd.net/o43/hub/media/1090/6882/01_headline_Muse.jpg",
  91. // Special cases
  92. "http://cdn.urbanislandz.com/wp-content/uploads/2011/10/MMSposter-large.jpg", // very large image
  93. "file:///sdcard/Universal Image Loader @#&=+-_.,!()~'%20.png", // Image from SD card with encoded symbols
  94. "assets://Living Things @#&=+-_.,!()~'%20.jpg", // Image from assets
  95. "drawable://" + R.drawable.ic_launcher, // Image from drawables
  96. "http://upload.wikimedia.org/wikipedia/ru/b/b6/袣邪泻_泻芯褌_褋_屑褘褕邪屑懈_胁芯械胁邪谢.png", // Link with UTF-8
  97. "https://www.eff.org/sites/default/files/chrome150_0.jpg", // Image from HTTPS
  98. "http://bit.ly/soBiXr", // Redirect link
  99. "http://img001.us.expono.com/100001/100001-1bc30-2d736f_m.jpg", // EXIF
  100. "", // Empty link
  101. "http://wrong.site.com/corruptedLink", // Wrong link
  102. };
  103. private Constants() {
  104. }
  105. // 配置
  106. public static class Config {
  107. public static final boolean DEVELOPER_MODE = false;
  108. }
  109. // 额外类
  110. public static class Extra {
  111. public static final String IMAGES = "com.nostra13.example.universalimageloader.IMAGES";
  112. public static final String IMAGE_POSITION = "com.nostra13.example.universalimageloader.IMAGE_POSITION";
  113. }
  114. }

/2013.8.19_Universal_Image_Loader_Demo/src/com/nostra13/example/universalimageloader/ImageListActivity.java

  1. /*******************************************************************************
  2. * Copyright 2011-2013 Sergey Tarasevich
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. *******************************************************************************/
  16. package com.nostra13.example.universalimageloader;
  17. import java.util.Collections;
  18. import java.util.LinkedList;
  19. import java.util.List;
  20. import android.content.Intent;
  21. import android.graphics.Bitmap;
  22. import android.os.Bundle;
  23. import android.view.View;
  24. import android.view.ViewGroup;
  25. import android.widget.AdapterView;
  26. import android.widget.AdapterView.OnItemClickListener;
  27. import android.widget.BaseAdapter;
  28. import android.widget.ImageView;
  29. import android.widget.ListView;
  30. import android.widget.TextView;
  31. import com.nostra13.example.universalimageloader.Constants.Extra;
  32. import com.nostra13.universalimageloader.core.DisplayImageOptions;
  33. import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
  34. import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
  35. import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
  36. import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
  37. /**
  38. * @author Sergey Tarasevich (nostra13[at]gmail[dot]com)
  39. */
  40. public class ImageListActivity extends AbsListViewBaseActivity {
  41. DisplayImageOptions options;        // DisplayImageOptions是用于设置图片显示的类
  42. String[] imageUrls;                 // 图片路径
  43. @Override
  44. public void onCreate(Bundle savedInstanceState) {
  45. super.onCreate(savedInstanceState);
  46. setContentView(R.layout.ac_image_list);
  47. Bundle bundle = getIntent().getExtras();
  48. imageUrls = bundle.getStringArray(Extra.IMAGES);
  49. // 使用DisplayImageOptions.Builder()创建DisplayImageOptions
  50. options = new DisplayImageOptions.Builder()
  51. .showStubImage(R.drawable.ic_stub)          // 设置图片下载期间显示的图片
  52. .showImageForEmptyUri(R.drawable.ic_empty)  // 设置图片Uri为空或是错误的时候显示的图片
  53. .showImageOnFail(R.drawable.ic_error)       // 设置图片加载或解码过程中发生错误显示的图片
  54. .cacheInMemory(true)                        // 设置下载的图片是否缓存在内存中
  55. .cacheOnDisc(true)                          // 设置下载的图片是否缓存在SD卡中
  56. .displayer(new RoundedBitmapDisplayer(20))  // 设置成圆角图片
  57. .build();                                   // 创建配置过得DisplayImageOption对象
  58. listView = (ListView) findViewById(android.R.id.list);
  59. ((ListView) listView).setAdapter(new ItemAdapter());
  60. listView.setOnItemClickListener(new OnItemClickListener() {
  61. @Override
  62. public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
  63. // 点击列表项转入ViewPager显示界面
  64. startImagePagerActivity(position);
  65. }
  66. });
  67. }
  68. @Override
  69. public void onBackPressed() {
  70. AnimateFirstDisplayListener.displayedImages.clear();
  71. super.onBackPressed();
  72. }
  73. private void startImagePagerActivity(int position) {
  74. Intent intent = new Intent(this, ImagePagerActivity.class);
  75. intent.putExtra(Extra.IMAGES, imageUrls);
  76. intent.putExtra(Extra.IMAGE_POSITION, position);
  77. startActivity(intent);
  78. }
  79. /**
  80. *
  81. * 自定义列表项适配器
  82. *
  83. */
  84. class ItemAdapter extends BaseAdapter {
  85. private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
  86. private class ViewHolder {
  87. public TextView text;
  88. public ImageView image;
  89. }
  90. @Override
  91. public int getCount() {
  92. return imageUrls.length;
  93. }
  94. @Override
  95. public Object getItem(int position) {
  96. return position;
  97. }
  98. @Override
  99. public long getItemId(int position) {
  100. return position;
  101. }
  102. @Override
  103. public View getView(final int position, View convertView, ViewGroup parent) {
  104. View view = convertView;
  105. final ViewHolder holder;
  106. if (convertView == null) {
  107. view = getLayoutInflater().inflate(R.layout.item_list_image, parent, false);
  108. holder = new ViewHolder();
  109. holder.text = (TextView) view.findViewById(R.id.text);
  110. holder.image = (ImageView) view.findViewById(R.id.image);
  111. view.setTag(holder);        // 给View添加一个格外的数据
  112. } else {
  113. holder = (ViewHolder) view.getTag(); // 把数据取出来
  114. }
  115. holder.text.setText("Item " + (position + 1));  // TextView设置文本
  116. /**
  117. * 显示图片
  118. * 参数1:图片url
  119. * 参数2:显示图片的控件
  120. * 参数3:显示图片的设置
  121. * 参数4:监听器
  122. */
  123. imageLoader.displayImage(imageUrls[position], holder.image, options, animateFirstListener);
  124. return view;
  125. }
  126. }
  127. /**
  128. * 图片加载第一次显示监听器
  129. * @author Administrator
  130. *
  131. */
  132. private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {
  133. static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());
  134. @Override
  135. public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
  136. if (loadedImage != null) {
  137. ImageView imageView = (ImageView) view;
  138. // 是否第一次显示
  139. boolean firstDisplay = !displayedImages.contains(imageUri);
  140. if (firstDisplay) {
  141. // 图片淡入效果
  142. FadeInBitmapDisplayer.animate(imageView, 500);
  143. displayedImages.add(imageUri);
  144. }
  145. }
  146. }
  147. }
  148. }

/2013.8.19_Universal_Image_Loader_Demo/src/com/nostra13/example/universalimageloader/ImageGridActivity.java

网格视图Activity

  1. /*******************************************************************************
  2. * Copyright 2011-2013 Sergey Tarasevich
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. *******************************************************************************/
  16. package com.nostra13.example.universalimageloader;
  17. import android.content.Intent;
  18. import android.graphics.Bitmap;
  19. import android.os.Bundle;
  20. import android.view.View;
  21. import android.view.ViewGroup;
  22. import android.widget.AdapterView;
  23. import android.widget.AdapterView.OnItemClickListener;
  24. import android.widget.BaseAdapter;
  25. import android.widget.GridView;
  26. import android.widget.ImageView;
  27. import com.nostra13.example.universalimageloader.Constants.Extra;
  28. import com.nostra13.universalimageloader.core.DisplayImageOptions;
  29. /**
  30. * 网格视图显示Activity
  31. * @author Sergey Tarasevich (nostra13[at]gmail[dot]com)
  32. */
  33. public class ImageGridActivity extends AbsListViewBaseActivity {
  34. String[] imageUrls;                 // 图片Url
  35. DisplayImageOptions options;        // 显示图片的设置
  36. @Override
  37. public void onCreate(Bundle savedInstanceState) {
  38. super.onCreate(savedInstanceState);
  39. setContentView(R.layout.ac_image_grid);
  40. Bundle bundle = getIntent().getExtras();
  41. imageUrls = bundle.getStringArray(Extra.IMAGES);
  42. options = new DisplayImageOptions.Builder()
  43. .showStubImage(R.drawable.ic_stub)
  44. .showImageForEmptyUri(R.drawable.ic_empty)
  45. .showImageOnFail(R.drawable.ic_error)
  46. .cacheInMemory(true)
  47. .cacheOnDisc(true)
  48. .bitmapConfig(Bitmap.Config.RGB_565)     //设置图片的解码类型
  49. .build();
  50. listView = (GridView) findViewById(R.id.gridview);
  51. ((GridView) listView).setAdapter(new ImageAdapter());           // 填充数据
  52. listView.setOnItemClickListener(new OnItemClickListener() {
  53. @Override
  54. public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
  55. startImagePagerActivity(position);
  56. }
  57. });
  58. }
  59. private void startImagePagerActivity(int position) {
  60. Intent intent = new Intent(this, ImagePagerActivity.class);
  61. intent.putExtra(Extra.IMAGES, imageUrls);
  62. intent.putExtra(Extra.IMAGE_POSITION, position);
  63. startActivity(intent);
  64. }
  65. public class ImageAdapter extends BaseAdapter {
  66. @Override
  67. public int getCount() {
  68. return imageUrls.length;
  69. }
  70. @Override
  71. public Object getItem(int position) {
  72. return null;
  73. }
  74. @Override
  75. public long getItemId(int position) {
  76. return position;
  77. }
  78. @Override
  79. public View getView(int position, View convertView, ViewGroup parent) {
  80. final ImageView imageView;
  81. if (convertView == null) {
  82. imageView = (ImageView) getLayoutInflater().inflate(R.layout.item_grid_image, parent, false);
  83. } else {
  84. imageView = (ImageView) convertView;
  85. }
  86. // 将图片显示任务增加到执行池,图片将被显示到ImageView当轮到此ImageView
  87. imageLoader.displayImage(imageUrls[position], imageView, options);
  88. return imageView;
  89. }
  90. }
  91. }

/2013.8.19_Universal_Image_Loader_Demo/src/com/nostra13/example/universalimageloader/ImagePagerActivity.java

ViewPager视图Activity

  1. /*******************************************************************************
  2. * Copyright 2011-2013 Sergey Tarasevich
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. *******************************************************************************/
  16. package com.nostra13.example.universalimageloader;
  17. import android.graphics.Bitmap;
  18. import android.os.Bundle;
  19. import android.os.Parcelable;
  20. import android.support.v4.view.PagerAdapter;
  21. import android.support.v4.view.ViewPager;
  22. import android.view.LayoutInflater;
  23. import android.view.View;
  24. import android.view.ViewGroup;
  25. import android.widget.ImageView;
  26. import android.widget.ProgressBar;
  27. import android.widget.Toast;
  28. import com.nostra13.example.universalimageloader.Constants.Extra;
  29. import com.nostra13.universalimageloader.core.DisplayImageOptions;
  30. import com.nostra13.universalimageloader.core.assist.FailReason;
  31. import com.nostra13.universalimageloader.core.assist.ImageScaleType;
  32. import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
  33. import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
  34. /**
  35. * ViewPager页面显示Activity
  36. * @author Sergey Tarasevich (nostra13[at]gmail[dot]com)
  37. */
  38. public class ImagePagerActivity extends BaseActivity {
  39. private static final String STATE_POSITION = "STATE_POSITION";
  40. DisplayImageOptions options;
  41. ViewPager pager;
  42. public void onCreate(Bundle savedInstanceState) {
  43. super.onCreate(savedInstanceState);
  44. setContentView(R.layout.ac_image_pager);
  45. Bundle bundle = getIntent().getExtras();
  46. String[] imageUrls = bundle.getStringArray(Extra.IMAGES);
  47. // 当前显示View的位置
  48. int pagerPosition = bundle.getInt(Extra.IMAGE_POSITION, 0);
  49. // 如果之前有保存用户数据
  50. if (savedInstanceState != null) {
  51. pagerPosition = savedInstanceState.getInt(STATE_POSITION);
  52. }
  53. options = new DisplayImageOptions.Builder()
  54. .showImageForEmptyUri(R.drawable.ic_empty)
  55. .showImageOnFail(R.drawable.ic_error)
  56. .resetViewBeforeLoading(true)
  57. .cacheOnDisc(true)
  58. .imageScaleType(ImageScaleType.EXACTLY)
  59. .bitmapConfig(Bitmap.Config.RGB_565)
  60. .displayer(new FadeInBitmapDisplayer(300))
  61. .build();
  62. pager = (ViewPager) findViewById(R.id.pager);
  63. pager.setAdapter(new ImagePagerAdapter(imageUrls));
  64. pager.setCurrentItem(pagerPosition);    // 显示当前位置的View
  65. }
  66. @Override
  67. public void onSaveInstanceState(Bundle outState) {
  68. // 保存用户数据
  69. outState.putInt(STATE_POSITION, pager.getCurrentItem());
  70. }
  71. private class ImagePagerAdapter extends PagerAdapter {
  72. private String[] images;
  73. private LayoutInflater inflater;
  74. ImagePagerAdapter(String[] images) {
  75. this.images = images;
  76. inflater = getLayoutInflater();
  77. }
  78. @Override
  79. public void destroyItem(ViewGroup container, int position, Object object) {
  80. ((ViewPager) container).removeView((View) object);
  81. }
  82. @Override
  83. public void finishUpdate(View container) {
  84. }
  85. @Override
  86. public int getCount() {
  87. return images.length;
  88. }
  89. @Override
  90. public Object instantiateItem(ViewGroup view, int position) {
  91. View imageLayout = inflater.inflate(R.layout.item_pager_image, view, false);
  92. ImageView imageView = (ImageView) imageLayout.findViewById(R.id.image);
  93. final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.loading);
  94. imageLoader.displayImage(images[position], imageView, options, new SimpleImageLoadingListener() {
  95. @Override
  96. public void onLoadingStarted(String imageUri, View view) {
  97. spinner.setVisibility(View.VISIBLE);
  98. }
  99. @Override
  100. public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
  101. String message = null;
  102. switch (failReason.getType()) {     // 获取图片失败类型
  103. case IO_ERROR:              // 文件I/O错误
  104. message = "Input/Output error";
  105. break;
  106. case DECODING_ERROR:        // 解码错误
  107. message = "Image can't be decoded";
  108. break;
  109. case NETWORK_DENIED:        // 网络延迟
  110. message = "Downloads are denied";
  111. break;
  112. case OUT_OF_MEMORY:         // 内存不足
  113. message = "Out Of Memory error";
  114. break;
  115. case UNKNOWN:               // 原因不明
  116. message = "Unknown error";
  117. break;
  118. }
  119. Toast.makeText(ImagePagerActivity.this, message, Toast.LENGTH_SHORT).show();
  120. spinner.setVisibility(View.GONE);
  121. }
  122. @Override
  123. public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
  124. spinner.setVisibility(View.GONE);       // 不显示圆形进度条
  125. }
  126. });
  127. ((ViewPager) view).addView(imageLayout, 0);     // 将图片增加到ViewPager
  128. return imageLayout;
  129. }
  130. @Override
  131. public boolean isViewFromObject(View view, Object object) {
  132. return view.equals(object);
  133. }
  134. @Override
  135. public void restoreState(Parcelable state, ClassLoader loader) {
  136. }
  137. @Override
  138. public Parcelable saveState() {
  139. return null;
  140. }
  141. @Override
  142. public void startUpdate(View container) {
  143. }
  144. }
  145. }

/2013.8.19_Universal_Image_Loader_Demo/src/com/nostra13/example/universalimageloader/ImageGalleryActivity.java

画廊视图的Activity

  1. /*******************************************************************************
  2. * Copyright 2011-2013 Sergey Tarasevich
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. *******************************************************************************/
  16. package com.nostra13.example.universalimageloader;
  17. import android.content.Intent;
  18. import android.graphics.Bitmap;
  19. import android.os.Bundle;
  20. import android.view.View;
  21. import android.view.ViewGroup;
  22. import android.widget.AdapterView;
  23. import android.widget.AdapterView.OnItemClickListener;
  24. import android.widget.BaseAdapter;
  25. import android.widget.Gallery;
  26. import android.widget.ImageView;
  27. import com.nostra13.example.universalimageloader.Constants.Extra;
  28. import com.nostra13.universalimageloader.core.DisplayImageOptions;
  29. /**
  30. * 画廊视图Activity
  31. * @author Sergey Tarasevich (nostra13[at]gmail[dot]com)
  32. */
  33. @SuppressWarnings("deprecation")
  34. public class ImageGalleryActivity extends BaseActivity {
  35. String[] imageUrls;
  36. DisplayImageOptions options;
  37. public void onCreate(Bundle savedInstanceState) {
  38. super.onCreate(savedInstanceState);
  39. setContentView(R.layout.ac_image_gallery);
  40. Bundle bundle = getIntent().getExtras();
  41. imageUrls = bundle.getStringArray(Extra.IMAGES);
  42. options = new DisplayImageOptions.Builder()
  43. .showStubImage(R.drawable.ic_stub)
  44. .showImageForEmptyUri(R.drawable.ic_empty)
  45. .showImageOnFail(R.drawable.ic_error)
  46. .cacheInMemory(true)
  47. .cacheOnDisc(true)
  48. .bitmapConfig(Bitmap.Config.RGB_565)
  49. .build();
  50. // 自API 16之后就被抛弃了
  51. Gallery gallery = (Gallery) findViewById(R.id.gallery);
  52. gallery.setAdapter(new ImageGalleryAdapter());
  53. gallery.setOnItemClickListener(new OnItemClickListener() {
  54. @Override
  55. public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
  56. startImagePagerActivity(position);
  57. }
  58. });
  59. }
  60. private void startImagePagerActivity(int position) {
  61. Intent intent = new Intent(this, ImagePagerActivity.class);
  62. intent.putExtra(Extra.IMAGES, imageUrls);
  63. intent.putExtra(Extra.IMAGE_POSITION, position);
  64. startActivity(intent);
  65. }
  66. private class ImageGalleryAdapter extends BaseAdapter {
  67. @Override
  68. public int getCount() {
  69. return imageUrls.length;
  70. }
  71. @Override
  72. public Object getItem(int position) {
  73. return position;
  74. }
  75. @Override
  76. public long getItemId(int position) {
  77. return position;
  78. }
  79. @Override
  80. public View getView(int position, View convertView, ViewGroup parent) {
  81. ImageView imageView = (ImageView) convertView;
  82. if (imageView == null) {
  83. imageView = (ImageView) getLayoutInflater().inflate(R.layout.item_gallery_image, parent, false);
  84. }
  85. imageLoader.displayImage(imageUrls[position], imageView, options);
  86. return imageView;
  87. }
  88. }
  89. }

关于桌面控件的代码我就不贴了,朋友们可以自己下载我这个Demo

还有就是Manifest文件代码

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  3. package="com.nostra13.example.universalimageloader"
  4. android:versionCode="35"
  5. android:versionName="1.8.7" >
  6. <uses-sdk
  7. android:minSdkVersion="5"
  8. android:targetSdkVersion="16" />
  9. <!-- 网络访问权限 -->
  10. <uses-permission android:name="android.permission.INTERNET" />
  11. <!-- 文件写入SD卡权限 -->
  12. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  13. <application
  14. android:name=".UILApplication"
  15. android:icon="@drawable/ic_launcher"
  16. android:label="@string/app_name" >
  17. <activity
  18. android:name=".HomeActivity"
  19. android:label="@string/app_name" >
  20. <intent-filter>
  21. <action android:name="android.intent.action.MAIN" />
  22. <category android:name="android.intent.category.LAUNCHER" />
  23. </intent-filter>
  24. </activity>
  25. <activity
  26. android:name=".ImageListActivity"
  27. android:label="@string/ac_name_image_list" />
  28. <activity
  29. android:name=".ImageGridActivity"
  30. android:label="@string/ac_name_image_grid" />
  31. <activity
  32. android:name=".ImagePagerActivity"
  33. android:label="@string/ac_name_image_pager" />
  34. <activity
  35. android:name=".ImageGalleryActivity"
  36. android:label="@string/ac_name_image_gallery" />
  37. <!-- Widget -->
  38. <receiver android:name=".widget.UILWidgetProvider" >
  39. <meta-data
  40. android:name="android.appwidget.provider"
  41. android:resource="@xml/widget_provider" />
  42. <intent-filter>
  43. <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
  44. </intent-filter>
  45. </receiver>
  46. </application>
  47. </manifest>

以上的代码已经很详尽了,读者可以把它整合到你的项目当中,就可以实现完美异步加载图片。在这里要感谢那些为我们开源的大神们,他们的贡献让我们这些开发者更快更有效的完成工作,希望我们的开源会越做越好,我相信我们的开发者有这个能力。