【问题标题】:How do I check to see if a resource exists in Android如何检查Android中是否存在资源
【发布时间】:2010-12-27 15:19:10
【问题描述】:

是否有内置方法来检查资源是否存在,或者我是否正在做类似以下的事情:

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

【问题讨论】:

  • 这似乎不是一个很难的方法。这种方法有什么困扰你的地方?
  • 也许不是,但我喜欢为我做错误处理的内置插件,而不是到处都坚持 try/finally。
  • 这里不需要任何错误处理。请阅读下面的评论。
  • 仅供参考,上面的代码总是将结果保留为false。这就是finally 的全部意义——这并不意味着“如果有错误”,而是意味着“总是”

标签: java android


【解决方案1】:

代码中的 try/catch 块完全没用(而且是错误的),因为 getResources()getIdentifier(...) 都不会抛出异常。

所以,getIdentifier(...) 已经将您所需的一切归还给您。事实上,如果它返回 0,那么您正在寻找的资源不存在。否则,它将返回关联的资源标识符(确实是"0 is not a valid resource 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;
}

【讨论】:

    【解决方案2】:

    根据 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..... 然后它只是在退出 finally 后“重新抛出”异常条款。而且我想这不是你想要在异常情况下做的事情。

    【讨论】:

    • 你能举个例子吗?
    • 如果我有“my_resource.png”和“my_resource.xml”怎么办?如何区分它们?
    【解决方案3】:

    我喜欢做这样的事情:

    public static boolean isResource(Context context, int resId){
            if (context != null){
                try {
                    return context.getResources().getResourceName(resId) != null;
                } catch (Resources.NotFoundException ignore) {
                }
            }
            return false;
        }
    

    所以现在它不仅仅是用于可绘制的

    【讨论】:

    • 它真的会抛出 NotFoundException 吗?
    • 是的!我找不到不存在的我的 ID
    • 好吧,试试666这样的任意数字。如果666存在,从1000循环到5000,那里应该有一些不作为资源存在的ID。
    • 这种方法的问题(无论如何)是在资源值不作为 Drawable 存在,而是作为 String 存在的情况下。如果您正在检查 Drawable,那么您只是导致了崩溃。
    【解决方案4】:

    如果有人想知道,"my_resource_name" in

    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());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-23
      • 2018-03-09
      • 1970-01-01
      • 1970-01-01
      • 2012-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多