avigationView和ActionBarDrawerTog

avigationView和ActionBarDrawerTog

本文介绍了NavigationView和ActionBarDrawerToggle的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

随着新的 NavigationView 是它仍然推荐使用 ActionBarDrawerToggle 或这是不是材料设计?例如previously我们应该隐藏动作栏项目的抽屉被打开的时候,但现在的指导方针说,他们应该留下来。


解决方案

No, it's not required.

If you look at the "official" demo code for the new Design Library, ActionBarDrawerToggle is no longer used, since the new NavigationView and AppCompatActivity don't really need it.

With the new v22 support library, you can strip out all of your ActionBarDrawerToggle code and just use the following to handle the interaction between NavigationDrawer and the ActionBar/ToolBar hamburger icon:

@Override
protected void onCreate(Bundle savedInstanceState) {
    ...
    final ActionBar actionBar = getSupportActionBar();
    actionBar.setHomeAsUpIndicator(R.drawable.ic_menu);
    actionBar.setDisplayHomeAsUpEnabled(true);
    ...
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            mDrawerLayout.openDrawer(GravityCompat.START);
            return true;
        ....
    }
    return super.onOptionsItemSelected(item);
}

You will need to provide your own "hamburger" drawable (R.drawable.ic_menu in my example). Besides that, the above code is all that's needed to handle opening of the drawer. The android.R.id.home case in onOptionsItemSelected() represents your hamburger drawer button. It points to a built-in resource id (not something you add to you menu xml), and it's handled automatically.

Besides that, you have to implement closing of the drawer by simply adding closeDrawers() to your click listener, like this:

navigationView.setNavigationItemSelectedListener(
    new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(MenuItem menuItem) {
            // Handle menu item clicks here.
            drawerLayout.closeDrawers();
            return true;
        }
    });

closeDrawers() is a method of DrawerLayout, and takes care of everything. That's it. That's all the code you really need to properly handle navigation drawers now. No more messy code for flipping hamburgers and such!

Of course, if you really want to, you can still use NavigationView with ActionBarDrawerToggle the old way. But you certainly don't have to.

If you want drawer callbacks

Even though ActionBarDrawerToggle is not required to open/close the drawer, it may still be useful for handling additional callbacks (especially if you're using ActionBar already). Otherwise, you can implement your own by using DrawerLayout.DrawerListener or by using DrawerLayout.SimpleDrawerListener(), to handle other open/close related events.

这篇关于NavigationView和ActionBarDrawerToggle的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-04 21:17