How to check if two drawables are the same?

5

Good evening!    I'm having difficulty retrieving the current image from my android imageView. It is an image to favor for the user (give like), and I want when the user clicks on that image, I check if the current image is = a heart icon with no fill, if yes then perform the tanking function, if otherwise, perform the descurtit function. In the current code the validation always exits as FALSE, even when it should be TRUE and the drawable variable 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!

    
asked by anonymous 21.05.2018 / 04:10

1 answer

3

You are comparing a Drawable with an integer ( R.drawable.ic_favorite_border is an integer).

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

Start by getting the Drawable corresponding to the 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())){

}
    
21.05.2018 / 11:57