【问题标题】:My code for swap the backgrounds of two views doesn't work我的交换两个视图背景的代码不起作用
【发布时间】:2012-07-04 09:59:47
【问题描述】:

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

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

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 而不是背景,或者

网格视图。但请我想知道为什么这段代码不能完全工作。

【问题讨论】:

  • 你的代码到处都是。发布问题时请花一些时间来格式化它。欢迎来到 StackOverflow。 :)
  • 它更好。谢谢你。在这里,投赞成票。

标签: android view background imageview swap


【解决方案1】:

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

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

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

在一种情况下:

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

反之亦然:

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

【讨论】:

    猜你喜欢
    • 2017-11-13
    • 1970-01-01
    • 2020-03-16
    • 2010-12-08
    • 2017-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-11
    相关资源
    最近更新 更多