首页 > 解决方案 > 从 API 27 弃用 FragmentStatePagerAdapter

问题描述

FragmentStatePagerAdapter已从 API 27 中弃用。有什么替代方法FragmentStatePagerAdapter

private class MainPagerAdapter extends FragmentStatePagerAdapter {

    MainPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        Fragment result = new DummyFragment();
        return result;
    }

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

}

上面的代码显示FragmentStatePagerAdapter,getItem(...)super(...)已弃用。

标签: androidandroid-support-libraryfragmentstatepageradapter

解决方案


切换到ViewPager2并改用FragmentStateAdapter

从那里您可以使用 onPause 和 onResume 回调来确定当前对用户可见的片段。当一个片段变得可见时调用 onResume,当它停止可见时调用 onPause。->阅读更多

基于EricReejesh的评论。


旧答案(现在也已弃用)

以下构造函数做同样的事情

super(@NonNull FragmentManager fm)
super(@NonNull FragmentManager fm, BEHAVIOR_SET_USER_VISIBLE_HINT)

传递BEHAVIOR_SET_USER_VISIBLE_HINT已被弃用。你应该通过BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT

通过这些的差异在以下内容中进行了解释FragmentPagerAdapter

 /**
 * Indicates that Fragment#setUserVisibleHint(boolean) will be 
 * called when the current fragment changes.
 */
@Deprecated
public static final int BEHAVIOR_SET_USER_VISIBLE_HINT = 0;

/**
 * Indicates that only the current fragment will be 
 * in the Lifecycle.State#RESUMED state. All other Fragments 
 * are capped at Lifecycle.State#STARTED.
 */
public static final int BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT = 1;

推荐阅读