1. 程式人生 > >Android讀取assets目錄下所有檔案

Android讀取assets目錄下所有檔案

package org.crazyit.image;

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;

/**
 * Description:
 * <br/>site: <a href="http://www.crazyit.org">crazyit.org</a> 
 * <br/>Copyright (C), 2001-2012, Yeeku.H.Lee
 * <br/>This program is protected by copyright laws.
 * <br/>Program Name:
 * <br/>Date:
 * @author  Yeeku.H.Lee 
[email protected]
* @version 1.0 */ public class BitmapTest extends Activity { String[] images = null; AssetManager assets = null; int currentImg = 0; ImageView image; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); image = (ImageView)findViewById(R.id.image); try { assets = getAssets(); //獲取/assets/目錄下所有檔案 images = assets.list(""); } catch (IOException e) { e.printStackTrace(); } //獲取bn按鈕 final Button next = (Button)findViewById(R.id.next); //為bn按鈕繫結事件監聽器,該監聽器將會檢視下一張圖片 next.setOnClickListener(new OnClickListener() { @Override public void onClick(View sources) { //如果發生陣列越界 if (currentImg >= images.length) { currentImg = 0; } //找到下一個圖片檔案 while (!images[currentImg].endsWith(".png") && !images[currentImg].endsWith(".jpg") && !images[currentImg].endsWith(".gif")); { currentImg++; //如果已發生陣列越界 if (currentImg >= images.length) { currentImg = 0; } } InputStream assetFile = null; try { //開啟指定資源對應的輸入流 assetFile = assets .open(images[currentImg++]); } catch (IOException e) { e.printStackTrace(); } BitmapDrawable bitmapDrawable = (BitmapDrawable) image .getDrawable(); //如果圖片還未回收,先強制回收該圖片 if (bitmapDrawable != null && !bitmapDrawable.getBitmap().isRecycled()) //① { bitmapDrawable.getBitmap().recycle(); } //改變ImageView顯示的圖片 image.setImageBitmap(BitmapFactory.decodeStream(assetFile)); //② } }); } }