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>
相关推荐
城东米粉儿2 小时前
Android MediaPlayer 笔记
android
Jony_3 小时前
Android 启动优化方案
android
阿巴斯甜3 小时前
Android studio 报错:Cause: error=86, Bad CPU type in executable
android
张小潇3 小时前
AOSP15 Input专题InputReader源码分析
android
_小马快跑_7 小时前
Kotlin | 协程调度器选择:何时用CoroutineScope配置,何时用launch指定?
android
_小马快跑_7 小时前
Kotlin | 从SparseArray、ArrayMap的set操作符看类型检查的不同
android
_小马快跑_7 小时前
Android | 为什么有了ArrayMap还要再设计SparseArray?
android
_小马快跑_7 小时前
Android TextView图标对齐优化:使用LayerList精准控制drawable位置
android
_小马快跑_7 小时前
Kotlin协程并发控制:多线程环境下的顺序执行
android
_小马快跑_7 小时前
Kotlin协程异常捕获陷阱:try-catch捕获异常失败了?
android