業務場景:有的時候我們的頁面可能是Activity 嵌套多個Fragment ..其中某個Fragment 又嵌套多個Fragment。
其中某個子Fragment 定義為 NewsFragment 。父容器 Fragment 定義為 ShouYeMainFragment
ShouYeMainFragment 嵌套 NewsFragment 。此時如果NewsFragment 想調用 ShouYeMainFragment 里面的方法怎么做呢?
解決辦法:
通過NewsFragment 獲取 父類Fragment 的容器管理器的所有Fragment 集合。然后 遍歷。找到父容器Fragment.執行它的方法。
代碼如下:
List<Fragment>list=(List<Fragment>)NewsFragment.this.getFragmentManager().getFragments(); for(Fragment f:list){ if(f!=null&&f instanceof ShouYeMainFragment){ ((ShouYeMainFragment) f).changView(); break; } }