Drawer 拖拉方向設定


在 DrawerLayout 下使用 layout_gravity 來決定拖拉方向
layout_gravity:
  該屬性是指該佈局在父佈局是從何處對齊,在 DrawerLayout 下只能選 start (left) 、 end (right) 或是
  不設置,否則會使程序崩潰(笑 

tools:openDrawer
  該屬性是允許在預覽(Preview pane of the layout editor)時就觀看導航欄拉開的樣子一樣可選擇
  start (left) 、 end (right) 或是不設置

可以看到內部實現拿取要拖拉的畫面時的function
DrawerLayout.kt
/**
     * @param gravity the gravity of the child to return. If specified as a
     *            relative value, it will be resolved according to the current
     *            layout direction.
     * @return the drawer with the specified gravity
     */
    View findDrawerWithGravity(int gravity) {
        final int absHorizGravity = GravityCompat.getAbsoluteGravity(
                gravity, ViewCompat.getLayoutDirection(this)) & Gravity.HORIZONTAL_GRAVITY_MASK;
        final int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            final View child = getChildAt(i);
            final int childAbsGravity = getDrawerViewAbsoluteGravity(child);
            if ((childAbsGravity & Gravity.HORIZONTAL_GRAVITY_MASK) == absHorizGravity) {
                return child;
            }
        }
        return null;
    }

接著先看看原來的效果,基本的導航欄



原來的程式碼:

activity_main.xml

<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.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:menu="@menu/activity_main_drawer"/>

</android.support.v4.widget.DrawerLayout>


修改過後
app_bar_main android:layout_gravity="start"
navigation_view android:layout_gravity="end"




留言

熱門文章