android - 我的交换两个 View 背景的代码不起作用

标签 android view background imageview swap

我有 20 个带有背景图像集的 ImageView 。

当用户单击一张图像并单击第二张图像时,我希望这两个图像

imageviews 可以交换图像背景。

通过我构建的代码,我发现只有单击的第一个图像才会更新他的背景。

private View z; //view for temporary save the first clicked image public ImageView[] images = new ImageView[20]; //array with my imageviews public void onClick(View v) { if (attivo == false) { attivo = true; z = v; } //save the clicked view to a temporary one else { //we enter here when we click on the second image //this cycles search inside the array which imageview //has the same ID of the saved one or the new one (the first/second image clicked) for (int h = 0; h<20; h++) { if (images[h].getId()== z.getId()) { images[h].setBackgroundDrawable(v.getBackground());} } for (int h = 0; h<20; h++) { if (images[h].getId()== v.getId()) { images[h].setBackgroundDrawable(z.getBackground());} } attivo = false; } }

第一个周期有效!将第二个背景设置为单击的第一个 ImageView 。

第二个循环,即使命令执行了,也不行!背景始终是原始背景。

我知道我可以通过一些不同的方式来做到这一点,例如使用 src 而不是背景,或者

GridView 。但我想知道为什么这段代码不能完全工作。

最佳答案

最好的解决方案应该将您的后台资源存储在两个变量中:

Drawable d1 = v1.getBackgound();
Drawable d2 = v2.getBackgound();

然后将背景可绘制对象设置为对该变量的引用:

在一种情况下:

 images[h].setBackgroundDrawable(d1);
 images[h].setBackgroundDrawable(d2);

反之亦然:

 images[h].setBackgroundDrawable(d2);
 images[h].setBackgroundDrawable(d1);

关于android - 我的交换两个 View 背景的代码不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11326755/

相关文章:

java - 如何在 playframework Java 上将 List<Object> 转换为 JSON

android - 在 Android 设备上查看传感器列表

Android:使用选择器设置 ImageView 的背景颜色

ruby-on-rails - Rails 将脚本作为后台作业执行

android - 当我按下onClick Android时按钮会缩小

Android ADK - 连接多个设备

android - Gradle Javadoc 失败并显示 "error: package ... does not exist"

android - java.lang.AssertionError : CALL 'public final fun <get-currentComposer>

ruby-on-rails - 在 View 中使用另一个模型导致测试错误

firefox - css3 border-image firefox 15.0.1(第二轮)