in my MainActivity, which extends from AppCompatActivity, I want to override the onBackPressed method like so:
@Override
public void onBackPressed() {
Log.d("MainActivity","onBackPressed");
Toast.makeText(getApplicationContext(),"onBackPressed",Toast.LENGTH_SHORT).show();
}
but onBackPressed does not get called. How ever if I do not override onBackPressed, the application closes, when I press the backbutton and if I do override it it doesn't.
The rest of my activity looks like this:
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private Drawer drawer;
private FloatingActionButton fab_test;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
fab_test = (FloatingActionButton) findViewById(R.id.fab_test);
fab_test.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(),"FAB Test pressed",Toast.LENGTH_SHORT).show();
}
});
buildDrawer();
getSupportFragmentManager().beginTransaction().add(R.id.fragmentContainer,page).commit();
}
@Override
public void onBackPressed() {
Log.d("MainActivity","onBackPressed");
Toast.makeText(getApplicationContext(),"onBackPressed",Toast.LENGTH_SHORT).show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
}
EDIT: I'm talking about the hardware-backbutton(not the actionbar one)
onBackPressed()
, no need foronKeyDown
. From the docs:Called when the activity has detected the user's press of the back key. The default implementation simply finishes the current activity, but you can override this to do whatever you want.
There must be any other problem for this behaviour. – PanteutonismonKeyDown
for back button? Because if you have done this anywhere in your code, possibly you haven´t returned true andonBackPressed
is not called.... – Panteutonismsuper.OnBackPressed()
, the method should work without this. What exactly isn´t working? The Log? The Toast? If it´s the toast, maybe it´s because of yourgetApplicationContext()
call. Just usethis
orgetActivity().getApplicationContext();
– Panteutonism