本文主要是寫關於ImageSwitcher結合Gallery組件如何展示SDCard中的資源圖片,相信大家都看過API Demo 中也有關於這個例子的,但API Demo 中的例子是展示工程中Drawable目錄下的資源圖片,這樣調用系統的API比較容易實現,但我們在開發項目過程中,但有些圖片還不能完全確定下來,例如需要展示相機拍照的圖片,SDCard中某個目錄下的資源圖片等功能。其實系統中也提供相應的API給我們應用去實現該功能,下面就用異於API Demo中例子方式展示下如何?該功能。
【1】我們先看下該例子代碼的結構圖:
下面就直接上各個檔案的代碼了,不在這裡詳細解釋了,最後會看到實現的的..呵呵
【2】res/layout/main.xml 檔案源碼:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:background="#55000000" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center" android:text="Welcome to Andy.Chen's Blog!" android:textSize="20sp"/> <ImageSwitcher android:id="@+id/switcher" android:layout_width="wrap_content" android:layout_height="350dip" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" /> <Gallery android:id="@+id/mygallery" android:layout_width="fill_parent" android:layout_height="80dp" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:gravity="center_vertical" android:spacing="16dp" /> </LinearLayout>
【3】res/values/attrs.xml 檔案源碼:
<?xml version="1.0" encoding="utf-8"?><resources> <declare-styleable name="Gallery"> <attr name="android:galleryItemBackground" /> </declare-styleable> </resources>
【4】ImageSwitcherAndGalleryDemoActivity.java 源碼:(這個類的源碼比較多,希望大家耐心看)
package com.andyidea.imagedemo;import java.io.File;import java.util.ArrayList;import java.util.List;import android.app.Activity;import android.content.Context;import android.content.res.TypedArray;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.net.Uri;import android.os.Bundle;import android.os.Environment;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.view.ViewGroup;import android.view.animation.AnimationUtils;import android.widget.AdapterView;import android.widget.AdapterView.OnItemClickListener;import android.widget.AdapterView.OnItemSelectedListener;import android.widget.BaseAdapter;import android.widget.Gallery;import android.widget.Gallery.LayoutParams;import android.widget.ImageSwitcher;import android.widget.ImageView;import android.widget.Toast;import android.widget.ViewSwitcher.ViewFactory;/** * ImageSwitcher和Gallery如何展示SD卡中的資源圖片 * @author Andy.Chen * @email:Chenjunjun.ZJ@gmail.com */public class ImageSwitcherAndGalleryDemoActivity extends Activity implements OnItemSelectedListener,ViewFactory{ private List<String> imagePathList; private String[] list; private ImageSwitcher mSwitcher;private Gallery mGallery;/** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); imagePathList=getImagePathFromSD(); list = imagePathList.toArray(new String[imagePathList.size()]); /* 設定Switcher */mSwitcher = (ImageSwitcher) findViewById(R.id.switcher);mSwitcher.setFactory(this);/* 設定載入Switcher的模式 */mSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,android.R.anim.fade_in));/* 設定輸出Switcher的模式 */mSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,android.R.anim.fade_out));mSwitcher.setOnClickListener(new OnClickListener() {public void onClick(View v) {Toast.makeText(ImageSwitcherAndGalleryDemoActivity.this, "你點擊了ImageSwitch上的圖片",Toast.LENGTH_SHORT).show();}});mGallery = (Gallery) findViewById(R.id.mygallery);/* 新增幾ImageAdapter並設定給Gallery對象 */mGallery.setAdapter(new ImageAdapter(this, getImagePathFromSD()));mGallery.setOnItemSelectedListener(this);/* 設定一個itemclickListener事件 */mGallery.setOnItemClickListener(new OnItemClickListener() {public void onItemClick(AdapterView<?> parent, View v,int position, long id) {Toast.makeText(ImageSwitcherAndGalleryDemoActivity.this, "你點擊了Gallery上的圖片",Toast.LENGTH_SHORT).show();}}); } /** 從SD卡中擷取資源圖片的路徑 */private List<String> getImagePathFromSD() {/* 設定目前所在路徑 */List<String> it = new ArrayList<String>();//根據自己的需求讀取SDCard中的資源圖片的路徑String imagePath = Environment.getExternalStorageDirectory().toString()+"/hknational/image";File mFile = new File(imagePath);File[] files = mFile.listFiles();/* 將所有檔案存入ArrayList中 */for (int i = 0; i < files.length; i++) {File file = files[i];if (checkIsImageFile(file.getPath()))it.add(file.getPath());}return it;}/** 判斷是否相應的圖片格式 */private boolean checkIsImageFile(String fName) {boolean isImageFormat;/* 取得副檔名 */String end = fName.substring(fName.lastIndexOf(".") + 1, fName.length()).toLowerCase();/* 按副檔名的類型決定MimeType */if (end.equals("jpg") || end.equals("gif") || end.equals("png")|| end.equals("jpeg") || end.equals("bmp")) {isImageFormat = true;} else {isImageFormat = false;}return isImageFormat;}/* 改寫BaseAdapter自訂一ImageAdapter class */public class ImageAdapter extends BaseAdapter {/* 聲明變數 */int mGalleryItemBackground;private Context mContext;private List<String> lis;/* ImageAdapter的構造符 */public ImageAdapter(Context c, List<String> li) {mContext = c;lis = li;/* * 使用res/values/attrs.xml中的<declare-styleable>定義 的Gallery屬性. */TypedArray mTypeArray = obtainStyledAttributes(R.styleable.Gallery);/* 取得Gallery屬性的Index id */mGalleryItemBackground = mTypeArray.getResourceId(R.styleable.Gallery_android_galleryItemBackground, 0);/* 讓對象的styleable屬效能夠反覆使用 */mTypeArray.recycle();}/* 重寫的方法getCount,傳回圖片數目 */public int getCount() {return lis.size();}/* 重寫的方法getItem,傳回position */public Object getItem(int position) {return position;}/* 重寫的方法getItemId,傳並position */public long getItemId(int position) {return position;}/* 重寫方法getView,傳並幾View對象 */public View getView(int position, View convertView, ViewGroup parent) {/* 產生ImageView對象 */ImageView i = new ImageView(mContext);/* 設定圖片給imageView對象 */Bitmap bm = BitmapFactory.decodeFile(lis.get(position).toString());i.setImageBitmap(bm);/* 重新設定圖片的寬高 */i.setScaleType(ImageView.ScaleType.FIT_XY);/* 重新設定Layout的寬高 */i.setLayoutParams(new Gallery.LayoutParams(136, 88));/* 設定Gallery背景圖 */i.setBackgroundResource(mGalleryItemBackground);/* 傳回imageView對象 */return i;}} @Overridepublic View makeView() { ImageView iv = new ImageView(this); iv.setBackgroundColor(0xFF000000); iv.setScaleType(ImageView.ScaleType.FIT_CENTER); iv.setLayoutParams(new ImageSwitcher.LayoutParams( LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT)); return iv; }@Overridepublic void onItemSelected(AdapterView<?> parent, View view, int position,long id) {// TODO Auto-generated method stubString photoURL = list[position];Log.i("A", String.valueOf(position));mSwitcher.setImageURI(Uri.parse(photoURL));}@Overridepublic void onNothingSelected(AdapterView<?> parent) {// TODO Auto-generated method stub}}
【5】程式運行如下:
至此大功告成了!
本文為 Andy.Chen原創,歡迎大家轉載,轉載請註明出處,謝謝大家關注。