Как сделать переменную в build.gradle файле и передать ее в манифест файл AndroidManifest.xml | Android Studio | Kotlin
последнее обновление: 7 января 2024
В build.gradle файле я написал функцию funcCreateVariable которая создает переменную:
Файл build.gradle
...
android {
defaultConfig {
// my function for simple create variable
def funcCreateVariable = {constantName, constantValue ->
manifestPlaceholders += [ (constantName):constantValue]
buildConfigField "String" , "${constantName}" , "\" ${constantValue}\""
}
// my variables
funcCreateVariable ("MY_APPLICATION_LABEL" , "Hello" )
funcCreateVariable ("MY_APPLICATION_ICON" , "@mipmap/ic_launcher" )
}
}
MY_APPLICATION_LABEL это моя первая переменная в build.gradle файле
MY_APPLICATION_ICON это моя вторая переменная в build.gradle файле
В AndroidManifest.xml файле чтобы использовать переменную нужно писать так: ${название переменной}
<?xml version="1.0" encoding="utf-8" ?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
<application
...
android:icon="${MY_APPLICATION_ICON} "
android:label="${MY_APPLICATION_LABEL} "
...
</application>
</manifest>
Шаг 1. Создаем новый проект
Шаг 2. Поменяем код в файле build.gradle
Цвет означает, что добавлен новый код.
Файл build.gradle
plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
}
android {
namespace 'com.example.androidkotlinapp1'
compileSdk 33
defaultConfig {
applicationId "com.example.androidkotlinapp1"
minSdk 27
targetSdk 33
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
// my function for simple create variable
def funcCreateVariable = {constantName, constantValue ->
manifestPlaceholders += [ (constantName):constantValue]
buildConfigField "String" , "${constantName}" , "\" ${constantValue}\""
}
// my variables
funcCreateVariable ("MY_APPLICATION_LABEL" , "Hello" )
funcCreateVariable ("MY_APPLICATION_ICON" , "@mipmap/ic_launcher" )
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt' ), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
}
dependencies {
implementation 'androidx.core:core-ktx:1.7.0'
implementation 'androidx.appcompat:appcompat:1.6.1'
implementation 'com.google.android.material:material:1.9.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
}
Шаг 3. Поменяем код в файле AndroidManifest.xml
Цвет означает, что добавлен новый код.
Файл AndroidManifest.xml
<?xml version="1.0" encoding="utf-8" ?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" >
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="${MY_APPLICATION_ICON}"
android:label="${MY_APPLICATION_LABEL}"
android:supportsRtl="true"
android:theme="@style/Theme.AndroidKotlinApp1"
tools:targetApi="31" >
<activity
android:name=".MainActivity"
android:exported="true" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
На заметку 1 Как передать системную переменную build.gradle файла в файл AndroidManifest.xml
Есть системная переменная applicationId в файле build.gradle
Файл build.gradle
android {
namespace 'com.example.androidkotlinapp1'
compileSdk 33
defaultConfig {
applicationId "com.example.androidkotlinapp1"
minSdk 27
targetSdk 33
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
...
}
dependencies {
...
}
Я хочу использовать applicationId в файле AndroidManifest.xml
Ответ:
В AndroidManifest.xml файле чтобы использовать переменную нужно писать так: ${название переменной}
Пример:
Файл AndroidManifest.xml
<?xml version="1.0" encoding="utf-8" ?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" >
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
<uses-permission android:name="android.permission.READ_MEDIA_VIDEO" />
<uses-permission android:name="android.permission.READ_MEDIA_AUDIO" />
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/Theme.AndroidKotlinApp1"
tools:targetApi="31" >
<activity
android:name=".MainActivity"
android:exported="true" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider "
android:exported="false"
android:grantUriPermissions="true" >
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
</application>
</manifest>
На заметку 2 Можно ли использовать мои переменные в MainActivity.kt файле?
Чтобы использовать MY_APPLICATION_LABEL и MY_APPLICATION_ICON переменные в MainActivity.kt файле нужно просто написать:
val text1 = BuildConfig.MY_APPLICATION_LABEL
Посмотрим на весь файл MainActivity.kt :
Цвет означает, что добавлен новый код.
Файл MainActivity.kt
package com.example.androidkotlinapp1
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
override fun onCreate (savedInstanceState: Bundle?) {
super .onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val text1 = BuildConfig.MY_APPLICATION_LABEL
// text1 = "Hello"
}
}
Объяснение:
Класс BuildConfig создается сам при компиляции проекта и находится в папке build :