I am attempting to override onBackPressed(). However it appears to not detect when I click the back button in the action bar.
I currently have this code:
@Override
public void onBackPressed() {
Log.i("DATA", "Hit onBackPressed()");
super.onBackPressed();
}
The log message never appears in the LogCat. I know that this log statement works because it is copied from another method with a different message that DOES display in the LogCat.
I have searched for answers, and I have tried using onKeyDown and detecting if it is the BACK button being clicked but I still have the same issue. Information about the project:
Any help would be greatly appreciated!!
EDIT:
This is a copy of my working code (this is test code so the activity name is not descriptive):
public class MainActivity2 extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity2);
getActionBar().setDisplayHomeAsUpEnabled(true);//Displays the back button
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main_activity2, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Log.i("DATA", "Hit Actionbar Back Button");
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
The message "Hit Actionbar Back Button" now appears in the LogCat.
The onBackPressed() is a default action called from onKeyDown() in API < 5 and a default action called from onKeyUp() from API level 5 and up. If onKeyUp() does not call super. onKeyUp() , onBackPressed() will not be called.
To create the second activity, follow these steps: In the Project window, right-click the app folder and select New > Activity > Empty Activity. In the Configure Activity window, enter "DisplayMessageActivity" for Activity Name. Leave all other properties set to their defaults and click Finish.
onBackPressed()
is invoked when user clicks on a hardware back button (or on the 'up' button in the navigation bar), not the button in the action bar. For this one you need to override onOptionsItemSelected()
method. Example:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// click on 'up' button in the action bar, handle it here
return true;
default:
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