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

Android 基礎 UI 第十二篇:ScrollView、ProgressBar 與 SeekBar

編輯:關於 Android 程式設計

ScrollView 滾動視圖

ScrollView 繼承自 FrameLayout,同樣是容器元件。由於手機螢幕空間有限,當畫面需要容納大量內容時,ScrollView 可以把它包起來,讓使用者透過滑動瀏覽。要特別注意的是,ScrollView 只能包含一個直接子元件,若有多組內容需要滾動,得先放一個 LinearLayout 再往裡頭塞。

實作程式碼:

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_scrollview);
    tv_scrollview_show = (TextView) findViewById(R.id.tv_show);
    btn_to_top    = (Button) findViewById(R.id.btn_to_top);
    btn_to_bottom = (Button) findViewById(R.id.btn_to_bottom);
    scrollView    = (ScrollView) findViewById(R.id.sc);
    initData();

    btn_to_top.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            scrollView.fullScroll(ScrollView.FOCUS_UP);   // 捲回頂端
        }
    });
    btn_to_bottom.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            scrollView.fullScroll(ScrollView.FOCUS_DOWN); // 捲到底端
        }
    });
}

private void initData() {
    StringBuffer buffer = new StringBuffer();
    for (int i = 1; i < 120; i++) {
        buffer.append("這是第" + i + "個條目" + "\n");
    }
    tv_scrollview_show.setText(buffer.toString());
}

效果圖:

ScrollView 大致就這些,實務上使用頻率其實不算高。

ProgressBar 進度條

進度條在許多場景都用得上。執行耗時操作時如果沒有任何進度回饋,使用者很容易誤以為 App 當掉了,體驗自然不好。Android 提供的 ProgressBar 繼承自 View,常用屬性如下:

android:max                 // 進度條最大值
android:progress              // 已完成的進度
android:progressDrawable      // 設定軌道對應的 Drawable
android:indeterminate         // 設為 true 時不精確顯示進度
android:indeterminateDrawable // 不精確模式下顯示的 Drawable
android:indeterminateDuration // 不精確模式下的動畫持續時間
android:secondaryProgress     // 二級進度,例如影片的緩衝進度

對應的 Java 方法:

getMax()                          // 取得上限
getProgress()                     // 取得目前進度
getSecondaryProgress()            // 取得次要進度
incrementProgressBy(int diff)     // 增加指定進度
isIndeterminate()                 // 是否處於不確定模式
setIndeterminate(boolean)         // 設定是否進入不確定模式

系統自帶的進度條比較簡單,這裡不多贅述。下面直接看一個自訂的圓形進度條:

package com.example.hello_baseui.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.view.View;
import com.example.hello_baseui.R;

public class CircleProgressBar extends View {
    /** 畫筆物件 */
    private Paint paint;
    /** 圓環顏色 */
    private int circleColor;
    /** 進度圓環顏色 */
    private int circleProgressColor;
    /** 中間百分比文字顏色 */
    private int textColor;
    /** 中間百分比文字大小 */
    private float textSize;
    /** 圓環寬度 */
    private float circleWidth;
    /** 最大進度 */
    private int max;
    /** 目前進度 */
    private int progress;
    /** 是否顯示中間的進度文字 */
    private boolean isShowProgressText;
    /** 進度風格:實心或空心 */
    private int circleStyle;
    private float strokeWidth;

    /** 空心 */
    public static final int STROKE = 0;
    /** 實心 */
    public static final int FILL = 1;

    public CircleProgressBar(Context context) {
        this(context, null);
    }

    public CircleProgressBar(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CircleProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context, attrs);
    }

    /** 初始化元件屬性 */
    private void initView(Context context, AttributeSet attrs) {
        paint = new Paint();
        TypedArray mTypedArray = context.obtainStyledAttributes(attrs, R.styleable.CircleProgressBar);
        circleColor         = mTypedArray.getColor(R.styleable.CircleProgressBar_circleColor, Color.RED);
        circleProgressColor = mTypedArray.getColor(R.styleable.CircleProgressBar_circleProgressColor, Color.BLUE);
        textColor           = mTypedArray.getColor(R.styleable.CircleProgressBar_textColor, Color.BLUE);
        textSize            = mTypedArray.getDimension(R.styleable.CircleProgressBar_textSize, 14);
        circleWidth         = mTypedArray.getDimension(R.styleable.CircleProgressBar_circleWidth, 10);
        isShowProgressText  = mTypedArray.getBoolean(R.styleable.CircleProgressBar_isShowProgressText, true);
        circleStyle         = mTypedArray.getInt(R.styleable.CircleProgressBar_circleStyle, 0);
        mTypedArray.recycle();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // 繪製最外層的大圓
        int centre = getWidth() / 2;                        // 圓心座標
        int radius = (int) (centre - circleWidth / 2) - 2;  // 圓環半徑
        paint.setColor(circleColor);
        paint.setStyle(Paint.Style.STROKE);   // 空心
        paint.setStrokeWidth(strokeWidth);    // 圓環寬度
        paint.setAntiAlias(true);             // 消除鋸齒
        canvas.drawCircle(centre, centre, radius, paint);

        // 繪製中間的進度百分比
        paint.setStrokeWidth(0);
        paint.setColor(textColor);
        paint.setTextSize(textSize);
        paint.setTypeface(Typeface.DEFAULT_BOLD);
        // 先轉 float 再相除,否則整數除法會得到 0
        int percent = (int) (((float) progress / (float) max) * 100);
        float textWidth = paint.measureText(percent + "%"); // 測量文字寬度以便置中
        if (isShowProgressText && circleStyle == STROKE) {
            canvas.drawText(percent + "%", centre - textWidth / 2, centre + textSize / 2, paint);
        }

        // 繪製圓弧進度
        paint.setStrokeWidth(strokeWidth);
        paint.setColor(circleProgressColor);
        RectF oval = new RectF(centre - radius - 1, centre - radius - 1,
                               centre + radius + 1, centre + radius + 1);
        switch (circleStyle) {
            case STROKE: {
                paint.setStyle(Paint.Style.STROKE);
                canvas.drawArc(oval, 90, 360 * progress / max, false, paint);
                break;
            }
            case FILL: {
                paint.setStyle(Paint.Style.FILL_AND_STROKE);
                if (progress != 0) {
                    canvas.drawArc(oval, 90, 360 * progress / max, true, paint);
                }
                break;
            }
        }
    }

    /** 設定最大值 */
    public synchronized void setMax(int max) {
        if (max < 0) {
            throw new IllegalArgumentException("The max cannot less than 0");
        }
        this.max = max;
    }

    public synchronized int getMax() { return max; }

    public synchronized int getProgress() { return progress; }

    /**
     * 設定進度。此為執行緒安全控件,考慮多執行緒情境需同步。
     * postInvalidate() 可在非 UI 執行緒刷新介面
     */
    public synchronized void setProgress(int progress) {
        if (progress < 0) {
            throw new IllegalArgumentException("The progress cannot less then 0");
        }
        if (progress > max) {
            progress = max;
        }
        if (progress <= max) {
            this.progress = progress;
            postInvalidate();
        }
    }

    public int  getCircleColor() { return circleColor; }
    public void setCircleColor(int circleColor) { this.circleColor = circleColor; }

    public int  getTextColor() { return textColor; }
    public void setTextColor(int textColor) { this.textColor = textColor; }

    public float getTextSize() { return textSize; }
    public void  setTextSize(float textSize) { this.textSize = textSize; }

    public float getCircleWidth() { return circleWidth; }
    public void  setCircleWidth(float circleWidth) { this.circleWidth = circleWidth; }

    public boolean isShowProgressText() { return isShowProgressText; }
    public void setShowProgressText(boolean showProgressText) { isShowProgressText = showProgressText; }

    public int  getCircleStyle() { return circleStyle; }
    public void setCircleStyle(int circleStyle) { this.circleStyle = circleStyle; }

    public float getStrokeWidth() { return strokeWidth; }
    public void  setStrokeWidth(float strokeWidth) { this.strokeWidth = strokeWidth; }

    public int  getCircleProgressColor() { return circleProgressColor; }
    public void setCircleProgressColor(int circleProgressColor) { this.circleProgressColor = circleProgressColor; }
}

布局檔案:



    

Activity 程式碼,用子執行緒推進進度,再透過 Handler 回主執行緒更新畫面:

private CircleProgressBar circleProgressBar;
int progressStatus = 0;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_progressbar);
    circleProgressBar = (CircleProgressBar) findViewById(R.id.cpb);
    circleProgressBar.setMax(100);
    circleProgressBar.setCircleWidth(30);
    circleProgressBar.setStrokeWidth(10);
    circleProgressBar.setCircleProgressColor(Color.BLUE);

    final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                circleProgressBar.setProgress(progressStatus);
            }
        }
    };

    new Thread(new Runnable() {
        @Override
        public void run() {
            while (progressStatus < 100) {
                progressStatus += 3;
                try {
                    Thread.sleep(1000);
                    handler.sendEmptyMessage(0);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }).start();
}

實作效果:

SeekBar 拖動條

SeekBar 是 ProgressBar 的子類,ProgressBar 的屬性它都能用,差別在於允許使用者拖動來改變進度,常用於媒體播放控制。下面做一個簡單示範。

布局檔案:



    

Activity 程式碼:

private SeekBar sb;
private TextView textView;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_seekbar);
    sb = (SeekBar) findViewById(R.id.sb);
    textView = (TextView) findViewById(R.id.tv_seek_bar);
    textView.setMovementMethod(ScrollingMovementMethod.getInstance()); // 讓文字可滾動

    // SeekBar 需要實作三個回呼
    sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        /** 拖動過程中 */
        @Override
        public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
            textView.setText("正在拖動,拖動了:" + sb.getProgress() + "\n");
        }
        /** 剛開始拖動 */
        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            textView.setText("開始拖動,拖動了:" + sb.getProgress() + "\n");
        }
        /** 停止拖動 */
        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            textView.setText("停止拖動了,已經拖動了:" + sb.getProgress() + "\n");
        }
    });
}

實作效果:

本篇小結

ScrollView 解決「內容超出螢幕」的問題,ProgressBar 解決「等待沒有回饋」的問題,SeekBar 則把進度的控制權交回使用者手上。三者都屬於 Android 常用 UI 元件,接下來可以進一步看 Android 的五大布局。範例原始碼可參考文中提及的對應頁面。

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