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

解决NavigationView在非根布局DrawerLayout中使用match_parent定义宽高时出现的问题,通过自定义MyDrawerLayout并重写onMeasure方法,实现NavigationView正确显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

因为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小一点,待补充。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值