对我来说,这个问题更多地与背景的垂直居中有关(可绘制轨道)。这是我最初使用的有缺陷的可绘制代码(产生了问题),正如 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 可绘制对象中设置背景(轨道)功能,而是在自定义 SeekBar 样式的 layout_background 功能中设置它。这可确保轨道始终在水平 SeekBar 中垂直居中。