Android 拖拽View

    /**
     * @view 需要拖拽的view
     * @data 拖拽需要携带的数据
     */
    fun dragView(view: View,data:Any) {
        var shadow = View.DragShadowBuilder(view)
        ViewCompat.startDragAndDrop(view, null, shadow, data, 0)
    }

下面是接受拖拽的区域的代码

  layout.setOnDragListener { v, event ->
            when (event?.action) {
            DragEvent.ACTION_DRAG_ENTERED -> v.setBackgroundColor(GREEN)
            DragEvent.ACTION_DRAG_EXITED -> v.setBackgroundColor(RED)
            DragEvent.ACTION_DRAG_ENDED -> v.setBackgroundColor(WHITE)
                DragEvent.ACTION_DROP -> {
                    val dropX = event.getX()
                    val dropY = event.getY()
                    val data  = event.getLocalState()
                  
                    var shape = ImageView(context)
                    shape.setImageResource(R.drawable.test)
                    var layoutParams = FrameLayout.LayoutParams(data.width, data.height)
                    layoutParams.marginStart = (dropX - data.width.toFloat() / 2).toInt()
                    layoutParams.topMargin = (dropY - data.height.toFloat() / 2).toInt()
                    ident_frame.addView(shape, layoutParams)
                    shape.setOnClickListener {
                        layout.removeView(it)
                   }
                }
                else -> {
                }
            }
            true
        }
  • 注,event.getLocalState() 为生成 dragView 中的 data 一般会包括 dragView 的宽高等数据。

以上即可实现view拖拽。

你可能感兴趣的:(Android 拖拽View)