How do you check if two Drawables are the same?

Asked

Viewed 176 times

5

Good night ! I’m having trouble recovering the current image from my android imageView. It is a favorite image for the user(dar like), and I want that when the user click on this image, I check if the current image is = to an unfilled heart icon, if yes then run the like function, otherwise run the descurtit function. In the current code the validation always comes out as FALSE, even when it should be TRUE and the variable drawable is receiving = ""

public void favoritar(){

    Versiculos favoritar = new Versiculos();
    SharedPreferencias preferencias = new SharedPreferencias(getApplicationContext());

    Drawable drawable = imLike.getDrawable();

    if (drawable.equals(R.drawable.ic_favorite_border)){
        //Curtindo
        favoritar.curtirVersiculo(idVersiculo, preferencias.getCHAVE_ID());
        imLike.setImageResource(R.drawable.ic_favorite);

    } else {
        //Descurtindo
        favoritar.descurtirVersiculo(idVersiculo, preferencias.getCHAVE_ID());
        imLike.setImageResource(R.drawable.ic_favorite_border);

    }
}

Thank you!

1 answer

3


You’re comparing a Drawable to a whole(R.drawable.ic_favorite_border is a whole).

On the other hand, to compare Drawables, you must use the object returned by the method getConstantState().

Start by getting Drawable corresponding to id R.drawable.ic_favorite_border

Drawable favoriteBorder = getResources().getDrawable(R.drawable.ic_favorite_border);

then make the comparison like this:

if (drawable.getConstantState().equals(favoriteBorder.getConstantState())){

}
  • It worked exactly as I needed, yet, as I’m treating the click action by calling a method and not an action that received the Image view, I needed to keep the drawable variable = imLike.getDrawable() (as you predicted in the resolution above), thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.