public interface DrawerListener {void onDrawerSlide(View var1, float var2);void onDrawerOpened(View var1);void onDrawerClosed(View var1);void onDrawerStateChanged(int var1);}本文讲一下drawLayout.setDrawerListener(toggle);方式,ActionBarDrawerToggle 就是实现了这个接口。他主要作用在于。toggle = new ActionBarDrawerToggle(this, /* host Activity */mDrawerLayout, /* DrawerLayout object */R.drawable.ic_drawer, /* nav drawer image to replace "Up" caret */R.string.drawer_open, /* "open drawer" description for accessibility */R.string.drawer_close /* "close drawer" description for accessibility */) {public void onDrawerClosed(View view) {getActionBar().setTitle(mTitle);invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()}public void onDrawerOpened(View drawerView) {getActionBar().setTitle(mDrawerTitle);invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()}};初始化相关比较简单看注释就行。在监听的回调方法中我们用invalidateOptionsMenu通知activity重绘menu,然后activity就有机会在onPrepareOptionsMenu方法中更新menu元素的显示与隐藏。 private void initActionBar() { // enable ActionBar app icon to behave as action to toggle nav drawerActionBar actionBar = getActionBar();actionBar.setDisplayHomeAsUpEnabled(true);actionBar.setHomeButtonEnabled(true);} 不难看出是显示菜单键以及设置为可点击使用的菜单键。@Overrideprotected void onPostCreate(Bundle savedInstanceState) {super.onPostCreate(savedInstanceState);// Sync the toggle state after onRestoreInstanceState has occurred. toggle.syncState();}@Overridepublic void onConfigurationChanged(Configuration newConfig) {super.onConfigurationChanged(newConfig);// Pass any configuration change to the drawer toggls toggle.onConfigurationChanged(newConfig);}@Overridepublic boolean onOptionsIwotemSelected(MenuItem item) {// The action bar home/up action should open or close the drawer.// ActionBarDrawerToggle will take care of this. if (toggle.onOptionsItemSelected(item)) { return true; }return super.onOptionsItemSelected(item);}在这里如果不去实现onOptionsIwotemSelected中的代码那么点击菜单是没有效果的。
在android.support.v7.app.ActionBarDrawerToggle;中的ActionBarDrawerToggle第三个参数
即:R.drawable.ic_drawer, /* nav drawer image to replace "Up" caret */
更换为Toolbar对象,这样一来你可以自定一个Toolbar做更为漂亮UI。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。