首页 > 代码库 > Activity中通过标签获取当前Fragment

Activity中通过标签获取当前Fragment

初始化完成之后才有数据,否则获取不到

  String tag = "android:switcher:"+viewPager.getId()+":"+viewPager.getCurrentItem();

  Fragment fg = getSupportFragmentManager().findFragmentByTag(tag);

  if (fg == null) {
      return;
  }

  switch (viewPager.getCurrentItem()) {
      case 0:
                ((Fragment1)fg).updateUI();
            break;
      case 1:
              ((Fragment2) fg).upDateUI();
         break;
      case 2:
          ((Fragment3) fg).upDateUI();
          break;

  }

 

//ViewPage滑动变化监听

 viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
             //   doSomething
            }

            @Override
            public void onPageSelected(int position) {
                     switch (position){
                      case 0:
                     //   doSomething
                          break;
                      case 1:
                         //   doSomething

                   break;
                      case 2:
                          //   doSomething
                          break;
                  }
              }

            @Override
            public void onPageScrollStateChanged(int state) {
                //完全隐藏或显示时
                if (state == 0) {
                      //   doSomething
                }
             }
     });

 

Activity中通过标签获取当前Fragment