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

Android 自訂 UI:實作垂直方向的 SeekBar

編輯:關於 Android 程式設計

系統自帶的 SeekBar 樣式是水平的,若需要垂直方向的效果就得自訂了。原理很簡單:定義一個類繼承於 SeekBar,並在 onDraw 方法中將視圖旋轉一下即可。

程式碼如下:

package android.widget;
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
public class VerticalSeekBar extends SeekBar {
    public VerticalSeekBar(Context context) {
        super(context);
    }
    public VerticalSeekBar(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }
    public VerticalSeekBar(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(h, w, oldh, oldw);
    }
    @Override
    protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(heightMeasureSpec, widthMeasureSpec);
        setMeasuredDimension(getMeasuredHeight(), getMeasuredWidth());
    }
    protected void onDraw(Canvas c) {
        c.rotate(-90); // 將 SeekBar 旋轉 90 度
        c.translate(-getHeight(), 0); // 將旋轉後的視圖移動回來
        super.onDraw(c);
    }
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (!isEnabled()) {
            return false;
        }
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_MOVE:
            case MotionEvent.ACTION_UP:
                // 獲取滑動的距離並設置進度
                int i = getMax() - (int) (getMax() * event.getY() / getHeight());
                setProgress(i);
                break;
            case MotionEvent.ACTION_CANCEL:
                break;
        }
        return true;
    }
}

xml 佈局檔:

<?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"
    android:gravity="center"
    android:background="@android:color/white"
    android:orientation="horizontal" >
    <TextView
        android:id="@+id/reverse_sb_progresstext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/seekbar_reverse"
        android:gravity="center" />
    <TextView
        android:id="@+id/vertical_sb_progresstext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/vertical_Seekbar"
        android:layout_toRightOf="@+id/seekbar_reverse"
        android:gravity="center" />
</RelativeLayout>

關鍵在於 onDraw 中利用 Canvas 的 rotate() 與 translate() 兩個方法,先將畫布旋轉 -90 度,再將坐標平移回來,即可讓水平的 SeekBar 呈現垂直效果;onMeasure 與 onTouchEvent 也需相應調整寬高與觸摸坐標的計算。

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