How to generate android resource (xml) files by using Kotlin KSP

652 Views Asked by At

I'm working on a custom generator to generate code from annotation on Android platform. I currently using KSP for code generating. After I generate the code, I need to generate some resource xml files, What shall I do for it?

I considered some points:

  1. There are official way to generate resource file in build.gradle, but because the content of the resource is derived from the annotation so I can't move the generator code to build.gradle.
  2. Another way is move the generator code to build.gradle totally, but I can't parse the annotation in source file without ksp or apt/kapt.
  3. Where should I store the generated resource file? It seems I can't get output dir from KSP api.
1

There are 1 best solutions below

0
On

What do you mean by moving to build.gradle? Do you mean generate resources from gradle task?

You can generate resources from your SymbolProcessor in similar fashion as you would generate a source code. KSP runs before the sources are compiled and resources are merged. You can generate аn XML at generated resources directory e.g app/src/myplugin/res then include the generated resources, so your app can recognize them:

sourceSets {
        main {
            res.srcDirs = ['src/main/res/', 'src/myplugin/res',]
        }
    }

You can specify the target resource directory as KSP argument as:

ksp {
    arg("generatedResourceDir", "$projectDir/src/myplugin/res")
}

Arguments provided will available in SymbolProcessorEnvironment.options