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();
}
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.
just use finish(); – V.J. @user1216003 you are on right way. you will do same as back button with setting the flag in intent.
getActionBar(). setDisplayShowHomeEnabled(false); //disable back button getActionBar(). setHomeButtonEnabled(false); In a older android phone, the back button is removed with these two code lines.
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();
}
});
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With