按下返回按钮时的导航抽屉活动为空活动
问题描述:
我在导航抽屉菜单中使用带抽象的导航抽屉活动。我想要的是当用户按两次退出按钮退出应用程序。但相反,这是空白的活动。按下返回按钮时的导航抽屉活动为空活动
onCreate方法:
@Override
protected void onCreate(Bundle savedInstanceState) {
if (broj == 1) {
startActivity(new Intent(this, Cover.class));
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
FragmentMainPage pocetnaFragment = new FragmentMainPage();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.addToBackStack(null).replace(R.id.relativeLayoutZaFragment, pocetnaFragment, "1");
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
fragmentTransaction.addToBackStack(null);
// Pozivanje metode
getSupportActionBar().setTitle("Auto magazin");
ActionBar.LayoutParams p = new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
p.gravity = Gravity.LEFT;
view = getLayoutInflater().inflate(R.layout.action_bar, null);
ActionBar.LayoutParams params = new ActionBar.LayoutParams(
ActionBar.LayoutParams.WRAP_CONTENT,
ActionBar.LayoutParams.MATCH_PARENT,
Gravity.LEFT);
TextView Title = (TextView) view.findViewById(R.id.actionbar_title);
Title.setText("Auto magazin");
getSupportActionBar().setCustomView(view,params);
getSupportActionBar().setDisplayShowCustomEnabled(true); //show custom title
getSupportActionBar().setDisplayShowTitleEnabled(false); //hide the default title
// getSupportActionBar().setIcon(R.drawable.logo);
}
onBackPressed()方法是:
boolean doubleBackToExitPressedOnce = false;
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
assert drawer != null;
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
return;
}
else if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Press again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
}
这是因为您已将FragmentTransaction添加到后端堆栈。 'super.onBackPressed()'调用将首先弹出该事务。如果您不想通过按下后退按钮删除'Fragment',请不要将'FragmentTransaction'添加到后退堆栈中。 –
是的,这是正确的答案。谢谢很多。 – smiljka