Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference build.gradle versionName attribute in xml layout

Tags:

I'd like to have a layout file which references the versionName attribute in my gradle file:

... defaultConfig {     applicationId "se.test.myapp"     minSdkVersion 14     targetSdkVersion 22     versionCode 1     versionName "1.0" } .... 

Something like

<TextView     android:layout_width="wrap_content"     android:layout_height="wrap_content"     android:text="@string/versionName"     /> 

Is there a neat way to to this, without having to set up the layout in my code?

like image 771
Marcus Avatar asked Apr 08 '15 20:04

Marcus


1 Answers

According to http://tools.android.com/tech-docs/new-build-system you can create resources directly from gradle, so putting

android { ...     defaultConfig {         applicationId "se.test.myapp"         minSdkVersion 14         targetSdkVersion 22         versionCode 1         versionName "1.0"     }     ...     applicationVariants.all { variant ->             variant.resValue "string", "versionName", variant.versionName     }     ... } 

in your build.gradle will do the trick

It creates resource file generated.xml during compilation in generated/res folder which is included alongside with resources provided by you in values folder. So you can use android:text="@string/versionName" to reference this value. Unfortunately, sometimes IDE can't resolve this reference, so it'll look like an error in your layout resource (while it's a valid statement and will be resolved at runtime).

You can suppress the error by clicking inside the "@string/versionName", then Alt+Enter, in the menu select "Create string value resource 'versionName", then "Suppress for tag".

like image 183
OleGG Avatar answered Oct 05 '22 23:10

OleGG