Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
346 views
in Technique[技术] by (71.8m points)

android - Reference build.gradle versionName attribute in xml layout

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...