如何通过Kotlin将拖动视图的ID传递给setImageResource(resID:Int)函数?

huangapple go评论86阅读模式
英文:

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

问题

我想将一张图片移动到另一张空白图片中。在执行此操作时,拖动的图片应该被移除,目标位置应该复制拖动的图片包含的数据。

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
}

我可以使用 localState 将拖动的数据复制到 draggedView 中。之后,当发生放置事件时,它应该更改放置目标的图像资源,但它没有。这是程序崩溃的地方。

setImageResource 要求一个整数参数,但据我所知,它只接受 setImageResource(R.drawable.name) 语法。

如何将拖动视图的ID传递给 setImageResource(resID:Int)

英文:

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) ?

答案1

得分: 0

尝试首先使用资源ID设置标签

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

然后您可以获取标签

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
}
英文:

try first setting tag with resource id

val myImageView = findViewById&lt;ImageView&gt;(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 -&gt;
    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
}

huangapple
  • 本文由 发表于 2020年1月3日 20:38:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/59578792.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定