Mar*_*arc 4 android android-activity android-resources
我想知道 - 有没有办法在Activity之外访问android资源和/或资产文件(或来自任何其他文件夹的文件)(不传递上下文)?
没有上下文无法访问:
getResources().getIdentifier("resource_name", "drawable", getPackageName());
getAssets().open("file_in_assets_folder_name");
Run Code Online (Sandbox Code Playgroud)
如果不在Activity中则抛出异常:
try {
Class class = R.drawable.class;
Field field = class.getField("resource_name");
Integer i = new Integer(field.getInt(null));
} catch (Exception e) {}
Run Code Online (Sandbox Code Playgroud)
也试过下面,但它抱怨文件不存在(这里做错了什么?):
URL url = new URL("file:///android_asset/file_name.ext");
InputSource source = new InputSource(url.openStream());
//exception looks like so 04-10 00:40:43.382: W/System.err(5547): java.io.FileNotFoundException: /android_asset/InfoItems.xml (No such file or directory)
Run Code Online (Sandbox Code Playgroud)
如果文件夹包含在项目构建路径中,您可以在android.content.Context之外使用ClassLoader访问文件,例如,从POJO(如果您不想传递android.content的引用) .Context):
String file = "res/raw/test.txt";
InputStream in = this.getClass().getClassLoader().getResourceAsStream(file);
Run Code Online (Sandbox Code Playgroud)
要在项目构建路径中添加文件夹,请右键单击您的项目 - 构建路径 - 配置构建路径,将您的文件夹(例如,资产,如果使用以后的SDK版本)添加为构建路径中的Source文件夹.
检查出类似的问题,我之前在回答这里.
| 归档时间: |
|
| 查看次数: |
10811 次 |
| 最近记录: |