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

在 Android 開發中用 Gallery 實作「多級聯動」

編輯:進階開發

先前我們介紹過如何在 Android 中讓 Service 動態更新 UI。做 UI 時常會需要圖庫相簿那樣的元件,而 Gallery 正是 Android 上一個開源、免費、擴展性相當不錯的橫向捲動元件。本文示範用兩個 Gallery 做出類似「多級聯動」的效果。

概念很單純:上面一個 Gallery 顯示歌曲專輯封面,下面一個 Gallery 顯示該專輯的歌曲。滑動上面的專輯 Gallery,下面的歌曲清單也跟著換。

Gallery 的版面配置

主要結構是兩個 Gallery 加上一個 RelativeLayout 作為定位依據:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    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_alignParentTop="true"
        android:gravity="center_horizontal"
        android:spacing="16dp"
        android:unselectedAlpha="0.5"/>

    <!-- 歌曲 -->
    <Gallery android:id="@+id/gallery2"
        android:background="#FFF"
        android:layout_width="fill_parent"
        android:layout_height="30dp"
        android:layout_below="@id/gallery"
        android:layout_alignParentLeft="true"
        android:gravity="center_vertical"
        android:spacing="16dp"
        android:unselectedAlpha="0.5" />
</RelativeLayout>

兩個 Gallery 的 Adapter

Android 的 Adapter 可以說是 MVC 概念的實踐者,它同時負責提供資料與決定每個項目外觀。這裡我們繼承 BaseAdapter,實作兩個 Gallery 各自需要的 Adapter。

專輯用的 AlbumAdapter:

/**
 * 專輯 Adapter
 */
public class AlbumAdapter extends BaseAdapter {

    private Context context;
    private Cursor cursor;
    private Bitmap[] bitmaps;

    public AlbumAdapter(Context context) {
        this.context = context;
        this.cursor = context.getContentResolver().query(
                MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, null, null, null,
                MediaStore.Audio.Albums.DEFAULT_SORT_ORDER);
        bitmaps = new Bitmap[cursor.getCount()];
        initBitmaps();
    }

    /** 初始化專輯封面圖片 */
    private void initBitmaps() {
        if (cursor.moveToFirst()) {
            do {
                bitmaps[cursor.getPosition()] = MusicUtils.getArtwork(context, -1, cursor
                        .getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Albums._ID)));
            } while (cursor.moveToNext());
        }
    }

    public int getCount() {
        if (cursor != null) {
            return cursor.getCount();
        }
        return 0;
    }

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

    public long getItemId(int position) {
        if (cursor != null) {
            cursor.moveToPosition(position);
            return cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Albums._ID));
        }
        return 0;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView iv = new ImageView(context);
        iv.setLayoutParams(new Gallery.LayoutParams(100, 100));
        iv.setAdjustViewBounds(true);
        iv.setImageBitmap(bitmaps[position]);
        return iv;
    }
}

歌曲用的 AudioAdapter,多了一個 albumId 參數,並提供一個可帶參數的 notifyDataSetChanged,用來在專輯改變時換掉查詢結果:

/**
 * 歌曲 Adapter
 */
public class AudioAdapter extends BaseAdapter {

    private Context context;
    private Cursor cursor;
    /** 專輯 ID */
    private int albumId;

    public AudioAdapter(Context context, int albumId) {
        this.context = context;
        this.albumId = albumId;
        this.cursor = context.getContentResolver().query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null,
                MediaStore.Audio.Media.ALBUM_ID + "=" + albumId, null,
                MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
    }

    public int getCount() {
        if (cursor != null) {
            return cursor.getCount();
        }
        return 0;
    }

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

    public long getItemId(int position) {
        if (cursor != null) {
            cursor.moveToPosition(position);
            return cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID));
        }
        return 0;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        cursor.moveToPosition(position);
        TextView t = new TextView(context);
        String title = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
        t.setLayoutParams(new Gallery.LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT));
        t.setText(title);
        t.setTextColor(Color.BLACK);
        return t;
    }

    /**
     * 當專輯改變了,呼叫此方法更新 Adapter 的資料
     * @param albumId 專輯 ID
     */
    public void notifyDataSetChanged(int albumId) {
        this.cursor = context.getContentResolver().query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null,
                MediaStore.Audio.Media.ALBUM_ID + "=" + albumId, null,
                MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
        super.notifyDataSetChanged();
    }
}

Activity 串起聯動

最後讓 Activity 實作 OnItemSelectedListener,在上層 Gallery 的選項改變時,把新的專輯 ID 交給下層 Adapter:

public class MainActivity extends Activity implements AdapterView.OnItemSelectedListener {

    private Gallery album;
    private Gallery audio;
    private AlbumAdapter albumAdapter;
    private AudioAdapter audioAdapter;

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

    private void setupViews() {
        album = (Gallery) findViewById(R.id.gallery);
        audio = (Gallery) findViewById(R.id.gallery2);

        albumAdapter = new AlbumAdapter(this);
        album.setAdapter(albumAdapter);

        int aid = (int) albumAdapter.getItemId(0);
        audioAdapter = new AudioAdapter(this, aid);
        audio.setAdapter(audioAdapter);

        audio.setOnItemSelectedListener(this);
        album.setOnItemSelectedListener(this);
    }

    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        if (parent == album) {
            // 專輯被選中
            int aid = (int) albumAdapter.getItemId(position);
            audioAdapter.notifyDataSetChanged(aid);   // 更新歌曲 Gallery
        } else if (parent == audio) {
            // TODO 在此處理歌曲被選中的行為
        }
    }

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

這就是在 Android 開發中使用 Gallery 實作「多級聯動」的完整示範。

兩個實作上的提醒:Gallery 的 getView 每次都 new 一個 View,在真机上大量資料時容易造成 GC 抖動,正式專案建議搭配 convertView 重用;另外每次換專輯都重新 query MediaStore 一次成本不低,若資料量龐大,可考慮一次把 albums 與 songs 讀進記憶體後自行篩選。

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