图形之实现/assets/目录下的图片浏览器
大部分时候,我们只要把图片放在drawable目录下,就可以在程序中通过资源ID获取封装该图片的Drawable对象。但是由于手机系统的内存比较小,如果系统不停去解析、创建Bitmap对象,可能由于前面创建的Bitmap所占用的内存还没有回收,而导致程序运行时引发OutOfMemory错误
布局文件代码
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
tools:context=".MainActivity">
<ImageView
android:id="@+id/image"
android:layout_width="400dp"
android:layout_height="500dp"
android:scaleType="fitCenter" />
<Button
android:id="@+id/btn_next"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/image"
android:text="下一张" />
</RelativeLayout>
Activity代码
package com.shake.bitmaptest;
import android.content.res.AssetManager;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import java.io.IOException;
import java.io.InputStream;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
String [] images =null;
AssetManager assets =null;
int currentImage=0;
ImageView image;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image= (ImageView) findViewById(R.id.image);
try {
assets=getAssets();
// 获取/assets/目录下所有文件
images=assets.list("");
Log.i("LIST","数组的长度:"+images.length);
} catch (IOException e) {
e.printStackTrace();
}
findViewById(R.id.btn_next).setOnClickListener(this);
}
@Override
public void onClick(View v) {
//如果发生下标越界
if (currentImage>=images.length){
currentImage=0;
}
//过滤掉文件夹中不属于图片类型的资源
while (!images[currentImage].endsWith(".png")&&!images[currentImage].endsWith(".jpg")&&!images[currentImage].endsWith(".gif")){
currentImage++;
Log.i("LIST","现在的下标:"+currentImage);
//如果发生下标越界
if(currentImage>=images.length){
currentImage=0;
}
}
InputStream inputStream =null;
try {
// 打开指定资源对应的输入流
inputStream=assets.open(images[currentImage++]);
Log.i("LIST","图片上的下标又是多少:"+currentImage);
} catch (IOException e) {
e.printStackTrace();
}
BitmapDrawable bitmapDrawable = (BitmapDrawable) image.getDrawable();
//如果图片还没有回收,先强制回收该图片
if(bitmapDrawable!=null&&!bitmapDrawable.getBitmap().isRecycled()){
bitmapDrawable.getBitmap().recycle();
}
//改变ImageView显示的图片
image.setImageBitmap(BitmapFactory.decodeStream(inputStream));
}
}
效果