Android seekbar solution

后端 未结 5 411
情话喂你
情话喂你 2020-12-28 20:17

Is it possible to have the seekbar move only when the thumb is moved. Right now the seekbar moves even on finger touch in the progressdrawable. How do we disable the movemen

5条回答
  •  春和景丽
    2020-12-28 21:02

    Here's a Kotlin version of awy's answer with the caveat that absolutely no movement happens when you tap outside the drawable. The whole point is that you don't want users to be able to skip.

    import android.content.Context
    import android.util.AttributeSet
    import android.view.MotionEvent
    import androidx.appcompat.widget.AppCompatSeekBar
    
    class NoSkipSeekBar @JvmOverloads constructor(
        context: Context,
        attrs: AttributeSet? = null,
        defStyle: Int = 0
    ) : AppCompatSeekBar(context, attrs, defStyle) {
    
        private var isDragging = false
    
        private fun isWithinThumb(event: MotionEvent): Boolean {
            return thumb.bounds.contains(event.x.toInt(), event.y.toInt())
        }
    
        override fun onTouchEvent(event: MotionEvent): Boolean {
            if (!isEnabled || thumb == null) return super.onTouchEvent(event)
    
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    if (isWithinThumb(event)) {
                        isDragging = true
                        return super.onTouchEvent(event)
                    } else {
                        return true
                    }
                }
                MotionEvent.ACTION_UP -> {
                    isDragging = false
    
                    return when {
                        isWithinThumb(event) -> super.onTouchEvent(event)
                        else -> true
                    }
                }
                MotionEvent.ACTION_MOVE -> if (!isDragging) return true
                MotionEvent.ACTION_CANCEL -> isDragging = false
            }
            return super.onTouchEvent(event)
        }
    }
    

提交回复
热议问题