【问题标题】:Android Annotation processor access resources (assets)Android Annotation 处理器访问资源(资产)
【发布时间】:2016-05-14 10:58:42
【问题描述】:

我想在我的注释处理器中访问我的 Android Studio 项目中的资源。

我首先尝试使用 filer 中的 getResource 方法:

FileObject fo = processingEnv.getFiler().getResource(StandardLocation.SOURCE_PATH, "", "src/main/res/layout/activity_main.xml");

,但它总是抛出一个异常,只是将“src/main/res/layout/activity_main.xml”作为消息返回。

接下来认为我尝试过的是

this.getClass().getResource("src/main/res/layout/activity_main.xml")

,但这总是返回 null。

我尝试使用的最后一个想法是:

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
            StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null);
            Iterable<? extends File> locations = fm.getLocation(StandardLocation.SOURCE_PATH);
            for (File file : locations) {
                System.out.print(file.getAbsolutePath());
            }

,但是会抛出空指针异常

【问题讨论】:

  • 在适用于传统 Java(Android 除外)的工具中对术语“资源”的任何引用均指 Java/JAR 资源,而不是 Android 资源。
  • 我找到了解决办法

标签: java android android-resources annotation-processing


【解决方案1】:

我使用以下命令从注释处理器中获取布局文件夹:

private File findLayouts() throws Exception {
        Filer filer = processingEnv.getFiler();

        JavaFileObject dummySourceFile = filer.createSourceFile("dummy" + System.currentTimeMillis());
        String dummySourceFilePath = dummySourceFile.toUri().toString();

        if (dummySourceFilePath.startsWith("file:")) {
            if (!dummySourceFilePath.startsWith("file://")) {
                dummySourceFilePath = "file://" + dummySourceFilePath.substring("file:".length());
            }
        } else {
            dummySourceFilePath = "file://" + dummySourceFilePath;
        }

        URI cleanURI = new URI(dummySourceFilePath);

        File dummyFile = new File(cleanURI);

        File projectRoot = dummyFile.getParentFile().getParentFile().getParentFile().getParentFile().getParentFile().getParentFile();

        return new File(projectRoot.getAbsolutePath() + "/src/main/res/layout");
    }

【讨论】:

  • 我知道在 cmets 中感谢你是违反规则的,但我忍不住!谢谢!
【解决方案2】:

处理器实例在项目的根级别运行,因此您可以通过以下简单方式进行操作:

String fileSeparator = System.getProperty("file.separator");
    String absoluteFilePth = "app" + fileSeparator + "src" + fileSeparator + "main" + fileSeparator + "res" + fileSeparator + "layout";
    File file = new File(absoluteFilePth);

问候,

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-14
    • 2014-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-09
    • 2019-12-05
    • 1970-01-01
    相关资源
    最近更新 更多