Android xml, how to get gradle parameter value

Refresh

April 2019

Views

541 time

1

I'm developing an Android app and I have to show the app's version, which is stored at the build.gradle file, at an xml layout, I want to set the value from the xml. How can I do that?

This is the content in my gradle file

android{
    defaultConfig {
        minSdkVersion 9
        targetSdkVersion 19
        versionCode 2
        versionName "v2.0"
    }
}

I want to write "v2.0" in a textview, but I can't :(

Thanks

2 answers

3

There is no way you can use the value from your build files in the layout.

On the other hand, you can do it from the Java code, and you don't even need to use package manager for this. During the build stage Gradle generates for you the class called BuildConfig which has the String field VERSION_NAME, containing the value you provided in the build file.

So, mTextView.setText(BuildConfig.VERSION_NAME); is all you need.

aga
1

you can get this with the help of package manager:-

 PackageInfo pInfo = null;
    try {
        pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
        String versionName = pInfo.versionName;

    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }

and then set the string versionName in your textview or view,wherever you want to use it.

as you mentioned you want to get if from your textview,do it as:

yourtextview.getText();