我该如何检查,看看是否在Android中的资源存在

问题描述:

有一个内置的方法来检查,看是否有资源存在还是我留下做一些这样的:

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;
try {
    int test = mContext.getResources().getIdentifier("my_resource_name", "drawable", mContext.getPackageName());
    if (test != 0) 
        result = true;
}
finally {
    result = false;
}

另外,我甚至需要在尝试,终于阻止?

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

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

如果则getIdentifier()返回零,这意味着没有这样的资源存在。
也为0 - 是非法的资源ID

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

所以,你的结果布尔变量等效于(测试!= 0)

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

反正你的try /总算是不好的,因为它的作用是设定的结果变量设置为false,即使异常是从尝试的身体抛出: mContext.get ..... ,然后它只是重新抛出走出终于子句后例外。而我想这是不是你想要做的情况下,异常的事情。

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.