Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 用 Gallery 搭配 ImageSwitcher 實作圖片瀏覽

編輯:關於 Android 程式設計

Gallery 提供橫向捲動的縮圖列表,ImageSwitcher 則負責把選中的圖片帶著切換動畫呈現出來,兩者搭配起來,就是一個最經典的簡易相簿。這個組合的優點是程式碼量很少,適合快速做出可用的圖片瀏覽體驗。

版面配置

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Gallery
        android:id="@+id/gallery1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <ImageSwitcher
        android:id="@+id/imageSwitcher1"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

</LinearLayout>

這裡讓 ImageSwitcher 使用 layout_height="0dp" 搭配 layout_weight="1",它便會自動占滿 Gallery 以下的剩餘空間,Gallery 則依內容決定高度,版面不會互相擠壓。

縮圖的項目配置

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/an01" />

</LinearLayout>

MainActivity 實作

public class MainActivity extends Activity {

    private Gallery gallery;
    private ImageSwitcher imageSwitcher;

    private int res[] = new int[] {
        R.drawable.ic_launcher,
        R.drawable.an01, R.drawable.an02, R.drawable.an03,
        R.drawable.an01, R.drawable.an02, R.drawable.an03
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        gallery = (Gallery) findViewById(R.id.gallery1);
        imageSwitcher = (ImageSwitcher) findViewById(R.id.imageSwitcher1);

        // ImageSwitcher 需要透過工廠產生實際顯示用的 View,只需設定一次
        imageSwitcher.setFactory(new ImageSwitcher.ViewFactory() {
            @Override
            public View makeView() {
                ImageView imageView = new ImageView(MainActivity.this);
                imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
                return imageView;
            }
        });

        // 加上淡入淡出,切換時不會有突兀的閃跳
        imageSwitcher.setInAnimation(
                AnimationUtils.loadAnimation(this, android.R.anim.fade_in));
        imageSwitcher.setOutAnimation(
                AnimationUtils.loadAnimation(this, android.R.anim.fade_out));

        // 整理資料,餵給 SimpleAdapter
        List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
        for (int i = 0; i < res.length; i++) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("imageView", res[i]);
            data.add(map);
        }

        SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.activity_cell,
                new String[] { "imageView" }, new int[] { R.id.imageView1 });
        gallery.setAdapter(adapter);

        gallery.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // 用取餘確保資料循環,捲到尾端不會越界
                int imageResId = res[position % res.length];
                imageSwitcher.setImageResource(imageResId);
            }
        });
    }
}

幾個實作要點

setFactory 只呼叫一次。ImageSwitcher 內部只會保留兩個子 View 用來做切換動畫,工廠負責產生它們,重複設定反而會造成狀態混亂。

自訂 Adapter 可換取無限捲動。若希望兩端可以無限循環,可改寫繼承 BaseAdapter 的 MyAdapter,讓 getCount() 回傳 Integer.MAX_VALUE,並以 res[position % res.length] 取值。這也是範例中原本註解掉的那段程式碼的用意。

Gallery 已被標記為 deprecated。它在新版 Android 中不再建議使用,若是新專案,建議改用 RecyclerView 搭配 LinearLayoutManager(橫向)實作同樣的效果,並可獲得更好的回收機制與效能表現。若只是維護舊專案,理解 Gallery 的運作方式仍有其價值。

大圖載入要留意記憶體。若圖片來源是相簿中的高解析度照片,直接 setImageResource 或解碼原圖容易觸發 OutOfMemoryError。實務上會先用 BitmapFactory.Options 的 inJustDecodeBounds 讀取尺寸,再以 inSampleSize 降採樣,或改用 Glide、Picasso 這類影像載入框架來處理快取與回收。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved