AppCompatActivity onBackPressed() method fails to trigger in my activity.
I see the back arrow button and get the animation when pressing it, but nothing else happens. a
back_button on the actionbar
this will wok
Toolbar toolbar=(Toolbar) findViewById(R.id.appBar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_HOME_AS_UP);
getSupportActionBar().setDisplayShowHomeEnabled(true);
@Override
public void onBackPressed() {
super.onBackPressed();
this.finish();
}
or set which activity load when click back
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.ParentActivity" />
onBackPressed() is not present in AppCompactActivity, You have to implement an InterFace KeyEvent.Callback and override onKeyUp method and check if the key is BackButton or you can extend ActionBarActivity which is child class of AppCompactActivity
I believe onBackPressed()
is only called when the physical back button is pressed. If you're attempting to catch the toolbar back button press (the navigation icon), try using the following snippet:
@Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home: {
// Your code here
}
}
return (super.onOptionsItemSelected(menuItem));
}
This code works for me. Obviously there isn't all the code, but i think it can usefull for you to understand how to implements the backPressed event.
public class RedActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
...
final ActionBar ab = getSupportActionBar();
ab.setHomeAsUpIndicator(R.drawable.ic_menu);
ab.setDisplayHomeAsUpEnabled(true);
...
}
...
@Override
public void onBackPressed() {
if (isDrawerOpen()) {
drawerLayout.closeDrawer(GravityCompat.START);
} else if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
} else {
//Ask the user if they want to quit
new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(R.string.quit)
.setMessage(R.string.really_quit)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton(R.string.no, null)
.show();
}
}
}
In your manifest file define the following inside your activity tag:
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.ParentActivity" />
After that in your activity:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
This is what you need to add
@Override
public void onBackPressed() {
finish();
}