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

前端 未结 4 1498
北恋
北恋 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;
    }
    
    0 讨论(0)
  • 2020-12-01 07:36

    In case someone is wondering, the "my_resource_name" in

    int checkExistence = mContext.getResources().getIdentifier("my_resource_name", "drawable", mContext.getPackageName());
    

    is actually

    String resourceName = String.valueOf(R.drawable.my_resource_name);
    int checkExistence = mContext.getResources().getIdentifier(resourceName , "drawable", mContext.getPackageName());
    
    0 讨论(0)
  • According to the javadoc you don't need the try catch: http://developer.android.com/reference/android/content/res/Resources.html#getIdentifier%28java.lang.String,%20java.lang.String,%20java.lang.String%29

    if getIdentifier() returns zero, it means that no such resource exists.
    Also 0 - is an illegal resource id.

    So your result boolean variable is equivalent to (test != 0).

    Anyway your try/finally is bad, because all it does it set the result variable to false even if exception is thrown from the body of try: mContext.get..... and then it just "rethrows" the exception after getting out of finally clause. And I suppose that is not what you want to do in case of exception.

    0 讨论(0)
  • 2020-12-01 07:56

    i like to do something like that:

    public static boolean isResource(Context context, int resId){
            if (context != null){
                try {
                    return context.getResources().getResourceName(resId) != null;
                } catch (Resources.NotFoundException ignore) {
                }
            }
            return false;
        }
    

    so now it's not only for drawable

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