skip to Main Content

everyone. After clicking on an ImageView, I would like to change it depending on what kind of drawable is currently displayed. To do this, I compare the currently set image in the ImageView with one from the drawable folder. Unfortunately, it is currently the case that only the else branch is executed. The image changes after the first click, but then it no longer switches. What am I doing wrong?

 bookmark_site.setOnClickListener{
        vibrator.vibrate(50);

        var draw = bookmark_site.drawable.constantState


        if(draw == ContextCompat.getDrawable(this,R.drawable.ic_baseline_bookmark_filled_24)?.constantState)
        {
            bookmark_site.setImageDrawable(resources.getDrawable(R.drawable.ic_outline_bookmark_border_outline_24))
        }
        else{

         //Only this two is ever executed
            bookmark_site.setImageDrawable(resources.getDrawable(R.drawable.ic_baseline_bookmark_filled_24))
        }
    }

2

Answers


  1. you can’t base on constantState, its not desired to compare drawables as there is a different instance for every drawable, thus your if isn’t true never ever. in fact there is no way for getting resource of drawable already set for ImageView. most convenient way would be to keep some boolean flag outside onClick method informing that image is switched or not. optionally you may keep this flag "inside" ImageView using setTag(...) method

    bookmark_site.setOnClickListener{
        vibrator.vibrate(50);
    
        val switched = bookmark_site.tag != null
        
        bookmark_site.setImageResource(
            if (switched) R.drawable.ic_outline_bookmark_border_outline_24
            else R.drawable.ic_baseline_bookmark_filled_24
        )
        
        bookmark_site.tag = if (switched) null else "SWITCHED"
    }
    
    Login or Signup to reply.
  2. you should keep category or tag along with the image in the model class and then change the image on the basis of that tag or category.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search