SeekBar源码分析

前言

稍微读一下Seekbar的源码,了解一下具体实现。

正文

seekbar的父控件是ProgressBar,这个比较简单,大概基本就是一个把一个drawable在ondraw中给draw一下,onmesure则基本上是根据maxheight或者minheight来确定大小。
无论是drawable或者是maxheight、minheight都是通过style中定义的,我们看下系统的一个style如下:


    <style name="Widget.ProgressBar.Horizontal"> <item name="indeterminateOnly">false</item> <item name="progressDrawable">@drawable/progress_horizontal</item> <item name="indeterminateDrawable">@drawable/progress_indeterminate_horizontal</item> <item name="minHeight">20dip</item> <item name="maxHeight">20dip</item> <item name="mirrorForRtl">true</item> </style>


<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    
    <item android:id="@android:id/background">
        <shape>
            <corners android:radius="5dip" />
            <gradient android:startColor="#ff9d9e9d" android:centerColor="#ff5a5d5a" android:centerY="0.75" android:endColor="#ff747674" android:angle="270" />
        </shape>
    </item>
    
    <item android:id="@android:id/secondaryProgress">
        <clip>
            <shape>
                <corners android:radius="5dip" />
                <gradient android:startColor="#80ffd300" android:centerColor="#80ffb600" android:centerY="0.75" android:endColor="#a0ffcb00" android:angle="270" />
            </shape>
        </clip>
    </item>
    
    <item android:id="@android:id/progress">
        <clip>
            <shape>
                <corners android:radius="5dip" />
                <gradient android:startColor="#ffffd300" android:centerColor="#ffffb600" android:centerY="0.75" android:endColor="#ffffcb00" android:angle="270" />
            </shape>
        </clip>
    </item>
    
</layer-list>

<animation-list xmlns:android="http://schemas.android.com/apk/res/android" android:oneshot="false">
    <item android:drawable="@drawable/progressbar_indeterminate1" android:duration="200" />
    <item android:drawable="@drawable/progressbar_indeterminate2" android:duration="200" />
    <item android:drawable="@drawable/progressbar_indeterminate3" android:duration="200" />
</animation-list>

关于onDraw其实就是直接调用一个drawable的ondraw方法,所有的逻辑基本都集中在一个drawlist,这个暂时不是很清楚具体实现,不过我们稍微关注一下progressBar的一些逻辑:

private synchronized void doRefreshProgress(int id, int progress, boolean fromUser,
        setVisualProgress(id, scale);
}

private void setVisualProgress(int id, float progress) {
         d.setLevel(level);   
}    

这个是用来更新drawable的状态,稍微关注一下,主要逻辑就是这里,对drawable设置一下level。
下面我们关注一下seekbar,他主要加入了拖拽功能,也就是加入ontauch的回调功能,这里稍微分析一下。

onmessure功能就比较简单,通过滑块和Progressbar的高度宽度,功能控制大小。
onDraw就比较简单,直接通过mThumbOffset 来画一个滑块。
关于intouch方法也很简单,这里就不详细介绍,主要是调用setProgressInternal 来设置进度。

点赞