Glide是一款基于Android的圖片加載和圖片緩存組件,它可以最大性能地在Android設備上讀取、解碼、顯示圖片和視頻。Glide可以將遠程的圖片、視頻、動畫圖片等緩存在設備本地,便于提高用戶瀏覽圖片的流暢體驗。
Glide最核心的功能就是提高滾動圖片列表的性能,并且Glide還能滿足對遠程圖片的讀取、改變尺寸以及展示的性能要求。
最簡單的示例代碼如下:
- // For a simple view:
- @Override
- public void onCreate(Bundle savedInstanceState) {
- ...
- ImageView imageView = (ImageView) findViewById(R.id.my_image_view);
- Glide.with(this).load("http://goo.gl/h8qOq7").into(imageView);
- }
- // For a list:
- @Override
- public View getView(int position, View recycled, ViewGroup container) {
- final ImageView myImageView;
- if (recycled == null) {
- myImageView = (ImageView) inflater.inflate(R.layout.my_image_view,
- container, false);
- } else {
- myImageView = (ImageView) recycled;
- }
- String url = myUrls.get(position);
- Glide.with(myFragment)
- .load(url)
- .centerCrop()
- .placeholder(R.drawable.loading_spinner)
- .crossFade()
- .into(myImageView);
- return myImageView;
- }
Volley是Glide的可選項,可以支持http/https來讀取圖片。
用Gradle:
- dependencies {
- compile 'com.github.bumptech.glide:volley-integration:1.0.+'
- compile 'com.mcxiaoke.volley:library:1.0.+'
- }
或者用Maven:
- <dependency>
- <groupId>com.github.bumptech.glide</groupId>
- <artifactId>volley-integration</artifactId>
- <version>1.0.1</version>
- <type>jar</type>
- </dependency>
- <dependency>
- <groupId>com.mcxiaoke.volley</groupId>
- <artifactId>library</artifactId>
- <version>1.0.5</version>
- <type>aar</type>
- </dependency>
然后在Activity或者Application中注冊 Volley的加載項即可:
- public void onCreate() {
- Glide.get(this).register(GlideUrl.class, InputStream.class,
- new VolleyUrlLoader.Factory(yourRequestQueue));
- ...
- }
這樣所有的請求就會通過Volley了。
除了Volley,Glide中還可以使用OkHttp通信框架,OkHttp同樣支持http/https來讀取圖片。
用Gradle:
- dependencies {
- compile 'com.github.bumptech.glide:okhttp-integration:1.0.+'
- compile 'com.squareup.okhttp:okhttp:2.0.+'
- }
或者用Maven:
- <dependency>
- <groupId>com.github.bumptech.glide</groupId>
- <artifactId>okhttp-integration</artifactId>
- <version>1.0.1</version>
- <type>jar</type>
- </dependency>
- <dependency>
- <groupId>com.squareup.okhttp</groupId>
- <artifactId>okhttp</artifactId>
- <version>2.0.0</version>
- <type>jar</type>
- </dependency>
- 然后在Activity或者Application中注冊 OkHttp的加載項即可:
- public void onCreate() {
- Glide.get(this).register(GlideUrl.class, InputStream.class,
- new OkHttpUrlLoader.Factory(yourOkHttpClient));
- ...
- }
如果你的Android應用中涉及到遠程圖片的處理,那么Glide組件可以幫助你在圖片視頻方面優化應用程序。