How do I check to see if a resource exists in Android

前端 未结 4 1676
北恋
北恋 2020-12-01 07:23

Is there a built in way to check to see if a resource exists or am I left doing something like the following:

boolean result;
int test = mContext.getResource         


        
4条回答
  •  北海茫月
    2020-12-01 07:36

    The try/catch block in your code is totally useless (and wrong), since neither getResources() nor getIdentifier(...) throw an Exception.

    So, getIdentifier(...) will already return you all you need. Indeed, if it will return 0, then the resource you are looking for does not exist. Otherwise, it will return the associated resource identifier ("0 is not a valid resource ID", indeed).

    Here the correct code:

    int checkExistence = mContext.getResources().getIdentifier("my_resource_name", "drawable", mContext.getPackageName());
    
    if ( checkExistence != 0 ) {  // the resource exists...
        result = true;
    }
    else {  // checkExistence == 0  // the resource does NOT exist!!
        result = false;
    }
    

提交回复
热议问题