如何在tabbar布局中仅加载一个选项卡

时间:2016-11-06 16:17:55

标签: java android

这是我的onCreate()方法。我想在实例上只加载一个选项卡。但它也会加载下一个标签。如何在调用此页面时只加载一个选项卡。如果我滑动到下一个标签,它应该只加载。

        View x =  inflater.inflate(R.layout.tab_layout,null);
        tabLayout = (TabLayout) x.findViewById(R.id.tabs);
        viewPager = (ViewPager) x.findViewById(R.id.viewpager);
        setupViewPager(viewPager); 
        tabLayout = (TabLayout) x.findViewById(R.id.tabs);
        if (tabLayout != null) {
            tabLayout.setupWithViewPager(viewPager);
        }
        setupTabIcons();
        return x;
     }
    private void setupTabIcons() {
        tabLayout.getTabAt(0).setIcon(tabIcons[0]);
        tabLayout.getTabAt(1).setIcon(tabIcons[1]);
        tabLayout.getTabAt(2).setIcon(tabIcons[2]);
        tabLayout.getTabAt(3).setIcon(tabIcons[3]);
        tabLayout.getTabAt(4).setIcon(tabIcons[4]);
    }
      private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getFragmentManager());
        adapter.addFrag(new Text(), "Text");
        adapter.addFrag(new Image(), "Image");
        adapter.addFrag(new Audio(), "Audio");
        adapter.addFrag(new Video(), "Video");
        adapter.addFrag(new Files(), "File");
        viewPager.setAdapter(adapter);
    }
   class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

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

        @Override
        public Fragment getItem(int position) {
            System.out.println("Tab set issssssssssss"+position);
            return mFragmentList.get(position);
        }

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

        public void addFrag(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }
    @Override public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
    }

}

1 个答案:

答案 0 :(得分:0)

声明:

boolean hasVisitedFragmentOnce=false;

现在将 setUserVisibleHint()功能更改为以下内容:

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {

    super.setUserVisibleHint(isVisibleToUser);

    if (isVisibleToUser && !hasVisitedFragmentOnce) {

        hasVisitedFragmentOnce = true;
        //do your stuff

    } else {

        // fragment is no longer visible

    }
}