TabLayout预加载下一个选项卡

时间:2017-03-02 16:43:25

标签: android android-viewpager android-tablayout android-pageradapter

我有一个带有ViewPager的tablayout(tab1,tab2,tab3)。似乎在app启动时tab2是预加载的,这很好。

但是,我需要在tab1上输入一些数据,我希望tab2更新其片段并根据tab1的数据输入隐藏一些按钮。

怎么做?有没有办法不预加载选项卡,以便当我滑动到tab2时,它将获取最新数据而不是旧数据?

这是我的代码

private ViewPager viewPager;
private PagerAdapter adapter;
private TabLayout tabLayout;

在活动中的onCreate方法中。

    tabLayout.addTab(tabLayout.newTab().setText("Input"));
    tabLayout.addTab(tabLayout.newTab().setText("Detail"));
    tabLayout.addTab(tabLayout.newTab().setText("Chart"));
    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

    viewPager = (ViewPager) findViewById(R.id.pager);
    adapter = new PagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
    viewPager.setAdapter(adapter);
    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });

这是我的pageadapater课程

public class PagerAdapter extends FragmentPagerAdapter {
int mNumOfTabs;
private InputFragment inputFragment;
private DetailFragment detailFragment;
private ChartFragment chartFragment;

public PagerAdapter(FragmentManager fm, int NumOfTabs) {
    super(fm);
    this.mNumOfTabs = NumOfTabs;
}

@Override
public int getItemPosition(Object object) {
    // TODO Auto-generated method stub
    return POSITION_NONE;
}


@Override
public Fragment getItem(int position) {
    switch (position) {
        case 0:
            inputFragment = new InputFragment();
            return inputFragment;
        case 1:
            detailFragment = new detailFragment();
            return detailFragment;
        case 2:
            chartFragment = new ChartFragment();
            return chartFragment;
        default:
            return null;
    }
}

@Override
public int getCount() {
    return mNumOfTabs;
}
}

1 个答案:

答案 0 :(得分:1)

在您的detailfragment片段

@Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {
//check values on tab 1 and try to update your tab 2 views accordingly
    }
    }