0
0
Android Kotlinmobile~5 mins

Modularization in Android Kotlin

Choose your learning style9 modes available
Introduction

Modularization helps split your app into smaller parts. This makes your app easier to build, test, and maintain.

When your app grows big and hard to manage.
When you want to work with a team and divide tasks.
When you want to reuse code in different apps.
When you want to build parts of the app faster.
When you want to test parts of the app separately.
Syntax
Android Kotlin
settings.gradle.kts:
include(":app", ":module1", ":module2")

app/build.gradle.kts:
dependencies {
    implementation(project(":module1"))
}

Each module has its own build file and code.

Modules can depend on each other by adding project dependencies.

Examples
This adds a network module to your project.
Android Kotlin
include(":app", ":network")
The app module uses the network module code.
Android Kotlin
dependencies {
    implementation(project(":network"))
}
Code inside a module is separate and can be called from other modules.
Android Kotlin
module1/src/main/java/com/example/module1/Utils.kt

fun greet() = "Hello from Module 1"
Sample App

This example shows two modules: app and greeting. The greeting module has a function that returns a message. The app module uses this function to show the message on screen.

Android Kotlin
/* settings.gradle.kts */
include(":app", ":greeting")

/* greeting/build.gradle.kts */
plugins {
    id("com.android.library")
    kotlin("android")
}

/* greeting/src/main/java/com/example/greeting/Greeting.kt */
package com.example.greeting

fun greet() = "Hello from Greeting Module"

/* app/build.gradle.kts */
plugins {
    id("com.android.application")
    kotlin("android")
}
dependencies {
    implementation(project(":greeting"))
}

/* app/src/main/java/com/example/app/MainActivity.kt */
package com.example.app

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import android.widget.TextView
import com.example.greeting.greet

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val textView = TextView(this)
        textView.text = greet()
        setContentView(textView)
    }
}
OutputSuccess
Important Notes

Keep modules focused on one feature or layer (like network, UI, or data).

Modularization can speed up build times by building only changed modules.

Use clear names for modules to know their purpose easily.

Summary

Modularization splits your app into smaller, manageable parts.

Modules have their own code and build files.

Modules can share code by adding dependencies.