Search code examples
androidkotlindrag-and-dropandroid-imageview

How can I pass the ID of dragged view into setImageResource(resID:Int) via Kotlin?


I want to move a picture into another empty picture. While doing this dragged picture should be removed and the drop target should copy the data which dragged picture contains.

        val myOnDragListener = View.OnDragListener { v, event ->
        val draggedView = event.localState as ImageView 

        if(event.action == DragEvent.ACTION_DROP){
            (v as ImageView).setImageResource(draggedView.id)
            draggedView.setImageDrawable(null)
        }

        true
    }

I can copy the dragged datas into draggedView using localState. After that when drop event occurs it should change the drop target's image resource but it doesn't. This is where the program collapses.

setImageResource says it wants an Int parameter but as far as I can see it only accepts setImageResource(R.drawable.name) syntax.

How can I pass the ID of dragged view into setImageResource(resID:Int) ?


Solution

  • try first setting tag with resource id

    val myImageView = findViewById<ImageView>(R.id.my_imageView);
    myImageView.setImageResource(R.drawable.drawable_name)          
    myImageView.setTag(R.drawable.drawable_name);
    

    then you can get the tag

     val myOnDragListener = View.OnDragListener { v, event ->
        val draggedView = event.localState as ImageView
    
        val tag=draggedView.tag as Int
        if(event.action == DragEvent.ACTION_DROP){
            (v as ImageView).setImageResource(tag)
            draggedView.setImageDrawable(null)
        }
    
        true
    }