ImageView再次单击

时间:2016-04-14 20:39:49

标签: java android xml

我希望我的ImageView在按下时更改drawable资源。第二次按下ImageView时会出现问题。

让我解释一下,如果第一次按下ImageView,我希望它从drawable A更改为drawable B.如果再次按ImageView我想要它从drawable B更改为drawable A。

再次按下部分不起作用..

这是我的代码:

public void imageViewBiljeskeNaListiCheckMarkMetoda(View view){
        imageViewBiljeskeNaListiCheckMark = (ImageView) findViewById(R.id.imageViewBiljeskeNaListiCheckMark);
        if (view == imageViewBiljeskeNaListiCheckMark){
            imageViewBiljeskeNaListiCheckMark.setImageResource(R.drawable.ic_biljeske_obavljeno);
        } else {
            imageViewBiljeskeNaListiCheckMark.setImageResource(R.drawable.ic_biljeske_nije_obavljeno);
        } 
    }

3 个答案:

答案 0 :(得分:2)

从方法中删除.... 您需要在onCreate ...

中初始化对象一次
imageViewBiljeskeNaListiCheckMark = (ImageView) findViewById(R.id.imageViewBiljeskeNaListiCheckMark);

然后添加一个布尔变量来控制视图的状态。

public void imageViewBiljeskeNaListiCheckMarkMetoda(View view){
        flag =!flag;

        if (view == imageViewBiljeskeNaListiCheckMark){
          if (flag) {imageViewBiljeskeNaListiCheckMark.setImageResource(R.drawable.ic_biljeske_obavljeno);
        } else {
            imageViewBiljeskeNaListiCheckMark.setImageResource(R.drawable.ic_biljeske_nije_obavljeno);
        } 
}

答案 1 :(得分:1)

我建议使用视图的“标记”,并在标记中保留您需要的信息(例如,如果是否按下视图)

http://developer.android.com/intl/es/reference/android/view/View.html#setTag(java.lang.Object)

答案 2 :(得分:1)

你不能只使用像这样的切换方法吗?

private void toggleDrawableOnClick(){

    /* now you can check to see if the set drawable is A using its id */
    if(visible drawable is A){
      imageViewBiljeskeNaListiCheckMark.setImageResource(R.drawable.ic_biljeske_nije_obavljeno);
    }else{
      imageViewBiljeskeNaListiCheckMark.setImageResource(R.drawable.ic_biljeske_obavljeno);
    }
}

我相信这应该更容易!!