Android 自訂UI-垂直方向的SeekBar

來源:互聯網
上載者:User

系統內建的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) {    //將SeekBar轉轉90度        c.rotate(-90);        //將旋轉後的視圖移動回來        c.translate(-getHeight(),0);        Log.i("getHeight()",getHeight()+"");        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=0;            //擷取滑動的距離            i=getMax() - (int) (getMax() * event.getY() / getHeight());            //設定進度                setProgress(i);                Log.i("Progress",getProgress()+"");                //每次拖動SeekBar都會調用                onSizeChanged(getWidth(), getHeight(), 0, 0);                Log.i("getWidth()",getWidth()+"");                Log.i("getHeight()",getHeight()+"");                break;            case MotionEvent.ACTION_CANCEL:                break;        }        return true;    }    }
xml布局檔案:

                
下載 推薦博文:Android Canvas編程:對rotate()和translate()兩個方法的研究

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.