Question Detail

I want to create an event on toolbar's back arrow dynamically. How can I set back arrow in the Android toolbar and also apply click listener?


QnA VBage for toolbar back button android

by adding 

android:parentActivityName="com.stayapt.Home_Activity"

in manifest file and its working fine. But it will take me always on Home_Activity I want to set it Dynamically.


Thread Reply

Hemant Sharma

- 1 years ago

try this :

android.R.id.home it will handle your toolbar's back event.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            // todo: goto back activity from here
            return true;
    }
    return true;
}

Hemant Sharma

- 1 years ago

try this :

android.R.id.home it will handle your toolbar's back event.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            // todo: goto back activity from here
            return true;
    }
    return true;
}

Anonymous

- 1 years ago

You need to only add : (For adding back arrow at Toolbar)
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
       setSupportActionBar(toolbar);
       getSupportActionBar().setDisplayHomeAsUpEnabled(true);
       getSupportActionBar().setDisplayShowHomeEnabled(true);

In your OnCreate function and Your activity should Extend AppCompatActivity 

For Handle its Dynamic Click event : 
Just add this to your Menu Function

 @Override
   public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == android.R.id.home) {
            onBackPressed(); //do here something what you want on clicks on the Home/Up button
        }
        return super.onOptionsItemSelected(item);
    }