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

2022-08-31 14:57:55

有没有一种内置的方法来检查资源是否存在,或者我是否要做类似下面的事情:

boolean result;
int test = mContext.getResources().getIdentifier("my_resource_name", "drawable", mContext.getPackageName());
result = test != 0;

答案 1

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

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

因此,您的结果布尔变量等效于 。(test != 0)

无论如何,你的try/final是坏的,因为它所做的一切将结果变量设置为false,即使从try的主体中抛出异常:然后它只是在退出final子句后“重新抛出”异常。我想这不是你在发生异常时想要做的。mContext.get.....


答案 2

代码中的 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;
}

推荐