我有一个场景,我需要在应用程序关闭或调用onDestroy()
时销毁ViewPager上的项目,但在ViewPager中没有API可以扩展PagerAdapter。 destroyItem()
只在刷页时被调用,这取决于在mViewPager.setOffscreenPageLimit(int)
中保存多少页。有没有办法强制ViewPager调用destroyItem()
?
我假设您的类从PagerAdapter扩展名为MyPagerAdapter。
my pager adapter.Java
public class MyPageAdapter extends FragmentPagerAdapter {
...
}
main activity.Java
public class MainActivity extends AppCompatActivity {
ViewPager viewPager;
MyPageAdapter pagerAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pagerAdapter = new MyPageAdapter(getSupportFragmentManager());
viewPager = findViewById(R.id.viewpager);
viewPager.setAdapter(pagerAdapter);
}
@Override
protected void onDestroy() {
// For example, call destroyItem when activity get destroyed.
forceDestroyCurrentItemInViewPager();
super.onDestroy();
}
// Call this method to call destroyItem() for current item in view pager.
private void forceDestroyCurrentItemInViewPager() {
int position = viewPager.getCurrentItem();
Object object = pagerAdapter.getItem(position);
pagerAdapter.destroyItem(viewPager, position, object);
}
}