View move to top after remove Relativelayout Rule in android

65 views Asked by At

I've added RelativeLayout into RelativeLayout by using below code.

var _root: ViewGroup? = null
private var _xDelta: Float = 0F
private var _yDelta: Float = 0F

lateinit var layoutParams: RelativeLayout.LayoutParams

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

    _root = findViewById(R.id.root)

    _view = RelativeLayout(this)
    _view?.setBackgroundColor(Color.BLUE)

    layoutParams = RelativeLayout.LayoutParams(280, 280)
    layoutParams.leftMargin = 0
    layoutParams.topMargin = 0
    layoutParams.bottomMargin = 0
    layoutParams.rightMargin = 0

    // Adding Rule
    layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM)
    layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT)

    _view?.layoutParams = layoutParams

    _view?.setOnTouchListener(this)
    _root?.addView(_view)

}

If I touch the view and I move the finger, It will move the view to follow my finger. Below is the code for it :-

override fun onTouch(view: View, event: MotionEvent): Boolean {
    val X = event.rawX
    val Y = event.rawY
    when (event.action and MotionEvent.ACTION_MASK) {
        MotionEvent.ACTION_DOWN -> {
            val lParams = view.layoutParams as RelativeLayout.LayoutParams
            _xDelta = X - lParams.leftMargin
            _yDelta = Y - lParams.topMargin
        }
        MotionEvent.ACTION_UP -> {
        }
        MotionEvent.ACTION_POINTER_DOWN -> {
        }
        MotionEvent.ACTION_POINTER_UP -> {
        }
        MotionEvent.ACTION_MOVE -> {

            // Removing the rule to apply the effects
            layoutParams.removeRule(RelativeLayout.ALIGN_PARENT_BOTTOM)
            layoutParams.removeRule(RelativeLayout.ALIGN_PARENT_RIGHT)

            layoutParams = view.layoutParams as RelativeLayout.LayoutParams
            layoutParams.leftMargin = (X - _xDelta).toInt()
            layoutParams.topMargin = (Y - _yDelta).toInt()
            layoutParams.rightMargin = 0
            layoutParams.bottomMargin = 0

            view.layoutParams = layoutParams

        }
    }
    _root?.invalidate()
    return true
}

But when I touch the view, it moves to the top - left corner. I want it to be at my finger touch area only. It works fine after I touch again. Is ther any solution? Please help.

0

There are 0 answers