布局文件:
<?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" >
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btn"
android:text="change img"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/img"/>
</LinearLayout>
java代码:
package com.example.android_test;
import java.io.IOException;
import java.io.InputStream;
import android.app.Activity;
import android.content.res.AssetManager;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class AssetTest extends Activity {
Button button;
ImageView image;
AssetManager manager=null;
String[] images=null;
int currentImg=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.asset_layout);
button=(Button) findViewById(R.id.btn);
image=(ImageView) findViewById(R.id.img);
try {
//获取资源
manager=getAssets();
//获取该目录下所有文件
images=manager.list("");
for (int i = 0; i < images.length; i++) {
System.out.println(images[i]);
}
} catch (IOException e) {
e.printStackTrace();
}
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
for (;;) {
System.out.println("当前文件:"+images[currentImg]+currentImg);
//遍历文件为以后缀为".jpg"的文件
if (images[currentImg].endsWith(".jpg")) {
if (currentImg>=images.length) {
currentImg=0;
}
InputStream in=null;
try {
//打开一个输入流
in=manager.open(images[currentImg]);
} catch (IOException e) {
e.printStackTrace();
}
BitmapDrawable bitmapDrawable=(BitmapDrawable) image.getDrawable();
//如果图片还未回收,强制回收
if (bitmapDrawable!=null && !bitmapDrawable.getBitmap().isRecycled()) {
System.out.println("bitmapDrawable!=null:"+(bitmapDrawable!=null)+"..."+"!bitmapDrawable.getBitmap().isRecycled():"+(!bitmapDrawable.getBitmap().isRecycled()));
bitmapDrawable.getBitmap().recycle();
}else {
System.out.println("空的...");
}
image.setImageBitmap(BitmapFactory.decodeStream(in));
currentImg++;
break;
}else {
currentImg++;
}
if (currentImg>=images.length) {
currentImg=0;
}
}
}
});
}
}