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

Gallery 與 ImageView:做出可橫向滑動的圖片瀏覽

編輯:Android 開發教學

Gallery 可以顯示一系列圖片並支援橫向滑動。以下示範如何用 Gallery 搭配 ImageView 做一個簡易的圖片瀏覽器。

一、建立專案 Gallery

二、main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Images of San Francisco" />

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

    <ImageView
        android:id="@+id/image1"
        android:layout_width="320dp"
        android:layout_height="250dp"
        android:scaleType="fitXY" />
</LinearLayout>

三、在 res/values 下建立 attrs.xml

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

四、準備圖片

把圖片放進 res/drawable-mdpi。

五、Adapter 與監聽

Gallery 本身不負責載入圖片,必須提供一個 Adapter。最簡單的做法是繼承 BaseAdapter,在 getView() 中回傳一個設好背景的 ImageView:

imageView.setLayoutParams(new Gallery.LayoutParams(150, 100));
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setImageResource(mImageIds[position]);
imageView.setBackgroundResource(
        android.R.drawable.galleryItemBackground);

再掛上 OnItemSelectedListener,在 onItemSelected 中把對應圖片設給下方的大 ImageView,滑動與預覽就連起來了。

attrs.xml 那段 declare-styleable 之所以必要,是因為 galleryItemBackground 這個屬性要透過它才能被正確解析,少了它會在執行時報找不到屬性的錯誤。另外提醒:Gallery 在新版 Android 中已被標記為不建議使用,官方建議改用 RecyclerView 搭配橫向 LayoutManager 或 ViewPager 來實作相同效果。

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