在Android 應用中使用assets目錄下存放的資源文件,assets目錄下存放的資源代表應用無法直接訪問的原生資源,應用程序通過AssetManager以二進制流的形式來讀取資源。此應用是查看/assets/目錄下的圖片查看器(圖片格式爲:.png),在assets目錄下放幾張PNG格式的圖片
該程序的界面十分簡單,只包含一個ImageView和一個按鈕
代碼如下:
佈局文件如下:bitmaptest.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:gravity="center_vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:id="@+id/btnBitmap"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TestBitmap"
/>
<ImageView
android:id="@+id/imageBitmap"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
java源代碼:
package com.infy.configuration;
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 BitmapTest extends Activity{
String[] images = null;
AssetManager assets = null;
int currentImge = 0;
ImageView image;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.bitmaptest);
image = (ImageView)findViewById(R.id.imageBitmap);
try{
assets = getAssets();
//獲取/assests/目錄下的所有的文件
images = assets.list("");
}catch(IOException e){
e.printStackTrace();
}
final Button next = (Button)findViewById(R.id.btnBitmap);
next.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(currentImge >= images.length){
currentImge = 0;
}
//找到下一個圖片文件
while(!images[currentImge].endsWith(".png")){
currentImge++;
//如果發生數組越界
if(currentImge >= images.length){
currentImge = 0;
}
}
InputStream assetFile = null;
try{
//打開指定資源對應的輸入流
assetFile = assets.open(images[currentImge++]);
}catch(IOException e){
e.printStackTrace();
}
BitmapDrawable bitmapDrawable = (BitmapDrawable)image.getDrawable();
//如果圖片還未回收,先強制回收該圖片
if(bitmapDrawable !=null && !bitmapDrawable.getBitmap().isRecycled()){
bitmapDrawable.getBitmap().recycle();
}
//該變現實的圖片
image.setImageBitmap(BitmapFactory.decodeStream(assetFile));
}
});
}
}