In Android development, we come across a situation where we have to refresh the activity without reopening it so that changes reflect like switch to night mode or day mode, change of locals means app language, applying theme etc. In those situation, Android provide a way to recreate the android activity without user can notice it.
You can use this learning in other situation also. I haven’t used it in other situation till now but If I will do then update this post.
You may like
Important Android interview questions with Answers
How can we achieve this. Let do some coding.
1. Add below line of code in AndroidManifest file required activity.
android:configChanges="uiMode"
It tells the Android system that It will handle by manually. Do not need to apply default system effect.
2. Start the activity as you know. Override default activity transition and animation. If you are lazy copy below code.(Code in Kotlin)
val intent = intent
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION)
finish()
overridePendingTransition(0, 0)
startActivity(intent)
From above code, you can learn two thinks.
- how to remove default animation from activity
- how to remove transition which we saw when you create new activity in Android.
You can test this by simply removing the code which we use in 1.
If you do 2 point without 1 then the effect of activity recreation will clearly visible to user. It is not good for user experience.
So important point in this topic is point 1. You can read more on the provided link.
Bonus: You can see more detail about API code by hovering the mouse over it in Android studio.
If it is helpful then share it with other Android developer on Twitter, Facebook, WhatsApp.
Happy coding.