FragmentManager 字段空 android

FragmentManager field null android

所以我试图通过单击 BottomNavigationView 中的一个选项卡切换到另一个片段,但我一直收到 NullPointer 异常。

我尝试将 xml 文件中的 fragment 标记更改为 androidx.fragment.app.FragmentContainerView,但我仍然遇到相同的错误。

Logcat:

java.lang.NullPointerException: Attempt to read from field 'androidx.fragment.app.FragmentManager androidx.fragment.app.Fragment.mFragmentManager' on a null object reference
        at androidx.fragment.app.BackStackRecord.hide(BackStackRecord.java:201)
        at com.murkoff.MusicPlayer.MainActivity.onNavigationItemChanged(MainActivity.java:214)
        at com.volcaniccoder.bottomify.BottomifyNavigationView.selectItem(BottomifyNavigationView.kt:240)
        at com.volcaniccoder.bottomify.BottomifyNavigationView.access$selectItem(BottomifyNavigationView.kt:19)
        at com.volcaniccoder.bottomify.BottomifyNavigationView$addListener.onTouch(BottomifyNavigationView.kt:207)
        at android.view.View.dispatchTouchEvent(View.java:11830)
        at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2994)
        at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2659)
        at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3000)
        at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2673)
        at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3000)
        at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2673)
        at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3000)
        at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2673)
        at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3000)
        at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2673)
        at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3000)
        at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2673)
        at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3000)
        at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2673)
        at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3000)
        at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2673)
        at com.android.internal.policy.DecorView.superDispatchTouchEvent(DecorView.java:592)
        at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1977)
        at android.app.Activity.dispatchTouchEvent(Activity.java:3405)
        at androidx.appcompat.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:69)
        at com.android.internal.policy.DecorView.dispatchTouchEvent(DecorView.java:548)
        at android.view.View.dispatchPointerEvent(View.java:12095)
        at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:4966)
        at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4761)
        at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4259)
        at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4329)
        at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4287)
        at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4429)
        at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4295)
        at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:4486)
        at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4259)
        at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4329)
        at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4287)
        at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4295)
        at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4259)
        at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:6854)
        at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:6828)
        at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:6783)
        at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:6966)
        at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:194)
        at android.os.MessageQueue.nativePollOnce(Native Method)
        at android.os.MessageQueue.next(MessageQueue.java:329)
        at android.os.Looper.loop(Looper.java:150)
2021-03-06 01:12:37.661 27094-27094/com.murkoff.MusicPlayer E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:6702)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:826)

xml 为 activity:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.motion.widget.MotionLayout
        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="@android:color/black"
        android:id="@+id/activity_main_motionlayout_test_container"
        tools:context=".MainActivity" app:layoutDescription="@xml/activity_main_motionlayout_test_scene">


    <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="0dp"
                                                       android:layout_height="0dp"
                                                       app:layout_constraintStart_toStartOf="parent"
                                                       app:layout_constraintEnd_toEndOf="parent"
                                                       app:layout_constraintBottom_toTopOf="@+id/main_bottom_nav_bar"
                                                       android:id="@+id/main_activity_fragment_container"
                                                       app:layout_constraintTop_toTopOf="parent">
        <androidx.fragment.app.FragmentContainerView
                android:layout_width="0dp"
                android:layout_height="0dp" android:name="com.murkoff.MusicPlayer.HomeFragment"
                android:id="@+id/fragment_tag" tools:layout="@layout/fragment_home"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHorizontal_bias="1.0"
                app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintTop_toTopOf="parent"/>

    </androidx.constraintlayout.widget.ConstraintLayout>


    <com.volcaniccoder.bottomify.BottomifyNavigationView android:layout_width="match_parent"
                                                         android:layout_height="60dp"
                                                         android:id="@+id/main_bottom_nav_bar"
                                                         android:background="#0E0E0E"
                                                         android:elevation="8dp"
                                                         app:menu="@menu/main_menu_bottom_bar"
                                                         app:item_text_size="13sp"
                                                         app:active_color="@color/bottomifyActiveColor"
                                                         app:passive_color="@color/bottomifyPassiveColor"
                                                         app:pressed_color="@color/bottomifyPressedColor"
                                                         android:orientation="horizontal"
                                                         app:layout_constraintBottom_toBottomOf="parent"
                                                         app:layout_constraintEnd_toEndOf="parent"
                                                         android:gravity="center_vertical"/>

</androidx.constraintlayout.motion.widget.MotionLayout>

Activity:

我正在使用 fragment1、fragment2、fragment3、fragment4 变量来防止重新创建片段,如

中所示
public class MainActivity extends AppCompatActivity{
   BottomifyNavigationView navigationView;

   HomeFragment fragment1;
   SearchFragment fragment2;
   PlaylistsFragment fragment3;
   SettingsFragment fragment4;

    final FragmentManager fragmentManager = getSupportFragmentManager();

    Fragment active = fragment1;

    boolean added = false;

    FragmentManager mFragmentManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main_motionlayout);

        if(fragmentManager!=null) {
            mFragmentManager = fragmentManager;
            Log.d("main activity", "fragment manager not null");
        }

        navigationView = findViewById(R.id.main_bottom_nav_bar);

        fragment1 = new HomeFragment();
        fragment2 = new SearchFragment();
        fragment3 = new PlaylistsFragment();
        fragment4 = new SettingsFragment();
        
    }

@Override
    protected void onStart() {
        super.onStart();

        if(!added) {
            fragmentManager.beginTransaction().add(R.id.main_activity_fragment_container_motionlayout, fragment4, "4").hide(fragment4).commit();
            fragmentManager.beginTransaction().add(R.id.main_activity_fragment_container_motionlayout, fragment3, "3").hide(fragment3).commit();
            fragmentManager.beginTransaction().add(R.id.main_activity_fragment_container_motionlayout, fragment2, "2").hide(fragment2).commit();
            fragmentManager.beginTransaction().add(R.id.main_activity_fragment_container_motionlayout, fragment1, "1").commit();
            added = true;
        }

        navigationView.setOnNavigationItemChangedListener(new OnNavigationItemChangeListener() {
            @Override
            public void onNavigationItemChanged(@NonNull BottomifyNavigationView.NavigationItem navigationItem) {
                switch(navigationItem.getPosition()){
                    case 0:
                        mFragmentManager.beginTransaction().hide(active).show(fragment1).commit();
                        active = fragment1;
                        break;

                    case 1:
                        Log.d("fragment", "commiting");
                        mFragmentManager.beginTransaction().hide(active).show(fragment2).commit();
                        active = fragment2;
                        break;

                    case 2:
                        mFragmentManager.beginTransaction().hide(active).show(fragment3).commit();
                        active = fragment3;
                        break;

                    case 3:
                        mFragmentManager.beginTransaction().hide(active).show(fragment4).commit();
                        active = fragment4;
                        break;
                }

            }
        });

    }
}

我该如何解决这个问题? 感谢您的帮助!

在class初始化期间不能调用final FragmentManager fragmentManager = getSupportFragmentManager();,因为superclass中的片段管理器还没有初始化。删除所有 class 成员并将所有 mFragmentManagerfragmentManager 替换为 getSupportFragmentManager()

使用导航图定义片段

build.gragle

dependencies {
...
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'androidx.core:core-ktx:1.0.2'
    implementation 'com.google.android.material:material:1.1.0-alpha10'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.navigation:navigation-fragment:2.0.0'
    implementation 'androidx.navigation:navigation-ui:2.0.0'
    implementation 'androidx.lifecycle:lifecycle-extensions:2.1.0'
    implementation 'androidx.navigation:navigation-fragment-ktx:2.0.0'
    implementation 'androidx.navigation:navigation-ui-ktx:2.0.0'
}

MainActivity.kt

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.findNavController
import androidx.navigation.ui.NavigationUI
import androidx.navigation.ui.setupWithNavController
import kotlinx.android.synthetic.main.activity_main1.*
    class MainActivity : AppCompatActivity() {
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
    
            val navController = findNavController(R.id.nav_host_fragment)
            bottomNavigationView_activityMain.setupWithNavController(navController)
            bottomNavigationView_activityMain.setOnNavigationItemSelectedListener {
                NavigationUI.onNavDestinationSelected(it, navController)
                true
            }
        }
    }

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="?attr/actionBarSize">

    <fragment
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toTopOf="@id/bottomNavigationView_activityMain"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/nav_graph" />

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottomNavigationView_activityMain"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="0dp"
        android:layout_marginEnd="0dp"
        android:background="?android:attr/windowBackground"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/bottom_nav_menu" />

</androidx.constraintlayout.widget.ConstraintLayout>

bottom_nav_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/navigation_home"
        android:icon="@drawable/ic_home_black_24dp"
        android:title="@string/home" />

    <item
        android:id="@+id/navigation_gallery"
        android:icon="@drawable/ic_menu_gallery"
        android:title="@string/gallery" />

    <item
        android:id="@+id/navigation_slideshow"
        android:icon="@drawable/ic_menu_slideshow"
        android:title="@string/slideshow" />
    
</menu>

nav_graph.xml

<?xml version="1.0" encoding="utf-8"?>
<navigation 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/mobile_navigation"
    app:startDestination="@id/navigation_home">

    <fragment
        android:id="@+id/navigation_home"
        android:name="com.pkg.android_navigation_sample.ui.home.HomeFragment"
        android:label="@string/home"
        tools:layout="@layout/fragment_home" />

    <fragment
        android:id="@+id/navigation_gallery"
        android:name="com.pkg.android_navigation_sample.ui.gallery.GalleryFragment"
        android:label="@string/gallery"
        tools:layout="@layout/fragment_gallery" />

    <fragment
        android:id="@+id/navigation_slideshow"
        android:name="com.pkg.android_navigation_sample.ui.slideshow.SlideshowFragment"
        android:label="@string/slideshow"
        tools:layout="@layout/fragment_slideshow" />

</navigation>

其他示例:https://github.com/android/architecture-components-samples/blob/main/NavigationAdvancedSample/app/src/main/java/com/example/android/navigationadvancedsample/MainActivity.kt