1/step : Create A New Project and add this code in activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="@+id/tvWelcome"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/welcome_message"
android:textSize="20sp" />
<Button
android:id="@+id/btnChangeLanguage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="@string/change_language" />
</LinearLayout>
2/Step : Add the res/values/strings.xml
<resources>
<string name="app_name">Language Change</string>
<string name="welcome_message">স্বাগতম</string>
<string name="change_language">ভাষা পরিবর্তন করুন</string>
</resources>
3/Step : Add the code in MainActivity
package com.alomkaisa.myapplication
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.widget.Button
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import java.util.Locale
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val savedLanguage = getSavedLanguage(this)
setLocale(this, savedLanguage)
setContentView(R.layout.activity_main)
val btnChangeLanguage = findViewById<Button>(R.id.btnChangeLanguage)
btnChangeLanguage.setOnClickListener {
val newLanguage = if (getSavedLanguage(this) == "en") "bn" else "en"
setLocale(this, newLanguage)
saveLanguagePreference(this, newLanguage)
// Restart activity to apply the language change
val intent = Intent(this, MainActivity::class.java)
finish()
startActivity(intent)
}
}
private fun setLocale(context: Context, language: String) {
val locale = Locale(language)
Locale.setDefault(locale)
val resources = context.resources
val config = resources.configuration
config.setLocale(locale)
resources.updateConfiguration(config, resources.displayMetrics)
}
private fun saveLanguagePreference(context: Context, language: String) {
val preferences: SharedPreferences =
context.getSharedPreferences("AppPreferences", Context.MODE_PRIVATE)
preferences.edit().putString("SelectedLanguage", language).apply()
}
private fun getSavedLanguage(context: Context): String {
val preferences: SharedPreferences =
context.getSharedPreferences("AppPreferences", Context.MODE_PRIVATE)
return preferences.getString("SelectedLanguage", "en") ?: "en"
}
}