編輯:關於 Android 開發
Gallery 雖然早已被標記為過時控件,但在維護老專案時仍然常見。它的用法其實很經典:自定義一個 BaseAdapter 把圖片餵進去,再掛上 OnItemClickListener 就能拿到點擊位置。下面是一個可直接跑的完整示例。
package com.example.Gallery;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Toast;
import com.example.Gallery.R;
public class MainActivity extends Activity {
private Gallery gallery;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gallery = (Gallery) findViewById(R.id.gallery);
// 設置圖片適配器
gallery.setAdapter(new ImageAdapter(this));
// 設置點擊監聽
gallery.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Toast.makeText(MainActivity.this,
"點擊了第 " + (arg2 + 1) + " 張圖片",
Toast.LENGTH_LONG).show();
}
});
}
}
class ImageAdapter extends BaseAdapter {
private Context context;
// 圖片資源數組
private Integer[] imageInteger = {
R.drawable.item1, R.drawable.item2, R.drawable.item3, R.drawable.item4,
R.drawable.item5, R.drawable.item6, R.drawable.item7, R.drawable.item8,
R.drawable.item9, R.drawable.item10, R.drawable.item11, R.drawable.item12,
R.drawable.item13, R.drawable.item14, R.drawable.item15
};
public ImageAdapter(Context c) {
context = c;
}
@Override public int getCount() {
return imageInteger.length;
}
@Override public Object getItem(int position) {
return position;
}
@Override public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(context);
imageView.setImageResource(imageInteger[position]);
imageView.setBackgroundColor(0xFF000000);
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageView.setLayoutParams(new Gallery.LayoutParams(136, 88));
return imageView;
}
}
幾個值得留意的細節:getItem 與 getItemId 這裡直接回傳 position,因為示例不需要更精細的標識;getView 中每次都 new 一個 ImageView,在 Gallery 這種元素數量有限的場景下可接受,但若圖片很多,仍建議加上 convertView 複用與ViewHolder 模式。
執行效果:

騰訊 GT 隨身調:Android 效能測試工具介紹
騰訊 GT 隨身調:手機端 App 效能測試工具 在進行 App 測試時,除了功能驗證,也需要關注 CPU、記憶體、流量、電量與流暢度等效能指標。騰訊開源的 GT(隨身調
Android 效能優化:常見的記憶體洩漏與對策
前言 記憶體洩漏幾乎每個人都遇過,只是它藏在堆(heap)中,看不見摸不著。要檢測是否發生洩漏,實務上常借助工具:MAT 功能強大但上手門檻高;LeakCanary 則是
用懸浮窗進一步降低螢幕亮度、護眼過濾藍光(Android App 實作)
用懸浮窗進一步降低螢幕亮度、護眼過濾藍光(Android App 實作) 專案網址:https://github.com/hwding/make-it-darker 歡迎
優秀 App 設計的 6 個關鍵習慣
偉大的設計往往來源於兩件事:一致性與對細節的執著。好消息是,這兩點並不依賴天賦——只要有足夠的紀律,任何團隊都能做到。以下六個習慣,是打造高品質 App 的必經之路。 一