写了个小例子,读取asset目录下的图片文件。通过点击Button,显示在ImageView上。
Asset目录截图:
主Activity code:
package com.cb.bitmaptest;
import java.io.IOException;
import java.io.InputStream;
import android.os.Bundle;
import android.app.Activity;
import android.content.res.AssetManager;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity {
private Button mSwicthButton;
private ImageView mImageView;
private AssetManager mAssetManager;
private String[] images = null;
private int mCurrentImageIndex = 0;
//若路径中没有图片文件,count统计文件数量,作为跳出循环的判断条件
private int count = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImageView = (ImageView)findViewById(R.id.imageview);
//返回一个AssetManager对象,可以通过它访问asset目录
mAssetManager = getAssets();
try {
//获取asset目录中的文件名
images = mAssetManager.list("");
} catch (IOException e) {
e.printStackTrace();
}
mSwicthButton = (Button)findViewById(R.id.switch_picture);
mSwicthButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
//计数,若已遍历了(文件数量)次,则退出
count = 0;
//判断文件是否是图片文件,若不是,则继续往下找,直到找到下一个图片文件
while (!isPicture() && (count != images.length)) {
mCurrentImageIndex++;
count++;
if (mCurrentImageIndex >= images.length) {
mCurrentImageIndex = 0;
}
}
if (count == images.length) {
Toast.makeText(MainActivity.this, R.string.no_picture, Toast.LENGTH_SHORT).show();
return ;
}
InputStream stream = null;
try {
//获取文件流对象
stream = mAssetManager.open(images[mCurrentImageIndex++]);
} catch (IOException e) {
e.printStackTrace();
}
//获得drawable对象.该drawable就是ImageView的android:src属性的值,可设可不设。
BitmapDrawable drawable = (BitmapDrawable) mImageView.getDrawable();
//ImageView控件上的bitmap若未回收,强制回收
if (drawable != null && !drawable.getBitmap().isRecycled()) {
drawable.getBitmap().recycle();
}
//ImageView更改显示图片
mImageView.setImageBitmap(BitmapFactory.decodeStream(stream));
}
});
}
public boolean isPicture() {
if ((!images[mCurrentImageIndex].endsWith(".png"))
&&(!images[mCurrentImageIndex].endsWith(".jpg"))
&&(!images[mCurrentImageIndex].endsWith(".gif"))) {
return false;
}
return true;
}
}
activity_main.xml
<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" >
<Button
android:id="@+id/switch_picture"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/switchPicture" />
<ImageView
android:id="@+id/imageview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
</LinearLayout>