編輯:Android 開發實例
GridView 以列與行交錯的方式排列內容,最適合呈現圖示、縮圖這類尺寸接近的方塊資料。它的用法與 Gallery 類似,核心同樣是「提供一個 Adapter,其餘交給元件」。
第一是欄數。透過 setNumColumns() 決定每一列放幾個單元格,這個值會直接影響整體版面的密度。第二是單元格外觀,這需要在 Adapter 的 getView() 裡自行決定,GridView 不會幫你排版內部內容。
package com.amaker.test;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
public class MainActivity extends Activity {
private GridView gv;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gv = (GridView)findViewById(R.id.GridView01);
gv.setNumColumns(4);
gv.setAdapter(new MyAdapter(this));
}
class MyAdapter extends BaseAdapter {
private Integer[] imgs = {
R.drawable.gallery_photo_1, R.drawable.gallery_photo_2,
R.drawable.gallery_photo_3, R.drawable.gallery_photo_4,
R.drawable.gallery_photo_5, R.drawable.gallery_photo_6,
R.drawable.gallery_photo_7, R.drawable.gallery_photo_8,
R.drawable.gallery_photo_1, R.drawable.gallery_photo_2,
R.drawable.gallery_photo_3, R.drawable.gallery_photo_4,
R.drawable.gallery_photo_5, R.drawable.gallery_photo_6,
R.drawable.gallery_photo_7, R.drawable.gallery_photo_8
};
Context context;
MyAdapter(Context context) {
this.context = context;
}
public int getCount() {
return imgs.length;
}
public Object getItem(int item) {
return item;
}
public long getItemId(int id) {
return id;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(context);
imageView.setLayoutParams(new GridView.LayoutParams(45, 45));
imageView.setAdjustViewBounds(false);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(imgs[position]);
return imageView;
}
}
}
getView() 裡出現了 if (convertView == null) 的判斷,這是列表類元件的標準複用寫法:屬性設定(尺寸、縮放模式、內距)只在建立新 View 時做一次,後續則直接重用傳入的 convertView,只更新圖片內容。這樣可以大幅減少 View 的建立次數,是效能上最重要的一課。
縮放模式選用 CENTER_CROP 而非 FIT_XY,是因為網格單元格通常尺寸固定,用裁切填滿比變形拉伸美觀。若想保留完整圖形,可改為 FIT_CENTER 並搭配背景色填補。
另外,若資料只是簡單的字串陣列,也可以直接改用 ArrayAdapter,不必自己繼承 BaseAdapter;只有在需要自訂單元格外觀時,才有必要走自訂 Adapter 這條路。
Android 實作 Market 風格的 Loading 效果:自訂版面取代 ProgressDialog
在 Android 裡做載入提示,直覺做法是 ProgressDialog。ApiDemos 中的 ProgressBar3.java 就示範了兩種典型用法:但仔細看 A
Android 應用本地化:讓同一支 App 說多國語言
一支上架的 Android 應用,可能被義大利的學生、西班牙的通勤族、日本的上班族同時打開。要讓每個人都覺得「這 App 是為我做的」,本地化(Localization)
Android 登入介面教學:三次錯誤即停用按鈕
需要帳號的服務,就一定會有登入畫面。使用者在此輸入一組憑證,App 驗證通過後才導向下一頁——Facebook、微博這類應用都是這個模式。本章示範如何從零做出一個登入介面
Android 登入功能:介面與安全機制實作
登入畫面是幾乎每款需要帳號的 App 都少不了的入口。使用者在此輸入帳號與密碼,系統驗證無誤後才允許進入——不論是 Facebook、微博等社群平台,還是各種自製服務,都