android 快速实现 垂直SeekBar(VerticalSeekBar)

1.话不多说上源码:

java 复制代码
package com.example.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.MotionEvent;

/**
 * Class to create a vertical slider
 */
public class VerticalSeekBar extends androidx.appcompat.widget.AppCompatSeekBar {

    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) {
        c.rotate(-90);
        c.translate(-getHeight(), 0);

        super.onDraw(c);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (!isEnabled()) {
            return false;
        }

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_MOVE:
            case MotionEvent.ACTION_UP:
                setProgress(getMax() - (int) (getMax() * event.getY() / getHeight()));
                onSizeChanged(getWidth(), getHeight(), 0, 0);
                break;

            case MotionEvent.ACTION_CANCEL:
                break;
        }
        return true;
    }
}

2.布局中使用:

XML 复制代码
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@android:color/darker_gray"
    >
    
    <com.example.widget.VerticalSeekBar
        android:id="@+id/sb_volume"
        android:layout_width="40dp"
        android:layout_height="180dp"
        />
</FrameLayout>
相关推荐
东京老树根1 小时前
Android - 用Scrcpy 将手机投屏到Windows电脑上
android
Wgllss2 小时前
完整烟花效果,Compose + 协程 + Flow + Channel 轻松实现
android·架构·android jetpack
扛麻袋的少年2 小时前
6.Kotlin的Duration类
android·开发语言·kotlin
独自破碎E2 小时前
得物25年春招-安卓部分笔试题1
android
雨白3 小时前
Android 自定义 View:精通文字的测量与高级排版
android
Jasonakeke3 小时前
【重学MySQL】八十八、8.0版本核心新特性全解析
android·数据库·mysql
一条上岸小咸鱼5 小时前
Kotlin 类型检查与转换
android·kotlin
闲暇部落6 小时前
android studio配置 build
android·android studio·build
_祝你今天愉快7 小时前
Android FrameWork - Zygote 启动流程分析
android
龙之叶8 小时前
Android系统模块编译调试与Ninja使用指南
android