在ConstraintLayout中拖放

时间:2018-10-09 11:59:57

标签: android

我正在尝试在ConstraintLayout中拖放,如下所示

require

我的拖动侦听器是

override fun onLongClick(v: View?): Boolean {
    val dragData = ClipData.newPlainText("", "")
    val myShadow = View.DragShadowBuilder(v)

    if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.N) {
        startDragAndDrop(dragData, myShadow, v, 0)
    }else{
        startDrag(dragData, myShadow, v, 0)
    }
    return true
}

这是我的xml

private val mDragListen = View.OnDragListener { v, event ->
    val view = event.localState as TextView
    when (event.action) {
        DragEvent.ACTION_DRAG_STARTED -> {
            layoutParams = view.layoutParams as ConstraintLayout.LayoutParams?
            true
        }
        DragEvent.ACTION_DRAG_ENTERED -> {
            true
        }

        DragEvent.ACTION_DRAG_LOCATION ->
            true
        DragEvent.ACTION_DRAG_EXITED -> {
            true
        }
        DragEvent.ACTION_DROP -> {
            layoutParams?.marginStart = event.x.toInt()
            layoutParams?.topMargin = event.y.toInt()
            view.layoutParams = layoutParams
            view.invalidate()
            true
        }

        DragEvent.ACTION_DRAG_ENDED -> {
            when (event.result) {
                true ->
                    Toast.makeText(activity, "The drop was handled.", Toast.LENGTH_LONG)
                else ->
                    Toast.makeText(activity, "The drop didn't work.", Toast.LENGTH_LONG)
            }.show()
            true
        }
        else -> {
            Log.e("DragDrop Example", "Unknown action type received by OnDragListener.")
            false
        }
    }
}

这是有效的,但没有达到预期效果,请参见输出。

enter image description here

1 个答案:

答案 0 :(得分:1)

DragEvent方法getX()和getY()返回此处https://developer.android.com/reference/android/view/DragEvent.html#getX()指向的拖动点的坐标

在您的情况下,只需减去视图高度和宽度的一半即可达到预期的结果

layoutParams?.marginStart = event.x.toInt() - (view.width.div(2))
layoutParams?.topMargin = event.y.toInt() - (view.height.div(2))