在另一个ViewPager的片段中检测ViewPager中的片段可见

时间:2017-08-23 03:16:44

标签: android android-fragments android-viewpager setuservisiblehint

例如,我有

MainActivity (contain a ViewPager)
  Fragment0
  Fragment1 (contain a ViewPager)
          Fragment1a
          Fragment1b
  Fragment2

我希望每次可见时都会刷新Fragment1a,因此我在setUserVisibleHint内使用Fragment1a但效果不佳。

当我在片段Fragment1aFragment1b之间切换时,setUserVisibleHint Fragment1a称为
但是当我从Fragment0 Fragment1Fragment2转到Fragment1 setUserVisibleHint Fragment1a (and Fragment1b) 未被称为 <时/ p>

如何检测Fragment1a (and Fragment1b)可见?任何帮助或建议都将非常感激。

1 个答案:

答案 0 :(得分:2)

setUserVisibleHint也不能正常工作我用另一种方式更新片段中的数据,当查看寻呼机更改片段时,下面就是这样,

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

                @Override
                public void onPageSelected(int position) {
                    try {
                        if(viewPagerAdapter.getItem(position) instanceof Fragment1a){
                            Fragment1a frag1 = (Fragment1a) viewPagerAdapter.getItem(position);
                            frag1.updateData(data); // here is the public method of fragment which declared for udpate data in fragment
                        }else if(viewPagerAdapter.getItem(position) instanceof Fragment1b){
                            Fragment1b frag2 = (Fragment1b) viewPagerAdapter.getItem(position);
                            frag2.updateData(data); // here is the public method of fragment which declared for udpate data in fragment
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onPageScrollStateChanged(int state) {
                }
            });
viewpager.setCurrentItem(0);

这样您可以直接更新数据只需要在片段中创建一个公共方法。

这是适配器

class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<TabModel> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFragment(Fragment fragment, TabModel title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position).getTabName();
        }

    }