片段的条件自定义 OnBackPress

Conditional Custom OnBackPress for Fragment

我的应用程序有一个底部导航栏,可以打开内容、搜索和最近的片段。因此,您可以通过在内容列表中查找、向上搜索或最近查找来扩充 "inner" 片段。

根据您到达此 "inner" 片段的方式,我想在按下后退按钮时导航至 contents/search/recent 片段。因此,我实现了一个 onBackPress 接口,类似于这篇文章:。这很好用。

然后我尝试修改 "inner" 片段中实现的 onBackPress 如下:

@Override
public boolean onBackPressed() {

    bottomNavigationView = bottomNavigationView.findViewById(R.id.bottomNav);

    if (getView() != null && bottomNavigationView.getSelectedItemId()==R.id.nav_content) {
        FragmentTransaction fr = getFragmentManager().beginTransaction();
        fr.replace(R.id.fragmentContainer, new ContentFragment());
        fr.commit();
        return true;}
   else if (getView() != null && selectedItemId==R.id.nav_recents) {
        FragmentTransaction fr = getFragmentManager().beginTransaction();
        fr.replace(R.id.fragmentContainer, new FragmentRecents());
        fr.commit();
        return true;
    } else if (getView() != null && selectedItemId==R.id.nav_search) {
        FragmentTransaction fr = getFragmentManager().beginTransaction();
        fr.replace(R.id.fragmentContainer, new FragmentSearch());
        fr.commit();
        return true;
    } else {return false;}

这导致应用程序在我按返回键时崩溃。

java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View com.google.android.material.bottomnavigation.BottomNavigationView.findViewById(int)' on a null object reference

我不确定为什么会这样。是不是因为我只能从 main activity 观察底部导航视图,而不能从片段观察?如果有人有任何建议,请告诉我!谢谢!

您应该从 Activity 中找到视图 bottomNavigationView 试试这个

bottomNavigationView = getActivity().findViewById(R.id.bottomNav)