How to Change ActionBar Title Programmatically in Android?
Whenever we develop an Android application and run it, we often observe that the application comes with an ActionBar with the name of the application in it. This happens by default unless explicitly changed. This text is called the title in the application. One can change the title of the application by making changes to the app_name string present in the values.
But, if an application has more than one activity, all of these activities will have the same title. Suppose we have MainActivity, SecondActivity, and ThirdActivity. While navigating, one can observe that all of them will have the same title, i.e. name of the application. So through this article, we will show how you can dynamically change the title of the application at runtime. You can apply the same concept if there is more than one activity to distinguish among them.
Step by Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.
Step 2: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. Add EditText and a Button in the layout file. We shall type the desired title in the EditText and click the button which would perform the title change operation.
Step 4: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
You can see that we are able to change the title at runtime.