查看/assets/目錄下的圖片查看器

本程序包含一個按鈕Button 和一個圖片視圖ImageView

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" >

    <ImageView
        android:id="@+id/p_w_picpath"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="顯示圖片" />

</LinearLayout>

代碼:

package com.wsl.bitmaptest;

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.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends Activity {
 String[] p_w_picpaths = null;
 AssetManager assetManager = null;
 int currentImage = 0;
 ImageView p_w_picpathView;
 Button button;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  p_w_picpathView = (ImageView) this.findViewById(R.id.p_w_picpath);
  try {
   assetManager = getAssets();

//獲取目錄下所有文件
   p_w_picpaths = assetManager.list("");
  } catch (Exception e) {
   e.printStackTrace();
  }
  button = (Button) this.findViewById(R.id.button);

  button.setOnClickListener(new OnClickListener() {

   public void onClick(View v) {
    if (currentImage >= p_w_picpaths.length) {
     currentImage = 0;
    }
    while (!p_w_picpaths[currentImage].endsWith(".png")
      && !p_w_picpaths[currentImage].endsWith(".jpg")
      && !p_w_picpaths[currentImage].endsWith(".gif")) {
     currentImage++;
     if (currentImage >= p_w_picpaths.length) {
      currentImage = 0;
     }
    }
    InputStream assetFile = null;
    try {
     assetFile = assetManager.open(p_w_picpaths[currentImage++]);
    } catch (Exception e) {
     e.printStackTrace();
    }

    BitmapDrawable bitmapDrawable = (BitmapDrawable) p_w_picpathView
      .getDrawable();

    if (bitmapDrawable != null
      && !bitmapDrawable.getBitmap().isRecycled()) {
     bitmapDrawable.getBitmap().recycle();
    }
    p_w_picpathView.setImageBitmap(BitmapFactory.decodeStream(assetFile));
   }
  });

 }
 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  getMenuInflater().inflate(R.menu.activity_main, menu);
  return true;
 }
}
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章