使用了Navigation,则必然存在一个NavHostFragment,其它的Fragment都是它的子Fragment,所以,想获取其它fragment,就要从它的子fragment中获取,参考示例:
- //先获取NavHostFragment
- Fragment mMainNavFragment = getSupportFragmentManager().findFragmentById(nav_host_fragment_content_main);
- //再获取当前的Fragment
- Fragment fra = mMainNavFragment.getChildFragmentManager().getPrimaryNavigationFragment();
- //判断当前的fragment是否是自己想要的Fragment
- if (fra instanceof ScanFragment) {
- //如果是,就转成目标Fragment,就可以调用它的公开方法及公开属性
- ScanFragment fra=(ScanFragment)frag;
- //调用该frangment的公开方法
- fra.Reset();
- }
参考:https://www.zhihu.com/question/360688235/answer/974850558