Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

讓 Gallery 無限循環顯示圖片

編輯:Android 開發實例

Gallery 主要用來橫向排列圖片。依慣例寫法,它只會顯示你給的那幾張,滑到最後一張就到底了。多數情況夠用,但我們有時希望滑到尾端能回到第一張,形成循環。要做到這件事,得改動 Adapter。

傳統用法回顧

把圖片放進 res/drawable,然後用一個 int 陣列記住資源 ID:

private int[] resIds = new int[]
    { 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 };

佈局裡放一個 Gallery:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <Gallery android:id="@+id/gallery"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp" />
</LinearLayout>

在 onCreate 中掛上 Adapter:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    // 裝載 Gallery 組件
    Gallery gallery = (Gallery) findViewById(R.id.gallery);
    // 建立描述圖片資料的 Adapter
    ImageAdapter imageAdapter = new ImageAdapter(this);
    gallery.setAdapter(imageAdapter);
}

Adapter 本身繼承 BaseAdapter:

public class ImageAdapter extends BaseAdapter {
    int mGalleryItemBackground;
    private Context mContext;

    public ImageAdapter(Context context) {
        mContext = context;
        // 取得 Gallery 的屬性
        TypedArray typedArray = obtainStyledAttributes(R.styleable.Gallery);
        mGalleryItemBackground = typedArray.getResourceId(
                R.styleable.Gallery_android_galleryItemBackground, 0);
    }

    // 傳回圖片總數
    public int getCount() {
        return resIds.length;
    }

    public Object getItem(int position) {
        return position;
    }

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

    // 傳回指定位置的 ImageView
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView = new ImageView(mContext);
        imageView.setImageResource(resIds[position]);
        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
        imageView.setLayoutParams(new Gallery.LayoutParams(163, 106));
        imageView.setBackgroundResource(mGalleryItemBackground);
        return imageView;
    }
}

上述屬性定義在 res/values/attrs.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="Gallery">
        <attr name="android:galleryItemBackground" />
    </declare-styleable>
</resources>

兩個要點:getCount() 傳回的數量不能超過實際圖片數(可以少於),否則會越界;getView() 則是 Gallery 每次要顯示某張圖時才呼叫,也就是說 Gallery 是「隨用隨取」,並不會一次把全部圖片都載入記憶體。

循環的原理

循環的概念跟循環鏈我一樣:最後一筆的下一筆又回到第一筆。

關鍵關係在 getCount() 與 getView() 的 position 參數——position 的範圍是 0 到 getCount() - 1。如果我們讓 getCount() 回傳一個極大的值,position 就能一路遞增;再用取餘把大索引折回陣列範圍內,圖片就會不斷循環:

resIds[position % resIds.length]

於是只需要兩處改動:

  • getCount() 回傳 Integer.MAX_VALUE。
  • getView() 用取餘取得資源 ID。

嚴格說這是「偽循環」——真的滑到第 20 億張還是會到底,只是那個數字大到實務上等同無限。

加上放大預覽

再搭配 ImageSwitcher,點選縮圖時在下方放大顯示,畫面會完整很多。

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <Gallery android:id="@+id/gallery"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp" />
    <ImageSwitcher android:id="@+id/imageswitcher"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp" />
</LinearLayout>
public class Main extends Activity implements OnItemSelectedListener, ViewFactory {
    private Gallery gallery;
    private ImageSwitcher imageSwitcher;
    private ImageAdapter imageAdapter;

    private int[] resIds = new int[]
        { 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 class ImageAdapter extends BaseAdapter {
        int mGalleryItemBackground;
        private Context mContext;

        public ImageAdapter(Context context) {
            mContext = context;
            TypedArray typedArray = obtainStyledAttributes(R.styleable.Gallery);
            mGalleryItemBackground = typedArray.getResourceId(
                    R.styleable.Gallery_android_galleryItemBackground, 0);
        }

        // 改動一:回傳極大值
        public int getCount() {
            return Integer.MAX_VALUE;
        }

        public Object getItem(int position) {
            return position;
        }

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

        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView imageView = new ImageView(mContext);
            // 改動二:取餘循環取得資源 ID
            imageView.setImageResource(resIds[position % resIds.length]);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            imageView.setLayoutParams(new Gallery.LayoutParams(163, 106));
            imageView.setBackgroundResource(mGalleryItemBackground);
            return imageView;
        }
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        // 選中縮圖時在 ImageSwitcher 中放大顯示
        imageSwitcher.setImageResource(resIds[position % resIds.length]);
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
    }

    @Override
    // ImageSwitcher 需要這個方法來建立顯示用的 View
    public View makeView() {
        ImageView imageView = new ImageView(this);
        imageView.setBackgroundColor(0xFF000000);
        imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
        imageView.setLayoutParams(new ImageSwitcher.LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
        return imageView;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        gallery = (Gallery) findViewById(R.id.gallery);
        imageAdapter = new ImageAdapter(this);
        gallery.setAdapter(imageAdapter);
        gallery.setOnItemSelectedListener(this);

        imageSwitcher = (ImageSwitcher) findViewById(R.id.imageswitcher);
        // 設定 ImageSwitcher 的工廠
        imageSwitcher.setFactory(this);
        // 設定切換動畫
        imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,
                android.R.anim.fade_in));
        imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,
                android.R.anim.fade_out));
    }
}

總結

實現循環顯示的關鍵只有兩句:getCount() 回傳一個極大的整數(例如 Integer.MAX_VALUE),並在 getView() 中透過取餘循環取得資源 ID。想改成真正的無限循環,也可以自行覆寫 Gallery 的滾動行為,但對絕大多數需求來說,上面這招已經足夠。

另外值得一提:Gallery 在新版 Android 已被標記為 deprecated,正式專案建議改用 HorizontalScrollView 搭配 RecyclerView 或 ViewPager 來實作同類效果。

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