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

第34章 Android 拖動條 SeekBar:音量調節與三個關鍵事件

編輯:Android 技術基礎

聽歌時左右拖動的播放進度、按側鍵調整的音量,背後都是同一個元件:SeekBar。它讓使用者用「滑動」這種最省力的手勢,連續地改寫一個數值,並即時看到結果。

一、版面:一條 SeekBar 加兩行狀態文字

開啟 res/layout/activity_main.xml,從工具欄拖出 1 個 SeekBar 與 2 個 TextView。

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

    <SeekBar
        android:id="@+id/seekbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="100"
        android:progress="50"
        android:secondaryProgress="75" />

    <TextView
        android:id="@+id/info01"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/info02"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

三個屬性值得留意:android:max 決定最大值(預設 100),android:progress 是當前進度,而 android:secondaryProgress 是「第二層進度」——播放器常用它畫出緩衝已下載但未播放的那一段。

二、實作三個監聽事件

開啟 src/com.genwoxue.seekbar/MainActivity.java:

package com.genwoxue.seekbar;

import android.app.Activity;
import android.os.Bundle;
import android.widget.SeekBar;
import android.widget.TextView;

// 類別同時繼承 Activity、實作 OnSeekBarChangeListener
public class MainActivity extends Activity implements SeekBar.OnSeekBarChangeListener {

    private SeekBar sbVolume = null;
    private TextView tvInfo01 = null;
    private TextView tvInfo02 = null;

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

        sbVolume  = (SeekBar) findViewById(R.id.seekbar);
        tvInfo01  = (TextView) findViewById(R.id.info01);
        tvInfo02  = (TextView) findViewById(R.id.info02);

        sbVolume.setOnSeekBarChangeListener(this);
    }

    // 數值改變(拖動過程中會連續觸發)
    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {
        tvInfo01.setText("音量目前值:" + progress);
    }

    // 開始拖動
    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        tvInfo02.setText("音量正在調整");
    }

    // 停止拖動
    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        tvInfo02.setText("音量停止調整");
    }
}

三、三個事件的分工

SeekBar 可以被使用者自由控制,所以必須實作 SeekBar.OnSeekBarChangeListener,它一共要求三個方法:

  • onProgressChanged:數值改變時觸發。拖動期間會密集呼叫,適合更新文字或做即時預覽;若要在這裡做重運算或寫檔,記得節流。
  • onStartTrackingTouch:手指剛開始拖動。適合暫停播放、取消自動更新。
  • onStopTrackingTouch:手指離開。適合在這裡才真正送出「使用者選好的值」,例如一次性的網路請求。

四、常用方法

  • setMax(int):設定最大值。
  • setProgress(int):設定當前進度。
  • setSecondaryProgress(int):設定第二進度,常用來表示緩衝或建議值。

五、執行結果

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