Android百分比布局(PercentRelativeLayout)嵌套NavigationView自定义宽度

故事扮演 提交于 2019-12-20 15:16:21

因为NavigationView必须嵌套在DrawerLayout里,当DrawerLayout不是根布局时,就没办法用match_parent等定义宽高,会报错。所以要重写DrawerLayout的onMeasure()方法:

public class MyDrawerLayout extends DrawerLayout {
    public MyDrawerLayout(@NonNull Context context) {
        super(context);
    }

    public MyDrawerLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public MyDrawerLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        widthMeasureSpec = MeasureSpec.makeMeasureSpec(
                MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.EXACTLY);
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(
                MeasureSpec.getSize(heightMeasureSpec), MeasureSpec.EXACTLY);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}

(以上代码copy的)

然后进行嵌套布局:

<android.support.percent.PercentRelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <hyjob.dhcc.com.test_1.MyDrawerLayout
        app:layout_widthPercent="70%"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true">

        <android.support.design.widget.NavigationView
            android:id="@+id/menu"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            app:headerLayout="@layout/layout_menu_header"
            app:menu="@menu/menu" />
    </hyjob.dhcc.com.test_1.MyDrawerLayout>
</android.support.percent.PercentRelativeLayout>

但是吧,NavigationView的宽度要比DrawerLayout小一点,待补充。

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!