編輯:Android 開發實例
進入百度圖片、輸入關鍵字後,你會先看到一整片縮圖;點擊其中一張,便進入大圖頁面,而該頁還內含一個圖片藝廊,且當前大圖正是你剛點的那張。本文示範如何在 Android 中實現類似效果。
要顯示縮圖網格,沒有什麼比 GridView 更合適。佈局檔如下:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <GridView android:id="@+id/view_photos" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_marginTop="10dp" android:columnWidth="100dp" android:numColumns="auto_fit" android:horizontalSpacing="5dp" android:verticalSpacing="5dp" android:listSelector="@drawable/frame_select" /> </LinearLayout>
GridView 的每一項是一張縮圖,需繼承 BaseAdapter 實作自訂的 GridImageAdapter。Activity 透過查詢 MediaStore 的圖片縮圖庫來載入所有縮圖(縮圖位於 MediaStore.Images.Thumbnails):
package com.liner.manager;
import java.util.ArrayList;
import java.util.List;
import com.liner.manager.adapter.GridImageAdapter;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
public class MainActivity extends Activity {
private GridView photoView;
private GridImageAdapter imageAdapter;
private Cursor cursor;
private int[] thumbIds;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
photoView = (GridView)this.findViewById(R.id.view_photos);
photoView.setOnItemClickListener(photoClickListener);
showThumbnails();
}
private void showThumbnails() {
cursor = BitmapUtils.queryThumbnails(this);
if (cursor.moveToFirst()) {
List<Bitmap> bitmaps = new ArrayList<Bitmap>();
thumbIds = new int[cursor.getCount()];
for (int i = 0; i < cursor.getCount(); i++) {
cursor.moveToPosition(i);
String currPath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails.DATA));
thumbIds[i] = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID));
Bitmap b = BitmapUtils.decodeBitmap(currPath, 100, 100);
bitmaps.add(b);
}
imageAdapter = new GridImageAdapter(this.getApplication(), bitmaps);
photoView.setAdapter(imageAdapter);
}
}
private AdapterView.OnItemClickListener photoClickListener = new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> p, View v, int position, long id) {
// 點擊某張縮圖時,轉到圖片顯示介面
Intent intent = new Intent();
intent.setClass(MainActivity.this, GalleryActivity.class);
intent.putExtra("thumbIds", thumbIds);
intent.putExtra("currentPos", position);
startActivity(intent);
}
};
}
關鍵做法:把所有縮圖對應的 id 陣列與使用者點選的位置,透過 Intent 傳給第二個展示介面。
第二個介面用一個 Gallery 加一個 ImageButton 實現。佈局檔如下:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"> <Gallery android:id="@+id/image_gallery" android:layout_width="fill_parent" android:layout_height="100dp" /> <ImageButton android:id="@+id/image_current" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="10dp" android:layout_marginTop="10dp" /> </LinearLayout>
對應的 Activity 如下:
package com.liner.manager;
import java.util.List;
import com.liner.manager.adapter.GridImageAdapter;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Gallery;
import android.widget.ImageButton;
import android.widget.AdapterView.OnItemClickListener;
public class GalleryActivity extends Activity {
private ImageButton currentImage;
private Gallery gallery;
private int[] thumbIds;
private int currentPos;
private Bitmap currentBitmap;
private List<Bitmap> bitmapCache;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gallery);
currentImage = (ImageButton)this.findViewById(R.id.image_current);
gallery = (Gallery)this.findViewById(R.id.image_gallery);
gallery.setOnItemClickListener(galleryItemClickListener);
init();
}
private OnItemClickListener galleryItemClickListener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> p, View v, int position, long id) {
// 點擊事件
showCurrentImage(position);
}
};
private void init() {
thumbIds = this.getIntent().getIntArrayExtra("thumbIds");
currentPos = this.getIntent().getIntExtra("currentPos", 0);
bitmapCache = BitmapUtils.queryThumbnailListByIds(this, thumbIds);
GridImageAdapter adapter = new GridImageAdapter(this.getApplication(), bitmapCache);
gallery.setAdapter(adapter);
gallery.setSelection(currentPos);
showCurrentImage(currentPos);
}
private void showCurrentImage(int position) {
if (currentBitmap != null) {
currentBitmap.recycle();
}
currentBitmap = BitmapUtils.queryImageByThumbnailId(GalleryActivity.this, thumbIds[position]);
if (currentBitmap != null) {
currentImage.setImageBitmap(currentBitmap);
}
}
}
當使用者點擊 Gallery 中的某一項,觸發 onItemClick,我們便依該縮圖對應的 Image_ID,從 MediaStore.Images.Media 中查回大圖並顯示於 ImageButton 上。
當圖片很多時可能發生記憶體溢出。為避免此問題,可善用 Gallery 的特點做緩存:只保留當前可見縮圖的前三張與後三張,其餘全部 recycle。當使用者滑動 Gallery 時,再依當前位置重新更新緩存,讓記憶體中的縮圖數量維持在一個固定視窗內——這其實就是一個在全部縮圖座標上游動的浮動緩存視窗。
程式中用到的 BitmapUtils 封裝了一系列查詢圖片並解析為 Bitmap 的方法,核心包含縮放與查詢兩類:
package com.liner.manager;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.provider.MediaStore;
public final class BitmapUtils {
// 依指定顯示寬高縮放解碼
public static Bitmap decodeBitmap(String path, int displayWidth, int displayHeight) {
BitmapFactory.Options op = new BitmapFactory.Options();
op.inJustDecodeBounds = true;
Bitmap bmp = BitmapFactory.decodeFile(path, op); // 取得尺寸資訊
// 取得比例大小
int wRatio = (int)Math.ceil(op.outWidth / (float)displayWidth);
int hRatio = (int)Math.ceil(op.outHeight / (float)displayHeight);
// 若超出指定大小,則縮小相應比例
if (wRatio > 1 && hRatio > 1) {
if (wRatio > hRatio) {
op.inSampleSize = wRatio;
} else {
op.inSampleSize = hRatio;
}
}
op.inJustDecodeBounds = false;
bmp = BitmapFactory.decodeFile(path, op);
return Bitmap.createScaledBitmap(bmp, displayWidth, displayHeight, true);
}
// 以最大邊長決定縮放
public static Bitmap decodeBitmap(String path, int maxImageSize) {
BitmapFactory.Options op = new BitmapFactory.Options();
op.inJustDecodeBounds = true;
Bitmap bmp = BitmapFactory.decodeFile(path, op); // 取得尺寸資訊
int scale = 1;
if (op.outWidth > maxImageSize || op.outHeight > maxImageSize) {
scale = (int)Math.pow(2, (int)Math.round(Math.log(maxImageSize / (double)Math.max(op.outWidth, op.outHeight)) / Math.log(0.5)));
}
op.inJustDecodeBounds = false;
op.inSampleSize = scale;
bmp = BitmapFactory.decodeFile(path, op);
return bmp;
}
public static Cursor queryThumbnails(Activity context) {
String[] columns = new String[]{
MediaStore.Images.Thumbnails.DATA,
MediaStore.Images.Thumbnails._ID,
MediaStore.Images.Thumbnails.IMAGE_ID
};
return context.managedQuery(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, columns, null, null, MediaStore.Images.Thumbnails.DEFAULT_SORT_ORDER);
}
public static Cursor queryThumbnails(Activity context, String selection, String[] selectionArgs) {
String[] columns = new String[]{
MediaStore.Images.Thumbnails.DATA,
MediaStore.Images.Thumbnails._ID,
MediaStore.Images.Thumbnails.IMAGE_ID
};
return context.managedQuery(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, columns, selection, selectionArgs, MediaStore.Images.Thumbnails.DEFAULT_SORT_ORDER);
}
public static Bitmap queryThumbnailById(Activity context, int thumbId) {
String selection = MediaStore.Images.Thumbnails._ID + " = ?";
String[] selectionArgs = new String[]{ thumbId + "" };
Cursor cursor = BitmapUtils.queryThumbnails(context, selection, selectionArgs);
if (cursor.moveToFirst()) {
String path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails.DATA));
cursor.close();
return BitmapUtils.decodeBitmap(path, 100, 100);
} else {
cursor.close();
return null;
}
}
public static Bitmap[] queryThumbnailsByIds(Activity context, Integer[] thumbIds) {
Bitmap[] bitmaps = new Bitmap[thumbIds.length];
for (int i = 0; i < bitmaps.length; i++) {
bitmaps[i] = BitmapUtils.queryThumbnailById(context, thumbIds[i]);
}
return bitmaps;
}
// 取得全部縮圖
public static List<Bitmap> queryThumbnailList(Activity context) {
List<Bitmap> bitmaps = new ArrayList<Bitmap>();
Cursor cursor = BitmapUtils.queryThumbnails(context);
for (int i = 0; i < cursor.getCount(); i++) {
cursor.moveToPosition(i);
String path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails.DATA));
Bitmap b = BitmapUtils.decodeBitmap(path, 100, 100);
bitmaps.add(b);
}
cursor.close();
return bitmaps;
}
public static List<Bitmap> queryThumbnailListByIds(Activity context, int[] thumbIds) {
List<Bitmap> bitmaps = new ArrayList<Bitmap>();
for (int i = 0; i < thumbIds.length; i++) {
Bitmap b = BitmapUtils.queryThumbnailById(context, thumbIds[i]);
bitmaps.add(b);
}
return bitmaps;
}
public static Cursor queryImages(Activity context) {
String[] columns = new String[]{
MediaStore.Images.Media._ID,
MediaStore.Images.Media.DATA,
MediaStore.Images.Media.DISPLAY_NAME
};
return context.managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null, null, MediaStore.Images.Media.DEFAULT_SORT_ORDER);
}
public static Cursor queryImages(Activity context, String selection, String[] selectionArgs) {
String[] columns = new String[]{
MediaStore.Images.Media._ID,
MediaStore.Images.Media.DATA,
MediaStore.Images.Media.DISPLAY_NAME
};
return context.managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, selection, selectionArgs, MediaStore.Images.Media.DEFAULT_SORT_ORDER);
}
public static Bitmap queryImageById(Activity context, int imageId) {
String selection = MediaStore.Images.Media._ID + "=?";
String[] selectionArgs = new String[]{ imageId + "" };
Cursor cursor = BitmapUtils.queryImages(context, selection, selectionArgs);
if (cursor.moveToFirst()) {
String path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
cursor.close();
return BitmapUtils.decodeBitmap(path, 220);
} else {
cursor.close();
return null;
}
}
/**
* 依縮圖的 Id 取得對應的大圖
*/
public static Bitmap queryImageByThumbnailId(Activity context, Integer thumbId) {
String selection = MediaStore.Images.Thumbnails._ID + " = ?";
String[] selectionArgs = new String[]{ thumbId + "" };
Cursor cursor = BitmapUtils.queryThumbnails(context, selection, selectionArgs);
if (cursor.moveToFirst()) {
int imageId = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails.IMAGE_ID));
cursor.close();
return BitmapUtils.queryImageById(context, imageId);
} else {
cursor.close();
return null;
}
}
}
如此一來,就實現了類似百度圖片的瀏覽效果:縮圖網格瀏覽、點擊進入大圖藝廊、並以浮動視窗緩存控制記憶體,兼顧流暢與穩定。
Android 自定義 ImageView 實現透明圓弧與弧形文字
最近因為項目需求,需要在 ImageView 上疊加一層透明圓弧,並且沿著圓弧方向顯示相應的文字,效果如下圖所示: 拿到這個需求,我最直覺的思路就是自定義一個 Imag
Android 載入 Spinner:不確定進度列的顯示與隱藏
在 Android 中,ProgressBar 可分為有明確進度的進度列,以及不確定進度的加載 Spinner。當任務耗時未知,例如等待網路回應,Spinner 很適合提
Android 視圖控件架構解析:View 與 ViewGroup
控件樹的組成 Android 的視圖控件大致分為兩類:ViewGroup 與 View。ViewGroup 充當父容器,負責包含並管理子 View,兩者交錯組合便形成一棵
Android 的 Style 與 Theme:一次搞懂主題與樣式的分層設計
現在幾乎每家公司都會在 Android 上部署自己的客戶端,而使用者對介面美觀度的期待也越來越高。Style 與 Theme 就是 Android 用來統一視覺風格、提升