在做store demo的時候碰到一種情況是,自己的類(非context的子類)需要訪問android的相關資源,一開始不知如何下手.
google了一下 找到了方式:
/**
* @author eric
* 自定義application,以便static class 容易的訪問app相關的Resources
*/
public class SingleApplication extends Application {
public static Application nfcstore;
@Override
public void onCreate() {
super.onCreate();
nfcstore = this;
}
}
透過它可以搞定
另外一個情形,透過資源名找資源id(編譯后的標識)方法是:
public static int findImageId(String imageName) {
Log.d("findImageId,packageName:",SingleApplication.nfcstore.getPackageName());
return SingleApplication.nfcstore.getResources().getIdentifier(imageName, "drawable",SingleApplication.nfcstore.getPackageName());
}