我需要帮助。我在pic
有这样的情况我需要将拖放功能从回收站释放到我的自定义视图。我的自定义视图是一个容器,其中包含四个其他视图。此视图有两种类型:空视图和包含回收项目的视图。当用户从回收站中拖动项目时,我需要在我拖动的视图边界内移动时更改容器中某个视图的背景颜色。所以我知道OnDragListener仅在父视图内部处理事件。然后,我为回收站中的项目和容器视图编写了两个OnDragListeners,例如:
interface DragItemListener {
fun onDragItem(item: item?)
}
class DragController(val item: Item) : OnDragListener {
override fun onDrag(v: View, event: DragEvent): Boolean {
val action = event.action
when (action) {
DragEvent.ACTION_DRAG_STARTED -> {
dragItemListener?.onDragItem(item)
}
DragEvent.ACTION_DROP -> {
dragItemListener?.onDragItem(null)
}
}
return true
}
}
class MyCustomContainer(context: Context) : LinearLayout(context) {
init {
this.setOnDragListener(DraggingItemListener())
}
fun setDraggableElement(item: Item?) {
this.draggedItem = item
}
private fun findItemView(x: Float, y: Float) : View?{
(0 until childCount).map { getChildAt(it) }.forEach {
if (it is EmptyView || it is ItemView) {
val bounds = getViewBounds(it)
if (x > bounds.left && x < bounds.right && y > bounds.top && y < bounds.bottom){
it.setBackgroundResource(R.color.selected_background)
return it
}else {
it.setBackgroundResource(R.color.background)
}
}
}
return null
}
private fun getViewBounds(view: View) : Rect{
return Rect(view.left, view.top, view.left + view.width, view.top + view.height)
}
inner class DraggingItemListener : OnDragListener {
private var currentView: View? = null
override fun onDrag(v: View?, event: DragEvent): Boolean {
if (draggedItem != null) {
when(event.action) {
DragEvent.ACTION_DRAG_LOCATION -> {
currentView = findItemView(event.x, event.y)
}
DragEvent.ACTION_DROP -> {
when(currentView) {
is EmptyView -> {
}
is ItemView -> {
}
}
currentView?.setBackgroundResource(R.color.background)
currentView = null
}
}else{
currentView = null
}
return true
}
}
}
是解决我的问题的正确方法还是我做错了?但是效果很好