Search code examples
androidkotlinimageviewonclicklistenerandroid-constraintlayout

How to move ImageView when it is clicked in Kotlin?


So I want to have a box that can be moved when we clicked it. The box starts in left top border and when we click it, I want it to move to bottom right border. I thought I have implemented the code correctly but when I run the app and click the box, it didn't move. Where am I missing?

Here's the function to move the box

fun placement() {
    box.visibility = View.VISIBLE
    box.isClickable = true
    box.setOnClickListener {
        val params = box.layoutParams as ConstraintLayout.LayoutParams
        params.rightToLeft = contentMainBinding.RightBorder.id
        params.topToBottom = contentMainBinding.BottomBorder.id
        box.layoutParams = params
    }
}

Here's the initial box position

<ImageView
    android:id="@+id/box"
    android:layout_width="20dp"
    android:layout_height="30dp"
    android:background="#000000"
    app:layout_constraintStart_toEndOf="@+id/LeftBorder"
    app:layout_constraintTop_toBottomOf="@+id/TopBorder"
    tools:ignore="MissingConstraints" />

Solution

  • You should UNSET for top and start connect. Change your onclick like this:

    fun placement() {
        box.visibility = View.VISIBLE
        box.isClickable = true
        box.setOnClickListener {
            val params = box.layoutParams as ConstraintLayout.LayoutParams
            params.rightToLeft = contentMainBinding.RightBorder.id
            params.bottomToTop = contentMainBinding.BottomBorder.id    //change topToBottom
    
            //UNSET connection here
            params.startToEnd = ConstraintLayout.LayoutParams.UNSET
            params.topToBottom = ConstraintLayout.LayoutParams.UNSET
    
            box.layoutParams = params
        }
    }