Android onBackPressed() 不被调用?
在我的 MainActivity 中,从 AppCompatActivity 扩展而来,我想覆盖 onBackPressed 方法,如下所示:
@Override
public void onBackPressed() {
Log.d("MainActivity","onBackPressed");
Toast.makeText(getApplicationContext(),"onBackPressed",Toast.LENGTH_SHORT).show();
}
但是onBackPressed不会被调用。如果我不覆盖onBackPressed,应用程序就会关闭,当我按下后按钮时,如果我覆盖它,它就不会关闭。
我的其余活动如下所示:
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;
}
}
编辑:我说的是硬件后按钮(不是动作栏)