如何在安卓中制作一个垂直的SeekBar?

88

一个 SeekBar 可以垂直吗?由于我不是很擅长UI设计,你能否提供一些模板和示例来帮助���让 SeekBar 更美观。


2
你必须自己实现。这里链接了一个未完成的版本(https://dev59.com/0HRB5IYBdhLWcg3wa2m2),另一个链接在这里(http://groups.google.com/group/android-developers/browse_thread/thread/bec05b0368c20e03)。 - Pentium10
最近我需要实现它。请看这个链接:https://github.com/chanjungkim/VerticalSeekbar。 - c-an
19个回答

2
移动 EditText 中的 thumb 时,垂直 Seekbar 的 setProgress 可能无法正常工作。以下代码可以帮助解决问题:
    @Override
public synchronized void setProgress(int progress) {
    super.setProgress(progress);
    updateThumb();
}

private void updateThumb() {
    onSizeChanged(getWidth(), getHeight(), 0, 0);
}

这段代码来自于这里: https://dev59.com/4Yfca4cB1Zd3GeqPmrlq#33064140

1

我尝试了许多种方法,但对我起作用的是:在FrameLayout中使用SeekBar。

<FrameLayout
    android:id="@+id/VolumeLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@id/MuteButton"
    android:layout_below="@id/volumeText"
    android:layout_centerInParent="true">
        <SeekBar
        android:id="@+id/volume"
        android:layout_width="500dp"
        android:layout_height="60dp"
        android:layout_gravity="center"
        android:progress="50"
        android:secondaryProgress="40"
        android:progressDrawable="@drawable/seekbar_volume"
        android:secondaryProgressTint="@color/tint_neutral"
        android:thumbTint="@color/tint_neutral"
    />

而在编程方面。

在SeekBar上设置Pre Draw回调,您可以在其中更改SeekBar的宽度和高度。我在C#中完成了这部分,所使用的代码是:

            var volumeSlider = view.FindViewById<SeekBar>(Resource.Id.home_link_volume);

            var volumeFrameLayout = view.FindViewById<FrameLayout>(Resource.Id.linkVolumeFrameLayout);

            void OnPreDrawVolume(object sender, ViewTreeObserver.PreDrawEventArgs e)
            {
                volumeSlider.ViewTreeObserver.PreDraw -= OnPreDrawVolume;
                var h = volumeFrameLayout.Height;
                volumeSlider.Rotation = 270.0f;
                volumeSlider.LayoutParameters.Width = h;
                volumeSlider.RequestLayout();
            }

            volumeSlider.ViewTreeObserver.PreDraw += OnPreDrawVolume;

在这里我添加了PreDraw事件的监听器,当它被触发时,我会移除PreDraw以避免进入无限循环。

因此当执行Pre Draw时,我获取FrameLayout的高度并将其分配给SeekBar。同时将SeekBar的旋转设置为270度。 由于我的SeekBar位于Frame Layout内,且其重心设置为中心,所以我不需要担心平移问题。SeekBar始终保持在Frame Layout的中央。

我移除事件处理程序的原因是seekbar.RequestLayout();会导致该事件再次执行。


1
通过使用 RotateLayout,创建垂直的 SeekBar 轻而易举。只需将那个可怕的 SeekBar 包装到其中,就可以轻松实现了:

<com.github.rongi.rotate_layout.layout.RotateLayout
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:angle="-90"
    >

        <androidx.appcompat.widget.AppCompatSeekBar
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
        />

</com.github.rongi.rotate_layout.layout.RotateLayout>

https://github.com/rongi/rotate-layout


0
在我的情况下,我使用了普通的 seekBar 并仅翻转了布局。
seekbar_layout.xml - 我的布局包含我们需要垂直显示的 seekbar。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rootView"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

<SeekBar
    android:id="@+id/seekBar"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_alignParentBottom="true"/>

</RelativeLayout>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.vgfit.seekbarexample.MainActivity">

<View
    android:id="@+id/headerView"
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:background="@color/colorAccent"/>

<View
    android:id="@+id/bottomView"
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:layout_alignParentBottom="true"
    android:background="@color/colorAccent"/>

<include
    layout="@layout/seekbar_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@id/bottomView"
    android:layout_below="@id/headerView"/>

 </RelativeLayout>

在MainActivity中,我旋转了seekbar_layout:

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.RelativeLayout
import kotlinx.android.synthetic.main.seekbar_layout.*


class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    rootView.post {
        val w = rootView.width
        val h = rootView.height

        rootView.rotation = 270.0f
        rootView.translationX = ((w - h) / 2).toFloat()
        rootView.translationY = ((h - w) / 2).toFloat()

        val lp = rootView.layoutParams as RelativeLayout.LayoutParams
        lp.height = w
        lp.width = h
        rootView.requestLayout()
    }
}
}

因此,我们拥有必要的垂直滚动条: 输入图像描述


0

开始

将以下代码添加到build.gradle文件中。

dependencies {
    compile 'com.h6ah4i.android.widget.verticalseekbar:verticalseekbar:0.7.2'
}

使用方法

Java 代码

public class TestVerticalSeekbar extends AppCompatActivity {
    private SeekBar volumeControl = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_vertical_seekbar);

        volumeControl = (SeekBar) findViewById(R.id.mySeekBar);

        volumeControl.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            int progressChanged = 0;

            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                progressChanged = progress;
            }

            public void onStartTrackingTouch(SeekBar seekBar) {
                // TODO Auto-generated method stub
            }

            public void onStopTrackingTouch(SeekBar seekBar) {
                Toast.makeText(getApplicationContext(), "seek bar progress:" + progressChanged,
                        Toast.LENGTH_SHORT).show();
            }
        });
    }

}

布局 XML

<!-- This library requires pair of the VerticalSeekBar and VerticalSeekBarWrapper classes -->
<com.h6ah4i.android.widget.verticalseekbar.VerticalSeekBarWrapper
    android:layout_width="wrap_content"
    android:layout_height="150dp">
    <com.h6ah4i.android.widget.verticalseekbar.VerticalSeekBar
        android:id="@+id/mySeekBar"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:max="100"
        android:progress="0"
        android:splitTrack="false"
        app:seekBarRotation="CW90" /> <!-- Rotation: CW90 or CW270 -->
</com.h6ah4i.android.widget.verticalseekbar.VerticalSeekBarWrapper>

注意:在Android N+中需要android:splitTrack="false"


0

我几年前为了解决这个问题而制作了一个垂直滑动条库,请参见:

https://github.com/ASE55471/Android-VSlider

这个库不会将原始的SeekBar旋转90度或270度,它是从头开始重写的,以解决“拇指位置不正确”、“无法从代码中设置位置”、“无法对齐背景可绘制对象”、“触摸位置偏移”等问题。此外,它还具有一些额外的有用功能。


0
你可以自己完成 - 这并不难。以下是我的项目示例:https://github.com/AlShevelev/WizardCamera 让我们从设置(attrs.xml)开始。
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="ExpositionBar">
        <attr name="button_icon" format="reference" />
        <attr name="button_icon_size" format="dimension" />

        <attr name="stroke_width" format="dimension" />

        <attr name="stroke_color" format="color" />
        <attr name="button_color" format="color" />
        <attr name="button_color_pressed" format="color" />

        <attr name="min_value" format="float" />
        <attr name="max_value" format="float" />
    </declare-styleable>
</resources>

这是一些实用函数:

以下是代码:

fun <T: Comparable<T>>T.fitInRange(range: Range<T>): T =
    when {
        this < range.lower -> range.lower
        this > range.upper -> range.upper
        else -> this
    }

fun Float.reduceToRange(rangeFrom: Range<Float>, rangeTo: Range<Float>): Float =
    when {
        this == rangeFrom.lower -> rangeTo.lower
        this == rangeFrom.upper -> rangeTo.upper
        else -> {
            val placeInRange = (this - rangeFrom.lower) / (rangeFrom.upper - rangeFrom.lower)
            ((rangeTo.upper - rangeTo.lower) * placeInRange) + rangeTo.lower
        }
    }

最后但同样重要的是,一个用于垂直滑动条的类:
class ExpositionBar
@JvmOverloads
constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    private val drawingRect = RectF(0f, 0f, 0f, 0f)
    private val drawingPaint = Paint(Paint.ANTI_ALIAS_FLAG)

    private val strokeWidth: Float

    @ColorInt
    private val strokeColor: Int
    @ColorInt
    private val buttonFillColor: Int
    @ColorInt
    private val buttonFillColorPressed: Int

    private val icon: VectorDrawable

    private val valuesRange: Range<Float>

    private var centerX = 0f
    private var minY = 0f
    private var maxY = 0f

    private var buttonCenterY = 0f
    private var buttonRadiusExt = 0f
    private var buttonRadiusInt = 0f
    private var buttonMinY = 0f
    private var buttonMaxY = 0f
    private var buttonCenterBoundsRange = Range(0f, 0f)

    private var iconTranslationX = 0f
    private var iconTranslationY = 0f

    private var isInDragMode = false

    private var onValueChangeListener: ((Float) -> Unit)? = null

    private var oldOutputValue = Float.MIN_VALUE

    init {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.ExpositionBar)

        icon =  typedArray.getDrawable(R.styleable.ExpositionBar_button_icon) as VectorDrawable
        val iconSize = typedArray.getDimensionPixelSize(R.styleable.ExpositionBar_button_icon_size, 0)
        icon.setBounds(0, 0, iconSize, iconSize)

        strokeWidth = typedArray.getDimensionPixelSize(R.styleable.ExpositionBar_stroke_width, 0).toFloat()
        drawingPaint.strokeWidth = strokeWidth

        strokeColor = typedArray.getColor(R.styleable.ExpositionBar_stroke_color, Color.WHITE)
        buttonFillColor = typedArray.getColor(R.styleable.ExpositionBar_button_color, Color.BLACK)
        buttonFillColorPressed = typedArray.getColor(R.styleable.ExpositionBar_button_color_pressed, Color.BLUE)

        val minValue = typedArray.getFloat(R.styleable.ExpositionBar_min_value, 0f)
        val maxValue = typedArray.getFloat(R.styleable.ExpositionBar_max_value, 0f)
        valuesRange = Range(minValue, maxValue)

        typedArray.recycle()
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)

        drawingRect.right = width.toFloat()
        drawingRect.bottom = height.toFloat()

        buttonCenterY = drawingRect.centerY()

        recalculateDrawingValues()
    }

    override fun onDraw(canvas: Canvas) {
        drawingPaint.color = strokeColor
        drawingPaint.style = Paint.Style.STROKE

        // Draw the center line
        canvas.drawLine(centerX, minY, centerX, buttonMinY, drawingPaint)
        canvas.drawLine(centerX, buttonMaxY, centerX, maxY, drawingPaint)

        // Draw the button
        canvas.drawCircle(centerX, buttonCenterY, buttonRadiusExt, drawingPaint)
        drawingPaint.style = Paint.Style.FILL
        drawingPaint.color = if(isInDragMode) buttonFillColorPressed else buttonFillColor
        canvas.drawCircle(centerX, buttonCenterY, buttonRadiusInt, drawingPaint)

        // Draw button icon
        canvas.translate(iconTranslationX, iconTranslationY)
        icon.draw(canvas)
        canvas.translate(-iconTranslationX, -iconTranslationY)
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun onTouchEvent(event: MotionEvent): Boolean {
        if(!isEnabled) {
            return false
        }

        when(event.actionMasked) {
            MotionEvent.ACTION_DOWN -> {
                if(isButtonHit(event.y)){
                    isInDragMode = true
                    invalidate()
                }
            }
            MotionEvent.ACTION_MOVE -> {
                if(isInDragMode) {
                    buttonCenterY = event.y.fitInRange(buttonCenterBoundsRange)
                    recalculateDrawingValues()
                    invalidate()

                    val outputValue = buttonCenterY.reduceToRange(buttonCenterBoundsRange, valuesRange)
                    if (outputValue != oldOutputValue) {
                        onValueChangeListener?.invoke(outputValue)
                        oldOutputValue = outputValue
                    }
                }
            }
            MotionEvent.ACTION_UP,
            MotionEvent.ACTION_CANCEL -> {
                isInDragMode = false
                invalidate()
            }
        }
        return true
    }

    fun setOnValueChangeListener(listener: ((Float) -> Unit)?) {
        onValueChangeListener = listener
    }

    private fun recalculateDrawingValues() {
        centerX = drawingRect.left + drawingRect.width()/2
        minY = drawingRect.top
        maxY = drawingRect.bottom

        buttonRadiusExt = drawingRect.width() / 2 - strokeWidth / 2
        buttonRadiusInt = buttonRadiusExt - strokeWidth / 2
        buttonMinY = buttonCenterY - buttonRadiusExt
        buttonMaxY = buttonCenterY + buttonRadiusExt

        val buttonCenterMinY = minY + buttonRadiusExt + strokeWidth / 2
        val buttonCenterMaxY = maxY - buttonRadiusExt - strokeWidth / 2
        buttonCenterBoundsRange = Range(buttonCenterMinY, buttonCenterMaxY)

        iconTranslationX = centerX - icon.bounds.width() / 2
        iconTranslationY = buttonCenterY - icon.bounds.height() / 2
    }

    private fun isButtonHit(y: Float): Boolean {
        return y >= buttonMinY && y <= buttonMaxY
    }
}

您可以按照以下所示使用它:

<com.shevelev.wizard_camera.main_activity.view.widgets.ExpositionBar
    android:id="@+id/expositionBar"
    android:layout_width="@dimen/mainButtonSize"
    android:layout_height="300dp"
    android:layout_gravity="end|center_vertical"

    android:layout_marginEnd="@dimen/marginNormal"
    android:layout_marginBottom="26dp"

    app:button_icon = "@drawable/ic_brightness"
    app:button_icon_size = "@dimen/toolButtonIconSize"
    app:stroke_width = "@dimen/strokeWidthNormal"
    app:stroke_color = "@color/mainButtonsForeground"
    app:button_color = "@color/mainButtonsBackground"
    app:button_color_pressed = "@color/mainButtonsBackgroundPressed"
    app:min_value="-100"
    app:max_value="100"
/>

Voila!

0

隐藏式垂直 SeekBar

简单来说,您可以制作一个像这样的 SeekBar。

就像在视频播放器中 增加或减少音量 的方式一样。所有三个最后的属性都可以在 SeekBar 中进行操作。

<LinearLayout
        android:layout_width="@dimen/_40dp"
        android:layout_height="wrap_content"
        android:layout_marginVertical="100dp"
        android:gravity="center"
        android:orientation="vertical"
        >
        <SeekBar
            android:layout_width="500dp"
            android:layout_height="300dp"
            android:layout_gravity="center"
            android:rotation="270"
            android:secondaryProgress="6"
            android:progress="15"
            android:progressDrawable="@null"
            android:thumbTint="@null"
            android:secondaryProgressTint="@null"
            />
    </LinearLayout>

-1

简单回答

不要在SeekBar内使用android:rotation="270",而是在它外面包裹一个FrameLayout并在其中使用它。

 <FrameLayout
    android:background="@color/gray"
    android:layout_width="300dp"
    android:layout_height="5dp"
    android:layout_marginEnd="-126dp"
    android:rotation="270"
    android:orientation="vertical"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toTopOf="parent">
<SeekBar
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    />
</FrameLayout>

为了使我的框架布局向右边有24dp的边距,我计算了宽度减去150dp再加上24dp,因为框架布局首先是水平绘制,然后再垂直旋转。

不起作用.... - Vitaly

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接