第一次后,视图分页器中的片段不会加载数据

时间:2019-02-15 13:32:27

标签: java android android-fragments android-viewpager

当我第一次打开3个片段中的一个加载其中的数据时,我有视图分页器包含3个片段,但是当我转到另一个片段并重新打开旧片段时,数据将不会加载。

这是viewpagerAdapter的代码:

public class ViewPagerAdapter extends FragmentPagerAdapter {
Context context;

public ViewPagerAdapter(FragmentManager fragmentManager, Context context) {
    super(fragmentManager);
    this.context = context;
}

/**
 * @return the number of pages to display
 */
@Override
public int getCount() {
    return 3;
}

// BEGIN_INCLUDE (pageradapter_getpagetitle)

/**
 * Return the title of the item at {@code position}. This is important as what this method
 * <p>
 * Here we construct one using the position value, but for real application the title should
 * refer to the item's contents.
 */
@Override
public CharSequence getPageTitle(int position) {
    String title = "";
    switch (position) {
        case 0:
            title = "تعلم";
            break;
        case 1:
            title = "الصفحة الرئيسية";
            break;
        case 2:
            title = "التحديات";
            break;
    }
    return title;
}
// END_INCLUDE (pageradapter_getpagetitle)

@Override
public Fragment getItem(int position) {
    switch (position) {
        case 0:
            return new ChallengersFragment();
        case 1:
            return new HomeFragment();
        case 2:
            return new ChallengesFragment();
    }

    return null;
}

}

1 个答案:

答案 0 :(得分:0)

我通过重写setUserVisibleHint方法解决了该问题并重新下载其中的数据。每次片段的可见性更改时,都会调用此方法。这是代码:

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {
        presenter.getUserData();
    }
}