【发布时间】:2023-03-22 08:12:01
【问题描述】:
我的应用有一个底部导航栏,可以打开内容、搜索和最近的片段。因此,您可以通过在内容列表中查找、搜索或在最近的内容中查找来扩充“内部”片段。
根据您如何找到这个“内部”片段,我想在按下后退按钮时导航到内容/搜索/最近的片段。因此,我实现了一个 onBackPress 接口,类似于本文:https://stackoverflow.com/a/46425415。这很好用。
然后我尝试修改“内部”片段中实现的 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
我不确定为什么会这样。是不是因为我只能从主要活动中观察底部导航视图,而不能从片段中观察?如果有人有任何建议,请告诉我!谢谢!
【问题讨论】:
-
bottomNavigationView = bottomNavigationView.findViewById(R.id.bottomNav);这行错误,bottomNavigationView在哪里初始化?在活动中对吗?
-
@CôngHải 是的,它在主要活动 xml 中
标签: android android-fragments nullpointerexception conditional-statements onbackpressed