1. 程式人生 > >滑動菜單--DrawerLayout

滑動菜單--DrawerLayout

item 1.0 lba left @+ .com 手機 isp 獲取

技術分享

DrawerLayout是一個布局,在布局裏面只允許放兩個直接子控件,第一個是主屏幕顯示的內容,第二個是滑動菜單中顯示的內容。,第二個子控件加黑需要註意,必須添加,該屬性是指,在手機哪一側劃出菜單,star根據系統語言進行判斷,left,由左向右劃出,right相反

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.ca.sd.zsl.toolbartest" android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="ca.sd.zsl.toolbartest.MainActivity"> <FrameLayoutandroid:layout_width="match_parent" android:layout_height
="match_parent"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" android:popupTheme
="@style/ThemeOverlay.AppCompat.Light" android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" /> </FrameLayout> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="start"
     android:text="這是策劃菜單"
/> </android.support.v4.widget.DrawerLayout>

在ToolBar上添加按鈕彈出菜單,

  //設置按鈕彈出菜單
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);先獲取布局實例,
        ActionBar actionBar = getSupportActionBar();然後獲取ActionBar實例,
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);讓按鈕顯示出來
            actionBar.setHomeAsUpIndicator(R.drawable.ic_menu);設置圖片
        }

home按鈕的點擊事件,重寫onOptionsItemSelected方法。

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            /**
             * 在ToolBar最左側的圖標就叫做HomeAsUp按鈕,含義是返回上一個活動,
             * 它的ID永遠是android.R.id.home
             */
            case android.R.id.home:
STAR:打開視圖到x軸的開始位置,不改變大小,END:打開視圖到x軸的結束位置,不改變大小 mDrawerLayout.openDrawer(GravityCompat.START);
break;default: break; } return true; }

滑動菜單--DrawerLayout