Set navigation bar in android

The up navigation will allow our application to move to previous activity from the next activity. It can be done like this.

To implement Up navigation, the first step is to declare which activity is the appropriate parent for each activity. You can do it by specifying parentActivityName attribute in an activity. 

android:parentActivityName = "com.example.test.MainActivity" 

After that you need to call setDisplayHomeAsUpEnabled method of getActionBar() in the onCreate method of the activity. This will enable the back button in the top action bar.


The last thing you need to do is to override onOptionsItemSelected method. when the user presses it, your activity receives a call to onOptionsItemSelected(). The ID for the action is syntax is given below −

public boolean onOptionsItemSelected(MenuItem item) {
   switch (item.getItemId()) {
      return true;

Handling device back button

Since you have enabled your back button to navigate within your application, you might want to put the application close function in the device back button.

It can be done by overriding onBackPressed and then calling moveTaskToBack and finish method. Its syntax is given below −

public void onBackPressed() {