天天看點

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();
            }

        }
    };

}