8

how can I create a code for my android app where When I pressed the back button on the toolbar (Action Bar) some code will happening.

I tried but it does not work.

Added in main activity. onbackpress method

@Override
public void onBackPressed() {
    super.onBackPressed();
    stopActivityTask();
}
Gracy Patel
  • 101
  • 1
  • 1
  • 10
  • 1
    check my answer: http://stackoverflow.com/questions/39827732/when-toolbar-back-button-is-pressed/39827808#39827808 – Damini Mehra Oct 03 '16 at 09:16
  • The onBackPressed() method will be called when a user presses the _Back_ button; what you mean is called the _Home_ button if I am right. – M.S. Oct 03 '16 at 09:30

3 Answers3

12

You can Try this way..

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
    case android.R.id.home:
        // this takes the user 'back', as if they pressed the left-facing    

      triangle icon on the main android toolbar.
        // if this doesn't work as desired, another possibility is to call   

        stopActivityTask();  // finish() here.
        getActivity().onBackPressed();
        return true;
    default:
        return super.onOptionsItemSelected(item);
}
}

If Not Work

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        // Title and subtitle
        toolbar.setTitle(R.string.about_toolbar_title);
        toolbar.setNavigationIcon(R.drawable.ic_action_back);
        toolbar.setNavigationOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                stopActivityTask(); 
                finish();
            }
        });
Jigar Patel
  • 1,550
  • 2
  • 13
  • 29
2
 @Override
  public boolean onOptionsItemSelected(MenuItem item) {

    int id  = item.getItemId();

    // click on icon to go back
    //triangle icon on the main android toolbar.

    if (id == android.R.id.home) {
       //your code
        return true;
    }
    return super.onOptionsItemSelected(item);
}
Damini Mehra
  • 3,257
  • 3
  • 13
  • 24
D.J
  • 1,439
  • 1
  • 12
  • 23
2
    private Toolbar toolbar;

Then add this in your onCreate method

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

Then you add these lines :

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
        /*
            ADD WHAT YOU WANT TO DO WHEN ARROW IS PRESSED
        */
        return super.onOptionsItemSelected(item);
}
Hugo Houyez
  • 470
  • 3
  • 19