[英]How do I check to see if a resource exists in Android
是否有内置的方法来检查资源是否存在,或者我是否继续执行以下操作:
boolean result;
int test = mContext.getResources().getIdentifier("my_resource_name", "drawable", mContext.getPackageName());
result = test != 0;
根据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.....
然后它只是在出去后“重新抛出”异常最后一句。 而且我想这不是你想要做的例外情况。
代码中的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;
}
万一有人想知道, "my_resource_name"
在
int checkExistence = mContext.getResources().getIdentifier("my_resource_name", "drawable", mContext.getPackageName());
实际上是
String resourceName = String.valueOf(R.drawable.my_resource_name);
int checkExistence = mContext.getResources().getIdentifier(resourceName , "drawable", mContext.getPackageName());
我喜欢做那样的事情:
public static boolean isResource(Context context, int resId){
if (context != null){
try {
return context.getResources().getResourceName(resId) != null;
} catch (Resources.NotFoundException ignore) {
}
}
return false;
}
所以现在它不仅仅是为了绘画
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.