You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

BottomSheetBehavior获取为空引发空指针异常问题求助

Android底部弹出导航抽屉空指针问题解决

问题场景

开发Android应用时,尝试通过BottomAppBar与NavigationView组合实现底部弹出导航抽屉,已在布局中为NavigationView配置app:layout_behavior="com.google.android.material.bottomsheet.BottomSheetBehavior"属性,但在代码中调用bottomSheetBehavior.addBottomSheetCallback时触发空指针异常,提示BottomSheetBehavior对象为null。

相关代码

布局代码

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#C4C4C4">

    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="?attr/actionBarSize">

        <FrameLayout
            android:id="@+id/scrim"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

        <com.google.android.material.navigation.NavigationView
            android:id="@+id/nav_host_fragment_apoya_test"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_behavior="com.google.android.material.bottomsheet.BottomSheetBehavior"
            app:behavior_hideable="true"/>

    </androidx.coordinatorlayout.widget.CoordinatorLayout>

    <com.google.android.material.bottomappbar.BottomAppBar
        android:id="@+id/bottomAppBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:background="@color/white"
        app:menu="@menu/bottom_nav_menu_apoya"
        app:navigationIcon="@drawable/ic_menu_24"/>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

逻辑代码

navigationViewTest = findViewById(R.id.nav_host_fragment_apoya_test);
bottomAppBar = findViewById(R.id.bottomAppBar);
bottomAppBar.setNavigationOnClickListener(this);

bottomSheetBehavior.from(navigationViewTest);
//bottomSheetBehavior.setPeekHeight(ActionBar);
// 此处触发空指针
bottomSheetBehavior.addBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
    @Override
    public void onStateChanged(@NonNull View bottomSheet, int newState) {

        if (newState == BottomSheetBehavior.STATE_EXPANDED) {
            Toast.makeText(MainActivityApoyaLogin.this, "Expandido", Toast.LENGTH_SHORT).show();
        }

        if (newState == BottomSheetBehavior.STATE_COLLAPSED) {
            Toast.makeText(MainActivityApoyaLogin.this, "Oculto", Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    public void onSlide(@NonNull View bottomSheet, float slideOffset) {

        // Si tuvieramos un float button aqui lo ocultariamos

    }

});

报错信息

2022-09-01 18:33:59.866 11708-11708/com.seccion.seccin15hibrida E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.seccion.seccin15hibrida, PID: 11708
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.seccion.seccin15hibrida/com.seccion.seccin15hibrida.uiCajaSession.InicioCajaA.CajaApoyaBeta.MainActivityApoyaLogin}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.material.bottomsheet.BottomSheetBehavior.addBottomSheetCallback(com.google.android.material.bottomsheet.BottomSheetBehavior$BottomSheetCallback)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.material.bottomsheet.BottomSheetBehavior.addBottomSheetCallback(com.google.android.material.bottomsheet.BottomSheetBehavior$BottomSheetCallback)' on a null object reference
        at com.seccion.seccin15hibrida.uiCajaSession.InicioCajaA.CajaApoyaBeta.MainActivityApoyaLogin.onCreate(MainActivityApoyaLogin.java:49)
        at android.app.Activity.performCreate(Activity.java:7994)
        at android.app.Activity.performCreate(Activity.java:7978)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)

问题原因及解决方法

核心问题

代码中调用BottomSheetBehavior.from(navigationViewTest)时,未将返回的BottomSheetBehavior实例赋值给bottomSheetBehavior变量,导致该变量始终为null,后续调用addBottomSheetCallback触发空指针异常。

修复步骤

  1. 正确赋值BottomSheetBehavior实例
    将逻辑代码中的bottomSheetBehavior.from(navigationViewTest);修改为:

    bottomSheetBehavior = BottomSheetBehavior.from(navigationViewTest);
    

    确保变量接收from()方法返回的有效实例。

  2. 补充初始化(可选)
    可给bottomSheetBehavior设置默认折叠高度,适配底部栏高度:

    bottomSheetBehavior.setPeekHeight(getActionBar() != null ? getActionBar().getHeight() : getResources().getDimensionPixelSize(R.dimen.default_peek_height));
    

修改后的完整逻辑代码片段:

navigationViewTest = findViewById(R.id.nav_host_fragment_apoya_test);
bottomAppBar = findViewById(R.id.bottomAppBar);
bottomAppBar.setNavigationOnClickListener(this);

// 修复:正确获取BottomSheetBehavior实例
bottomSheetBehavior = BottomSheetBehavior.from(navigationViewTest);
// 设置折叠高度,适配底部栏
bottomSheetBehavior.setPeekHeight(getActionBar() != null ? getActionBar().getHeight() : getResources().getDimensionPixelSize(R.dimen.default_peek_height));

bottomSheetBehavior.addBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
    @Override
    public void onStateChanged(@NonNull View bottomSheet, int newState) {

        if (newState == BottomSheetBehavior.STATE_EXPANDED) {
            Toast.makeText(MainActivityApoyaLogin.this, "已展开", Toast.LENGTH_SHORT).show();
        }

        if (newState == BottomSheetBehavior.STATE_COLLAPSED) {
            Toast.makeText(MainActivityApoyaLogin.this, "已收起", Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    public void onSlide(@NonNull View bottomSheet, float slideOffset) {
        // 可在此处理滑动过程中的UI变化,比如隐藏悬浮按钮
    }
});

内容的提问来源于stack exchange,提问作者Enrique Espinosa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 07:54:26