天天看点

MaterialDrawer+ToolBar飘逸的导航和抽屉侧滑(用户登录信息的抽屉布局)

ToolBar的实现:

toolbar右上角菜单menu
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <!--toolbar右上角菜单menu的显示隐藏-->
    <item android:id="@+id/action_search"
        android:title=""
        android:icon="@drawable/profile5"
        app:showAsAction="ifRoom"/>
    <item android:id="@+id/action_notification"
        android:title="消息"
        android:icon="@drawable/profile3"
        app:showAsAction="ifRoom"/>
    <item android:id="@+id/action_item1"
        android:title="item1"
        android:icon="@drawable/profile4"
        app:showAsAction="never"/>
    <item android:id="@+id/action_item2"
        android:title="item2"
        android:icon="@drawable/profile5"
        app:showAsAction="never"/>
</menu>
           
主布局中ToolBar控件的添加
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:toolbar="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/holo_blue_light"
    android:orientation="vertical">
<!-- xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:toolbar="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"-->
    <android.support.v7.widget.Toolbar
        android:id="@+id/tb_toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/holo_red_light"
        toolbar:logo="@mipmap/ic_launcher"
        toolbar:subtitle="子布局"
        toolbar:title="主布局">
        <!--自定义控件-->
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="clock"
            android:textSize="10sp"
            android:layout_marginLeft="5dp"
            android:gravity="center"/>
    </android.support.v7.widget.Toolbar>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:text="主布局" />

</LinearLayout>
           

MaterialDrawerActivity.class中抽屉侧滑布局的实现,

不需要任何xml文件,在build.gradle文件中添加依赖:

compile(‘com.mikepenz:materialdrawer:[email protected]’ ) {

transitive = true

}

compile ‘com.mikepenz:google-material-typeface:[email protected]’谷歌官方图片库

compile ‘com.mikepenz:fontawesome-typeface:[email protected]’谷歌官方字体库

ToolBar和MaterialDrawer抽屉联动功能的实现:

package com.example.pc.ytf;

import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.Toast;

import com.mikepenz.fontawesome_typeface_library.FontAwesome;
import com.mikepenz.google_material_typeface_library.GoogleMaterial;
import com.mikepenz.materialdrawer.AccountHeader;
import com.mikepenz.materialdrawer.AccountHeaderBuilder;
import com.mikepenz.materialdrawer.Drawer;
import com.mikepenz.materialdrawer.DrawerBuilder;
import com.mikepenz.materialdrawer.holder.BadgeStyle;
import com.mikepenz.materialdrawer.interfaces.OnCheckedChangeListener;
import com.mikepenz.materialdrawer.model.ExpandableBadgeDrawerItem;
import com.mikepenz.materialdrawer.model.PrimaryDrawerItem;
import com.mikepenz.materialdrawer.model.ProfileDrawerItem;
import com.mikepenz.materialdrawer.model.SecondaryDrawerItem;
import com.mikepenz.materialdrawer.model.SectionDrawerItem;
import com.mikepenz.materialdrawer.model.SwitchDrawerItem;
import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem;
import com.mikepenz.materialdrawer.model.interfaces.IProfile;
import com.mikepenz.materialdrawer.model.interfaces.Nameable;

public class MaterialDrawerActivity extends AppCompatActivity {
    private IProfile profile = null;//登录用户信息
    private AccountHeader headerResult = null;//head头布局
    private PrimaryDrawerItem primaryItem = null;//菜单item
    private SectionDrawerItem sectionItem = null;//分组的item类似于group标签,无点击效果
    private ExpandableBadgeDrawerItem expandableItem = null;//伸缩式item
    private SecondaryDrawerItem secondItem = null;//子item
    private SwitchDrawerItem switchItem1 = null;//带有switch开关的item1
    private SwitchDrawerItem switchItem2 = null;//带有switch开关的item2
    private Drawer result = null;//嵌套抽屉

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_material_drawer);
        Toolbar toolbar= (Toolbar) findViewById(R.id.tb_toolbar);
        toolbar.setNavigationIcon(R.drawable.profile2);//设置导航栏图标
        toolbar.inflateMenu(R.menu.base_toolbar_menu);//设置右上角填充menu
        toolbar.setTitleTextAppearance(this, R.style.toolbarTextSize);
        toolbar.setTitleTextColor(getResources().getColor(android.R.color.holo_orange_dark));
        toolbar.setSubtitleTextAppearance(this,R.style.toolbarsubTextSize);
        //修改标题和子标题的字体大小、颜色等,可以调用
        // setTitleTextColor、setTitleTextAppearance、
        // setSubtitleTextColor、setSubtitleTextAppearance 这些API;
        //设置每一个menu菜单的点击事件
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
//                int menuItemId = item.getItemId();
//                if(menuItemId==R.id.action_search){
//
//                }
                switch (item.getItemId()){
                    case R.id.action_search:
                        break;
                    case R.id.action_settings:
                        break;
                    case R.id.action_notification:
                        break;
                    case R.id.action_toggle:
                        break;
                }
                return false;
            }
        });
        setProfile();
        //创建和NavigationView相似的Headerlayout
        setHeadLayout(savedInstanceState);//方法中不能直接设置此属性,所以oncreat中传参
        result = new DrawerBuilder()
                .withActivity(this)
                .addDrawerItems(setPrimaryItem())
                .build();
        //最后创建抽屉,将配置好的布局属性加进去
         new DrawerBuilder().withActivity(this)
                .withAccountHeader(headerResult)
                 .withToolbar(toolbar)//和toolbar关联
                 .withActionBarDrawerToggle(true) //启用toolbar的ActionBarDrawerToggle动画
                .addDrawerItems(setPrimaryItem(), setSectionItem(), setExpandableItem(),
                        setSwitchItem1(), setSwitchItem2(),setSectionItem())//给抽屉添加item布局
                .withShowDrawerOnFirstLaunch(false) //默认开启抽屉
                .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
                    @Override
                    public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
                        //监听方法实现
                        Toast.makeText(MaterialDrawerActivity.this, drawerItem.getIdentifier() + "is clicked", Toast.LENGTH_SHORT).show();
                        return false;
                    }
                }) //抽屉中item的监听事件
                .withDrawerGravity(Gravity.LEFT) //设置抽屉打开方向默认从左,end从右侧打开
//                .append(result);
                .build();


    }

    /**
     * ①IProfile创建登录用户对象
     */
    private void setProfile() {
        profile = new ProfileDrawerItem()
                .withName("yangtianfu")
                .withEmail("[email protected]")
                .withIcon("http://noavatar.csdn.net/5/D/8/1_soma5431.jpg")
                .withIdentifier();//标识符,当设置监听事件时可以根据这个来区别对象
    }

    /**
     * ②创建head布局,显示概要,将创建的profile加入布局中
     * withOnAccountHeaderListener
     * 获得标识符进行判断点击事件是来自哪个用户对象而执行相应的响应方法。
     * 这里获取标识符的方法getIdentifier方法的返回值是long型的,
     * 而switch是不接受long变量的,所以这里需要转一下变量类型。
     * 监听事件的方法是返回值的,一般是按照原来给出的返回false就可以了,
     * 表示当执行完点击事件后,关闭抽屉菜单;
     * withTranslucentStatusBar(true) 设置是否启用沉浸式状态栏
     * addProfiles(profile) 于添加用户对象,可以添加多个,使用逗号进行隔开;
     * withSaveIntstance方法就是将意外被杀掉的Activity的状态设置回来。
     * 之后我们使用build就可以获得一个类似Headerlayout的对象。
     * 把新创建的AccountHeader对象添加进去的方法:
     * new DrawerBuilder()
     * .withActivity(this)
     * .withAccountHeader(headerResult)
     * .build();
     */
    private void setHeadLayout(Bundle savedInstanceState) {
        headerResult = new AccountHeaderBuilder()
                .withActivity(this)
                .withHeaderBackground(R.drawable.header)
                .withTranslucentStatusBar(true) //半透明效果
                .addProfiles(profile)
                .withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() {
                    @Override
                    public boolean onProfileChanged(View view, IProfile profile, boolean current) {
                        switch ((int) profile.getIdentifier()) {
                            case ://根据不同标识符监听不同对象
                                Toast.makeText(MaterialDrawerActivity.this, "头像被点击", Toast.LENGTH_SHORT).show();
                                break;
                            default:
                                break;
                        }
                        return false;
                    }
                })
                .withSavedInstance(savedInstanceState)
                .build();//至此头布局head构建完成
    }

    /**
     * ③创建自定义菜单布局
     *创建自己的带有图标和任何字体DrawerItems
     * 添加依赖:
     *  compile 'com.mikepenz:google-material-typeface:[email protected]'
     *  compile 'com.mikepenz:fontawesome-typeface:[email protected]'
     * @return
     */
    private PrimaryDrawerItem setPrimaryItem() {
        primaryItem = new PrimaryDrawerItem()
                .withName("User")
                .withDescription("This is a user")
                .withIcon(GoogleMaterial.Icon.gmd_accounts_list_alt)
                .withIdentifier()
                .withSelectable(false);
        return primaryItem;
    }

    /**
     * ④分组item,类似于group标签,无点击效果
     *
     * @return
     */
    private SectionDrawerItem setSectionItem() {
        sectionItem = new SectionDrawerItem()
                .withName("menu组")
                .withDivider(true)
                .withTextColor(R.color.md_deep_orange_500)
                .withIdentifier();
        return sectionItem;
    }

    /**
     * ⑤伸缩式item包含内部子item SecondaryDrawerItem
     * @return
     */
    private ExpandableBadgeDrawerItem setExpandableItem() {
        expandableItem = new ExpandableBadgeDrawerItem()
                .withName("伸缩式圆角item")
                .withIcon(FontAwesome.Icon.faw_apple)
                .withIdentifier()
                .withBadge("10") //设置圆角气泡中的数字
                .withBadgeStyle(new BadgeStyle().withTextColor(Color.RED).withColorRes(R.color.md_light_blue_A700))
                .withSubItems(new SecondaryDrawerItem().withName("内部item").withIdentifier()); //内部item
        return expandableItem;
    }
    private SwitchDrawerItem setSwitchItem1(){
        switchItem1=new SwitchDrawerItem()
                .withIcon(R.drawable.profile3)
                .withIdentifier()
                .withCheckable(false)
                .withOnCheckedChangeListener(checkedChangeListener)
                .withName("开关1");
        return switchItem1;
    }
    private SwitchDrawerItem setSwitchItem2(){
        switchItem2=new SwitchDrawerItem()
                .withIcon(R.drawable.profile4)
                .withIdentifier()
                .withCheckable(true)
                .withOnCheckedChangeListener(checkedChangeListener)
                .withName("开关2");
        return switchItem2;
    }
    //开关item的状态监听
   private OnCheckedChangeListener checkedChangeListener=new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(IDrawerItem drawerItem, CompoundButton buttonView, boolean isChecked) {
            if(drawerItem instanceof Nameable) {
                Toast.makeText(MaterialDrawerActivity.this,((Nameable)drawerItem).getName() + "'s check is" + isChecked,Toast.LENGTH_SHORT).show();
            }

        }
    };

}