Reputation: 137
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.
Upvotes: 10
Views: 8611
Reputation: 792
Please try this code,
public class MainActivity2 extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
Toast.makeText(getApplicationContext(), "back press is call", Toast.LENGTH_LONG).show();
}
}
Upvotes: 0
Reputation: 29416
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);
}
}
Upvotes: 25