How to programmatically navigate to previous activity on toolbar back arrow click

In this android programming source code example, we are going to explore how to programmatically navigate to previous activity on toolbar back arrow click.

Below is a step by step source code to programmatically navigate to previous activity on toolbar back arrow click.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".toolbar.Toolbar8">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar_top"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:minHeight="?attr/actionBarSize"
        android:background="@color/colorAccent"
        app:popupTheme="@style/AppTheme.PopupOverlay"  >

    </android.support.v7.widget.Toolbar>

</android.support.design.widget.CoordinatorLayout>

MainActivity.java

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Toast;


public class Toolbar8 extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_toolbar8);

        Toolbar toolbar = findViewById(R.id.toolbar_top);
        toolbar.setTitle("On Back Arrow Click");
        setSupportActionBar(toolbar);
        getSupportActionBar();
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               // startActivity(new Intent(Toolbar8.this, yourActivity.class));
                Toast.makeText(getApplicationContext(), "This will start your Activity", Toast.LENGTH_LONG).show();
            }
        });
    }
}

If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

 

Add a Comment