Anyway to compare int to drawable?ANDROID

前端 未结 2 858
一向
一向 2021-01-15 17:44

Is there anyway to compare s to a? In this code I have int s as the answer and if the drawable == s then I want to display a \"Correct!\" toast mes

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-15 18:40

    Comparing a Drawable instance to an int doesn't make sense. What are you trying to do? Do you want to check if the method res.getDrawable(R.drawable.exitbtn); returns the right object?

    I think it's redundant to fetch an identifier from R-file:

    int s = R.drawable.exitbtn;
    

    Then fetch the object using the very same identifier:

    Drawable drawable = res.getDrawable(R.drawable.exitbtn);
    

    And then try to check whether it's really the right object by comparing ids.

    I think that there's no place for mistake (specifically, confusion of an int value) when it comes to getting a Drawable by id. If you want to be sure the object has been created, check it against a null.

    Drawable drawable = res.getDrawable(R.drawable.exitbtn);
    if(drawable != null){
       //do stuff
    } else {
       //handle the situation where there's no drawable
    }
    

    Also, I think there's no way to fetch an id from a Drawable object. The instance returned by getDrawable does not contain such information.

    Better yet, you can use the fact that getDrawable can throw a NotFoundException if the id is somehow wrong. Check the docs for details.

提交回复
热议问题