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 TV WebView 遥控器按键处理:从全透传到白名单
android
plainGeekDev6 小时前
MVC 写法 → MVVM
android·java·kotlin
恋猫de小郭7 小时前
Flutter Patchwork,不用 Fork 改依赖包源码的第三方工具
android·前端·flutter
三少爷的鞋8 小时前
“结构化”这个词,本质上就是——把混乱的东西变成有组织、有规则、有边界的东西
android
方白羽1 天前
Android Gradle 缓存与文件目录深度解析
android·gradle·android studio
曲幽1 天前
Termux里的二进制和脚本,到底怎么运行才不踩坑?Termux-service 保活妙招!
android·termux·nohup·services·wake-lock
plainGeekDev1 天前
单例模式 → object 声明
android·java·kotlin
程序员陆业聪1 天前
读者点单·03|Compose 与传统 View 混用的 12 个真实坑
android
程序员陆业聪1 天前
读者点单·02|Android 启动优化实战:Trace 抓取→Application 编排→冷启动全流程拆解
android
Coffeeee1 天前
帮你快速理解AI Agent之我想招个Android实习生
android·人工智能·agent