DaxHR
DaxHR

Reputation: 683

ImageView on again click

I want my ImageView to change it's drawable resource as it is pressed. The problem occurs when ImageView is pressed for the second time.

Let me explain, if ImageView is pressed first time, I want it to change from drawable A to drawable B. If ImageView is pressed again I want it to change from drawable B to drawable A.

That pressed again part is not working..

Here's my code:

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);
        } 
    }

Upvotes: 0

Views: 47

Answers (3)

Remove this from the method.... You need to init the object once in the onCreate...

imageViewBiljeskeNaListiCheckMark = (ImageView) findViewById(R.id.imageViewBiljeskeNaListiCheckMark);

Then add a boolean variable to control the state of the view. .

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);
        } 
}

Upvotes: 2

Eenvincible
Eenvincible

Reputation: 5626

Can't you just use a toggle method like this?

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);
    }
}

This should be easier I believe!!

Upvotes: 1

Matias Elorriaga
Matias Elorriaga

Reputation: 9150

I sugggest to use the "tag" of the view, and keep in the tag the information you need (e.g. if the view is pressed or not)

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

Upvotes: 1

Related Questions