[英]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.