簡體   English   中英

在 Kotlin 中單擊時如何移動 ImageView?

[英]How to move ImageView when it is clicked in Kotlin?

所以我想要一個可以在我們單擊時移動的框。 該框從左上邊框開始,當我們單擊它時,我希望它移動到右下邊框。 我以為我已經正確實現了代碼,但是當我運行應用程序並單擊框時,它沒有移動。 我在哪里失蹤?

這是 function 移動盒子

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
    }
}

這是初始盒子 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" />

您應該取消設置頂部並開始連接。 像這樣更改您的 onclick:

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
    }
}

1.將params.topToBottom替換為params.bottomToTop

2.清除xml設置的約束。

params.startToEnd = ConstraintLayout.LayoutParams.UNSET
params.topToBottom = ConstraintLayout.LayoutParams.UNSET

順便說一句,還有其他方法可以移動盒子。

方法1:

box.updateLayoutParams<ConstraintLayout.LayoutParams> {
    rightToLeft = contentMainBinding.RightBorder.id
    bottomToTop = contentMainBinding.BottomBorder.id
    startToEnd = ConstraintLayout.LayoutParams.UNSET
    topToBottom = ConstraintLayout.LayoutParams.UNSET
}

方法2:

val constraintSet = ConstraintSet()
constraintSet.clone(contentMainBinding.root)
constraintSet.clear(contentMainBinding.box.id, ConstraintSet.TOP)
constraintSet.clear(contentMainBinding.box.id, ConstraintSet.START)
constraintSet.connect(
    contentMainBinding.box.id,
    ConstraintSet.BOTTOM,
    contentMainBinding.BottomBorder.id,
    ConstraintSet.TOP,
)
constraintSet.connect(
    contentMainBinding.box.id,
    ConstraintSet.RIGHT,
    contentMainBinding.RightBorder.id,
    ConstraintSet.LEFT,
)

constraintSet.applyTo(contentMainBinding.root)

方法3:

contentMainBinding.placeholder.setContentId(box.id)

xml:
<androidx.constraintlayout.widget.Placeholder
    android:id="@+id/placeholder"
    android:layout_width="20dp"
    android:layout_height="30dp"
    app:layout_constraintRight_toLeftOf="@id/RightBorder"
    app:layout_constraintBottom_toTopOf="@id/BottomBorder" />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM