Why isn't onBackPressed () called?

I am trying to override onBackPressed (). However, it does 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(); } 

A log message never appears in LogCat. I know that this log statement works because it is copied from another method with a different message that appears in LogCat.

I searched for the answers and I tried using onKeyDown and found that the BACK button was pressed, but I still have the same problem. Project Information:

  • Android Studio 0.9.3
  • The method is in empty activity.
  • target sdk 21
  • minimum sdk 15
  • the testing device is Samsung Galaxy 5 (not an emulator).

Any help would be greatly appreciated!

EDIT:

This is a copy of my working code (this is test code, so the action 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); } } } 

In "LogCat", the message "Press the back button."

+7
android android-studio
source share
2 answers

onBackPressed() is called when the user clicks the hardware return button (or the up button on the navigation bar), rather than the button on the action bar. To do this, you need to override the 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); } } 
+18
source share

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(); } } 
0
source share

All Articles