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

Android 音樂播放器(二):清單界面、播放控制與斜切轉場動畫

編輯:關於 Android 程式設計

寫程式的過程中想法總在變,同一個功能常常糾結於「哪一種做法更好」。這個音樂播放器原本規劃把歌單頁與歌詞頁放進同一個 Activity 的兩個 Fragment,靠左右滑動切換;後來看到酷狗的做法——點擊左下角按鈕,歌詞頁從右下角斜切上來——覺得更有意思,於是改成了後者。

先看一下實際效果(用 4.4 的 AVD 錄製,因為斜切動畫依賴 3.0 才有的屬性,2.3 的機器做不出來;模擬器跑起來實在慢):

做得比較趕,仍有若干 Bug,歌詞同步也還沒實作,敬請包容。

一、主界面布局

主界面由清單與底部控制列組成,進度條用了自訂樣式:

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

    <ListView
        android:id="@+id/lvSongs"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="8"
        android:cacheColorHint="#00000000" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="#BBBBBB">

        <Button
            android:id="@+id/btnDetail"
            android:layout_width="48dip"
            android:layout_height="48dip"
            android:background="@drawable/music_app"
            android:layout_alignParentBottom="true"
            android:layout_alignParentTop="true" />

        <SeekBar
            android:id="@+id/pbDuration"
            android:layout_width="wrap_content"
            android:layout_height="10dip"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:layout_toRightOf="@+id/btnDetail"
            android:maxHeight="1dip"
            android:minHeight="1dip"
            android:progressDrawable="@drawable/progress_style"
            android:thumb="@drawable/seekbar_thumb"
            android:thumbOffset="0dip" />

        <TextView
            android:id="@+id/tvCurrentMusic"
            android:layout_width="190dp"
            android:layout_height="32dip"
            android:layout_alignBaseline="@+id/btnNext"
            android:layout_toRightOf="@+id/btnDetail"
            android:gravity="left|center_vertical" />

        <Button
            android:id="@+id/btnStartStop"
            android:layout_width="32dip"
            android:layout_height="32dip"
            android:layout_alignBaseline="@+id/btnNext"
            android:layout_below="@+id/pbDuration"
            android:layout_toLeftOf="@+id/btnNext"
            android:background="@drawable/play" />

        <Button
            android:id="@+id/btnNext"
            android:layout_width="24dp"
            android:layout_height="24dp"
            android:layout_alignParentRight="true"
            android:layout_below="@+id/pbDuration"
            android:background="@drawable/forward" />
    </RelativeLayout>
</LinearLayout>

二、詳情頁布局

詳情頁自上而下分三塊:標題、歌詞區、進度與五個自訂圖示按鈕。歌詞暫未實作,先顯示「To Continue...」。

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

    <TextView
        android:id="@+id/tvTitle"
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="1"
        android:background="#00EEEE"
        android:gravity="center_vertical" />

    <TextView
        android:id="@+id/tvLyric"
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="9"
        android:gravity="center_vertical"
        android:text="To Continue...." />

    <LinearLayout
        android:id="@+id/llProgress"
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="1"
        android:gravity="center_horizontal"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/tvTimeElapsed"
            android:layout_width="0dip"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="00:00" />

        <SeekBar
            android:id="@+id/pbDuration"
            android:layout_width="0dip"
            android:layout_height="10dip"
            android:layout_weight="6"
            android:maxHeight="1dip"
            android:minHeight="1dip"
            android:progressDrawable="@drawable/progress_style"
            android:thumb="@drawable/seekbar_thumb"
            android:thumbOffset="0dip" />

        <TextView
            android:id="@+id/tvDuration"
            android:layout_width="0dip"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="00:00" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="2"
        android:orientation="horizontal">

        <com.example.nature.CustomAudioIcon
            android:id="@+id/btnMode"
            android:layout_width="0dip"
            android:layout_height="match_parent"
            android:layout_weight="1"
            custom:type="mode"
            custom:color="#66DD22" />
        <com.example.nature.CustomAudioIcon
            android:id="@+id/btnPrevious"
            android:layout_width="0dip"
            android:layout_height="match_parent"
            android:layout_weight="1"
            custom:type="backward"
            custom:color="#66DD22" />
        <com.example.nature.CustomAudioIcon
            android:id="@+id/btnStartStop"
            android:layout_width="0dip"
            android:layout_height="match_parent"
            android:layout_weight="1"
            custom:type="start"
            custom:color="#66DD22" />
        <com.example.nature.CustomAudioIcon
            android:id="@+id/btnNext"
            android:layout_width="0dip"
            android:layout_height="match_parent"
            android:layout_weight="1"
            custom:type="forward"
            custom:color="#66DD22" />
        <com.example.nature.CustomAudioIcon
            android:id="@+id/btnExit"
            android:layout_width="0dip"
            android:layout_height="match_parent"
            android:layout_weight="1"
            custom:type="exit"
            custom:color="#66DD22" />
    </LinearLayout>
</LinearLayout>

五個按鈕都是自訂 View,實作細節見上一篇〈自訂按鈕的實作〉。

三、控制邏輯

MainActivity 負責清單、播放列與和 Service 的綁定:

public class MainActivity extends Activity implements OnClickListener {
    public static final String TAG = "com.example.nature.MAIN_ACTIVITY";

    private ListView lvSongs;
    private SeekBar pbDuration;
    private TextView tvCurrentMusic;
    private List<MusicInfo> musicList;
    private int currentMusic;      // 正在播放的曲目索引
    private int currentPosition;   // 當前播放位置
    private int currentMax;        // 當前曲目總長
    private Button btnStartStop, btnNext, btnDetail;
    private ProgressReceiver progressReceiver;
    private NatureBinder natureBinder;

    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override public void onServiceDisconnected(ComponentName name) { }
        @Override public void onServiceConnected(ComponentName name, IBinder service) {
            natureBinder = (NatureBinder) service;
        }
    };

    private void connectToNatureService() {
        bindService(new Intent(this, NatureService.class),
                    serviceConnection, BIND_AUTO_CREATE);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        musicList = MusicLoader.instance(getContentResolver()).getMusicList();
        connectToNatureService();
        initComponents();
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver();
        if (natureBinder != null) {
            btnStartStop.setBackgroundResource(
                natureBinder.isPlaying() ? R.drawable.pause : R.drawable.play);
            natureBinder.notifyActivity();   // 主動向 Service 索取當前狀態
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(progressReceiver);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (natureBinder != null) unbindService(serviceConnection);
    }

    private void initComponents() {
        pbDuration = (SeekBar) findViewById(R.id.pbDuration);
        pbDuration.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
            @Override public void onStopTrackingTouch(SeekBar seekBar) { }
            @Override public void onStartTrackingTouch(SeekBar seekBar) { }
            @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) natureBinder.changeProgress(progress);
            }
        });

        tvCurrentMusic = (TextView) findViewById(R.id.tvCurrentMusic);
        btnStartStop = (Button) findViewById(R.id.btnStartStop);
        btnStartStop.setOnClickListener(this);
        btnNext = (Button) findViewById(R.id.btnNext);
        btnNext.setOnClickListener(this);
        btnDetail = (Button) findViewById(R.id.btnDetail);
        btnDetail.setOnClickListener(this);

        lvSongs = (ListView) findViewById(R.id.lvSongs);
        lvSongs.setAdapter(new MusicAdapter());
        lvSongs.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                currentMusic = position;
                natureBinder.startPlay(currentMusic, 0);
                if (natureBinder.isPlaying()) {
                    btnStartStop.setBackgroundResource(R.drawable.pause);
                }
            }
        });
    }

    private void registerReceiver() {
        progressReceiver = new ProgressReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(NatureService.ACTION_UPDATE_PROGRESS);
        filter.addAction(NatureService.ACTION_UPDATE_DURATION);
        filter.addAction(NatureService.ACTION_UPDATE_CURRENT_MUSIC);
        registerReceiver(progressReceiver, filter);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnStartStop:
                play(currentMusic, R.id.btnStartStop);
                break;
            case R.id.btnNext:
                natureBinder.toNext();
                break;
            case R.id.btnDetail:
                Intent intent = new Intent(this, DetailActivity.class);
                intent.putExtra(DetailActivity.MUSIC_LENGTH, currentMax);
                intent.putExtra(DetailActivity.CURRENT_MUSIC, currentMusic);
                intent.putExtra(DetailActivity.CURRENT_POSITION, currentPosition);
                startActivity(intent);
                break;
        }
    }

    private void play(int position, int resId) {
        if (natureBinder.isPlaying()) {
            natureBinder.stopPlay();
            btnStartStop.setBackgroundResource(R.drawable.play);
        } else {
            natureBinder.startPlay(position, currentPosition);
            btnStartStop.setBackgroundResource(R.drawable.pause);
        }
    }
}

清單的兩項標準優化

繼承 BaseAdapter 時有兩個約定俗成的優化:

  1. 複用 convertView:同一時刻螢幕上只需要少量 View 物件,回收再用可避免頻繁 inflate。
  2. 使用 ViewHolder:把 findViewById 的結果掛在 convertView.setTag() 上,不必每列都重新查找一次。
class MusicAdapter extends BaseAdapter {
    @Override public int getCount() { return musicList.size(); }
    @Override public Object getItem(int position) { return musicList.get(position); }
    @Override public long getItemId(int position) { return musicList.get(position).getId(); }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = LayoutInflater.from(MainActivity.this)
                                       .inflate(R.layout.music_item, null);
            holder = new ViewHolder(
                (ImageView) convertView.findViewById(R.id.albumPhoto),
                (TextView) convertView.findViewById(R.id.title),
                (TextView) convertView.findViewById(R.id.duration),
                (TextView) convertView.findViewById(R.id.artist));
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.imageView.setImageResource(R.drawable.audio);
        holder.title.setText(musicList.get(position).getTitle());
        holder.duration.setText(FormatHelper.formatDuration(musicList.get(position).getDuration()));
        holder.artist.setText(musicList.get(position).getArtist());
        return convertView;
    }
}

Service 與 Activity 的雙向溝通

播放、暫停、上下一首、切換模式這些動作全放在 Service 裡,Activity 只負責畫面。Service 內部提供一個 Binder,把能力暴露給 Activity:

class NatureBinder extends Binder {
    public void startPlay(int currentMusic, int currentPosition) { play(currentMusic, currentPosition); }
    public void stopPlay()  { stop(); }
    public void toNext()    { playNext(); }
    public void toPrevious(){ playPrevious(); }

    /** MODE_ONE_LOOP=1, MODE_ALL_LOOP=2, MODE_RANDOM=3, MODE_SEQUENCE=4 */
    public void changeMode() {
        currentMode = (currentMode + 1) % 4;
        Toast.makeText(NatureService.this, MODE_DESC[currentMode], Toast.LENGTH_SHORT).show();
    }

    public int  getCurrentMode() { return currentMode; }
    public boolean isPlaying()   { return isPlaying; }

    /** 讓 Activity 在 onResume 時主動拉一次最新狀態 */
    public void notifyActivity() {
        toUpdateCurrentMusic();
        toUpdateDuration();
    }

    public void changeProgress(int progress) { /* seek 到指定位置 */ }
}

反過來,Service 透過自訂的 BroadcastReceiver 主動推送狀態:目前播放位置、總長度、當前曲目,讓 Activity 更新進度條與標題。

四、兩個容易忽略的細節

廣播的註冊時機。建議放在 onResume() 註冊、onPause() 取消。這樣從歌詞頁切回主頁時只會走 onResume(),廣播自然重新掛上,不必讓它在你根本看不到畫面時還持續接收。

跨頁面的狀態同步。假設你在詳情頁聽完一首、Service 自動跳到下一首,此時切回主頁,Service 並不會「補發」一次廣播給主頁(它只在切歌那一刻廣播)。解法是在 onResume() 裡主動呼叫 natureBinder.notifyActivity(),向 Service 索取當前曲目與長度:

public void onResume() {
    super.onResume();
    registerReceiver();
    if (natureBinder != null) {
        natureBinder.notifyActivity();
    }
}

五、斜切轉場動畫

DetailActivity 用 overridePendingTransition 做出「從右下角斜切上來」的效果,進入動畫要在 setContentView() 之前設定,離場動畫則在 onPause()(畫面消失前)設定:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    overridePendingTransition(R.anim.push_right_in, R.anim.hold);
    ...
}

@Override
protected void onPause() {
    super.onPause();
    unregisterReceiver(progressReceiver);
    overridePendingTransition(R.anim.hold, R.anim.push_right_out);
}

方法簽名裡,第一個參數是「進入下一個 Activity 時的動畫」,第二個是「離開當前 Activity 時的動畫」。動畫本身用 XML 描述:

// res/anim/push_right_in.xml
<set xmlns:android="https://schemas.android.com/apk/res/android">
    <rotate android:fromDegrees="90" android:toDegrees="0"
            android:pivotX="100%p" android:pivotY="100%p"
            android:duration="500"/>
</set>

// res/anim/push_right_out.xml
<set xmlns:android="https://schemas.android.com/apk/res/android">
    <rotate android:fromDegrees="0" android:toDegrees="90"
            android:pivotX="100%p" android:pivotY="100%p"
            android:duration="500"/>
</set>

// res/anim/hold.xml —— 空動畫,用來讓主頁保持不動
<set xmlns:android="https://schemas.android.com/apk/res/android">
</set>

push_right_in 與 push_right_out 是一組反向操作:一個從右側斜切進場,一個斜切退場;hold 則確保背後的主頁紋絲不動,讓轉場看起來像是新頁面「蓋」上來。要注意 pivotX / pivotY 是 3.0 之後才支援的屬性,2.x 上寫了也不會有效果。

介面層大致就是這些,剩下與 Service 實作相關的部分留待下一篇再談。

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