Onbackpressed() Method Not Triggered In Appcompatactivity
Solution 1:
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:
@OverridepublicbooleanonOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home: {
// Your code here
}
}
return (super.onOptionsItemSelected(menuItem));
}
Solution 2:
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:
@OverridepublicbooleanonOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
returntrue;
default:
returnsuper.onOptionsItemSelected(item);
}
}
Solution 3:
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);
@OverridepublicvoidonBackPressed() {
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" />
Solution 4:
onBackPressed() is not present in AppCompactActivity, You have to implement an InterFaceKeyEvent.Callback and override onKeyUp method and check if the key is BackButton or you can extend ActionBarActivity which is child class of AppCompactActivity
Solution 5:
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.
publicclassRedActivityextendsAppCompatActivity {
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
...
finalActionBarab= getSupportActionBar();
ab.setHomeAsUpIndicator(R.drawable.ic_menu);
ab.setDisplayHomeAsUpEnabled(true);
...
}
...
@OverridepublicvoidonBackPressed() {
if (isDrawerOpen()) {
drawerLayout.closeDrawer(GravityCompat.START);
} elseif (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
} else {
//Ask the user if they want to quitnewAlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(R.string.quit)
.setMessage(R.string.really_quit)
.setPositiveButton(R.string.yes, newDialogInterface.OnClickListener() {
@OverridepublicvoidonClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton(R.string.no, null)
.show();
}
}
}
Post a Comment for "Onbackpressed() Method Not Triggered In Appcompatactivity"