ImageLoader在Listview中的使用

图片加载框架之ImageLoader

1_特点
1)多线程下载图片,图片可以来源于网络,文件系统,项目文件夹assets中以及drawable中等
2)支持随意的配置ImageLoader,例如线程池,图片下载器,内存缓存策略,硬盘缓存策略,图片显示选项以及其他的一些配置
3)支持图片的内存缓存,文件系统缓存或者SD卡缓存
4)支持图片下载过程的监听
5)根据控件(ImageView)的大小对Bitmap进行裁剪,减少Bitmap占用过多的内存
6)较好的控制图片的加载过程,例如暂停图片加载,重新开始加载图片,一般使用在ListView,GridView中,滑动过程中暂停加载图片,停止滑动的时候去加载图片
7)提供在较慢的网络下对图片进行加载

1)导入universal-image-loader-1.9.5.jar到项目中
2)创建MyApplication继承Application,在oncreate()中初始化ImageLoader
(1)初始化ImageLoaderConfiguration

package application.weiyuan.com.listviewimageloader;

import android.app.Application;

import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;

/**
 * Created by Administrator on 2017/7/26.
 */
public class MyApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        // 初始化参数
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)
                .threadPriority(Thread.NORM_PRIORITY - 2)               // 线程优先级
                .denyCacheImageMultipleSizesInMemory()                  // 当同一个Uri获取不同大小的图片,缓存到内存时,只缓存一个。默认会缓存多个不同的大小的相同图片
                .discCacheFileNameGenerator(new Md5FileNameGenerator()) // 将保存的时候的URI名称用MD5
                .tasksProcessingOrder(QueueProcessingType.LIFO)         // 设置图片下载和显示的工作队列排序
                .writeDebugLogs()                                       // 打印debug log
                .build();
        ImageLoader.getInstance().init(config);

    }
}

3)将创建的MyApplication在AndroidManifest.xml中注册

4)在AndroidManifest.xml中添加联网权限和写sdk权限

 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="application.weiyuan.com.listviewimageloader">
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

    <application
        android:name=".MyApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:background="@android:color/holo_blue_light"
        android:gravity="center"
        android:text="ImagleLoager_Listview"
        android:textColor="@android:color/white"
        android:textSize="25sp" />

    <ListView
        android:id="@+id/lv_imageloader"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </ListView>
</LinearLayout>

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="60dp"
    android:orientation="horizontal">
    <ImageView
        android:id="@+id/image"
        android:layout_width="60dp"
        android:layout_height="match_parent" />
    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/holo_blue_light"
        android:gravity="center"
        android:text="ImagleLoager_Listview"
        android:textColor="@android:color/white"
        android:textSize="25sp" />


</LinearLayout>

 

 
package application.weiyuan.com.listviewimageloader;

/**
 * Created by Administrator on 2017/7/26.
 */
public class Contants {

    public  static  String[]  imageUrls = new String[] {"http://h.hiphotos.baidu.com/image/w%3D230/sign=6e399656d343ad4ba62e41c3b2035a89/a08b87d6277f9e2fb00276fb1d30e924b899f30a.jpg"
            ,"http://h.hiphotos.baidu.com/image/w%3D230/sign=2c133914cdfc1e17fdbf8b327a91f67c/a8ec8a13632762d098b92abda2ec08fa513dc629.jpg"
            ,"http://g.hiphotos.baidu.com/image/w%3D230/sign=776ceec6c1cec3fd8b3ea076e689d4b6/faedab64034f78f0394889f97b310a55b3191c7c.jpg"
            ,"http://a.hiphotos.baidu.com/image/w%3D230/sign=a97edd106259252da3171a07049a032c/7dd98d1001e9390151b8b23479ec54e736d19605.jpg"
            ,"http://c.hiphotos.baidu.com/image/w%3D230/sign=5889f92579f40ad115e4c0e0672d1151/1b4c510fd9f9d72a32abde00d62a2834359bbbe4.jpg"
            ,"http://imgt8.bdstatic.com/it/u=2,926638203&fm=25&gp=0.jpg"
            ,"http://imgt8.bdstatic.com/it/u=2,926635772&fm=25&gp=0.jpg"
            ,"http://imgt9.bdstatic.com/it/u=2,926635207&fm=25&gp=0.jpg"
            ,"http://imgt8.bdstatic.com/it/u=2,926635826&fm=25&gp=0.jpg"
            ,"http://imgt7.bdstatic.com/it/u=2,767513653&fm=25&gp=0.jpg"
            ,"http://imgt9.bdstatic.com/it/u=2,861946843&fm=25&gp=0.jpg"
            ,"http://imgt7.bdstatic.com/it/u=2,956835248&fm=25&gp=0.jpg"
            ,"http://f.hiphotos.baidu.com/image/w%3D230/sign=1d32d901b9a1cd1105b675238913c8b0/d01373f082025aaf41e143faf8edab64034f1a2b.jpg"
            ,"http://imgt6.bdstatic.com/it/u=2,926633844&fm=25&gp=0.jpg"
            ,"http://imgt6.bdstatic.com/it/u=2,975762047&fm=25&gp=0.jpg"
            ,"http://imgt7.bdstatic.com/it/u=2,851741187&fm=25&gp=0.jpg"
            ,"http://imgt9.bdstatic.com/it/u=2,851680066&fm=25&gp=0.jpg"
            ,"http://imgt6.bdstatic.com/it/u=2,851165675&fm=25&gp=0.jpg"
            ,"http://imgt8.bdstatic.com/it/u=2,771262254&fm=25&gp=0.jpg"
            ,"http://imgt8.bdstatic.com/it/u=2,829083522&fm=25&gp=0.jpg"};

}

 

 
package application.weiyuan.com.listviewimageloader;

import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;

public class MainActivity extends Activity {

    private ListView lv_imageloader;
    private ListViewAdapter listViewAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initData();
    }

    private void initView() {
        lv_imageloader = (ListView)findViewById(R.id.lv_imageloader);
    }

    private void initData() {
// 创建适配器
        listViewAdapter = new ListViewAdapter(MainActivity.this);
// 添加适配器到listview中
        lv_imageloader.setAdapter(listViewAdapter);
    }

}

 

package application.weiyuan.com.listviewimageloader;

import android.content.Context;
import android.graphics.Bitmap;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by Administrator on 2017/7/26.
 */
public class ListViewAdapter extends BaseAdapter{

    private final List<String> displayedImages;
    private final DisplayImageOptions options;
    private Context mContext;
    private ImageLoader  imageLoader;
    private com.nostra13.universalimageloader.core.listener.ImageLoadingListener mFirstLoadImageListener = new SimpleImageLoadingListener(){

        // 图片加载完毕
        @Override
        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
            super.onLoadingComplete(imageUri, view, loadedImage);

            if(loadedImage != null) {
                ImageView imageView = (ImageView) view;

                // 是否第一次显示
                boolean firstDisplay = !displayedImages.contains(imageUri);

                if (firstDisplay) {

                    // 图片淡入效果
                    FadeInBitmapDisplayer.animate(imageView, 500);

                    displayedImages.add(imageUri);
                }
            }
        }
    };

    public ListViewAdapter(Context context){
        // 获取上下文
        mContext = context;

        // 获取ImageLoader实例
        imageLoader = ImageLoader.getInstance();

        options = new DisplayImageOptions.Builder()
                .showStubImage(R.mipmap.ic_launcher)          // 设置图片下载期间显示的图片
                .showImageForEmptyUri(R.mipmap.ic_launcher)  // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.mipmap.ic_launcher)       // 设置图片加载或解码过程中发生错误显示的图片
                .cacheInMemory(true)                        // 设置下载的图片是否缓存在内存中
                .cacheOnDisk(true)                          // 设置下载的图片是否缓存在SD卡中
                .displayer(new RoundedBitmapDisplayer(20))  // 设置成圆角图片
                .build();                                   // 创建配置过得DisplayImageOption对象

        // 存放已经显示的图片的集合
        displayedImages = Collections.synchronizedList(new LinkedList<String>());

    }
    @Override
    public int getCount() {
        return Contants.imageUrls.length;
    }

    @Override
    public Object getItem(int i) {
        return Contants.imageUrls[i];
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup viewGroup) {
        ViewHolder holder;

        if (convertView == null) {
            convertView = View.inflate(mContext, R.layout.listview_item, null);

            holder = new ViewHolder();
            holder.text = (TextView) convertView.findViewById(R.id.text);
            holder.image = (ImageView) convertView.findViewById(R.id.image);

            convertView.setTag(holder);        // 给View添加一个格外的数据
        } else {
            holder = (ViewHolder) convertView.getTag(); // 把数据取出来
        }

        holder.text.setText("Item " + (position + 1));    // TextView设置文本

        /**
         * 显示图片
         * 参数1:图片url
         * 参数2:显示图片的控件
         * 参数3:显示图片的设置
         * 参数4:监听器
         */
        imageLoader.displayImage(Contants.imageUrls[position], holder.image, options, mFirstLoadImageListener);

        return convertView;

    }

    public  static  class  ViewHolder{
        public TextView text;
        public ImageView image;
    }
}

 

 视频参看:尚硅谷Android视频《ImageLoader》

posted on 2017-07-26 22:53  luzhouxiaoshuai  阅读(133)  评论(0编辑  收藏  举报

导航