I have an activity with drawer layout.
I want to check if the drawer is closed or not then call onBackPressed
. If the drawer is open it should close first then onBackPressed
should get called.
I tried to do like this using addDrawerListener
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpUI();
listeners(
}
public void setUpUI() {
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Initializing NavigationView
navigationView = (NavigationView) findViewById(R.id.navigation_view);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
}
public void listeners()
drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
@Override
public void onDrawerSlide(View drawerView, float slideOffset) {
}
@Override
public void onDrawerOpened(View drawerView) {
}
@Override
public void onDrawerClosed(View drawerView) {
onBackPressed();
}
@Override
public void onDrawerStateChanged(int newState) {
}
});
}
@Override
public void onBackPressed()
drawerLayout.closeDrawer(Gravity.END);
if (!mBackPressCancelled) {
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStackImmediate();
} else {
super.onBackPressed();
}
}
}
}
With this drawer gets close half an app gets closed. I want to close the drawer the call onBaackPressed.
How can I do this? Please help. Thank you.
答案 0 :(得分:4)
You can check if drawer is closed or not with
if(mDrawerLayout.isDrawerOpen(GravityCompat.END)) {
//drawer is open
}else{
super.onBackPressed();
}
答案 1 :(得分:2)
This will be your code:
@Override
public void onBackPressed() {
if(mDrawerLayout.isDrawerOpen(GravityCompat.END)) {
mDrawerLayout.closeDrawer(GravityCompat.END)
} else {
super.onBackPressed();
}
}