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

后端 未结 10 1054
[愿得一人]
[愿得一人] 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:38

    New functionality in the framework and support libs allow exactly this. There are three 'pieces of the puzzle':

    1. Using Toolbar so that you can embed your action bar into your view hierarchy.
    2. Making DrawerLayout fitsSystemWindows so that it is layed out behind the system bars.
    3. Disabling Theme.Material's normal status bar coloring so that DrawerLayout can draw there instead.

    I'll assume that you will use the new appcompat.

    First, your layout should look like this:

    
    
    
        
        
    
            
            
    
            
    
        
    
        
        
    
            
    
        
    
    
    

    Then in your Activity/Fragment:

    public void onCreate(Bundled savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        // Your normal setup. Blah blah ...
    
        // As we're using a Toolbar, we should retrieve it and set it
        // to be our ActionBar
        Toolbar toolbar = (...) findViewById(R.id.my_awesome_toolbar);
        setSupportActionBar(toolbar);
    
        // Now retrieve the DrawerLayout so that we can set the status bar color.
        // This only takes effect on Lollipop, or when using translucentStatusBar
        // on KitKat.
        DrawerLayout drawerLayout = (...) findViewById(R.id.my_drawer_layout);
        drawerLayout.setStatusBarBackgroundColor(yourChosenColor);
    }
    

    Then you need to make sure that the DrawerLayout is visible behind the status bar. You do that by changing your values-v21 theme:

    values-v21/themes.xml

    
    

    Note: If a is used instead of

    
    
        
    
    
    

    the actual layout, the desired effect will be achieved if you call fitsSystemWindows(boolean) on a view that you return from onCreateView method.

    @Override
    public View onCreateView(LayoutInflater inflater, 
                             ViewGroup container,
                             Bundle savedInstanceState) {
        View mDrawerListView = inflater.inflate(
            R.layout.fragment_navigation_drawer, container, false);
        mDrawerListView.setFitsSystemWindows(true);
        return mDrawerListView;
    }
    

提交回复
热议问题