小爱智能音箱亮度调节控件和色温调节控件的自定义实现

Wondershare UniConverter 13_000001.GIF

亮度调节条的实现

image.png





/**
 * Copyright:MicoLauncher
 * Author: liyang <br>
 * Date:2021/8/23 2:08 下午<br>
 * Desc: <br>
 */
class VerticalSeekView(
    context: Context,
    attributeSet: AttributeSet? = null,
    defStyleAttr: Int = 0,
    defStyleRes: Int = 0
) : View(context, attributeSet, defStyleAttr, defStyleRes) {
    constructor(context: Context, attributeSet: AttributeSet? = null, defStyleAttr: Int = 0) : this(
        context,
        attributeSet,
        defStyleAttr,
        0
    )

    constructor(context: Context, attributeSet: AttributeSet?) : this(context, attributeSet, 0)
    constructor(context: Context) : this(context, null)
  ....
  ....
  ....

    companion object {
        const val TAG = "VerticalSeekView:"

        @JvmStatic
        @BindingAdapter("data")
        fun bindData(
            view: VerticalSeekView,
            data: DeviceInfoWrapper
        ) {
            data.deviceInfo.apply {
                when (data.modelInfo.deviceType) {
                    DeviceTypeDic.DT_LIGHT_LIGHT.deviceType, DeviceTypeDic.DT_LIGHT_MIRROR.deviceType, DeviceTypeDic.DT_LIGHT_NIGHT_LIGHT.deviceType -> {
                        view.showIcon = true
                        view.deviceTypeIcon = if (currentStatus) {
                            R.drawable.sh_ic_light_icon_on
                        } else {
                            R.drawable.sh_ic_light_icon_off
                        }

                    }
                    DeviceTypeDic.DT_ENV_HEATER.deviceType -> {
                        view.showIcon = true
                        view.deviceTypeIcon = if (currentStatus) {
                            R.drawable.sh_ic_heater_temperature_on
                        } else {
                            R.drawable.sh_ic_heater_temperature_off
                        }
                        view.foregroundColor = ContextCompat.getColor(
                            view.context,
                            if (currentStatus) R.color.sh_miot_heater_foreground_color else R.color.sh_miot_heater_foreground_color_off
                        )
                    }
                }
            }

        }


    }

  ....
  ....
  ....

    var volume: Double = 0.0
        set(value) {
            if (value in 0.0..1.0 && field != value) {
                field = value
                volumeChangeListener?.onVolumeChanged(value)
                refresh()
            }
        }



    var volumeChangeListener: OnVolumeChangeListener? = null


    private val minTouchSlop by lazy {
        ViewConfiguration.get(context).scaledTouchSlop
    }


    init {
        val typedArray = context.obtainStyledAttributes(attributeSet, R.styleable.VerticalSeekView)
        radius = typedArray.getDimensionPixelOffset(R.styleable.VerticalSeekView_radius, 0).let {
            var num = it
            if (it < 0) {
                num = 0
            }
            num
        }

        deviceTypeIcon = typedArray.getResourceId(
            R.styleable.VerticalSeekView_deviceTypeIcon,
            R.drawable.sh_ic_iot_lamp
        )
        bitmap = ContextCompat.getDrawable(context, deviceTypeIcon)?.toBitmap()

        underlyingColor = typedArray.getColor(
            R.styleable.VerticalSeekView_underlyingLayerColor,
            context.getColor(R.color.sh_miot_seek_view_background_color)
        )
        foregroundColor = typedArray.getColor(
            R.styleable.VerticalSeekView_foregroundLayerColor,
            context.getColor(R.color.sh_miot_seek_view_foreground_color)
        )
        volume = (typedArray.getFloat(R.styleable.VerticalSeekView_volume, 0.0f)
            .takeIf {
                it >= 0.0f || it <= 100.0f
            } ?: 0.0f)
            .toDouble()
        startColor = typedArray.getColor(R.styleable.VerticalSeekView_startColor, foregroundColor)
        endColor = typedArray.getColor(R.styleable.VerticalSeekView_endColor, foregroundColor)

        canDrag = typedArray.getBoolean(R.styleable.VerticalSeekView_canDrag, true)

        paint.isAntiAlias = true
        paint.isDither = true
        typedArray.recycle()
    }


    @SuppressLint("ClickableViewAccessibility")
    override fun onTouchEvent(event: MotionEvent?): Boolean {
        if (!canDrag) return super.onTouchEvent(event)
        when (event?.action) {
            MotionEvent.ACTION_DOWN -> {
                startX = event.x
                startY = event.y
                downTimestamp = System.currentTimeMillis()
                L.smarthome.d("$TAG onTouchEvent ACTION_DOWN downX=$startX,downY=$startY,minTouchSlop=$minTouchSlop")
                volumeChangeListener?.onVolumeChangedBegin(volume)
                startVolume = volume
                return true
            }
            MotionEvent.ACTION_MOVE -> {
                currentX = event.x
                currentY = event.y
                val offsetX = startX - currentX
                val offsetY = startY - currentY

                if (abs(offsetY) > abs(offsetX)) {//纵向滑动时,请求RecyclerView不拦截事件
                    parent.requestDisallowInterceptTouchEvent(true)
                    if (abs(offsetY) > minTouchSlop) {
                        if (!isFistMoveAction) {
                            volume = (offsetY / height).plus(startVolume).let {
                                var newVolume = it
                                if (it >= 1) {
                                    newVolume = 1.0
                                }
                                if (it <= 0) {
                                    newVolume = 0.0
                                }
                                newVolume
                            }

                            isVolumeChange = true
                            L.smarthome.d("$TAG onTouchEvent ACTION_MOVE setVolume=$volume")
                            return true
                        }
                        isFistMoveAction = false
                    }
                }

                lastX = currentX
                lastY = currentY

            }
            MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                currentX = 0f
                currentY = 0f
                lastY = 0f
                lastX = 0f
                isFistMoveAction = true
                parent.requestDisallowInterceptTouchEvent(false)
                L.smarthome.d("$TAG ${if (event.action == MotionEvent.ACTION_UP) "ACTION_UP" else "ACTION_CANCEL"} requestDisallowInterceptTouchEvent:false")
                val isLongClick =
                    (System.currentTimeMillis() - downTimestamp) >= ViewConfiguration.getLongPressTimeout()
                if (event.action == MotionEvent.ACTION_UP && !isVolumeChange && !isLongClick) {
                    performClick()
                }
                if (isVolumeChange) {
                    isVolumeChange = false
                }
                volumeChangeListener?.onVolumeChangedEnd(isVolumeChange, volume)

            }
        }
        return super.onTouchEvent(event)
    }


    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        canvas?.apply {
            layerId = saveLayer(0f, 0f, width.toFloat(), height.toFloat(), null)
            //画底层背景色
            onDrawUnderlyingLayer(this)
            //画上层填充色
            onDrawForegroundLayer(this)
            //画小横条
            onDrawHandler(this)
            //画底部的icon
            onDrawIcon(this)
            restoreToCount(layerId)
        }
    }

    private fun onDrawIcon(canvas: Canvas) {
        if (!showIcon)return
        bitmap?.apply {
            L.smarthome.d("$TAG,width=$width,height=$height")
            canvas.drawBitmap(this, Rect(0, 0, width, height), destRect, null)
        }
    }

    private fun onDrawHandler(canvas: Canvas) {
        if (!canDrag) return
        rectF.left = ((width - 40.toPx()) / 2).toFloat()
        rectF.top = (canvas.height - canvas.height * volume + 8.toPx()).toFloat()
        rectF.right = (width / 2 + 17).toFloat()
        rectF.bottom = rectF.top.minus(4)
        paint.color = ContextCompat.getColor(context, R.color.black_12_transparent)
        canvas.drawRoundRect(rectF, 1.5f, 1.5f, paint)
    }


    private fun onDrawUnderlyingLayer(canvas: Canvas) {
        paint.style = Paint.Style.FILL
        paint.color = underlyingColor

        rectF.left = 0f
        rectF.top = 0f
        rectF.right = canvas.width.toFloat()
        rectF.bottom = canvas.height.toFloat()
        canvas.drawRoundRect(rectF, radius.toFloat(), radius.toFloat(), paint)

    }

    private fun onDrawForegroundLayer(canvas: Canvas) {
        paint.style = Paint.Style.FILL
        paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP)
        val top = (canvas.height - canvas.height * volume).toFloat()
        val bottom = canvas.height.toFloat()
        if (startColor != foregroundColor || endColor != foregroundColor) {
            val gradient = LinearGradient(
                (width / 2).toFloat(),
                top,
                (width / 2).toFloat(),
                bottom,
                startColor,
                endColor,
                Shader.TileMode.CLAMP
            )
            paint.shader = gradient
        } else {
            paint.color = foregroundColor
        }

        rectF.left = 0f
        rectF.top = top
        rectF.right = canvas.width.toFloat()
        rectF.bottom = bottom

        canvas.drawRect(rectF, paint)
        paint.xfermode = null
        paint.shader = null
    }

    private fun refresh() {
        if (Looper.myLooper() != Looper.getMainLooper()) {
            postInvalidate()
        } else {
            invalidate()
        }
    }


}

interface OnVolumeChangeListener {
    fun onVolumeChangedBegin(volume: Double)
    fun onVolumeChanged(volume: Double)
    fun onVolumeChangedEnd(flag: Boolean, volume: Double)
}

色温调节条的实现

2022.02.14-11.49.56.png
package com.xiaomi.smarthome.ui.widgets



/**
 * Copyright:MicoLauncher
 * Author: liyang <br>
 * Date:2021/8/23 2:08 下午<br>
 * Desc: <br>
 */
class VerticalSeekView2(
    context: Context,
    attributeSet: AttributeSet? = null,
    defStyleAttr: Int = 0,
    defStyleRes: Int = 0
) : View(context, attributeSet, defStyleAttr, defStyleRes) {
    constructor(context: Context, attributeSet: AttributeSet? = null, defStyleAttr: Int = 0) : this(
        context,
        attributeSet,
        defStyleAttr,
        0
    )

    constructor(context: Context, attributeSet: AttributeSet?) : this(context, attributeSet, 0)
    constructor(context: Context) : this(context, null)

    ......
    ......

    var volume: Double = 0.0
        set(value) {
            if (value in 0.0..1.0 && field != value) {
                field = value
                refresh()
                volumeChangeListener?.onVolumeChanged(value)
            }
        }
    var volumeChangeListener: OnVolumeChangeListener? = null

   ......
   ......
   ......


    init {

        val typedArray = context.obtainStyledAttributes(attributeSet, R.styleable.VerticalSeekView2)
        radius = typedArray.getDimensionPixelOffset(R.styleable.VerticalSeekView2_radius, 0).let {
            var num = it
            if (it < 0) {
                num = 0
            }
            num
        }

        startColor = typedArray.getColor(R.styleable.VerticalSeekView2_startColor, Color.WHITE)
        endColor = typedArray.getColor(R.styleable.VerticalSeekView2_endColor, Color.BLUE)

        volume = (typedArray.getFloat(R.styleable.VerticalSeekView2_volume, 0.0f)
            .takeIf {
                it >= 0.0f || it <= 100.0f
            } ?: 0.0f)
            .toDouble()

        paint.isAntiAlias = true
        paint.isDither = true

        typedArray.recycle()
    }


    @SuppressLint("ClickableViewAccessibility")
    override fun onTouchEvent(event: MotionEvent?): Boolean {
        when (event?.action) {
            MotionEvent.ACTION_DOWN, MotionEvent.ACTION_MOVE -> {
                if (event.action == MotionEvent.ACTION_DOWN) {
                    parent.requestDisallowInterceptTouchEvent(true)
                }
                currentX = event.y
                currentY = event.x
                val offsetX = lastX - currentX
                val offsetY = lastY - currentY
                if (abs(offsetX) < abs(offsetY)) {//纵向滑动时,请求RecyclerView不拦截事件
                    parent.requestDisallowInterceptTouchEvent(true)
                }
                volume = ((height - currentX) / height).toDouble().let {
                    var newVolume = it
                    if (it >= 1) {
                        newVolume = 1.0
                    }
                    if (it <= 0) {
                        newVolume = 0.0
                    }
                    newVolume
                }
                lastX = currentX
                lastY = currentY
                L.smarthome.d("$TAG onTouchEvent currentX=$currentX,currentY=$currentY")
                return true
            }
            MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                currentX = 0f
                currentY = 0f
                lastY = 0f
                lastX = 0f
                parent.requestDisallowInterceptTouchEvent(false)
                L.smarthome.d("${TAG}requestDisallowInterceptTouchEvent:false")
            }
        }
        return super.onTouchEvent(event)
    }


    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        canvas?.apply {
            layerId = saveLayer(0f, 0f, width.toFloat(), height.toFloat(), null)
            onDrawUnderlyingLayer(this)
            onDrawHandler(this)
            restoreToCount(layerId)
        }
    }

    private fun onDrawHandler(canvas: Canvas) {
        rectF.left = 0f
        rectF.top = (canvas.height - canvas.height * volume).toFloat().let {
            var newVal=it
            if (it>=canvas.height+48.toPx()){
                newVal=(canvas.height+48.toPx()).toFloat()
            }else if (it<=48.toPx()){
                newVal=48.toPx().toFloat()
            }
            newVal
        }
        rectF.right = width.toFloat()
        rectF.bottom = rectF.top.minus(48.toPx())
        paint.color = Color.WHITE
        canvas.drawRoundRect(rectF, 26f, 26f, paint)
    }


    private fun onDrawUnderlyingLayer(canvas: Canvas) {
        paint.style = Paint.Style.FILL
        val gradient = LinearGradient((width / 2).toFloat(), 0f, (width / 2).toFloat(), height.toFloat(),startColor,endColor,Shader.TileMode.REPEAT)
        paint.shader=gradient

        rectF.left = 0f
        rectF.top = 0f
        rectF.right = canvas.width.toFloat()
        rectF.bottom = canvas.height.toFloat()
        canvas.drawRoundRect(rectF, radius.toFloat(), radius.toFloat(), paint)
        paint.shader=null
    }


    private fun refresh() {
        if (Looper.myLooper() != Looper.getMainLooper()) {
            postInvalidate()
        } else {
            invalidate()
        }
    }

}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 215,076评论 6 497
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,658评论 3 389
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 160,732评论 0 350
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,493评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,591评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,598评论 1 293
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,601评论 3 415
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,348评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,797评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,114评论 2 330
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,278评论 1 344
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,953评论 5 339
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,585评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,202评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,442评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,180评论 2 367
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,139评论 2 352

推荐阅读更多精彩内容