android studio for android learning (十三) 一個簡單的圖片檢視器示例
阿新 • • 發佈:2019-01-26
1、程式介面很簡單,一個按鈕和一個ImageView元件,當用戶按下按鈕時,程式會自動搜尋/assets/目錄下的一張圖片。
2.在android studio中新建的工程並不存在assets目錄,需要自己建立,在main目錄下,建立assets目錄,並在裡面放入圖片資源
activity_main.xml佈局檔案
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools ="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.dragon.testevent.MainActivity">
<Button
android:id="@+id/bn"
android:layout_width="wrap_content"
android:layout_height ="wrap_content"
android:text="Next"
/>
<ImageView
android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
程式碼檔案
package com.dragon.testevent;
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.widget.Button;
import android.widget.ImageView;
import java.io.IOException;
import java.io.InputStream;
public class MainActivity extends Activity {
String[] images = null;
AssetManager assets = null;
int currentImg=0;
ImageView image;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image = (ImageView) findViewById(R.id.image);
try{
// 獲取AssetManager的引用
assets = getAssets();
//獲取/assests/目錄下的所有的檔案
images = assets.list("");
}
catch(IOException e){
// 在命令列列印異常資訊在程式中出錯的位置及原因
e.printStackTrace();
}
final Button next = (Button) findViewById(R.id.bn);
// 按鈕點選事件
next.setOnClickListener(new View.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));
}
});
}
}