Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/xamarin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何检查Android中是否存在资源_Java_Android - Fatal编程技术网

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

Java 如何检查Android中是否存在资源,java,android,Java,Android,是否有一种内置的方法来检查资源是否存在,或者让我执行以下操作: boolean result; int test = mContext.getResources().getIdentifier("my_resource_name", "drawable", mContext.getPackageName()); result = test != 0; 根据javadoc,您不需要try-catch: 如果getIdentifier()返回零,则表示不存在此类资源。 0-也是非法的资源id 因

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

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

根据javadoc,您不需要try-catch:

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

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


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

代码中的try/catch块完全没有用处(而且是错误的),因为nor和nor都不会引发异常

所以,我已经把你需要的全部还给你了。事实上,如果它将返回0,则您正在查找的资源不存在。否则,它将返回关联的资源标识符(,实际上)

下面是正确的代码:

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;
}

如果有人想知道,请在

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;
    }

因此,现在不仅是可绘制的

要做到这一点似乎并不难。这种方法有什么困扰您的地方?也许没有,但我喜欢为我做错误处理的内置程序,而不是到处使用try/finally。在这里您不需要任何错误处理。请阅读我下面的评论。仅供任何人参考,上面的代码总是将结果保留为
false
。这就是
最后的全部要点
——它不是指“如果有错误”,而是指“总是”你能提供一个例子吗?如果我有“my_resource.png”和“my_resource.xml”怎么办?我如何区分它们呢?它真的抛出了NotFoundException吗?是的!我找不到不存在的Id。请尝试使用任意数字,如666。如果666存在,则从1000循环到5000,其中应该有一些不作为资源存在的ID。