我有一个ViewPager 2,它是一个水平的ImageView滚动器,它启用了自动滚动。这个自动滚动是用Timer.schedule()实现的。
我正在努力解决的问题是,我希望当包含该片段的片段不再对用户可见时,此自动滚动停止在那里,一旦用户恢复此片段,ViewPager应从它离开的同一位置开始自动滚动。
我的ViewPager代码:
public class ChannelPagerViewHolder extends RecyclerView.ViewHolder {
private static final int LIMIT = 7;
private static final @ViewPager2.OffscreenPageLimit int OFFSCREEN_PAGE_LIMIT = 2;
private Context mContext;
private LifecycleOwner mLifecycleOwner;
private ViewPager2 viewPager;
private LiveData<List<ChannelItem>> mChannelItemList;
private BannerAdapter bannerAdapter;
private Handler mHandler;
private int currentPage;
private int prevPageNumber;
public ChannelPagerViewHolder(View view, Context context, LifecycleOwner lifecycleOwner, int placement) {
super(view);
Log.d("ChannelPagerViewHolder","");
mContext = context;
mLifecycleOwner = lifecycleOwner;
viewPager = view.findViewById(R.id.view_pager);
viewPager.setOffscreenPageLimit(OFFSCREEN_PAGE_LIMIT);
viewPager.getLayoutParams().width =
(int) (Resources.getSystem().getDisplayMetrics().widthPixels);
viewPager.getLayoutParams().height =
viewPager.getLayoutParams().width / 2;
bannerAdapter = new BannerAdapter(mContext, placement);
viewPager.setAdapter(bannerAdapter);
viewPager.setClipToPadding(false);
viewPager.setPadding(24,0,24,0);
// Hack to make left and right banner visible.
RecyclerView recyclerView = ((RecyclerView) viewPager.getChildAt(0));
recyclerView.setClipToPadding(false);
UserEventLogger.getInstance(context).addImpressionLogger(
recyclerView,
placement
);
mHandler = new Handler();
currentPage = 0;
viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
super.onPageScrolled(position, positionOffset, positionOffsetPixels);
currentPage = position;
prevPageNumber = currentPage;
}
});
new Timer().schedule(
new TimerTask() {
@Override
public void run() {
mHandler.post(new Runnable() {
@Override
public void run() {
viewPager.setCurrentItem(currentPage++);
}
});
}
},
1000,
1000
);
}
}
ViewPager的用户界面:My ViewPager
任何帮助都将不胜感激!
1条答案
按热度按时间tpgth1q71#
由于您在RecyclerView的ViewHolder中使用
ViewPager
,因此需要将该特定项的ViewPager
的currentPosition
存储在某个地方,并在重新绑定该项时恢复它。我的解决方案是在类中使用一个可变字段来表示回收器视图的
Item
,并在每次ViewPager
的页面更改时将其设置为一个新位置,然后在将该项反弹到ViewHolder
时将其恢复。您的
Item
类可以是这样的:然后在你的
ViewHolder
里