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

Android Gallery 圖片集控件詳解:橫向滾動相簿實作

編輯:Android 開發實例

Gallery 是 Android 中用來實作橫向滾動相簿的控件,項目會自動吸附在畫面中央,滑動時帶有流暢的慣性效果,很適合照片瀏覽、封面選擇這類介面。

一、簡介

Gallery 以水平方向排列清單項目,並將焦點項目鎖定在中心位置。它同樣是透過 Adapter 提供資料,可以顯示圖片、文字或任何自訂檢視。

二、實作範例

1. 布局檔

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

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

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

        <Gallery android:id="@+id/gallery1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_vertical"
            android:spacing="16dp" />

    </LinearLayout>

</LinearLayout>

2. 屬性宣告檔(res/values/attrs.xml)

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <declare-styleable name="TogglePrefAttrs">
        <attr name="android:preferenceLayoutChild" />
    </declare-styleable>

    <!-- 以下屬性供 view/Gallery1.java 從主題中讀取 -->
    <declare-styleable name="Gallery1">
        <attr name="android:galleryItemBackground" />
    </declare-styleable>

    <declare-styleable name="LabelView">
        <attr name="text" format="string" />
        <attr name="textColor" format="color" />
        <attr name="textSize" format="dimension" />
    </declare-styleable>

</resources>

3. Java 程式碼

package wjq.WidgetDemo;

import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.Contacts.People;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.SimpleCursorAdapter;
import android.widget.SpinnerAdapter;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;

public class GalleryDemo extends Activity {

    private Gallery gallery;
    private Gallery gallery1;

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

        gallery = (Gallery) findViewById(R.id.gallery);
        gallery.setAdapter(new ImageAdapter(this));

        registerForContextMenu(gallery);

        // 以「聯絡人」資料表作為第二個 Gallery 的資料來源
        Cursor c = getContentResolver().query(
                People.CONTENT_URI, null, null, null, null);
        startManagingCursor(c);

        SpinnerAdapter adapter = new SimpleCursorAdapter(this,
                android.R.layout.simple_gallery_item,
                c,
                new String[] { People.NAME },
                new int[] { android.R.id.text1 });

        gallery1 = (Gallery) findViewById(R.id.gallery1);
        gallery1.setAdapter(adapter);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {
        menu.add("Action");
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterContextMenuInfo info =
                (AdapterContextMenuInfo) item.getMenuInfo();
        Toast.makeText(this, "Longpress: " + info.position,
                Toast.LENGTH_SHORT).show();
        return true;
    }

    public class ImageAdapter extends BaseAdapter {

        int mGalleryItemBackground;
        private Context mContext;

        private Integer[] mImageIds = {
            R.drawable.b, R.drawable.c,
            R.drawable.d, R.drawable.f, R.drawable.g
        };

        public ImageAdapter(Context context) {
            mContext = context;

            TypedArray a = obtainStyledAttributes(R.styleable.Gallery1);
            mGalleryItemBackground = a.getResourceId(
                    R.styleable.Gallery1_android_galleryItemBackground, 0);
            a.recycle();
        }

        @Override
        public int getCount() {
            return mImageIds.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 i = new ImageView(mContext);

            i.setImageResource(mImageIds[position]);
            i.setScaleType(ImageView.ScaleType.FIT_XY);
            i.setLayoutParams(new Gallery.LayoutParams(300, 400));

            // 套用偏好的 Gallery 項目背景
            i.setBackgroundResource(mGalleryItemBackground);

            return i;
        }
    }
}

三、重點解析

這個範例示範了 Gallery 的兩種資料來源:一是自訂 BaseAdapter 搭配本地圖片資源陣列,二是用 SimpleCursorAdapter 直接把資料庫 Cursor 綁上去。此外,透過 obtainStyledAttributes 讀取自訂屬性,能把項目背景做成可從主題切換的樣式,這是 Android 自訂控件的標準做法。而 registerForContextMenu 加上長按選單,則提供了取得目前項目索引的簡便途徑。

四、實務提醒

Gallery 在新版 Android 中已被標示為不建議使用(deprecated),官方建議改用 RecyclerView 搭配水平方向的 LinearLayoutManager 來實作相同效果,效能與客製彈性都更好。理解 Gallery 的 Adapter 思維,有助於無痛遷移到 RecyclerView。

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