ViewPager2.setOffscreenPageLimit () проблема

API 30 Android 10.0+ (Google API), AVD (x86)

Проблема в том ... Просто для проверки ViewPager2. Я использовал ViewPager2 с TabLayout и прикрепленными фрагментами. Затем я установил «предельное значение страницы вне экрана» на 1. Я ожидал, что будет сохранено 3 страницы. (текущая, левая, правая страница) Но сохраняется около 6 страниц. Когда я использую предыдущий ViewPager, он работает хорошо.

Я прочитал ... Я прочитал документ на ‹веб-сайте разработчиков Android ›. Но я не могу найти причину вышеуказанной проблемы, и я не знаю, что «OFFSCREEN_PAGE_LIMIT_DEFAULT» в документе означает, сколько страниц нужно поддерживать. Он определяется просто -1.

Код ...

public class MainActivity extends AppCompatActivity { 
    private TabLayout tabLayout; 
    private ViewPager2 viewPager; 
    private ViewPagerAdapter viewPagerAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tabLayout = findViewById(R.id.tabLayout);
        viewPager = findViewById(R.id.viewPager);

        viewPager.setOffscreenPageLimit(1);
        viewPager.setAdapter(new ViewPagerAdapter(this, 9));

        new TabLayoutMediator(tabLayout, viewPager, new TabLayoutMediator.TabConfigurationStrategy() {
            @Override public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                tab.setText("Tab " + (position + 1));
            }
        }).attach();
    }
}

person tomo622    schedule 05.09.2020    source источник
comment
Мне это кажется ошибкой. Я создал для этого отчет в IssueTracker, здесь.   -  person Adil Hussain    schedule 19.10.2020
comment
@AdilHussain Вы решили эту проблему?   -  person tomo622    schedule 03.11.2020
comment
Нет, я просто вернулся к тому, чтобы полагаться на лимит страниц вне экрана по умолчанию, а не на вызов этого установщика. Для меня это не было большой проблемой.   -  person Adil Hussain    schedule 03.11.2020
comment
@AdilHussain Я тоже, я хотел убедиться, что это моя ошибка.   -  person tomo622    schedule 04.11.2020


Ответы (1)


У меня такая же проблема. Я решил использовать следующий код при использовании setOffscreenPageLimit(1):

/**
 * Sets whether the LayoutManager should be queried for views outside of
 * its viewport while the UI thread is idle between frames.
 *
 * <p>If enabled, the LayoutManager will be queried for items to inflate/bind in between
 * view system traversals on devices running API 21 or greater. Default value is true.</p>
 *
 * <p>On platforms API level 21 and higher, the UI thread is idle between passing a frame
 * to RenderThread and the starting up its next frame at the next VSync pulse. By
 * prefetching out of window views in this time period, delays from inflation and view
 * binding are much less likely to cause jank and stuttering during scrolls and flings.</p>
 *
 * <p>While prefetch is enabled, it will have the side effect of expanding the effective
 * size of the View cache to hold prefetched views.</p>
 *
 * @param enabled <code>True</code> if items should be prefetched in between traversals.
 *
 * @see #isItemPrefetchEnabled()
 */
RecyclerView.LayoutManager layoutManager =  ((RecyclerView)(viewPager.getChildAt(0))).getLayoutManager();
if(layoutManager != null) {
    layoutManager.setItemPrefetchEnabled(false);
}


/**
 * Set the number of offscreen views to retain before adding them to the potentially shared
 * {@link #getRecycledViewPool() recycled view pool}.
 *
 * <p>The offscreen view cache stays aware of changes in the attached adapter, allowing
 * a LayoutManager to reuse those views unmodified without needing to return to the adapter
 * to rebind them.</p>
 *
 * @param size Number of views to cache offscreen before returning them to the general
 *             recycled view pool
 */ 
RecyclerView recyclerView=  ((RecyclerView)(viewPager.getChildAt(0)));
if(recyclerView != null) {
    recyclerView.setItemViewCacheSize(0);
}
person Sabrina N    schedule 10.07.2021