Steve2955 Steve2955 - 2 months ago 26
Android Question

Android onBackPressed() is not being called?

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)

Answer

You are missing, super.onBackPressed();

@Override
public void onBackPressed() {
    super.onBackPressed();
}

or you can use

@Override  
public boolean onKeyDown(int keyCode, KeyEvent event)  
{  
     //replaces the default 'Back' button action  
     if(keyCode==KeyEvent.KEYCODE_BACK)   {  
// something here
            finish();
     }  
     return true;  
 }  

thanks