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

用 Gallery 實作「多級聯動」:專輯與歌曲的雙層選單

編輯:Android 開發實例

這個範例要做的效果是:上方一個 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>

unselectedAlpha 設為 0.5 是個小細節,能讓未被選中的項目半透明,視覺焦點自然落在中央。

二、兩個 Gallery 的 Adapter

在 Android 中,Adapter 很好地體現了 MVC 的思想,為元件提供資料與 View 的實作。這裡我們需要繼承 BaseAdapter,分別實作專輯與歌曲兩個適配器。

AlbumAdapter(專輯)

/**
 * 專輯
 */
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;
    }
}

這裡透過 MediaStore 查詢裝置上所有專輯,並在建立時先把封面圖全部讀進 Bitmap 陣列快取,避免 getView 呼叫時才去解圖造成滑動卡頓。

AudioAdapter(歌曲)

/**
 * 歌曲
 */
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();
    }
}

關鍵在最後那個自訂的 notifyDataSetChanged(int albumId):重新用新的專輯 ID 查一次資料庫、換掉 cursor,再呼叫父類別的 notifyDataSetChanged() 觸發重繪。這是整個聯動效果的樞紐。

三、Activity

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) {
            // 專輯被選中,取出專輯 ID
            int aid = (int) albumAdapter.getItemId(position);
            // 更新歌曲 Gallery
            audioAdapter.notifyDataSetChanged(aid);
        } else if (parent == audio) {
            // TODO 處理歌曲被選中的邏輯
        }
    }

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

思路很單純:讓 Activity 同時實作 OnItemSelectedListener,兩個 Gallery 都掛上同一個監聽器,然後在 onItemSelected 裡用 parent == album 判斷來源。當事件來自專輯 Gallery,就取出該位置的專輯 ID,交給歌曲 Adapter 的 notifyDataSetChanged(aid) 重新載入對應曲目,畫面立刻同步更新。

剩下的 onItemSelected 中 audio 的分支,你可以填入播放歌曲、更新 Now Playing 列等自己的邏輯,一個簡易的音樂播放器雛形就成形了。

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