How to Add Back Arrow in Android Activity

Here is a simple method to add a back arrow to other Activity to come back to MainActivity. To enter a new activity we create an Intent then start a new Activity using that intent instance using the startActivity method.

After we enter the new activity we add a listener on action bar instance to finish other activity to come back to MainActivity.

Let’s Start Coding…

Step 1) Here I will give an example of simple Empty Activity new project. I which we will create a new Activity.

 

Step 2) In res >> layout >> activity_main.xml we will add a button which will open a new other activity.

activity_main.xml

Here
we added a button “OPEN OTHER ACTIVITY” with onClick even “openActivity

MainActivity.class

In “openActivity” event we will open OtherActivity using Intent

 

Step 3) Now right click on the main package and create a new activity named “OtherActivity

 

Step 4) Now we add back button and handle event listener in OtherActivity

other_activity.xml

OtherActivity.class

When the user selects an item from the options menu (including action items in the app bar), the system calls your activity’s onOptionsItemSelected() method. 

Here we are finishing current Activity which is Other Activity to go back to main Activity.

Find source in Google Drive here

Leave a Reply

avatar
  Subscribe  
Notify of