ITeye博客

android如何在非context環境訪問資源

ltwoini · 2010-07-22 11:38 · android · 编程语言 · Google · Android · Markdown

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

}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。