---
title: "android如何在非context環境訪問資源"
author: "ltwoini"
date: "2010-07-22T11:38:04Z"
tags: ["Android", "Google"]
categories: ["编程语言"]
slug: "android-context"
draft: false
lastmod: "2010-07-22T11:38:04Z"
id: 718713
url: "https://ltwoini.iteye.com/blog/718713"
---

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

}