系统自带的seekbar样式是水平的,如果需求一个垂直方向的效果就需要自定义了。原理很简单,即定义一个类继承于seekbar,并在ondraw方法里面旋转一下视图。
代码如下:
[java] view
plaincopy
package android.widget;
import android.content.context;
import android.graphics.canvas;
import android.util.attributeset;
import android.util.log;
import android.view.motionevent;
public class verticalseekbar extends seekbar {
public verticalseekbar(context context) {
super(context);
}
public verticalseekbar(context context, attributeset attrs, int defstyle) {
super(context, attrs, defstyle);
public verticalseekbar(context context, attributeset attrs) {
super(context, attrs);
protected void onsizechanged(int w, int h, int oldw, int oldh) {
super.onsizechanged(h, w, oldh, oldw);
@override
protected synchronized void onmeasure(int widthmeasurespec, int heightmeasurespec) {
super.onmeasure(heightmeasurespec, widthmeasurespec);
setmeasureddimension(getmeasuredheight(), getmeasuredwidth());
protected void ondraw(canvas c) {
//将seekbar转转90度
c.rotate(-90);
//将旋转后的视图移动回来
c.translate(-getheight(),0);
log.i("getheight()",getheight()+"");
super.ondraw(c);
public boolean ontouchevent(motionevent event) {
if (!isenabled()) {
return false;
}
switch (event.getaction()) {
case motionevent.action_down:
case motionevent.action_move:
case motionevent.action_up:
int i=0;
//获取滑动的距离
i=getmax() - (int) (getmax() * event.gety() / getheight());
//设置进度
setprogress(i);
log.i("progress",getprogress()+"");
//每次拖动seekbar都会调用
onsizechanged(getwidth(), getheight(), 0, 0);
log.i("getwidth()",getwidth()+"");
log.i("getheight()",getheight()+"");
break;
case motionevent.action_cancel:
return true;
}
xml布局文件:
[html] view
<?xml version="1.0" encoding="utf-8"?>
<relativelayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:background="@android:color/white"
android:orientation="horizontal" >
<android.widget.verticalseekbar_reverse
android:id="@+id/seekbar_reverse"
android:layout_width="wrap_content"
android:layout_height="450dip"
android:layout_marginright="30dip" />
<textview
android:id="@+id/reverse_sb_progresstext"
android:layout_height="wrap_content"
android:layout_below="@+id/seekbar_reverse"
android:gravity="center" />
<android.widget.verticalseekbar
android:id="@+id/vertical_seekbar"
android:layout_torightof="@+id/seekbar_reverse" />
android:id="@+id/vertical_sb_progresstext"
android:layout_below="@+id/vertical_seekbar"
android:layout_torightof="@+id/seekbar_reverse"
</relativelayout>
代码下载
推荐博文:android
canvas编程:对rotate()和translate()两个方法的研究