英文:
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<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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论