1. 程式人生 > >Android入門教程三十之SeekBar(拖動條)

Android入門教程三十之SeekBar(拖動條)

本節我們繼續來學習Android的基本UI控制元件中的拖動條——SeekBar,相信大家對他並不陌生,最常見的 地方就是音樂播放器或者視訊播放器了,音量控制或者播放進度控制,都用到了這個SeekBar,我們 先來看看SeekBar的類結構,來到官方文件:SeekBar

嘿嘿,這玩意是ProgressBar的子類耶,也就是ProgressBar的屬性都可以用咯! 而且他還有一個自己的屬性就是:android:thumb,就是允許我們自定義滑塊~ 好的,開始本節內容!

1.SeekBar基本用法

好吧,基本用法其實很簡單,常用的屬性無非就下面這幾個常用的屬性,Java程式碼裡只要setXxx即可:

android:max=”100” //滑動條的最大值

android:progress=”60” //滑動條的當前值

android:secondaryProgress=”70” //二級滑動條的進度

android:thumb = “@mipmap/sb_icon” //滑塊的drawable

接著要說下SeekBar的事件了,SeekBar.OnSeekBarChangeListener 我們只需重寫三個對應的方法:

onProgressChanged:進度發生改變時會觸發

onStartTrackingTouch

:按住SeekBar時會觸發

onStopTrackingTouch:放開SeekBar時觸發

簡單的程式碼示例:

效果圖:

實現程式碼:

publicclassMainActivityextendsAppCompatActivity{privateSeekBar sb_normal;privateTextView txt_cur;privateContext mContext;@Overrideprotectedvoid onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);
        setContentView
(R.layout.activity_main); mContext =MainActivity.this; bindViews();}privatevoid bindViews(){ sb_normal =(SeekBar) findViewById(R.id.sb_normal); txt_cur =(TextView) findViewById(R.id.txt_cur); sb_normal.setOnSeekBarChangeListener(newSeekBar.OnSeekBarChangeListener(){@Overridepublicvoid onProgressChanged(SeekBar seekBar,int progress,boolean fromUser){ txt_cur.setText("當前進度值:"+ progress +" / 100 ");}@Overridepublicvoid onStartTrackingTouch(SeekBar seekBar){Toast.makeText(mContext,"觸碰SeekBar",Toast.LENGTH_SHORT).show();}@Overridepublicvoid onStopTrackingTouch(SeekBar seekBar){Toast.makeText(mContext,"放開SeekBar",Toast.LENGTH_SHORT).show();}});}}

2.簡單SeekBar定製:

本來還想著自定義下SeekBar的,後來想想,還是算了,涉及到自定義View的一些東西,可能初學者並 不瞭解,看起來也有點難度,關於自定義View的還是放到進階那裡吧,所以這裡就只是簡單的定製下SeekBar! 定製的內容包括滑塊,以及軌道!

程式碼例項:

執行效果圖:

程式碼實現: 1.滑塊狀態Drawable:sb_thumb.xml

<?xml version="1.0" encoding="utf-8"?><selectorxmlns:android="http://schemas.android.com/apk/res/android"><itemandroid:state_pressed="true"android:drawable="@mipmap/seekbar_thumb_pressed"/><itemandroid:state_pressed="false"android:drawable="@mipmap/seekbar_thumb_normal"/></selector>

貼下素材:

seekbar_thumb_normal.pngseekbar_thumb_pressed.png

2.條形欄Bar的Drawable:sb_bar.xml

這裡用到一個layer-list的drawable資源!其實就是層疊圖片,依次是:背景,二級進度條,當前進度:

<?xml version="1.0" encoding="utf-8"?><layer-listxmlns:android="http://schemas.android.com/apk/res/android"><itemandroid:id="@android:id/background"><shape><solidandroid:color="#FFFFD042"/></shape></item><itemandroid:id="@android:id/secondaryProgress"><clip><shape><solidandroid:color="#FFFFFFFF"/></shape></clip></item><itemandroid:id="@android:id/progress"><clip><shape><solidandroid:color="#FF96E85D"/></shape></clip></item></layer-list>

3.然後佈局引入SeekBar後,設定下progressDrawable與thumb即可!

<SeekBarandroid:id="@+id/sb_normal"android:layout_width="match_parent"android:layout_height="wrap_content"android:maxHeight="5.0dp"android:minHeight="5.0dp"android:progressDrawable="@drawable/sb_bar"android:thumb="@drawable/sb_thumb"/>

就是這麼簡單!