2

The question

When you need to use resource files, such as images, in your Android project, typically you put them in the res directory (e.g. res/drawable), and the Android build process picks them up by default. But what if your resource files come from a directory outside of your Android project? How do you copy them into a folder like res/drawable during sync or build?

What I have tried

I have a feeling that the solution is to write Gradle code, but I'm not sure how to do it. I tried the following code in my app module build.gradle file:

task copyResources(type: Copy) {
    from '../../../images'
    into 'res/drawable'
}

But it did not copy anything as far as I can tell. This is probably just my ignorance of how to use Gradle, and I could use some help.

I realize I could manually copy from ../../../images to res/drawable, but let's say those files change often, and I want to get the current version automatically whenever I sync or maybe whenever I build. If this is possible, I would appreciate knowing how to do it. If it is not possible, I would like to know that as well.

Gary Sheppard
  • 4,764
  • 3
  • 25
  • 35
  • 1
    "But it did not copy anything as far as I can tell" -- did you run the task? Tasks do not execute of their own accord. Either you execute them yourself, or you write a bit of additional Gradle code to add them to the existing series of tasks for a build. – CommonsWare Oct 21 '16 at 21:48
  • 1
    See http://stackoverflow.com/questions/18532415/execute-task-before-android-gradle-build – Toris Oct 21 '16 at 22:18

2 Answers2

2

Generally you don't want to do that. The reason is that it makes what would otherwise be a clean source control system confused by the copied files.

A better idea would be to build an Android library (AAR) housed in a separate project, then consume them by adding that AAR as a dependency to the parent project.

Jeffrey Blattman
  • 22,176
  • 9
  • 79
  • 134
2

See How to run copy task with android studio into assets folder


Can do with adding

preBuild.dependsOn copyResources

after task copyResources(){...} in your build.gradle.

But, it's not a good way for copying resources.

Community
  • 1
  • 1
Toris
  • 2,348
  • 13
  • 16
  • Thanks! This was it! But why do you say "it's not a good way for copying resources?" Would you recommend making a library like the other answer says, or is there some other reason you said that? – Gary Sheppard Oct 22 '16 at 00:10
  • If lacks some image file (or renaming), editor may be confused with @drawable etc. Batch file is an alternative, I think. – Toris Oct 22 '16 at 00:26