对我来说,问题更多地与背景(轨道可绘制对象)的垂直居中有关。这是我最初使用的有缺陷的可绘制代码(导致了问题),它是由Android开发人员和其他StackOverflow条目建议的:
<item
android:id="@android:id/background"
android:drawable="@drawable/seekbar_track"/>
<item android:id="@android:id/secondaryProgress">
<scale
android:drawable="@drawable/seekbar_progress2"
android:scaleWidth="100%" />
</item>
<item android:id="@android:id/progress">
<scale
android:drawable="@drawable/seekbar_progress"
android:scaleWidth="100%" />
</item>
这里的问题在于SeekBar的背景。许多条目会告诉你将layout_minHeight设置为某个较大的值,以避免拇指和其轨道之间出现垂直空间断开的情况。但这对我来说并不是解决方案 - 在平板电脑上查看时,背景仍然绘制为其较小的基于手机的大小 - 因此轨道始终位于SeekBar轨道的中心以上。解决方案是在SeekBar drawable中删除此条目,使其看起来像这样:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@android:id/secondaryProgress">
<scale
android:drawable="@drawable/seekbar_progress2"
android:scaleWidth="100%" />
</item>
<item android:id="@android:id/progress">
<scale
android:drawable="@drawable/seekbar_progress"
android:scaleWidth="100%" />
</item>
</layer-list>
然后,在SeekBar的样式定义中,将layout_background设置为track drawable。我的代码如下:
<style name="styleSeekBar" parent="@android:style/Widget.SeekBar">
<item name="android:padding">@dimen/base_0dp</item>
<item name="android:background">@drawable/seekbar_track</item>
<item name="android:progressDrawable">@drawable/abratingbar</item>
<item name="android:minHeight">@dimen/base_29dp</item>
<item name="android:maxHeight">@dimen/base_29dp</item>
<item name="android:layout_marginLeft">@dimen/base_10dp</item>
<item name="android:layout_marginRight">@dimen/base_10dp</item>
<item name="android:layout_marginTop">@dimen/base_10dp</item>
<item name="android:layout_marginBottom">@dimen/base_10dp</item>
<item name="android:scaleType">fitXY</item>
</style>
之前,这里的背景设置只是一个颜色[白色]。
这是我布局中使用了样式和可绘制资源的入口:
<SeekBar
android:id="@+id/seekbar_page_number"
style="@style/styleSeekBar"
android:layout_width="match_parent"
android:layout_height="@dimen/base_29dp"
android:minHeight="@dimen/base_29dp"
android:maxHeight="@dimen/base_29dp"
android:layout_marginLeft="@dimen/base_230dp"
android:layout_gravity="bottom|right"
android:progress="1"
android:max="20"
android:progressDrawable="@drawable/abseekbar"
android:thumb="@drawable/abseekbar_thumb"/>
因此,总结一下,在自定义SeekBar drawable中不要设置背景(track)功能,而是在自定义SeekBar样式的layout_background功能中设置它。这可以确保轨道始终在水平SeekBar中垂直居中。