How do I use DrawerLayout to display over the ActionBar/Toolbar and under the status bar?

后端 未结 10 1016
[愿得一人]
[愿得一人] 2020-11-22 04:05

I\'ve seen in the new material design Side Nav spec that you can display the drawer over the action bar and behind the status bar. How can I implement this?

10条回答
  •  眼角桃花
    2020-11-22 04:34

    All answers mentioned here are too old and lengthy.The best and short solution that work with latest Navigationview is

    @Override
    public void onDrawerSlide(View drawerView, float slideOffset) {
        super.onDrawerSlide(drawerView, slideOffset);
    
        try {
            //int currentapiVersion = android.os.Build.VERSION.SDK_INT;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP){
                // Do something for lollipop and above versions
    
            Window window = getWindow();
    
            // clear FLAG_TRANSLUCENT_STATUS flag:
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
    
            // add FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS flag to the window
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
    
            // finally change the color to any color with transparency
    
             window.setStatusBarColor(getResources().getColor(R.color.colorPrimaryDarktrans));}
    
        } catch (Exception e) {
    
            Crashlytics.logException(e);
    
        }
    }
    

    this is going to change your status bar color to transparent when you open the drawer

    Now when you close the drawer you need to change status bar color again to dark.So you can do it in this way.

            public void onDrawerClosed(View drawerView) {
            super.onDrawerClosed(drawerView);
            try {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP){
        // Do something for lollipop and above versions
    
        Window window = getWindow();
    
        // clear FLAG_TRANSLUCENT_STATUS flag:
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
    
        // add FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS flag to the window
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
    
        // finally change the color again to dark
        window.setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));}
        } catch (Exception e) {
        Crashlytics.logException(e);
                        }
                        }
    

    and then in main layout add a single line i.e

                android:fitsSystemWindows="true"
    

    and your drawer layout will look like

                
    

    and your navigation view will look like

        
    

    I have tested it and its fully working.Hope it helps someone.This may not be the best approach but it works smoothly and is simple to implement. Mark it up if it helps.Happy coding :)

提交回复
热议问题