android inflate assets,查看/assets/目录下的图片查看器

本程序包含一个按钮Button 和一个图片视图ImageView

xml文件:

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical" >

android:id="@+id/p_w_picpath"

android:layout_width="fill_parent"

android:layout_height="wrap_content" />

android:id="@+id/button"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="显示图片" />

代码:

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;

}

}

你可能感兴趣的:(android,inflate,assets)