在Android中由于默认的SeekBar是水平样式的,所以垂直的样式需要通过自定义来确定样式。首先上自定义的代码
public class VerticalSeekBar extends SeekBar {
private SeekBar.OnSeekBarChangeListener mOnSeekBarChangeListener;
int i=0;
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);
}
public void setOnSeekBarChangeListener(SeekBar.OnSeekBarChangeListener l) {
mOnSeekBarChangeListener = l;
}
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);
}
void onStartTrackingTouch() {
if (mOnSeekBarChangeListener != null) {
mOnSeekBarChangeListener.onStartTrackingTouch(this);
}
}
void onProgressChanged() {
if (mOnSeekBarChangeListener != null) {
mOnSeekBarChangeListener.onProgressChanged(this,i,true);
}
}
void onStopTrackingTouch() {
if (mOnSeekBarChangeListener != null) {
mOnSeekBarChangeListener.onStopTrackingTouch(this);
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (!isEnabled()) {
return false;
}
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
onStartTrackingTouch();
break;
case MotionEvent.ACTION_MOVE:
//获取滑动的距离
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()+"");
onProgressChanged();
break;
case MotionEvent.ACTION_UP:
onStopTrackingTouch();
break;
case MotionEvent.ACTION_CANCEL:
onStopTrackingTouch();
break;
}
return true;
}
}
接下来在xml中引用自定义文件就可以了
<com.mornningtime.clighten.view.VerticalSeekBar
android:id="@+id/bar_kk1"
android:layout_width="30dp"
android:layout_height="200dp"
android:layout_marginLeft="60dp"
android:layout_alignParentBottom="true"
android:layout_marginBottom="50dp"
android:progress="0"
android:max="100"
android:progressDrawable="@drawable/seekbar_bg"
/>
由于有时候需要自己更改SeekBar的背景,所以要在Drawable创建文件更改背景
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@android:id/background">
<shape>
<corners android:radius="5dp"/>
<solid android:color="@color/gray"/>
</shape>
</item>
<item android:id="@android:id/secondaryProgress">
<clip>
<shape>
<corners android:radius="5dp"/>
<solid android:color="#11ce33"/>
</shape>
</clip>
</item>
<item android:id="@android:id/progress">
<clip>
<shape>
<corners android:radius="5dp"/>
<solid android:color="@color/redxy" />
</shape>
</clip>
</item>
</layer-list>