传送门:https://github.com/mikepenz/MaterialDrawer
MaterialDrawer是一个多功能的侧拉抽屉第三方库
首先先添加依赖
implementation ('com.mikepenz:materialdrawer:5.9.0@aar') {
transitive = true
}
MaterialDrawer的使用不需要在xml文件中添加控件,所以,直接在代码中添加代码
//创建登录用户对象
IProfile iProfile = new ProfileDrawerItem()
.withName("测试员一号")
.withEmail("[email protected]")
.withIcon(R.drawable.picture1)
.withIdentifier(100); //设置标识码
//创建抽屉头部,也是代码实现
AccountHeader header = new AccountHeaderBuilder()
.withActivity(MainActivity.this) //绑定显示的活动对象,如果是fragment的话就传getActivity
.withTranslucentStatusBar(true) //设置启用沉浸式状态栏
.withHeaderBackground(R.color.colorPrimary) //设置背景图片
.addProfiles(iProfile) //添加用户对象,可以添加多个,用逗号隔开
.withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() {
@Override
public boolean onProfileChanged(View view, IProfile profile, boolean current) {
switch ((int) profile.getIdentifier()){
case 100:
Toast.makeText(MainActivity.this,"CLICK HEAD",Toast.LENGTH_SHORT).show();
break;
}
return true;
}
})
.withSavedInstance(savedInstanceState) //将意外被杀死的Activity的状态设置回来
.build();
//将头部信息添加进来到抽屉
new DrawerBuilder()
.withActivity(MainActivity.this)
.withAccountHeader(header) //添加头部
.addDrawerItems( //添加menu菜单
new PrimaryDrawerItem()
.withName("消息") //主标题
.withDescription("啦啦啦,有人敲门啦") //副标题
.withIcon(R.drawable.picture2) //设置icon
.withIdentifier(1) //设置标识码
.withSelectable(false), //是否被选择状态
new SectionDrawerItem().withName("menu组"), //分组item,类似于group标签,无点击效果
new ExpandableBadgeDrawerItem() //伸缩式item
.withName("伸缩式圆角item") //主标题
.withIcon(R.drawable.picture2) //添加icon
.withIdentifier(2) //标识码
.withBadge("10") //设置圆角气泡里的数字
.withSubItems(
new SecondaryDrawerItem().withName("内部item").withIdentifier(3) //添加子item
),
new SwitchDrawerItem() //添加带有switch开关的item
.withName("开关item1")
.withIcon(R.drawable.picture2)
.withIdentifier(3)
.withCheckable(false)
.withOnCheckedChangeListener(new OnCheckedChangeListener() { //开关按钮的监听
@Override
public void onCheckedChanged(IDrawerItem drawerItem, CompoundButton buttonView, boolean isChecked) {
}
})
)
.withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() { // item的监听
@Override
public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
switch ((int) draweritem.getIdentifier()){
case 1:
Toast.makeText(MainActivity.this,"CLICK 1",Toast.LENGTH_SHORT).show();
break;
case 2:
Toast.makeText(MainActivity.this,"CLICK 2",Toast.LENGTH_SHORT).show();
break;
}
return false;
}
})
.withSavedInstance(savedInstanceState)
.withShowDrawerOnFirstLaunch(true) //设置为默认启动抽屉菜单
.build();
效果图: