Android自定义SeekBar的样式

来源:互联网 发布:福州seo服务 编辑:程序博客网 时间:2024/05/17 08:39

SeekBar就是拖动条,是继承自ProgressBar的。SeekBar与ProgressBar一样都是用来显示进度的,不同的SeekBar有一个可拖动的滑块,可以用来改变进度。所以SeekBar主要使用来实现对数值进行调节,如调节音量,亮度等。
但是Android系统的SeekBar的样式基本上是不能满足我们的需求,所以自定义SeekBar的样式就是必然的了。
SeekBar自定义样式与ProgressBar自定义样式一样,都是通过自定义一个drawable资源文件作为progressDrawable属性值来实现。
自定义SeekBard的样式:

1.在res/drawable中定义一个资源文件 seekbar.xml

<?xml version="1.0" encoding="utf-8"?><layer-list xmlns:android="http://schemas.android.com/apk/res/android">    <item        android:id="@android:id/background"        android:drawable="@color/progress_bg"></item>    <item android:id="@android:id/secondaryProgress">        <scale            android:drawable="@color/second_progress"            android:scaleWidth="100%">        </scale>    </item>    <item android:id="@android:id/progress">        <scale            android:drawable="@color/progress"            android:scaleWidth="100%"></scale>    </item></layer-list>

第一个item定义的是进度条的背景,第二个item定义的是secondaryProgress的颜色,第三个item定义的是进度progress的颜色
定义progressDrawable的时候,必须要按照这个顺序(如果没有secondaryProgress可以去掉)来定义,并且secondaryProgress
和progress定义drawable时都必须用< scale/>子项,否则进度条会一直显示满的状态。

2.这里滑块我们也是用自定义的,在res/drawable中定义一个资源文件
mythumb.xml

<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android"    android:shape="oval">    <solid android:color="@color/colorAccent"></solid>    <size        android:width="10dp"        android:height="10dp"></size></shape>

定义了一个圆点作为thumb

3.在布局文件中使用SeekBar,并使用自定义的样式

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context="maqing.seekbardemo.MainActivity">    <SeekBar        android:id="@+id/seekBar"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:maxHeight="5dp"        android:minHeight="5dp"        android:progressDrawable="@drawable/seekbar"        android:thumb="@drawable/mythumb" /></RelativeLayout>

使用SeekBar的时候要注意,这里设置了android:minHeight和android:maxHeight属性,用这两个属性来设置进度条的高度,
而android:layout_height设为wrap_content,不要把android:layout_height设置为具体的值,否则thumb会不在SeekBar的中间。

这样就完成了一个自定义样式的SeekBar,效果如下:

点击下载源码

0 0
原创粉丝点击