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
you can’t base on
constantState
, its not desired to compare drawables as there is a different instance for every drawable, thus yourif
isn’ttrue
never ever. in fact there is no way for getting resource of drawable already set forImageView
. most convenient way would be to keep some boolean flag outsideonClick
method informing that image is switched or not. optionally you may keep this flag "inside"ImageView
usingsetTag(...)
methodyou 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.