Android_开发 实用滚轮效果选择数字(十三)
16lz
2021-01-24
Android_开发 实用滚轮效果选择数字(十三)
这个滚动的WheelView
view plain- /*
- *AndroidWheelControl.
- *https://code.google.com/p/android-wheel/
- *
- *Copyright2010YuriKanivets
- *
- *LicensedundertheApacheLicense,Version2.0(the"License");
- *youmaynotusethisfileexceptincompliancewiththeLicense.
- *YoumayobtainacopyoftheLicenseat
- *
- *http://www.apache.org/licenses/LICENSE-2.0
- *
- *Unlessrequiredbyapplicablelaworagreedtoinwriting,software
- *distributedundertheLicenseisdistributedonan"ASIS"BASIS,
- *WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.
- *SeetheLicenseforthespecificlanguagegoverningpermissionsand
- *limitationsundertheLicense.
- */
- packagekankan.wheel.widget;
- importjava.util.LinkedList;
- importjava.util.List;
- importandroid.content.Context;
- importandroid.graphics.Canvas;
- importandroid.graphics.Paint;
- importandroid.graphics.Rect;
- importandroid.graphics.drawable.Drawable;
- importandroid.graphics.drawable.GradientDrawable;
- importandroid.graphics.drawable.GradientDrawable.Orientation;
- importandroid.os.Handler;
- importandroid.os.Message;
- importandroid.text.Layout;
- importandroid.text.StaticLayout;
- importandroid.text.TextPaint;
- importandroid.util.AttributeSet;
- importandroid.util.FloatMath;
- importandroid.view.GestureDetector;
- importandroid.view.GestureDetector.SimpleOnGestureListener;
- importandroid.view.MotionEvent;
- importandroid.view.View;
- importandroid.view.animation.Interpolator;
- importandroid.widget.Scroller;
- importcom.shao.pwd.R;
- /**
- *Numericwheelview.
- *
- *@authorYuriKanivets
- */
- publicclassWheelViewextendsView{
- /**Scrollingduration*/
- privatestaticfinalintSCROLLING_DURATION=400;
- /**Minimumdeltaforscrolling*/
- privatestaticfinalintMIN_DELTA_FOR_SCROLLING=1;
- /**Currentvalue&labeltextcolor*/
- privatestaticfinalintVALUE_TEXT_COLOR=0xF0000000;
- /**Itemstextcolor*/
- privatestaticfinalintITEMS_TEXT_COLOR=0xFF000000;
- /**Topandbottomshadowscolors*/
- privatestaticfinalint[]SHADOWS_COLORS=newint[]{0xFF111111,
- 0x00AAAAAA,0x00AAAAAA};
- /**Additionalitemsheight(isaddedtostandardtextitemheight)*/
- privatestaticfinalintADDITIONAL_ITEM_HEIGHT=15;
- /**Textsize*/
- privatestaticfinalintTEXT_SIZE=24;
- /**Topandbottomitemsoffset(tohidethat)*/
- privatestaticfinalintITEM_OFFSET=TEXT_SIZE/5;
- /**Additionalwidthforitemslayout*/
- privatestaticfinalintADDITIONAL_ITEMS_SPACE=10;
- /**Labeloffset*/
- privatestaticfinalintLABEL_OFFSET=8;
- /**Leftandrightpaddingvalue*/
- privatestaticfinalintPADDING=10;
- /**Defaultcountofvisibleitems*/
- privatestaticfinalintDEF_VISIBLE_ITEMS=5;
- //WheelValues
- privateWheelAdapteradapter=null;
- privateintcurrentItem=0;
- //Widths
- privateintitemsWidth=0;
- privateintlabelWidth=0;
- //Countofvisibleitems
- privateintvisibleItems=DEF_VISIBLE_ITEMS;
- //Itemheight
- privateintitemHeight=0;
- //Textpaints
- privateTextPaintitemsPaint;
- privateTextPaintvaluePaint;
- //Layouts
- privateStaticLayoutitemsLayout;
- privateStaticLayoutlabelLayout;
- privateStaticLayoutvalueLayout;
- //Label&background
- privateStringlabel;
- privateDrawablecenterDrawable;
- //Shadowsdrawables
- privateGradientDrawabletopShadow;
- privateGradientDrawablebottomShadow;
- //Scrolling
- privatebooleanisScrollingPerformed;
- privateintscrollingOffset;
- //Scrollinganimation
- privateGestureDetectorgestureDetector;
- privateScrollerscroller;
- privateintlastScrollY;
- //Cyclic
- booleanisCyclic=false;
- //Listeners
- privateList<OnWheelChangedListener>changingListeners=newLinkedList<OnWheelChangedListener>();
- privateList<OnWheelScrollListener>scrollingListeners=newLinkedList<OnWheelScrollListener>();
- /**
- *Constructor
- */
- publicWheelView(Contextcontext,AttributeSetattrs,intdefStyle){
- super(context,attrs,defStyle);
- initData(context);
- }
- /**
- *Constructor
- */
- publicWheelView(Contextcontext,AttributeSetattrs){
- super(context,attrs);
- initData(context);
- }
- /**
- *Constructor
- */
- publicWheelView(Contextcontext){
- super(context);
- initData(context);
- }
- /**
- *Initializesclassdata
- *@paramcontextthecontext
- */
- privatevoidinitData(Contextcontext){
- gestureDetector=newGestureDetector(context,gestureListener);
- gestureDetector.setIsLongpressEnabled(false);
- scroller=newScroller(context);
- }
- /**
- *Getswheeladapter
- *@returntheadapter
- */
- publicWheelAdaptergetAdapter(){
- returnadapter;
- }
- /**
- *Setswheeladapter
- *@paramadapterthenewwheeladapter
- */
- publicvoidsetAdapter(WheelAdapteradapter){
- this.adapter=adapter;
- invalidateLayouts();
- invalidate();
- }
- /**
- *Setthethespecifiedscrollinginterpolator
- *@paraminterpolatortheinterpolator
- */
- publicvoidsetInterpolator(Interpolatorinterpolator){
- scroller.forceFinished(true);
- scroller=newScroller(getContext(),interpolator);
- }
- /**
- *Getscountofvisibleitems
- *
- *@returnthecountofvisibleitems
- */
- publicintgetVisibleItems(){
- returnvisibleItems;
- }
- /**
- *Setscountofvisibleitems
- *
- *@paramcount
- *thenewcount
- */
- publicvoidsetVisibleItems(intcount){
- visibleItems=count;
- invalidate();
- }
- /**
- *Getslabel
- *
- *@returnthelabel
- */
- publicStringgetLabel(){
- returnlabel;
- }
- /**
- *Setslabel
- *
- *@paramnewLabel
- *thelabeltoset
- */
- publicvoidsetLabel(StringnewLabel){
- if(label==null||!label.equals(newLabel)){
- label=newLabel;
- labelLayout=null;
- invalidate();
- }
- }
- /**
- *Addswheelchanginglistener
- *@paramlistenerthelistener
- */
- publicvoidaddChangingListener(OnWheelChangedListenerlistener){
- changingListeners.add(listener);
- }
- /**
- *Removeswheelchanginglistener
- *@paramlistenerthelistener
- */
- publicvoidremoveChangingListener(OnWheelChangedListenerlistener){
- changingListeners.remove(listener);
- }
- /**
- *Notifieschanginglisteners
- *@paramoldValuetheoldwheelvalue
- *@paramnewValuethenewwheelvalue
- */
- protectedvoidnotifyChangingListeners(intoldValue,intnewValue){
- for(OnWheelChangedListenerlistener:changingListeners){
- listener.onChanged(this,oldValue,newValue);
- }
- }
- /**
- *Addswheelscrollinglistener
- *@paramlistenerthelistener
- */
- publicvoidaddScrollingListener(OnWheelScrollListenerlistener){
- scrollingListeners.add(listener);
- }
- /**
- *Removeswheelscrollinglistener
- *@paramlistenerthelistener
- */
- publicvoidremoveScrollingListener(OnWheelScrollListenerlistener){
- scrollingListeners.remove(listener);
- }
- /**
- *Notifieslistenersaboutstartingscrolling
- */
- protectedvoidnotifyScrollingListenersAboutStart(){
- for(OnWheelScrollListenerlistener:scrollingListeners){
- listener.onScrollingStarted(this);
- }
- }
- /**
- *Notifieslistenersaboutendingscrolling
- */
- protectedvoidnotifyScrollingListenersAboutEnd(){
- for(OnWheelScrollListenerlistener:scrollingListeners){
- listener.onScrollingFinished(this);
- }
- }
- /**
- *Getscurrentvalue
- *
- *@returnthecurrentvalue
- */
- publicintgetCurrentItem(){
- returncurrentItem;
- }
- /**
- *Setsthecurrentitem.Doesnothingwhenindexiswrong.
- *
- *@paramindextheitemindex
- *@paramanimatedtheanimationflag
- */
- publicvoidsetCurrentItem(intindex,booleananimated){
- if(adapter==null||adapter.getItemsCount()==0){
- return;//throw?
- }
- if(index<0||index>=adapter.getItemsCount()){
- if(isCyclic){
- while(index<0){
- index+=adapter.getItemsCount();
- }
- index%=adapter.getItemsCount();
- }else{
- return;//throw?
- }
- }
- if(index!=currentItem){
- if(animated){
- scroll(index-currentItem,SCROLLING_DURATION);
- }else{
- invalidateLayouts();
- intold=currentItem;
- currentItem=index;
- notifyChangingListeners(old,currentItem);
- invalidate();
- }
- }
- }
- /**
- *Setsthecurrentitemw/oanimation.Doesnothingwhenindexiswrong.
- *
- *@paramindextheitemindex
- */
- publicvoidsetCurrentItem(intindex){
- setCurrentItem(index,false);
- }
- /**
- *Testsifwheeliscyclic.Thatmeansbeforethe1stitemthereisshownthelastone
- *@returntrueifwheeliscyclic
- */
- publicbooleanisCyclic(){
- returnisCyclic;
- }
- /**
- *Setwheelcyclicflag
- *@paramisCyclictheflagtoset
- */
- publicvoidsetCyclic(booleanisCyclic){
- this.isCyclic=isCyclic;
- invalidate();
- invalidateLayouts();
- }
- /**
- *Invalidateslayouts
- */
- privatevoidinvalidateLayouts(){
- itemsLayout=null;
- valueLayout=null;
- scrollingOffset=0;
- }
- /**
- *Initializesresources
- */
- privatevoidinitResourcesIfNecessary(){
- if(itemsPaint==null){
- itemsPaint=newTextPaint(Paint.ANTI_ALIAS_FLAG
- |Paint.FAKE_BOLD_TEXT_FLAG);
- //itemsPaint.density=getResources().getDisplayMetrics().density;
- itemsPaint.setTextSize(TEXT_SIZE);
- }
- if(valuePaint==null){
- valuePaint=newTextPaint(Paint.ANTI_ALIAS_FLAG
- |Paint.FAKE_BOLD_TEXT_FLAG|Paint.DITHER_FLAG);
- //valuePaint.density=getResources().getDisplayMetrics().density;
- valuePaint.setTextSize(TEXT_SIZE);
- valuePaint.setShadowLayer(0.1f,0,0.1f,0xFFC0C0C0);
- }
- if(centerDrawable==null){
- centerDrawable=getContext().getResources().getDrawable(R.drawable.wheel_val);
- }
- if(topShadow==null){
- topShadow=newGradientDrawable(Orientation.TOP_BOTTOM,SHADOWS_COLORS);
- }
- if(bottomShadow==null){
- bottomShadow=newGradientDrawable(Orientation.BOTTOM_TOP,SHADOWS_COLORS);
- }
- setBackgroundResource(R.drawable.wheel_bg);
- }
- /**
- *Calculatesdesiredheightforlayout
- *
- *@paramlayout
- *thesourcelayout
- *@returnthedesiredlayoutheight
- */
- privateintgetDesiredHeight(Layoutlayout){
- if(layout==null){
- return0;
- }
- intdesired=getItemHeight()*visibleItems-ITEM_OFFSET*2
- -ADDITIONAL_ITEM_HEIGHT;
- //Checkagainstourminimumheight
- desired=Math.max(desired,getSuggestedMinimumHeight());
- returndesired;
- }
- /**
- *Returnstextitembyindex
- *@paramindextheitemindex
- *@returntheitemornull
- */
- privateStringgetTextItem(intindex){
- if(adapter==null||adapter.getItemsCount()==0){
- returnnull;
- }
- intcount=adapter.getItemsCount();
- if((index<0||index>=count)&&!isCyclic){
- returnnull;
- }else{
- while(index<0){
- index=count+index;
- }
- }
- index%=count;
- returnadapter.getItem(index);
- }
- /**
- *Buildstextdependingoncurrentvalue
- *
- *@paramuseCurrentValue
- *@returnthetext
- */
- privateStringbuildText(booleanuseCurrentValue){
- StringBuilderitemsText=newStringBuilder();
- intaddItems=visibleItems/2+1;
- for(inti=currentItem-addItems;i<=currentItem+addItems;i++){
- if(useCurrentValue||i!=currentItem){
- Stringtext=getTextItem(i);
- if(text!=null){
- itemsText.append(text);
- }
- }
- if(i<currentItem+addItems){
- itemsText.append("\n");
- }
- }
- returnitemsText.toString();
- }
- /**
- *Returnsthemaxitemlengththatcanbepresent
- *@returnthemaxlength
- */
- privateintgetMaxTextLength(){
- WheelAdapteradapter=getAdapter();
- if(adapter==null){
- return0;
- }
- intadapterLength=adapter.getMaximumLength();
- if(adapterLength>0){
- returnadapterLength;
- }
- StringmaxText=null;
- intaddItems=visibleItems/2;
- for(inti=Math.max(currentItem-addItems,0);
- i<Math.min(currentItem+visibleItems,adapter.getItemsCount());i++){
- Stringtext=adapter.getItem(i);
- if(text!=null&&(maxText==null||maxText.length()<text.length())){
- maxText=text;
- }
- }
- returnmaxText!=null?maxText.length():0;
- }
- /**
- *Returnsheightofwheelitem
- *@returntheitemheight
- */
- privateintgetItemHeight(){
- if(itemHeight!=0){
- returnitemHeight;
- }elseif(itemsLayout!=null&&itemsLayout.getLineCount()>2){
- itemHeight=itemsLayout.getLineTop(2)-itemsLayout.getLineTop(1);
- returnitemHeight;
- }
- returngetHeight()/visibleItems;
- }
- /**
- *Calculatescontrolwidthandcreatestextlayouts
- *@paramwidthSizetheinputlayoutwidth
- *@parammodethelayoutmode
- *@returnthecalculatedcontrolwidth
- */
- privateintcalculateLayoutWidth(intwidthSize,intmode){
- initResourcesIfNecessary();
- intwidth=widthSize;
- intmaxLength=getMaxTextLength();
- if(maxLength>0){
- floattextWidth=FloatMath.ceil(Layout.getDesiredWidth("0",itemsPaint));
- itemsWidth=(int)(maxLength*textWidth);
- }else{
- itemsWidth=0;
- }
- itemsWidth+=ADDITIONAL_ITEMS_SPACE;//makeitsomemore
- labelWidth=0;
- if(label!=null&&label.length()>0){
- labelWidth=(int)FloatMath.ceil(Layout.getDesiredWidth(label,valuePaint));
- }
- booleanrecalculate=false;
- if(mode==MeasureSpec.EXACTLY){
- width=widthSize;
- recalculate=true;
- }else{
- width=itemsWidth+labelWidth+2*PADDING;
- if(labelWidth>0){
- width+=LABEL_OFFSET;
- }
- //Checkagainstourminimumwidth
- width=Math.max(width,getSuggestedMinimumWidth());
- if(mode==MeasureSpec.AT_MOST&&widthSize<width){
- width=widthSize;
- recalculate=true;
- }
- }
- if(recalculate){
- //recalculatewidth
- intpureWidth=width-LABEL_OFFSET-2*PADDING;
- if(pureWidth<=0){
- itemsWidth=labelWidth=0;
- }
- if(labelWidth>0){
- doublenewWidthItems=(double)itemsWidth*pureWidth
- /(itemsWidth+labelWidth);
- itemsWidth=(int)newWidthItems;
- labelWidth=pureWidth-itemsWidth;
- }else{
- itemsWidth=pureWidth+LABEL_OFFSET;//nolabel
- }
- }
- if(itemsWidth>0){
- createLayouts(itemsWidth,labelWidth);
- }
- returnwidth;
- }
- /**
- *Createslayouts
- *@paramwidthItemswidthofitemslayout
- *@paramwidthLabelwidthoflabellayout
- */
- privatevoidcreateLayouts(intwidthItems,intwidthLabel){
- if(itemsLayout==null||itemsLayout.getWidth()>widthItems){
- itemsLayout=newStaticLayout(buildText(isScrollingPerformed),itemsPaint,widthItems,
- widthLabel>0?Layout.Alignment.ALIGN_OPPOSITE:Layout.Alignment.ALIGN_CENTER,
- 1,ADDITIONAL_ITEM_HEIGHT,false);
- }else{
- itemsLayout.increaseWidthTo(widthItems);
- }
- if(!isScrollingPerformed&&(valueLayout==null||valueLayout.getWidth()>widthItems)){
- Stringtext=getAdapter()!=null?getAdapter().getItem(currentItem):null;
- valueLayout=newStaticLayout(text!=null?text:"",
- valuePaint,widthItems,widthLabel>0?
- Layout.Alignment.ALIGN_OPPOSITE:Layout.Alignment.ALIGN_CENTER,
- 1,ADDITIONAL_ITEM_HEIGHT,false);
- }elseif(isScrollingPerformed){
- valueLayout=null;
- }else{
- valueLayout.increaseWidthTo(widthItems);
- }
- if(widthLabel>0){
- if(labelLayout==null||labelLayout.getWidth()>widthLabel){
- labelLayout=newStaticLayout(label,valuePaint,
- widthLabel,Layout.Alignment.ALIGN_NORMAL,1,
- ADDITIONAL_ITEM_HEIGHT,false);
- }else{
- labelLayout.increaseWidthTo(widthLabel);
- }
- }
- }
- @Override
- protectedvoidonMeasure(intwidthMeasureSpec,intheightMeasureSpec){
- intwidthMode=MeasureSpec.getMode(widthMeasureSpec);
- intheightMode=MeasureSpec.getMode(heightMeasureSpec);
- intwidthSize=MeasureSpec.getSize(widthMeasureSpec);
- intheightSize=MeasureSpec.getSize(heightMeasureSpec);
- intwidth=calculateLayoutWidth(widthSize,widthMode);
- intheight;
- if(heightMode==MeasureSpec.EXACTLY){
- height=heightSize;
- }else{
- height=getDesiredHeight(itemsLayout);
- if(heightMode==MeasureSpec.AT_MOST){
- height=Math.min(height,heightSize);
- }
- }
- setMeasuredDimension(width,height);
- }
- @Override
- protectedvoidonDraw(Canvascanvas){
- super.onDraw(canvas);
- if(itemsLayout==null){
- if(itemsWidth==0){
- calculateLayoutWidth(getWidth(),MeasureSpec.EXACTLY);
- }else{
- createLayouts(itemsWidth,labelWidth);
- }
- }
- if(itemsWidth>0){
- canvas.save();
- //Skippaddingspaceandhideapartoftopandbottomitems
- canvas.translate(PADDING,-ITEM_OFFSET);
- drawItems(canvas);
- drawValue(canvas);
- canvas.restore();
- }
- drawCenterRect(canvas);
- drawShadows(canvas);
- }
- /**
- *Drawsshadowsontopandbottomofcontrol
- *@paramcanvasthecanvasfordrawing
- */
- privatevoiddrawShadows(Canvascanvas){
- topShadow.setBounds(0,0,getWidth(),getHeight()/visibleItems);
- topShadow.draw(canvas);
- bottomShadow.setBounds(0,getHeight()-getHeight()/visibleItems,
- getWidth(),getHeight());
- bottomShadow.draw(canvas);
- }
- /**
- *Drawsvalueandlabellayout
- *@paramcanvasthecanvasfordrawing
- */
- privatevoiddrawValue(Canvascanvas){
- valuePaint.setColor(VALUE_TEXT_COLOR);
- valuePaint.drawableState=getDrawableState();
- Rectbounds=newRect();
- itemsLayout.getLineBounds(visibleItems/2,bounds);
- //drawlabel
- if(labelLayout!=null){
- canvas.save();
- canvas.translate(itemsLayout.getWidth()+LABEL_OFFSET,bounds.top);
- labelLayout.draw(canvas);
- canvas.restore();
- }
- //drawcurrentvalue
- if(valueLayout!=null){
- canvas.save();
- canvas.translate(0,bounds.top+scrollingOffset);
- valueLayout.draw(canvas);
- canvas.restore();
- }
- }
- /**
- *Drawsitems
- *@paramcanvasthecanvasfordrawing
- */
- privatevoiddrawItems(Canvascanvas){
- canvas.save();
- inttop=itemsLayout.getLineTop(1);
- canvas.translate(0,-top+scrollingOffset);
- itemsPaint.setColor(ITEMS_TEXT_COLOR);
- itemsPaint.drawableState=getDrawableState();
- itemsLayout.draw(canvas);
- canvas.restore();
- }
- /**
- *Drawsrectforcurrentvalue
- *@paramcanvasthecanvasfordrawing
- */
- privatevoiddrawCenterRect(Canvascanvas){
- intcenter=getHeight()/2;
- intoffset=getItemHeight()/2;
- centerDrawable.setBounds(0,center-offset,getWidth(),center+offset);
- centerDrawable.draw(canvas);
- }
- @Override
- publicbooleanonTouchEvent(MotionEventevent){
- WheelAdapteradapter=getAdapter();
- if(adapter==null){
- returntrue;
- }
- if(!gestureDetector.onTouchEvent(event)&&event.getAction()==MotionEvent.ACTION_UP){
- justify();
- }
- returntrue;
- }
- /**
- *Scrollsthewheel
- *@paramdeltathescrollingvalue
- */
- privatevoiddoScroll(intdelta){
- scrollingOffset+=delta;
- intcount=scrollingOffset/getItemHeight();
- intpos=currentItem-count;
- if(isCyclic&&adapter.getItemsCount()>0){
- //fixpositionbyrotating
- while(pos<0){
- pos+=adapter.getItemsCount();
- }
- pos%=adapter.getItemsCount();
- }elseif(isScrollingPerformed){
- //
- if(pos<0){
- count=currentItem;
- pos=0;
- }elseif(pos>=adapter.getItemsCount()){
- count=currentItem-adapter.getItemsCount()+1;
- pos=adapter.getItemsCount()-1;
- }
- }else{
- //fixposition
- pos=Math.max(pos,0);
- pos=Math.min(pos,adapter.getItemsCount()-1);
- }
- intoffset=scrollingOffset;
- if(pos!=currentItem){
- setCurrentItem(pos,false);
- }else{
- invalidate();
- }
- //updateoffset
- scrollingOffset=offset-count*getItemHeight();
- if(scrollingOffset>getHeight()){
- scrollingOffset=scrollingOffset%getHeight()+getHeight();
- }
- }
- //gesturelistener
- privateSimpleOnGestureListenergestureListener=newSimpleOnGestureListener(){
- publicbooleanonDown(MotionEvente){
- if(isScrollingPerformed){
- scroller.forceFinished(true);
- clearMessages();
- returntrue;
- }
- returnfalse;
- }
- publicbooleanonScroll(MotionEvente1,MotionEvente2,floatdistanceX,floatdistanceY){
- startScrolling();
- doScroll((int)-distanceY);
- returntrue;
- }
- publicbooleanonFling(MotionEvente1,MotionEvente2,floatvelocityX,floatvelocityY){
- lastScrollY=currentItem*getItemHeight()+scrollingOffset;
- intmaxY=isCyclic?0x7FFFFFFF:adapter.getItemsCount()*getItemHeight();
- intminY=isCyclic?-maxY:0;
- scroller.fling(0,lastScrollY,0,(int)-velocityY/2,0,0,minY,maxY);
- setNextMessage(MESSAGE_SCROLL);
- returntrue;
- }
- };
- //Messages
- privatefinalintMESSAGE_SCROLL=0;
- privatefinalintMESSAGE_JUSTIFY=1;
- /**
- *Setnextmessagetoqueue.Clearsqueuebefore.
- *
- *@parammessagethemessagetoset
- */
- privatevoidsetNextMessage(intmessage){
- clearMessages();
- animationHandler.sendEmptyMessage(message);
- }
- /**
- *Clearsmessagesfromqueue
- */
- privatevoidclearMessages(){
- animationHandler.removeMessages(MESSAGE_SCROLL);
- animationHandler.removeMessages(MESSAGE_JUSTIFY);
- }
- //animationhandler
- privateHandleranimationHandler=newHandler(){
- publicvoidhandleMessage(Messagemsg){
- scroller.computeScrollOffset();
- intcurrY=scroller.getCurrY();
- intdelta=lastScrollY-currY;
- lastScrollY=currY;
- if(delta!=0){
- doScroll(delta);
- }
- //scrollingisnotfinishedwhenitcomestofinalY
- //so,finishitmanually
- if(Math.abs(currY-scroller.getFinalY())<MIN_DELTA_FOR_SCROLLING){
- currY=scroller.getFinalY();
- scroller.forceFinished(true);
- }
- if(!scroller.isFinished()){
- animationHandler.sendEmptyMessage(msg.what);
- }elseif(msg.what==MESSAGE_SCROLL){
- justify();
- }else{
- finishScrolling();
- }
- }
- };
- /**
- *Justifieswheel
- */
- privatevoidjustify(){
- if(adapter==null){
- return;
- }
- lastScrollY=0;
- intoffset=scrollingOffset;
- intitemHeight=getItemHeight();
- booleanneedToIncrease=offset>0?currentItem<adapter.getItemsCount():currentItem>0;
- if((isCyclic||needToIncrease)&&Math.abs((float)offset)>(float)itemHeight/2){
- if(offset<0)
- offset+=itemHeight+MIN_DELTA_FOR_SCROLLING;
- else
- offset-=itemHeight+MIN_DELTA_FOR_SCROLLING;
- }
- if(Math.abs(offset)>MIN_DELTA_FOR_SCROLLING){
- scroller.startScroll(0,0,0,offset,SCROLLING_DURATION);
- setNextMessage(MESSAGE_JUSTIFY);
- }else{
- finishScrolling();
- }
- }
- /**
- *Startsscrolling
- */
- privatevoidstartScrolling(){
- if(!isScrollingPerformed){
- isScrollingPerformed=true;
- notifyScrollingListenersAboutStart();
- }
- }
- /**
- *Finishesscrolling
- */
- voidfinishScrolling(){
- if(isScrollingPerformed){
- notifyScrollingListenersAboutEnd();
- isScrollingPerformed=false;
- }
- invalidateLayouts();
- invalidate();
- }
- /**
- *Scrollthewheel
- *@paramitemsToSkipitemstoscroll
- *@paramtimescrollingduration
- */
- publicvoidscroll(intitemsToScroll,inttime){
- scroller.forceFinished(true);
- lastScrollY=scrollingOffset;
- intoffset=itemsToScroll*getItemHeight();
- scroller.startScroll(0,lastScrollY,0,offset-lastScrollY,time);
- setNextMessage(MESSAGE_SCROLL);
- startScrolling();
- }
- }
主布局文件
view plain- <?xmlversion="1.0"encoding="utf-8"?>
- <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_height="wrap_content"
- android:orientation="vertical"
- android:background="@drawable/layout_bg"
- android:layout_width="fill_parent">
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_marginTop="24dp"
- android:layout_gravity="center_horizontal"
- android:textSize="20sp"
- android:textStyle="bold"
- android:text="PleaseenterPIN"/>
- <LinearLayout
- android:layout_marginTop="24dp"
- android:layout_gravity="center_horizontal"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content">
- <kankan.wheel.widget.WheelViewandroid:id="@+id/passw_1"
- android:layout_height="wrap_content"
- android:layout_width="wrap_content"/>
- <kankan.wheel.widget.WheelViewandroid:id="@+id/passw_2"
- android:layout_height="wrap_content"
- android:layout_width="wrap_content"/>
- <kankan.wheel.widget.WheelViewandroid:id="@+id/passw_3"
- android:layout_height="wrap_content"
- android:layout_width="wrap_content"/>
- <kankan.wheel.widget.WheelViewandroid:id="@+id/passw_4"
- android:layout_height="wrap_content"
- android:layout_width="wrap_content"/>
- <kankan.wheel.widget.WheelViewandroid:id="@+id/passw_5"
- android:layout_height="wrap_content"
- android:layout_width="wrap_content"/>
- <kankan.wheel.widget.WheelViewandroid:id="@+id/passw_6"
- android:layout_height="wrap_content"
- android:layout_width="wrap_content"/>
- </LinearLayout>
- <TextViewandroid:id="@+id/pwd_status"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_marginTop="24dp"
- android:layout_gravity="center_horizontal"
- android:textSize="18sp"
- android:textColor="#FFF"
- android:text="WrongPIN"/>
- <Buttonandroid:id="@+id/btn_mix"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="center_horizontal"
- android:layout_marginTop="12dp"
- android:textSize="18sp"
- android:text="Mix"/>
- </LinearLayout>
适配器adapter
- /*
- *Copyright2010YuriKanivets
- *
- *LicensedundertheApacheLicense,Version2.0(the"License");
- *youmaynotusethisfileexceptincompliancewiththeLicense.
- *YoumayobtainacopyoftheLicenseat
- *
- *http://www.apache.org/licenses/LICENSE-2.0
- *
- *Unlessrequiredbyapplicablelaworagreedtoinwriting,software
- *distributedundertheLicenseisdistributedonan"ASIS"BASIS,
- *WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.
- *SeetheLicenseforthespecificlanguagegoverningpermissionsand
- *limitationsundertheLicense.
- */
- packagekankan.wheel.widget;
- publicinterfaceWheelAdapter{
- /**
- *Getsitemscount
- *@returnthecountofwheelitems
- */
- publicintgetItemsCount();
- /**
- *Getsawheelitembyindex.
- *
- *@paramindextheitemindex
- *@returnthewheelitemtextornull
- */
- publicStringgetItem(intindex);
- /**
- *Getsmaximumitemlength.Itisusedtodeterminethewheelwidth.
- *If-1isreturnedtherewillbeusedthedefaultwheelwidth.
- *
- *@returnthemaximumitemlengthor-1
- */
- publicintgetMaximumLength();
- }
- /*
- *Copyright2010YuriKanivets
- *
- *LicensedundertheApacheLicense,Version2.0(the"License");
- *youmaynotusethisfileexceptincompliancewiththeLicense.
- *YoumayobtainacopyoftheLicenseat
- *
- *http://www.apache.org/licenses/LICENSE-2.0
- *
- *Unlessrequiredbyapplicablelaworagreedtoinwriting,software
- *distributedundertheLicenseisdistributedonan"ASIS"BASIS,
- *WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.
- *SeetheLicenseforthespecificlanguagegoverningpermissionsand
- *limitationsundertheLicense.
- */
- packagekankan.wheel.widget;
- /**
- *NumericWheeladapter.
- */
- publicclassNumericWheelAdapterimplementsWheelAdapter{
- /**Thedefaultminvalue*/
- publicstaticfinalintDEFAULT_MAX_VALUE=9;
- /**Thedefaultmaxvalue*/
- privatestaticfinalintDEFAULT_MIN_VALUE=0;
- //Values
- privateintminValue;
- privateintmaxValue;
- //format
- privateStringformat;
- /**
- *Defaultconstructor
- */
- publicNumericWheelAdapter(){
- this(DEFAULT_MIN_VALUE,DEFAULT_MAX_VALUE);
- }
- /**
- *Constructor
- *@paramminValuethewheelminvalue
- *@parammaxValuethewheelmaxvalue
- */
- publicNumericWheelAdapter(intminValue,intmaxValue){
- this(minValue,maxValue,null);
- }
- /**
- *Constructor
- *@paramminValuethewheelminvalue
- *@parammaxValuethewheelmaxvalue
- *@paramformattheformatstring
- */
- publicNumericWheelAdapter(intminValue,intmaxValue,Stringformat){
- this.minValue=minValue;
- this.maxValue=maxValue;
- this.format=format;
- }
- @Override
- publicStringgetItem(intindex){
- if(index>=0&&index<getItemsCount()){
- intvalue=minValue+index;
- returnformat!=null?String.format(format,value):Integer.toString(value);
- }
- returnnull;
- }
- @Override
- publicintgetItemsCount(){
- returnmaxValue-minValue+1;
- }
- @Override
- publicintgetMaximumLength(){
- intmax=Math.max(Math.abs(maxValue),Math.abs(minValue));
- intmaxLen=Integer.toString(max).length();
- if(minValue<0){
- maxLen++;
- }
- returnmaxLen;
- }
- }
监听器Listener文件:
view plain- /*
- *Copyright2010YuriKanivets
- *
- *LicensedundertheApacheLicense,Version2.0(the"License");
- *youmaynotusethisfileexceptincompliancewiththeLicense.
- *YoumayobtainacopyoftheLicenseat
- *
- *http://www.apache.org/licenses/LICENSE-2.0
- *
- *Unlessrequiredbyapplicablelaworagreedtoinwriting,software
- *distributedundertheLicenseisdistributedonan"ASIS"BASIS,
- *WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.
- *SeetheLicenseforthespecificlanguagegoverningpermissionsand
- *limitationsundertheLicense.
- */
- packagekankan.wheel.widget;
- /**
- *Wheelscrolledlistenerinterface.
- */
- publicinterfaceOnWheelScrollListener{
- /**
- *Callbackmethodtobeinvokedwhenscrollingstarted.
- *@paramwheelthewheelviewwhosestatehaschanged.
- */
- voidonScrollingStarted(WheelViewwheel);
- /**
- *Callbackmethodtobeinvokedwhenscrollingended.
- *@paramwheelthewheelviewwhosestatehaschanged.
- */
- voidonScrollingFinished(WheelViewwheel);
- }
- /*
- *Copyright2010YuriKanivets
- *
- *LicensedundertheApacheLicense,Version2.0(the"License");
- *youmaynotusethisfileexceptincompliancewiththeLicense.
- *YoumayobtainacopyoftheLicenseat
- *
- *http://www.apache.org/licenses/LICENSE-2.0
- *
- *Unlessrequiredbyapplicablelaworagreedtoinwriting,software
- *distributedundertheLicenseisdistributedonan"ASIS"BASIS,
- *WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.
- *SeetheLicenseforthespecificlanguagegoverningpermissionsand
- *limitationsundertheLicense.
- */
- packagekankan.wheel.widget;
- /**
- *Wheelchangedlistenerinterface.
- *<p>ThecurrentItemChanged()methodiscalledwhenevercurrentwheelpositionsischanged:
- *<li>NewWheelpositionisset
- *<li>Wheelviewisscrolled
- */
- publicinterfaceOnWheelChangedListener{
- /**
- *Callbackmethodtobeinvokedwhencurrentitemchanged
- *@paramwheelthewheelviewwhosestatehaschanged
- *@paramoldValuetheoldvalueofcurrentitem
- *@paramnewValuethenewvalueofcurrentitem
- */
- voidonChanged(WheelViewwheel,intoldValue,intnewValue);
- }
更多相关文章
- android(11)_文件操作读取模式
- android 关于 ScrollView嵌套GridView,ListView 显示和滑动的问题
- android中常用的方法备忘
- Android中JNI程序的编写(zhuan)
- (转)Android(安卓)TextView背景色、圆角、内部填充设置
- 使用libevent实现最简单的android http-server
- Eclipse,到了说再见的时候了——Android(安卓)Studio最全解析
- android 混淆后的代码还原
- Android实现 ScrollView + ListView无滚动条滚动