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

用 Gallery 元件打造類似 iPhone 的圖片滑動效果

編輯:關於 Android 程式設計

本文示範如何運用 Android 的 Gallery 元件,做出可以左右滑動切換的相簿效果,操作手感相當接近 iPhone 的圖片瀏覽。

第一步:在版面配置中放入 Gallery

<?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" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <Gallery
        android:id="@+id/gallery"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />
</LinearLayout>

第二步:自訂 Adapter 餵資料

Gallery 需要透過 Adapter 來填充內容,因此我們從 BaseAdapter 派生一個 ImageAdapter,把要顯示的圖片資源逐一載入:

public class ImageAdapter extends BaseAdapter {
    private Context context;
    private int[] MyImageIDs = {
        R.drawable.icon, R.drawable.carlogo_52design_09,
        R.drawable.carlogo_52design_13, R.drawable.carlogo_52design_19,
        R.drawable.carlogo_52design_24, R.drawable.carlogo_52design_27,
        R.drawable.carlogo_52design_29, R.drawable.carlogo_52design_31,
        R.drawable.carlogo_52design_34, R.drawable.carlogo_52design_36 };

    public ImageAdapter(Context context) {
        this.context = context;
    }

    @Override
    public int getCount() {
        return MyImageIDs.length;
    }

    @Override
    public Object getItem(int arg0) {
        return arg0;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView i = new ImageView(this.context);
        i.setImageResource(this.MyImageIDs[position]);
        i.setScaleType(ImageView.ScaleType.FIT_XY);
        i.setLayoutParams(new Gallery.LayoutParams(120, 120));
        return i;
    }
}

在 getView() 中,我們為每個位置建立一個 ImageView,設定圖片、縮放模式與尺寸,Gallery 便會自動處理滑動與對齊的細節。最後別忘了在 Activity 裡建立 Gallery 實例、套用這個 Adapter,就能得到流暢的左右滑動體驗。

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