Anyway to compare int to drawable?ANDROID

前端 未结 2 857
一向
一向 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:34

    try this

    public void MyClick(View view)
        {
         Drawable fDraw = view.getBackground();
         Drawable sDraw = getResources().getDrawable(R.drawable.twt_hover);
    
          if(fDraw.hashCode() == sDraw.hashCode())
          {
           //Not coming
          }
        }
    

    or use following code

    Use getTag() and setTag() for comparison

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题