【问题标题】:Conditional Custom OnBackPress for Fragment片段的条件自定义 OnBackPress
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • 非常感谢!我已经尝试解决这个问题好几个小时了;终于解决了:)
猜你喜欢
  • 2020-08-22
  • 1970-01-01
  • 2013-03-16
  • 1970-01-01
  • 2022-01-02
  • 1970-01-01
  • 1970-01-01
  • 2019-10-24
  • 2012-05-22
相关资源
最近更新 更多