在拖放时更改 imageview 背景

Change imageview backgrounds on drop

我创建了一个拖放应用程序,允许用户从顶部拖动 4 张图像并将它们按顺序放在底部。我在顶部有 4 个图像视图,在底部有 4 个图像视图。将它们放下非常有效,但是当我尝试将它们左右移动时,我 运行 遇到了问题。

我有 2 个临时图像视图,我将它们设置为等于一个图像视图。如果我将图像从图像视图 6 移动到图像视图 5,它应该交换图像,但它只是将图像视图 6 更改为图像视图 5,而图像视图 5 保持不变。

这是我尝试更改图像的代码片段

droppedSwap is equal to the image the user chose to move
dropTargetSwap is equal to where the user wants the image to go

if (dropTargetSwap.equals(ivHero5) && droppedSwap.equals(ivHero6))
            {
                //set temp imageview that is equal to ivHero5
                ImageView tempDropTarget = ivHero5;

                //set temp imageview that is equal to ivHero6
                ImageView tempDropped = ivHero6;

                //supposed to set ivHero6 to ivHero5 image
                droppedSwap.setBackground(tempDropTarget.getBackground());// working

                //supposed to set ivHero5 to ivHero6 image
                dropTargetSwap.setBackground(tempDropped.getBackground());// not working
            }

你的问题在于:

ImageView tempDropTarget = ivHero5;
ImageView tempDropped = ivHero6;

您实际上并不是在创建临时副本,而是对原始对象的引用,所以当您执行 droppedSwap.setBackground() 时,您实际上是在设置 ivHero6 背景,而当您执行 tempDropped.getBackground( ) 您将获得之前更改过的 ivHero6 背景。 你应该创建一个背景的副本,它是可绘制的,使用:

Drawable copy1 = ivHero5.getBackground().getConstantState().newDrawable();
Drawable copy2 = ivHero6.getBackground().getConstantState().newDrawable();