片段的条件自定义OnBackPress

问题描述 投票:0回答:1

我的应用程序有一个底部导航栏,可以打开内容,搜索和近期片段。因此,您可以通过在内容列表中找到“内部”片段,对其进行搜索或在最近的片段中对其进行充气。

基于您对这个“内部”片段的了解,我想在按下后退按钮时导航到内容/搜索/最近的片段。因此,我实现了一个类似于本文https://stackoverflow.com/a/46425415的onBackPress接口。效果很好。

然后,我尝试如下修改“内部”片段中实现的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

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

android android-fragments nullpointerexception conditional-statements onbackpressed
1个回答
0
投票

您应该从bottomNavigationView中找到视图Activity,请尝试此

bottomNavigationView = getActivity().findViewById(R.id.bottomNav)
© www.soinside.com 2019 - 2024. All rights reserved.