第 1 步:创建您的图像可绘制对象(9 个补丁)
在创建任何 XML 可绘制对象之前,请确保创建搜索栏背景、句柄和进度部分所需的图像可绘制对象(包括一个 9-patch 可绘制对象)。 9-patch drawables 将在以下步骤中被 XML drawables 使用。
创建以下可绘制对象并将它们放在 /res/drawable/ 文件夹中:
第 2 步:SeekBar 进度可绘制对象
现在为 Android seekbar 进度创建一个 XML 可绘制对象(示例中的蓝色条纹部分),将其命名为 seekbar_progress_bg.xml,并将其放在 /res/drawable/ 文件夹中:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<clip>
<shape>
<gradient
android:startColor="#FF5e8ea3"
android:centerColor="#FF32a0d2"
android:centerY="0.1"
android:endColor="#FF13729e"
android:angle="270"
/>
</shape>
</clip>
</item>
<item>
<clip>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@drawable/stripe_bg"
android:tileMode="repeat"
android:antialias="true"
android:dither="false"
android:filter="false"
android:gravity="left"
/>
</clip>
</item>
</layer-list>
上面的 XML 首先绘制了一个半透明的蓝色渐变,然后将半透明的条纹图像叠加在渐变的顶部。突出显示的代码行(第 20 行)是指在步骤 1 中创建的可绘制文件夹中的条纹(半透明)图像。
有关通过 XML 创建自定义形状的更多信息,请查看 Android 可绘制资源文档,特别是位图和形状部分。
第 3 步:SeekBar 背景可绘制对象
接下来创建主搜索栏进度drawable;它会为你的 seekbar 中的 seekbar 进度和 secondaryProgress 动作分配一个可绘制对象。将您的可绘制对象命名为 seekbar_progress.xml 之类的名称,将其放在 /res/drawable/ 文件夹中:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@android:id/background">
<nine-patch
xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@drawable/seekbar_background"
android:dither="true"
/>
</item>
<item android:id="@android:id/secondaryProgress">
<clip>
<shape>
<gradient
android:startColor="#80028ac8"
android:centerColor="#80127fb1"
android:centerY="0.75"
android:endColor="#a004638f"
android:angle="270"
/>
</shape>
</clip>
</item>
<item
android:id="@android:id/progress"
android:drawable="@drawable/seekbar_progress_bg"
/>
</layer-list>
上面突出显示的代码的第一位(第 8 行)是指在步骤 1 中创建的搜索栏背景图像(9-patch drawable),(第 29 行)是指您在上面的步骤 2 中创建的可绘制对象。
第 4 步:将所有内容整合在一起……
此时,你需要做的就是在声明你的 seekbar 时调用你的 seekbar_progress drawable:
<SeekBar
android:id="@+id/frequency_slider"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="20"
android:progress="0"
android:secondaryProgress="0"
android:progressDrawable="@drawable/seekbar_progress"
android:thumb="@drawable/seek_thumb"
/>
突出显示的两行代码用于设置 SeekBar 项的进度和拇指可绘制对象。 @drawable/seekbar_progress 指的是在上一步中创建的 XML drawable。