Android注解处理器访问资源(资产) [英] Android Annotation processor access resources (assets)

查看:95
本文介绍了Android注解处理器访问资源(资产)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to access a resource from my andoid studio project in my annotation processor.

我首先尝试使用文件管理器中的getResource方法:

I first tried to use the getResource method from filer:

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

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

, but it always throwed a exception that just returned "src/main/res/layout/activity_main.xml" as a message.

下一个以为我尝试过的是

Next think i have tried was

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

,但这始终返回null.

, but this always returned null.

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

The last think i have tried to use was this:

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());
            }

,但会引发空指针异常

推荐答案

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

I used the following to get the layout folder from my annotation processor:

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");
    }

这篇关于Android注解处理器访问资源(资产)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆