如何检测导航抽屉是否打开?

标题解释了这一切。 所有我想要做的是知道抽屉是否打开。 我在网上search了很多,发现方法isDrawerOpen(int drawerGravity)但找不到满意的答案,解释如何在一个方法中使用它。 如果有人向我解释,我将不胜感激。

提前致谢!

Solutions Collecting From Web of "如何检测导航抽屉是否打开?"

假设你已经在xml中定义了一个drawerlayout:

 DrawerLayout mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); ... if(mDrawerLayout.isDrawerOpen(GravityCompat.START)) { //drawer is open } 
  mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mDrawerToggle = new ActionBarDrawerToggle( this, /* host Activity */ mDrawerLayout, /* DrawerLayout object */ R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */ R.string.drawer_open, /* "open drawer" description */ R.string.drawer_close /* "close drawer" description */ ) { /** Called when a drawer has settled in a completely closed state. */ public void onDrawerClosed(View view) { super.onDrawerClosed(view); getActionBar().setTitle(mTitle); } /** Called when a drawer has settled in a completely open state. */ public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); getActionBar().setTitle(mDrawerTitle); } }; // Set the drawer toggle as the DrawerListener mDrawerLayout.setDrawerListener(mDrawerToggle); 

那听众使用:)

使用:

mDrawerLayout.isDrawerOpen()方法

例:

  if(mDrawerLayout.isDrawerOpen(GravityCompat.START)) { mDrawerLayout.closeDrawer(Gravity.LEFT); //CLOSE Nav Drawer! }else{ mDrawerLayout.openDrawer(Gravity.LEFT); //OPEN Nav Drawer! } 

shakeJ的答案是正确的,并记住你可以使用onDrawerSlide能够触发其他function…例如我用它来改变StatusBar的颜色。

  /** Called when a drawer has settled in a completely closed state. */ public void onDrawerClosed(View view) { super.onDrawerClosed(view); isOpen = false; } /** Called when a drawer has settled in a completely open state. */ public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); isOpen = true; } public void onDrawerSlide(View drawerView,float slideOffset){ super.onDrawerSlide(drawerView,slideOffset); if(!isOpen){ setStatusBarColor("#00102b"); } if(isOpen){ setStatusBarColor("#EFEFF0"); } } 

通过以下方式,您可以find抽屉打开或closures。

  public class YourActivity extends AppCompatActivity implements DrawerLayout.DrawerListener { DrawerLayout drawer; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dash_board); final DrawerLayout drawer=(DrawerLayout)findViewById(R.id.container); drawer.setDrawerListener(this); }//onCreate() @Override public void onDrawerOpened(View arg0) { //write your code } @Override public void onDrawerClosed(View arg0) { } @Override public void onDrawerSlide(View arg0, float arg1) { //write your code } @Override public void onDrawerStateChanged(int arg0) { //write your code } }//class