編輯:進階開發
先前我們介紹過如何在 Android 中讓 Service 動態更新 UI。做 UI 時常會需要圖庫相簿那樣的元件,而 Gallery 正是 Android 上一個開源、免費、擴展性相當不錯的橫向捲動元件。本文示範用兩個 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>
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 實作 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 讀進記憶體後自行篩選。
Android 應用區域詳解:進程隔離、Zygote 與 APK 的優化產物
Android 平台可以促使行動裝置創新,讓使用者體驗到最優越的行動服務。當年美國運營商 AT&T 和 Verizon 沒有加入,微軟沒有加入,獨樹一幟的加拿大
Android 與 Linux 的裂痕:授權之爭與開源社群的質疑
Android 包含一個核心庫,提供了 Java 語言核心庫的大部分功能。而論與 Linux 的距離,它比 Mac OS 之於 Linux 還要遠——這樣的形容並不誇張。
Android 開發入門教程(五):讓 TextView 出現在螢幕上
Activity 本身是 Context 的子類,所以它也是一個 Context,這就是為什麼我們能在 TextView 的建構子裡直接寫 this。 設定要顯示的文字
Android 2.0 全面解析:新 API、Eclair 與 G1 的三方合作
Android 智慧手機為開發者帶來了一系列新 API,包含同步與藍牙等功能。對開發人員而言,Android 2.0 平台可作為 SDK 的一部分下載,內容涵蓋完整的 A