如何检查Android中是否存在资源

use*_*209 53 java android

是否有内置的方法来检查资源是否存在,或者我是否继续执行以下操作:

boolean result;
int test = mContext.getResources().getIdentifier("my_resource_name", "drawable", mContext.getPackageName());
result = test != 0;
Run Code Online (Sandbox Code Playgroud)

m_v*_*aly 59

根据javadoc你不需要try catch:http: //developer.android.com/reference/android/content/res/Resources.html#getIdentifier%28java.lang.String,%20java.lang.String, %20java.lang.String 29%

如果getIdentifier()返回零,则表示不存在此类资源.
此外0 - 是非法资源ID.

所以你的结果布尔变量等价于(test != 0).

无论如何你的try/finally是坏的,因为它所做的就是将结果变量设置为false,即使从try的主体抛出异常:mContext.get.....然后它只是在退出finally子句后"重新抛出"异常.而且我想这不是你想要做的例外情况.

  • 你能提供一个例子吗? (4认同)

Pao*_*lli 29

代码中的try/catch块完全没用(而且是错误的),因为既getResources()不会getIdentifier(...)抛出异常也不会抛出异常.

所以,getIdentifier(...)你已经回归了所有你需要的东西.实际上,如果它将返回0,那么您正在寻找的资源不存在.否则,它将返回相关的资源标识符("0确实不是有效的资源ID").

这里是正确的代码:

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;
}
Run Code Online (Sandbox Code Playgroud)


Bug*_*pen 6

如果有人想知道"my_resource_name"

int checkExistence = mContext.getResources().getIdentifier("my_resource_name", "drawable", mContext.getPackageName());
Run Code Online (Sandbox Code Playgroud)

实际上是

String resourceName = String.valueOf(R.drawable.my_resource_name);
int checkExistence = mContext.getResources().getIdentifier(resourceName , "drawable", mContext.getPackageName());
Run Code Online (Sandbox Code Playgroud)


JCD*_*ary 5

我喜欢做这样的事情:

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

所以现在它不仅适用于 drawable