如何在android中刷新Pager选项卡片段?

时间:2017-09-13 06:38:56

标签: android android-fragments android-viewpager android-tablayout

当我从标签中滑动到另一个fragment时,我必须刷新fragment

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);
}


@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);

    mBinding = DataBindingUtil.inflate(inflater, R.layout.manage_work_shop_act, container, false);


    mBinding.layout.title.setText(getString(R.string.d_manage_my_staff));

    mBinding.tabs.setupWithViewPager(mBinding.viewpager);
    setupViewPager(mBinding.viewpager);

    mBinding.layout.nav.setVisibility(View.GONE);
    mBinding.layout.navMenu.setVisibility(View.VISIBLE);

    mBinding.layout.navMenu.setOnClickListener(view -> openDrawer());

    return mBinding.getRoot();
}


private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getChildFragmentManager());

    int limit = (adapter.getCount() > 1 ? adapter.getCount() - 1 : 1);

    adapter.addFragment(new MechanicListFragment(), getString(R.string.d_manage_my_staff));
    adapter.addFragment(new MechanicNewFragment(), getString(R.string.new_frag));
    viewPager.setAdapter(adapter);
    viewPager.setOffscreenPageLimit(limit);

    adapter.notifyDataSetChanged();
}

我的适配器就像这样

public 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) {
    return mFragmentList.get(position);
}

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

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

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

我尝试了所有方法来刷新fragment。 如果我滑动选项卡或单击另一个选项卡,则需要再次刷新可见选项卡。 在我当前的fragment没有刷新。

请帮我改写这个问题。

2 个答案:

答案 0 :(得分:0)

当您必须刷新适配器中的选项卡时,请尝试使用片段状态寻呼机适配器而不是片段适配器。

FragmentPagerAdapter存储从适配器获取的先前数据,而FragmentStatePagerAdapter每次执行时都从适配器获取新值。

答案 1 :(得分:0)

片段中有onHiddenChanged方法。

  

当隐藏状态(由isHidden()返回时调用)   片段已经改变了。片段开始没有隐藏;这将会   每当片段改变状态时调用。

覆盖每个标签片段中的onHiddenChanged方法,如果未隐藏,请执行刷新。例如:

class YourFragment extends Fragment {

    @Override public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            //you can refresh here now
        }
    }

}