Android 5.0 material design style navigation drawer for KitKat

后端 未结 4 936
攒了一身酷
攒了一身酷 2020-11-27 09:27

I see that Android introduced new navigation drawer icons, drawer icon and back arrow icon. How can we use that in Kitkat supported apps. See Google\'s latest version of New

4条回答
  •  一向
    一向 (楼主)
    2020-11-27 10:03

    You need to use the new Toolbar in the appcompat v21 and the new ActionBarDrawerToggle that is in this library as well.

    Add the gradle dependency to your gradle file:

    compile 'com.android.support:appcompat-v7:21.0.0'
    

    Your activity_main.xml layout would look something like that:

    
    
    
        
    
        
    
            
            
    
            
            
        
    
    

    Your Toolbar layout would look something like that:

    
    
    

    Your activity must extend from:

    ActionBarActivity
    

    When you find your views (drawer and toolbar) in the activity the set the toolbar as the support action bar and set the setDrawerListener:

    setSupportActionBar(mToolbar);
    mDrawerToggle= new ActionBarDrawerToggle(this, mDrawerLayout,mToolbar, R.string.app_name, R.string.app_name);
    mDrawerLayout.setDrawerListener(mDrawerToggle);
    

    After that you just need to take care of the menu items and drawerToogle state:

     @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = new MenuInflater(this);
        inflater.inflate(R.menu.menu_main,menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    
    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        mDrawerToggle.syncState();
    }
    
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mDrawerToggle.onConfigurationChanged(newConfig);
    }
    
    @Override
    public void onBackPressed() {
        if(mDrawerLayout.isDrawerOpen(Gravity.START|Gravity.LEFT)){
            mDrawerLayout.closeDrawers();
            return;
        }
        super.onBackPressed();
    }
    

    The implementation is the same as It was before the Toolbar and you receive the arrow animation for free. No headaches. For more information follow:

    • The documentation.

    • The ChrisBanes post

    • The official android blog post.

    If you want to display the drawer over the Toolbar and under the status bar, please refer to this question.

    EDIT: Use NavigationView from the support design library. Tutorial to learn how to use in here: http://antonioleiva.com/navigation-view/

提交回复
热议问题