Posted on

Android Gradle Plugin pt3


android gradle plugin

 

Today we finish creating a Gradle plugin that add default wrap_content width/height attributes to all views. Check previous post if you haven’t followed.

What is left is iterate through all views and layout files. We can do that using standard Java libraries. Once again, writing Gradle scripts is just like common Java, but with Groovy syntax and in .gradle files

Iterating Through Views

There’s a NodeList iterate and Node as View representation. By checking if a view have nested views we iterate over them and do the same for each view as well. I did it with recursion, here’s extracted method

There’s a node with name #text appearing all the time, don’t know what it’s for, but we ignore that one. Now we just call this method with a root NodeList for each file and we’re good.

Check All Files

Before we did check only for activity_main.xml. Getting a list of all files in a directory is simple with File#listFiles() method. Only thing that I noticed that in data-binding-layout-out/layout directory there’s bunch of other layouts not from src/res/layout. So best to get file names from src directory and read from output one to check only our files.

And there’s initial call for checkAttributes method with root NodeList.

Lint

As I mentioned in the first post those red underlying in layout files are just lint check with error severity. It does compile. And this inspection called AndroidResourcesValidation

android gradle plugin

Because we still going to get red errors for missing width/height attributes. You can fix that by disabling this inspection, but it does more than just width/height check, but all the different useful xml  which you don’t wanna give out. Unless I figure out how to modify this inspection, I wouldn’t want to disable it.

 

Alright, you can get source code here. Still don’t know if it’s useful or not, but that’s a good introduction to building gradle scripts and plugins. There’s more you can build with it, like default values to dp/sp depending on attribute so that you can just use a number. Still don’t understand why it’s required to include those in layouts. The biggest step here is to make adjustments to IDE so that your plugin shows useful lint hints etc

Alright, that was a final part for Gradle, hope you’ve enjoyed it. Don’t forget to subscribe, follow me on Twitter, Facebook, G+ and share with friends if you think they will benefit from it!