Android实现无限循环滚动
传统的ViewPager做循环滚动有两种思路。
一种是设置count为Integer.MAX,然后根据index对实际数量取模
一种是在开头在开头添加end,在末尾添加start。简单的说就是多两个,滑动到这两个的时候直接setCurrentItem到真正的位置。
在观察pdd的拼单的循环滚动的时候,想到几种实现方式。
1、通过Recyclerview,同样跟ViewPager做循环滚动的思路类似,多一点要拦截掉所有的触摸事件。但是这种方式的话无法像pdd的效果那样设置进入和出去的动画。
2、通过改造VerticalViewpager的形式,应该也是可以的,但是感觉比较麻烦。
3、通过自定义的方式实现。(原本以为挺简单的,实现了下,代码不多但是有些小细节需要注意下。)
我选择了自定义的这里只是一个demo,提供一种思路。
最核心的就是上面的item滑出屏幕的时候将它remove掉然后再加到自定义的ViewGroup的末尾。
publicclassLoopViewextendsViewGroup{
privatestaticfinalStringTAG="LoopView";
privatefloatdis;
privateObjectAnimatoranimator;
privateintcurrentIndex=0;
privateHandlerhandler=newHandler(Looper.getMainLooper());
publicLoopView(Contextcontext){
super(context);
init();
}
publicLoopView(Contextcontext,AttributeSetattrs){
super(context,attrs);
init();
}
publicLoopView(Contextcontext,AttributeSetattrs,intdefStyleAttr){
super(context,attrs,defStyleAttr);
init();
}
voidinit(){
Viewview1=newView(getContext());
view1.setTag("gray");
view1.setBackgroundColor(Color.GRAY);
LayoutParamslayoutParams=newLayoutParams(LayoutParams.MATCH_PARENT,200);
addView(view1,layoutParams);
Viewview2=newView(getContext());
view2.setTag("red");
view2.setBackgroundColor(Color.RED);
LayoutParamslayoutParams1=newLayoutParams(LayoutParams.MATCH_PARENT,200);
addView(view2,layoutParams1);
Viewview3=newView(getContext());
view3.setTag("green");
view3.setBackgroundColor(Color.GREEN);
LayoutParamslayoutParams2=newLayoutParams(LayoutParams.MATCH_PARENT,200);
addView(view3,layoutParams2);
animator=ObjectAnimator.ofFloat(this,"dis",0,1);
animator.setDuration(2000);
animator.addListener(newAnimatorListenerAdapter(){
@Override
publicvoidonAnimationEnd(Animatoranimation){
currentIndex++;
Viewfirst=getChildAt(0);
removeView(first);
addView(first);
handler.postDelayed(newRunnable(){
@Override
publicvoidrun(){
animator.clone().start();
}
},3000);
}
});
}
publicvoidstart(){
animator.start();
}
@Override
protectedvoidonMeasure(intwidthMeasureSpec,intheightMeasureSpec){
measureChildren(widthMeasureSpec,heightMeasureSpec);
super.onMeasure(widthMeasureSpec,MeasureSpec.makeMeasureSpec(200,MeasureSpec.EXACTLY));
}
@Override
protectedvoidonLayout(booleanchanged,intl,intt,intr,intb){
intchildCount=getChildCount();
inttop=currentIndex*getMeasuredHeight();
for(inti=0;i
需要注意的就是onLayout的时候对于top的取值。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。