Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pressed the back button on the toolbar [duplicate]

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();
}
like image 343
Gracy Patel Avatar asked Oct 03 '16 09:10

Gracy Patel


People also ask

What is the Back button bar called?

The action bar is a primary toolbar inside an activity that can be used to display an activity title and other interactive items. One of the most used items is a Back Navigation Button. The back button is used to move backward from the previously visited screen by the user.

How do you press back button?

just use finish(); – V.J. @user1216003 you are on right way. you will do same as back button with setting the flag in intent.

How do I get rid of the back arrow on my Android toolbar?

getActionBar(). setDisplayShowHomeEnabled(false); //disable back button getActionBar(). setHomeButtonEnabled(false); In a older android phone, the back button is removed with these two code lines.


2 Answers

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();
            }
        });
like image 131
Jigar Patel Avatar answered Sep 27 '22 19:09

Jigar Patel


    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);
}
like image 44
Hugo Houyez Avatar answered Sep 27 '22 18:09

Hugo Houyez