温馨提示×

Android SeekBar可以实现垂直样式吗

小樊
266
2024-08-02 18:42:19
栏目: 编程语言

Android SeekBar默认是水平样式的,但是可以通过自定义SeekBar来实现垂直样式。可以通过设置SeekBar的旋转角度或者使用自定义控件来实现垂直SeekBar。具体实现方式可以参考以下步骤:

  1. 通过设置SeekBar的旋转角度来实现垂直样式:
SeekBar seekBar = findViewById(R.id.seekBar);
seekBar.setRotation(90);
  1. 自定义垂直SeekBar控件: 可以通过继承SeekBar类自定义一个垂直SeekBar控件,具体实现如下:
public class VerticalSeekBar extends SeekBar {

    public VerticalSeekBar(Context context) {
        super(context);
    }

    public VerticalSeekBar(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public VerticalSeekBar(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    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());
    }

    @Override
    protected synchronized void onDraw(Canvas canvas) {
        canvas.rotate(-90);
        canvas.translate(-getHeight(), 0);
        super.onDraw(canvas);
    }

    @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;
        }

        return true;
    }
}

使用自定义的VerticalSeekBar控件:

<com.example.VerticalSeekBar
    android:id="@+id/verticalSeekBar"
    android:layout_width="wrap_content"
    android:layout_height="match_parent" />

0