我有一种情况,当应用关闭或调用onDestroy()
时,我需要销毁ViewPager上的项目,但是ViewPager中没有API可以扩展PagerAdapter。 destroyItem()
仅在滑动页面时被调用,这取决于要保存在mViewPager.setOffscreenPageLimit(int)
中的页面数。有没有一种方法可以强制ViewPager调用destroyItem()
?
答案 0 :(得分:1)
我假设您的课程是从名为MyPagerAdapter的PagerAdapter扩展的。
MyPagerAdapter.java
public class MyPageAdapter extends FragmentPagerAdapter {
...
}
MainActivity.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);
}
}