因为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小一点,待补充。
来源:CSDN
作者:月圆时立夏
链接:https://blog.csdn.net/gsmmSummer/article/details/103631656