http://blog.csdn.net/aomandeshangxiao/article/details/7397697
敬告:由于本文代码较多,所以文章分为了一二两篇,如果不便,敬请谅解,可以先下载文章下方的代码,打开参考本文查看,效果更好!
首先,先看下效果图:
这三张图分别是使用滚动控件实现城市,随机数和时间三个简单的例子,当然,界面有点简陋,下面我们就以时间这个为例,开始解析一下。
首先,先看下布局文件:
- <?xmlversion="1.0"encoding="utf-8"?>
- <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_height="wrap_content"
- android:layout_width="fill_parent"
- android:layout_marginTop="12dp"
- android:orientation="vertical"
- android:background="@drawable/layout_bg">
- <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_height="wrap_content"
- android:layout_width="fill_parent"
- android:layout_gravity="center_horizontal"
- android:paddingLeft="12dp"
- android:paddingRight="12dp"
- android:paddingTop="10dp">
- <kankan.wheel.widget.WheelViewandroid:id="@+id/hour"
- android:layout_height="wrap_content"
- android:layout_width="fill_parent"
- android:layout_weight="1"/>
- <kankan.wheel.widget.WheelViewandroid:id="@+id/mins"
- android:layout_height="wrap_content"
- android:layout_width="fill_parent"
- android:layout_weight="1"/>
- </LinearLayout>
- <TimePickerandroid:id="@+id/time"
- android:layout_marginTop="12dp"
- android:layout_height="wrap_content"
- android:layout_width="fill_parent"
- android:layout_weight="1"/>
- </LinearLayout>
里面只有三个控件,两个自定义的WheelView,还有一个TimePicker,然后进入代码里面看一下:
- publicclass TimeActivity extends Activity {
- // Time changed flag
- privateboolean timeChanged = false;
- //
- privateboolean timeScrolled = false;
- @Override
- publicvoid onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.time_layout);
- final WheelView hours = (WheelView) findViewById(R.id.hour);
- hours.setAdapter(new NumericWheelAdapter(0,23));
- hours.setLabel("hours");
- final WheelView mins = (WheelView) findViewById(R.id.mins);
- mins.setAdapter(new NumericWheelAdapter(0,59,"%02d"));
- mins.setLabel("mins");
- mins.setCyclic(true);
- final TimePicker picker = (TimePicker) findViewById(R.id.time);
- picker.setIs24HourView(true);
- // set current time
- Calendar c = Calendar.getInstance();
- int curHours = c.get(Calendar.HOUR_OF_DAY);
- int curMinutes = c.get(Calendar.MINUTE);
- hours.setCurrentItem(curHours);
- mins.setCurrentItem(curMinutes);
- picker.setCurrentHour(curHours);
- picker.setCurrentMinute(curMinutes);
- // add listeners
- addChangingListener(mins,"min");
- addChangingListener(hours,"hour");
- OnWheelChangedListener wheelListener =new OnWheelChangedListener() {
- publicvoid onChanged(WheelView wheel, int oldValue, int newValue) {
- if (!timeScrolled) {
- timeChanged =true;
- picker.setCurrentHour(hours.getCurrentItem());
- picker.setCurrentMinute(mins.getCurrentItem());
- timeChanged =false;
- }
- }
- };
- hours.addChangingListener(wheelListener);
- mins.addChangingListener(wheelListener);
- OnWheelScrollListener scrollListener =new OnWheelScrollListener() {
- publicvoid onScrollingStarted(WheelView wheel) {
- timeScrolled =true;
- }
- publicvoid onScrollingFinished(WheelView wheel) {
- timeScrolled =false;
- timeChanged =true;
- picker.setCurrentHour(hours.getCurrentItem());
- picker.setCurrentMinute(mins.getCurrentItem());
- timeChanged =false;
- }
- };
- hours.addScrollingListener(scrollListener);
- mins.addScrollingListener(scrollListener);
- picker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
- publicvoid onTimeChanged(TimePicker view, int hourOfDay, int minute) {
- if (!timeChanged) {
- hours.setCurrentItem(hourOfDay,true);
- mins.setCurrentItem(minute,true);
- }
- }
- });
- }
- /**
- * Adds changing listener for wheel that updates the wheel label
- * @param wheel the wheel
- * @param label the wheel label
- */
- privatevoid addChangingListener(final WheelView wheel, final String label) {
- wheel.addChangingListener(new OnWheelChangedListener() {
- publicvoid onChanged(WheelView wheel, int oldValue, int newValue) {
- wheel.setLabel(newValue !=1 ? label +"s" : label);
- }
- });
- }
- }
看一下,里面调用WheelView的方法有 setAdapter()、 setLabel("mins")、 setCyclic(true)、setCurrentItem()、getCurrentItem()、addChangingListener()、addScrollingListener()这些方法,其中setAapter设置数据适配器,setCyclic()设置是否是循环,setCurrentItem和getCurrentItem分别是设置现在选择的item和返回现在选择的item。后面两个设置监听的方法中,需要重写两个接口:
- /**
- * Wheel scrolled listener interface.
- */
- publicinterface OnWheelScrollListener {
- /**
- * Callback method to be invoked when scrolling started.
- * @param wheel the wheel view whose state has changed.
- */
- void onScrollingStarted(WheelView wheel);
- /**
- * Callback method to be invoked when scrolling ended.
- * @param wheel the wheel view whose state has changed.
- */
- void onScrollingFinished(WheelView wheel);
- }
和
- publicinterface OnWheelChangedListener {
- /**
- * Callback method to be invoked when current item changed
- * @param wheel the wheel view whose state has changed
- * @param oldValue the old value of current item
- * @param newValue the new value of current item
- */
- void onChanged(WheelView wheel, int oldValue, int newValue);
- }
在这里使用的是典型的回调方法模式。
然后现在,我们进入WheelView类,看一下他是如何构建,首先,WheelView继承了View类。代码的22行到45行是导入的所需要的类。从54行到135行是声明一些变量和类:
- /** Scrolling duration */
- privatestaticfinalint SCROLLING_DURATION = 400;
- /** Minimum delta for scrolling */
- privatestaticfinalint MIN_DELTA_FOR_SCROLLING = 1;
- /** Current value & label text color */
- privatestaticfinalint VALUE_TEXT_COLOR = 0xF0000000;
- /** Items text color */
- privatestaticfinalint ITEMS_TEXT_COLOR = 0xFF000000;
- /** Top and bottom shadows colors */
- privatestaticfinalint[] SHADOWS_COLORS = newint[] { 0xFF111111,
- 0x00AAAAAA,0x00AAAAAA };
- /** Additional items height (is added to standard text item height) */
- privatestaticfinalint ADDITIONAL_ITEM_HEIGHT = 15;
- /** Text size */
- privatestaticfinalint TEXT_SIZE = 24;
- /** Top and bottom items offset (to hide that) */
- privatestaticfinalint ITEM_OFFSET = TEXT_SIZE / 5;
- /** Additional width for items layout */
- privatestaticfinalint ADDITIONAL_ITEMS_SPACE = 10;
- /** Label offset */
- privatestaticfinalint LABEL_OFFSET = 8;
- /** Left and right padding value */
- privatestaticfinalint PADDING = 10;
- /** Default count of visible items */
- privatestaticfinalint DEF_VISIBLE_ITEMS = 5;
- // Wheel Values
- private WheelAdapter adapter = null;
- privateint currentItem = 0;
- // Widths
- privateint itemsWidth = 0;
- privateint labelWidth = 0;
- // Count of visible items
- privateint visibleItems = DEF_VISIBLE_ITEMS;
- // Item height
- privateint itemHeight = 0;
- // Text paints
- private TextPaint itemsPaint;
- private TextPaint valuePaint;
- // Layouts
- private StaticLayout itemsLayout;
- private StaticLayout labelLayout;
- private StaticLayout valueLayout;
- // Label & background
- private String label;
- private Drawable centerDrawable;
- // Shadows drawables
- private GradientDrawable topShadow;
- private GradientDrawable bottomShadow;
- // Scrolling
- privateboolean isScrollingPerformed;
- privateint scrollingOffset;
- // Scrolling animation
- private GestureDetector gestureDetector;
- private Scroller scroller;
- privateint lastScrollY;
- // Cyclic
- boolean isCyclic = false;
- // Listeners
- private List<OnWheelChangedListener> changingListeners = new LinkedList<OnWheelChangedListener>();
- private List<OnWheelScrollListener> scrollingListeners = new LinkedList<OnWheelScrollListener>();
在这里面,使用到了StaticLayout,在开发文档中找一下这个类:
- StaticLayout is a Layout for text that will not be edited after it is laid out. Use DynamicLayout for text that may change.
- This is used by widgets to control text layout. You should not need to use this class directly unless you are implementing your own widget or custom display object, or would be tempted to call Canvas.drawText() directly.
staticLayout被创建以后就不能被修改了,通常被用于控制文本组件布局。
还使用到了Drawable、Text'Paint、GradientDrawable、GestureDetector、Scroller类,在开发文档中,GradientDrawable的概述:
- A Drawable with a color gradient for buttons, backgrounds, etc.
- It can be defined in an XML file with the <shape> element. For more information, see the guide to Drawable Resources.
就是说这个类可以为按钮或者背景等提供渐变颜色的绘制。
TextPaint的概述:
- TextPaint is an extension of Paint that leaves room for some extra data used during text measuring and drawing.
GestureDetector:手势检测,看下开发文档中关于该类的概述:
- Detects various gestures and events using the supplied MotionEvents. The GestureDetector.OnGestureListener callback will notify users when a particular motion event has occurred. This class should only be used with MotionEvents reported via touch (don't use for trackball events).
为各种手势和事件提供MotionEvents。当一个具体的事件发生时会调用回调函数GestureDetector.OnGestureListener。这个类应该只适用于MotionEvents通过触摸触发的事件(不要使用追踪事件)。
140行到156行是构造方法,175到183行是set和getAdapter。在193行,setInterpolator()方法,设置interPolator这个动画接口,我们看下这个接口的概述:
- An interpolator defines the rate of change of an animation. This allows the basic animation effects (alpha, scale, translate, rotate) to be accelerated, decelerated, repeated, etc.
定义了一种基于变率的一个动画。这使得基本的动画效果( alpha, scale, translate, rotate )是加速,减慢,重复等。这个方法在随机数这个例子中被使用。
203行到213行设置显示的item条数。在setVisibleItems()方法里面调用了View的invalidate()方法,看下文档中对该方法的介绍:
- Invalidate the whole view. If the view is visible, onDraw(android.graphics.Canvas) will be called at some point in the future. This must be called from a UI thread. To call from a non-UI thread, call postInvalidate().
使全部视图失效,如果View视图是可见的,会在UI线程里面从新调用onDraw()方法。
223行到233行是设置Label,既后面图片中的hours.
245行到296行是设置监听,在上面已经简单的说了一下,这里不在累述。
307行到349行是设置正被选中item,就是在那个阴影条框下的那个部分,比较简单。里面主要调用了scroll这个方法:
- /**
- * Scroll the wheel
- * @param itemsToSkip items to scroll
- * @param time scrolling duration
- */
- publicvoid scroll(int itemsToScroll, int time) {
- scroller.forceFinished(true);
- lastScrollY = scrollingOffset;
- int offset = itemsToScroll * getItemHeight();
- scroller.startScroll(0, lastScrollY, 0, offset - lastScrollY, time);
- setNextMessage(MESSAGE_SCROLL);
- startScrolling();
- }
357行到365行是设置item数据能否循环使用。
384行的initResourcesIfNecessary()方法,从字面意思,如果需要的初始化资源。
- privatevoid initResourcesIfNecessary() {
- if (itemsPaint == null) {
- itemsPaint =new TextPaint(Paint.ANTI_ALIAS_FLAG
- | Paint.FAKE_BOLD_TEXT_FLAG);
- //itemsPaint.density = getResources().getDisplayMetrics().density;
- itemsPaint.setTextSize(TEXT_SIZE);
- }
- if (valuePaint == null) {
- valuePaint =new TextPaint(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 =new GradientDrawable(Orientation.TOP_BOTTOM, SHADOWS_COLORS);
- }
- if (bottomShadow == null) {
- bottomShadow =new GradientDrawable(Orientation.BOTTOM_TOP, SHADOWS_COLORS);
- }
- setBackgroundResource(R.drawable.wheel_bg);
- }
这个方法就是初始化在532行calculateLayoutWidth()方法中调用了这个方法,同时调用了487行的getMaxTextLength()这个方法。
471行getTextItem(int index)通过一个索引获取该item的文本。
这是第一部分,没有多少有太多意思的地方,重点的地方在以后532行到940行的内容,另起一篇,开始分析,这一篇先到这。
最后是下载地址:
Android仿iPhone滚动控件源码
http://download.csdn.net/detail/aomandeshangxiao/4175719android仿iPhone滚轮控件实现及源码分析(二)
分类: android小例子2012-03-27 17:46429人阅读 评论(8)收藏举报在上一篇android仿iPhone滚轮控件实现及源码分析(一)简单的说了下架构还有效果图,但是关于图形的绘制各方面的代码在532行到940行,如果写在一篇文章里面,可能会导致文章太长,效果不好,所以自作聪明的分成了两篇。闲言碎语不要讲,下面开始正事。
首先,先把代码贴出来:
- /**
- * Calculates control width and creates text layouts
- * @param widthSize the input layout width
- * @param mode the layout mode
- * @return the calculated control width
- */
- privateint calculateLayoutWidth(int widthSize, int mode) {
- initResourcesIfNecessary();
- int width = widthSize;
- int maxLength = getMaxTextLength();
- if (maxLength > 0) {
- float textWidth = FloatMath.ceil(Layout.getDesiredWidth("0", itemsPaint));
- itemsWidth = (int) (maxLength * textWidth);
- }else {
- itemsWidth =0;
- }
- itemsWidth += ADDITIONAL_ITEMS_SPACE;// make it some more
- labelWidth =0;
- if (label != null && label.length() > 0) {
- labelWidth = (int) FloatMath.ceil(Layout.getDesiredWidth(label, valuePaint));
- }
- boolean recalculate = false;
- if (mode == MeasureSpec.EXACTLY) {
- width = widthSize;
- recalculate =true;
- }else {
- width = itemsWidth + labelWidth +2 * PADDING;
- if (labelWidth > 0) {
- width += LABEL_OFFSET;
- }
- // Check against our minimum width
- width = Math.max(width, getSuggestedMinimumWidth());
- if (mode == MeasureSpec.AT_MOST && widthSize < width) {
- width = widthSize;
- recalculate =true;
- }
- }
- if (recalculate) {
- // recalculate width
- int pureWidth = width - LABEL_OFFSET - 2 * PADDING;
- if (pureWidth <= 0) {
- itemsWidth = labelWidth =0;
- }
- if (labelWidth > 0) {
- double newWidthItems = (double) itemsWidth * pureWidth
- / (itemsWidth + labelWidth);
- itemsWidth = (int) newWidthItems;
- labelWidth = pureWidth - itemsWidth;
- }else {
- itemsWidth = pureWidth + LABEL_OFFSET;// no label
- }
- }
- if (itemsWidth > 0) {
- createLayouts(itemsWidth, labelWidth);
- }
- return width;
- }
- /**
- * Creates layouts
- * @param widthItems width of items layout
- * @param widthLabel width of label layout
- */
- privatevoid createLayouts(int widthItems, int widthLabel) {
- if (itemsLayout == null || itemsLayout.getWidth() > widthItems) {
- itemsLayout =new StaticLayout(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)) {
- String text = getAdapter() !=null ? getAdapter().getItem(currentItem) :null;
- valueLayout =new StaticLayout(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 =new StaticLayout(label, valuePaint,
- widthLabel, Layout.Alignment.ALIGN_NORMAL,1,
- ADDITIONAL_ITEM_HEIGHT,false);
- }else {
- labelLayout.increaseWidthTo(widthLabel);
- }
- }
- }
- @Override
- protectedvoid onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
- int widthMode = MeasureSpec.getMode(widthMeasureSpec);
- int heightMode = MeasureSpec.getMode(heightMeasureSpec);
- int widthSize = MeasureSpec.getSize(widthMeasureSpec);
- int heightSize = MeasureSpec.getSize(heightMeasureSpec);
- int width = calculateLayoutWidth(widthSize, widthMode);
- int height;
- if (heightMode == MeasureSpec.EXACTLY) {
- height = heightSize;
- }else {
- height = getDesiredHeight(itemsLayout);
- if (heightMode == MeasureSpec.AT_MOST) {
- height = Math.min(height, heightSize);
- }
- }
- setMeasuredDimension(width, height);
- }
- @Override
- protectedvoid onDraw(Canvas canvas) {
- super.onDraw(canvas);
- if (itemsLayout == null) {
- if (itemsWidth == 0) {
- calculateLayoutWidth(getWidth(), MeasureSpec.EXACTLY);
- }else {
- createLayouts(itemsWidth, labelWidth);
- }
- }
- if (itemsWidth > 0) {
- canvas.save();
- // Skip padding space and hide a part of top and bottom items
- canvas.translate(PADDING, -ITEM_OFFSET);
- drawItems(canvas);
- drawValue(canvas);
- canvas.restore();
- }
- drawCenterRect(canvas);
- drawShadows(canvas);
- }
- /**
- * Draws shadows on top and bottom of control
- * @param canvas the canvas for drawing
- */
- privatevoid drawShadows(Canvas canvas) {
- topShadow.setBounds(0,0, getWidth(), getHeight() / visibleItems);
- topShadow.draw(canvas);
- bottomShadow.setBounds(0, getHeight() - getHeight() / visibleItems,
- getWidth(), getHeight());
- bottomShadow.draw(canvas);
- }
- /**
- * Draws value and label layout
- * @param canvas the canvas for drawing
- */
- privatevoid drawValue(Canvas canvas) {
- valuePaint.setColor(VALUE_TEXT_COLOR);
- valuePaint.drawableState = getDrawableState();
- Rect bounds =new Rect();
- itemsLayout.getLineBounds(visibleItems /2, bounds);
- // draw label
- if (labelLayout != null) {
- canvas.save();
- canvas.translate(itemsLayout.getWidth() + LABEL_OFFSET, bounds.top);
- labelLayout.draw(canvas);
- canvas.restore();
- }
- // draw current value
- if (valueLayout != null) {
- canvas.save();
- canvas.translate(0, bounds.top + scrollingOffset);
- valueLayout.draw(canvas);
- canvas.restore();
- }
- }
- /**
- * Draws items
- * @param canvas the canvas for drawing
- */
- privatevoid drawItems(Canvas canvas) {
- canvas.save();
- int top = itemsLayout.getLineTop(1);
- canvas.translate(0, - top + scrollingOffset);
- itemsPaint.setColor(ITEMS_TEXT_COLOR);
- itemsPaint.drawableState = getDrawableState();
- itemsLayout.draw(canvas);
- canvas.restore();
- }
- /**
- * Draws rect for current value
- * @param canvas the canvas for drawing
- */
- privatevoid drawCenterRect(Canvas canvas) {
- int center = getHeight() / 2;
- int offset = getItemHeight() / 2;
- centerDrawable.setBounds(0, center - offset, getWidth(), center + offset);
- centerDrawable.draw(canvas);
- }
- @Override
- publicboolean onTouchEvent(MotionEvent event) {
- WheelAdapter adapter = getAdapter();
- if (adapter == null) {
- returntrue;
- }
- if (!gestureDetector.onTouchEvent(event) && event.getAction() == MotionEvent.ACTION_UP) {
- justify();
- }
- returntrue;
- }
- /**
- * Scrolls the wheel
- * @param delta the scrolling value
- */
- privatevoid doScroll(int delta) {
- scrollingOffset += delta;
- int count = scrollingOffset / getItemHeight();
- int pos = currentItem - count;
- if (isCyclic && adapter.getItemsCount() > 0) {
- // fix position by rotating
- 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 {
- // fix position
- pos = Math.max(pos,0);
- pos = Math.min(pos, adapter.getItemsCount() -1);
- }
- int offset = scrollingOffset;
- if (pos != currentItem) {
- setCurrentItem(pos,false);
- }else {
- invalidate();
- }
- // update offset
- scrollingOffset = offset - count * getItemHeight();
- if (scrollingOffset > getHeight()) {
- scrollingOffset = scrollingOffset % getHeight() + getHeight();
- }
- }
- // gesture listener
- private SimpleOnGestureListener gestureListener = new SimpleOnGestureListener() {
- publicboolean onDown(MotionEvent e) {
- if (isScrollingPerformed) {
- scroller.forceFinished(true);
- clearMessages();
- returntrue;
- }
- returnfalse;
- }
- publicboolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
- startScrolling();
- doScroll((int)-distanceY);
- returntrue;
- }
- publicboolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
- lastScrollY = currentItem * getItemHeight() + scrollingOffset;
- int maxY = isCyclic ? 0x7FFFFFFF : adapter.getItemsCount() * getItemHeight();
- int minY = isCyclic ? -maxY : 0;
- scroller.fling(0, lastScrollY, 0, (int) -velocityY / 2,0,0, minY, maxY);
- setNextMessage(MESSAGE_SCROLL);
- returntrue;
- }
- };
- // Messages
- privatefinalint MESSAGE_SCROLL = 0;
- privatefinalint MESSAGE_JUSTIFY = 1;
- /**
- * Set next message to queue. Clears queue before.
- *
- * @param message the message to set
- */
- privatevoid setNextMessage(int message) {
- clearMessages();
- animationHandler.sendEmptyMessage(message);
- }
- /**
- * Clears messages from queue
- */
- privatevoid clearMessages() {
- animationHandler.removeMessages(MESSAGE_SCROLL);
- animationHandler.removeMessages(MESSAGE_JUSTIFY);
- }
- // animation handler
- private Handler animationHandler = new Handler() {
- publicvoid handleMessage(Message msg) {
- scroller.computeScrollOffset();
- int currY = scroller.getCurrY();
- int delta = lastScrollY - currY;
- lastScrollY = currY;
- if (delta != 0) {
- doScroll(delta);
- }
- // scrolling is not finished when it comes to final Y
- // so, finish it manually
- 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();
- }
- }
- };
- /**
- * Justifies wheel
- */
- privatevoid justify() {
- if (adapter == null) {
- return;
- }
- lastScrollY =0;
- int offset = scrollingOffset;
- int itemHeight = getItemHeight();
- boolean needToIncrease = 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();
- }
- }
- /**
- * Starts scrolling
- */
- privatevoid startScrolling() {
- if (!isScrollingPerformed) {
- isScrollingPerformed =true;
- notifyScrollingListenersAboutStart();
- }
- }
- /**
- * Finishes scrolling
- */
- void finishScrolling() {
- if (isScrollingPerformed) {
- notifyScrollingListenersAboutEnd();
- isScrollingPerformed =false;
- }
- invalidateLayouts();
- invalidate();
- }
- /**
- * Scroll the wheel
- * @param itemsToSkip items to scroll
- * @param time scrolling duration
- */
- publicvoid scroll(int itemsToScroll, int time) {
- scroller.forceFinished(true);
- lastScrollY = scrollingOffset;
- int offset = itemsToScroll * getItemHeight();
- scroller.startScroll(0, lastScrollY, 0, offset - lastScrollY, time);
- setNextMessage(MESSAGE_SCROLL);
- startScrolling();
- }
在629行到744行的代码是绘制图形,747行onTouchEvent()里面主要是调用了882行的justify()方法,用于调整画面,
- @Override
- publicboolean onTouchEvent(MotionEvent event) {
- WheelAdapter adapter = getAdapter();
- if (adapter == null) {
- returntrue;
- }
- if (!gestureDetector.onTouchEvent(event) && event.getAction() == MotionEvent.ACTION_UP) {
- justify();
- }
- returntrue;
- }
- /**
- * Justifies wheel
- */
- privatevoid justify() {
- if (adapter == null) {
- return;
- }
- lastScrollY =0;
- int offset = scrollingOffset;
- int itemHeight = getItemHeight();
- boolean needToIncrease = 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();
- }
- }
我们看下重写的系统回调函数onMeasure()(用于测量各个控件距离,父子控件空间大小等):
- @Override
- protectedvoid onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
- int widthMode = MeasureSpec.getMode(widthMeasureSpec);
- int heightMode = MeasureSpec.getMode(heightMeasureSpec);
- int widthSize = MeasureSpec.getSize(widthMeasureSpec);
- int heightSize = MeasureSpec.getSize(heightMeasureSpec);
- int width = calculateLayoutWidth(widthSize, widthMode);
- int height;
- if (heightMode == MeasureSpec.EXACTLY) {
- height = heightSize;
- }else {
- height = getDesiredHeight(itemsLayout);
- if (heightMode == MeasureSpec.AT_MOST) {
- height = Math.min(height, heightSize);
- }
- }
- setMeasuredDimension(width, height);
- }
里面用到了532行calculateLayoutWidth()的方法,就是计算Layout的宽度,在calculateLayoutWidth()这个方法里面调用了
- /**
- * Creates layouts
- * @param widthItems width of items layout
- * @param widthLabel width of label layout
- */
- privatevoid createLayouts(int widthItems, int widthLabel) {
- if (itemsLayout == null || itemsLayout.getWidth() > widthItems) {
- itemsLayout =new StaticLayout(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)) {
- String text = getAdapter() !=null ? getAdapter().getItem(currentItem) :null;
- valueLayout =new StaticLayout(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 =new StaticLayout(label, valuePaint,
- widthLabel, Layout.Alignment.ALIGN_NORMAL,1,
- ADDITIONAL_ITEM_HEIGHT,false);
- }else {
- labelLayout.increaseWidthTo(widthLabel);
- }
- }
- }
然后我们接着看onDraw()方法:
- @Override
- protectedvoid onDraw(Canvas canvas) {
- super.onDraw(canvas);
- if (itemsLayout == null) {
- if (itemsWidth == 0) {
- calculateLayoutWidth(getWidth(), MeasureSpec.EXACTLY);
- }else {
- createLayouts(itemsWidth, labelWidth);
- }
- }
- if (itemsWidth > 0) {
- canvas.save();
- // Skip padding space and hide a part of top and bottom items
- canvas.translate(PADDING, -ITEM_OFFSET);
- drawItems(canvas);
- drawValue(canvas);
- canvas.restore();
- }
- drawCenterRect(canvas);
- drawShadows(canvas);
- }
在onDraw方法中,也调用了CreateLayout()方法,然后在后面调用drawCenterRect()、drawItems()、drawValue()、绘制阴影drawShadows()两个方法:
- /**
- * Draws shadows on top and bottom of control
- * @param canvas the canvas for drawing
- */
- privatevoid drawShadows(Canvas canvas) {
- topShadow.setBounds(0,0, getWidth(), getHeight() / visibleItems);
- topShadow.draw(canvas);
- bottomShadow.setBounds(0, getHeight() - getHeight() / visibleItems,
- getWidth(), getHeight());
- bottomShadow.draw(canvas);
- }
- /**
- * Draws value and label layout
- * @param canvas the canvas for drawing
- */
- privatevoid drawValue(Canvas canvas) {
- valuePaint.setColor(VALUE_TEXT_COLOR);
- valuePaint.drawableState = getDrawableState();
- Rect bounds =new Rect();
- itemsLayout.getLineBounds(visibleItems /2, bounds);
- // draw label
- if (labelLayout != null) {
- canvas.save();
- canvas.translate(itemsLayout.getWidth() + LABEL_OFFSET, bounds.top);
- labelLayout.draw(canvas);
- canvas.restore();
- }
- // draw current value
- if (valueLayout != null) {
- canvas.save();
- canvas.translate(0, bounds.top + scrollingOffset);
- valueLayout.draw(canvas);
- canvas.restore();
- }
- }
- /**
- * Draws items
- * @param canvas the canvas for drawing
- */
- privatevoid drawItems(Canvas canvas) {
- canvas.save();
- int top = itemsLayout.getLineTop(1);
- canvas.translate(0, - top + scrollingOffset);
- itemsPaint.setColor(ITEMS_TEXT_COLOR);
- itemsPaint.drawableState = getDrawableState();
- itemsLayout.draw(canvas);
- canvas.restore();
- }
- /**
- * Draws rect for current value
- * @param canvas the canvas for drawing
- */
- privatevoid drawCenterRect(Canvas canvas) {
- int center = getHeight() / 2;
- int offset = getItemHeight() / 2;
- centerDrawable.setBounds(0, center - offset, getWidth(), center + offset);
- centerDrawable.draw(canvas);
- }
主要就是通过canvas类进行图形的绘制。
最后,我们看下840行定义的手势监听:
- // gesture listener
- private SimpleOnGestureListener gestureListener = new SimpleOnGestureListener() {
- publicboolean onDown(MotionEvent e) {
- if (isScrollingPerformed) {
- scroller.forceFinished(true);
- clearMessages();
- returntrue;
- }
- returnfalse;
- }
- publicboolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
- startScrolling();
- doScroll((int)-distanceY);
- returntrue;
- }
- publicboolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
- lastScrollY = currentItem * getItemHeight() + scrollingOffset;
- int maxY = isCyclic ? 0x7FFFFFFF : adapter.getItemsCount() * getItemHeight();
- int minY = isCyclic ? -maxY : 0;
- scroller.fling(0, lastScrollY, 0, (int) -velocityY / 2,0,0, minY, maxY);
- setNextMessage(MESSAGE_SCROLL);
- returntrue;
- }
- };
里面主要调用的方法:clearMessages()、startScrolling()、doScroll()、setNextMessage(),先看下中间的两个方法开始滑动和滑动
- /**
- * Scrolls the wheel
- * @param delta the scrolling value
- */
- privatevoid doScroll(int delta) {
- scrollingOffset += delta;
- int count = scrollingOffset / getItemHeight();
- int pos = currentItem - count;
- if (isCyclic && adapter.getItemsCount() > 0) {
- // fix position by rotating
- 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 {
- // fix position
- pos = Math.max(pos,0);
- pos = Math.min(pos, adapter.getItemsCount() -1);
- }
- int offset = scrollingOffset;
- if (pos != currentItem) {
- setCurrentItem(pos,false);
- }else {
- invalidate();
- }
- // update offset
- scrollingOffset = offset - count * getItemHeight();
- if (scrollingOffset > getHeight()) {
- scrollingOffset = scrollingOffset % getHeight() + getHeight();
- }
- }
- /**
- * Starts scrolling
- */
- privatevoid startScrolling() {
- if (!isScrollingPerformed) {
- isScrollingPerformed =true;
- notifyScrollingListenersAboutStart();
- }
- }
在startScrolling方法里面有287行的notifyScrollingListenersAboutStart函数。
再看clearMessages()、setMessageNext()
- privatevoid setNextMessage(int message) {
- clearMessages();
- animationHandler.sendEmptyMessage(message);
- }
- /**
- * Clears messages from queue
- */
- privatevoid clearMessages() {
- animationHandler.removeMessages(MESSAGE_SCROLL);
- animationHandler.removeMessages(MESSAGE_JUSTIFY);
- }
里面使用到了animationHandler,用来传递动画有段的操作:
- // animation handler
- private Handler animationHandler = new Handler() {
- publicvoid handleMessage(Message msg) {
- scroller.computeScrollOffset();
- int currY = scroller.getCurrY();
- int delta = lastScrollY - currY;
- lastScrollY = currY;
- if (delta != 0) {
- doScroll(delta);
- }
- // scrolling is not finished when it comes to final Y
- // so, finish it manually
- 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();
- }
- }
- };
里面调用了finishScrolling()
- /**
- * Finishes scrolling
- */
- void finishScrolling() {
- if (isScrollingPerformed) {
- notifyScrollingListenersAboutEnd();
- isScrollingPerformed =false;
- }
- invalidateLayouts();
- invalidate();
- }
完