Android Activity Quick How Tos

Here is a collection of how-to articles related to Android UI.

Skipping an Activity/Screen on Back Button Press

For example, say you have 3 activities, which are navigated as below.
Activity 1 -> Activity 2 -> Activity 3

Now from Activity 3, user can press back button to go to Activity 2 from where he can again press back button to go to Activity 1. Normally this is what you would expect.

But what if the Activity 2 is a intermediate splash screen which is shown temporarily and you want the user to go to Activity 1 from Activity 3 on back button press? It's pretty simple - you end Activity 2 when you go to Activity 3. Now, when user presses back button, it will go to Activity 1.

For ending the Activity 2, you need to call the finish(); method after starting Activity 3.

Example:
intent = Intent(this,Activity_3::class.java)
intent.putExtra("Param Value", param1)
startActivity(intent)
finish();

Using an Existing Activity instead of Creating a New Activity

Consider a simple application where two activities - Activity 1 & Activity 2. From Activity 2, you have a button in the UI, which when clicked, you want to go to Activity 1. You may use a function like below:
fun goToHome(view: View){
intent = Intent(this,MainActivity::class.java)
startActivity(intent)
finish();}

If you use the typical way code like above, it will actually cause a new instance of the Activity 1 instead of going to the existing activity. So, how do you make it go to the existing activity? Its pretty simple - you need to set a flag called "Intent.FLAG_ACTIVITY_REORDER_TO_FRONT" like below.
fun goToHome(view: View){
intent = Intent(this,MainActivity::class.java)
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); startActivity(intent)
finish();}

No comments:

Feel free to leave a piece of your mind.

Powered by Blogger.