android: move a view on touch move (ACTION_MOVE)

后端 未结 11 2344
终归单人心
终归单人心 2020-11-22 13:54

I\'d like to do a simple control: a container with a view inside. If I touch the container and I move the finger, I want to move the view to follow my finger.

What

11条回答
  •  野性不改
    2020-11-22 14:35

    Same implementation in Kotlin

        rightPanel.setOnTouchListener(View.OnTouchListener { view, event ->
            when (event?.action) {
                MotionEvent.ACTION_DOWN -> {
    
                    rightDX = view!!.x - event.rawX
                    // rightDY = view!!.getY() - event.rawY;
    
                }
                MotionEvent.ACTION_MOVE -> {
    
                    var displacement = event.rawX + rightDX
    
                    view!!.animate()
                            .x(displacement)
                            // .y(event.getRawY() + rightDY)
                            .setDuration(0)
                            .start()
                }
                else -> { // Note the block
                    return@OnTouchListener false
                }
            }
            true
     })
    

提交回复
热议问题