我该如何检查,看看是否在Android中的资源存在 [英] How do I check to see if a resource exists in Android

查看:214
本文介绍了我该如何检查,看看是否在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的,你不需要尝试捕捉: <一href="http://developer.android.com/reference/android/content/res/Resources.html#getIdentifier%28java.lang.String,%20java.lang.String,%20java.lang.String%29" rel="nofollow">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.

这篇关于我该如何检查,看看是否在Android中的资源存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆