《Android图片加载与缓存开源框架:Android Glide》
Android Glide是一个开源的图片加载和缓存处理的第三方框架。和Android的Picasso库类似,个人感觉比Android Picasso好用。Android Glide使自身内部已经实现了缓存策略,使得开发者摆脱Android图片加载的琐碎事务,专注逻辑业务的代码。Android Glide使用便利,短短几行简单明晰的代码,即可完成大多数图片从网络(或者本地)加载、显示的功能需求。
使用Android Glide,需要先下载Android Glide的库,Android Glide在github上的项目主页:
https://github.com/bumptech/glide 。
实际的项目使用只需要到Glide的releases页面把jar包下载后导入到本地的libs里面即可直接使用。Glide的releases的页面地址:https://github.com/bumptech/glide/releases ,在此页面找到最新的jar包,下载后放到自己项目的libs中,比如glide 3.6.0库的jar包下载地址:https://github.com/bumptech/glide/releases/download/v3.6.0/glide-3.6.0.jar
接下来是在自己的项目中具体使用,现在给出一个具体的使用例子加以简单说明(通过网络加载图片然后在ImageView中显示出来):
MainActivity.java
- import com.bumptech.glide.Glide;
-
- import android.support.v7.app.ActionBarActivity;
- import android.view.LayoutInflater;
- import android.view.View;
- import android.view.ViewGroup;
- import android.widget.ArrayAdapter;
- import android.widget.ImageView;
- import android.widget.ListView;
- import android.app.Activity;
- import android.content.Context;
- import android.os.Bundle;
-
- public class MainActivity extends ActionBarActivity {
-
- private Activity mActivity;
-
- private String img_url = "http://avatar.csdn.net/9/7/A/1_zhangphil.jpg";
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- mActivity = this;
-
- setContentView(R.layout.activity_main);
-
- ListView lv = (ListView) findViewById(R.id.listView);
- lv.setAdapter(new MyAdapter(this, R.layout.item));
- }
-
- private class MyAdapter extends ArrayAdapter {
-
- private int resource;
-
- public MyAdapter(Context context, int resource) {
- super(context, resource);
- this.resource = resource;
- }
-
- @Override
- public View getView(int position, View convertView, ViewGroup parent) {
- if (convertView == null) {
- convertView = LayoutInflater.from(mActivity).inflate(resource,
- null);
- }
-
- ImageView iv = (ImageView) convertView.findViewById(R.id.imageView);
-
- Glide.with(mActivity).load(img_url).centerCrop()
-
-
-
- .placeholder(R.drawable.loading).crossFade().into(iv);
-
- return convertView;
- }
-
- @Override
- public int getCount() {
-
- return 10000;
- }
- }
- }
MainActivity.java需要的两个布局文件:
activity_main.xml
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical" >
-
- <ListView
- android:id="@+id/listView"
- android:layout_width="match_parent"
- android:layout_height="wrap_content" >
- </ListView>
-
- </LinearLayout>
item.xml
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical" >
-
- <ImageView
- android:id="@+id/imageView"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content" />
-
- </LinearLayout>