android仿iPhone滚轮控件实现及源码分析

时间:2022-08-30 14:56:41

http://blog.csdn.net/aomandeshangxiao/article/details/7397697

敬告:由于本文代码较多,所以文章分为了一二两篇,如果不便,敬请谅解,可以先下载文章下方的代码,打开参考本文查看,效果更好!

首先,先看下效果图:

android仿iPhone滚轮控件实现及源码分析android仿iPhone滚轮控件实现及源码分析android仿iPhone滚轮控件实现及源码分析

这三张图分别是使用滚动控件实现城市,随机数和时间三个简单的例子,当然,界面有点简陋,下面我们就以时间这个为例,开始解析一下。

首先,先看下布局文件:

[html] view plaincopy
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_height="wrap_content"
  4. android:layout_width="fill_parent"
  5. android:layout_marginTop="12dp"
  6. android:orientation="vertical"
  7. android:background="@drawable/layout_bg">
  8. <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  9. android:layout_height="wrap_content"
  10. android:layout_width="fill_parent"
  11. android:layout_gravity="center_horizontal"
  12. android:paddingLeft="12dp"
  13. android:paddingRight="12dp"
  14. android:paddingTop="10dp">
  15. <kankan.wheel.widget.WheelViewandroid:id="@+id/hour"
  16. android:layout_height="wrap_content"
  17. android:layout_width="fill_parent"
  18. android:layout_weight="1"/>
  19. <kankan.wheel.widget.WheelViewandroid:id="@+id/mins"
  20. android:layout_height="wrap_content"
  21. android:layout_width="fill_parent"
  22. android:layout_weight="1"/>
  23. </LinearLayout>
  24. <TimePickerandroid:id="@+id/time"
  25. android:layout_marginTop="12dp"
  26. android:layout_height="wrap_content"
  27. android:layout_width="fill_parent"
  28. android:layout_weight="1"/>
  29. </LinearLayout>

里面只有三个控件,两个自定义的WheelView,还有一个TimePicker,然后进入代码里面看一下:

[java] view plaincopy
  1. publicclass TimeActivity extends Activity {
  2. // Time changed flag
  3. privateboolean timeChanged = false;
  4. //
  5. privateboolean timeScrolled = false;
  6. @Override
  7. publicvoid onCreate(Bundle savedInstanceState) {
  8. super.onCreate(savedInstanceState);
  9. setContentView(R.layout.time_layout);
  10. final WheelView hours = (WheelView) findViewById(R.id.hour);
  11. hours.setAdapter(new NumericWheelAdapter(0,23));
  12. hours.setLabel("hours");
  13. final WheelView mins = (WheelView) findViewById(R.id.mins);
  14. mins.setAdapter(new NumericWheelAdapter(0,59,"%02d"));
  15. mins.setLabel("mins");
  16. mins.setCyclic(true);
  17. final TimePicker picker = (TimePicker) findViewById(R.id.time);
  18. picker.setIs24HourView(true);
  19. // set current time
  20. Calendar c = Calendar.getInstance();
  21. int curHours = c.get(Calendar.HOUR_OF_DAY);
  22. int curMinutes = c.get(Calendar.MINUTE);
  23. hours.setCurrentItem(curHours);
  24. mins.setCurrentItem(curMinutes);
  25. picker.setCurrentHour(curHours);
  26. picker.setCurrentMinute(curMinutes);
  27. // add listeners
  28. addChangingListener(mins,"min");
  29. addChangingListener(hours,"hour");
  30. OnWheelChangedListener wheelListener =new OnWheelChangedListener() {
  31. publicvoid onChanged(WheelView wheel, int oldValue, int newValue) {
  32. if (!timeScrolled) {
  33. timeChanged =true;
  34. picker.setCurrentHour(hours.getCurrentItem());
  35. picker.setCurrentMinute(mins.getCurrentItem());
  36. timeChanged =false;
  37. }
  38. }
  39. };
  40. hours.addChangingListener(wheelListener);
  41. mins.addChangingListener(wheelListener);
  42. OnWheelScrollListener scrollListener =new OnWheelScrollListener() {
  43. publicvoid onScrollingStarted(WheelView wheel) {
  44. timeScrolled =true;
  45. }
  46. publicvoid onScrollingFinished(WheelView wheel) {
  47. timeScrolled =false;
  48. timeChanged =true;
  49. picker.setCurrentHour(hours.getCurrentItem());
  50. picker.setCurrentMinute(mins.getCurrentItem());
  51. timeChanged =false;
  52. }
  53. };
  54. hours.addScrollingListener(scrollListener);
  55. mins.addScrollingListener(scrollListener);
  56. picker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
  57. publicvoid onTimeChanged(TimePicker view, int hourOfDay, int minute) {
  58. if (!timeChanged) {
  59. hours.setCurrentItem(hourOfDay,true);
  60. mins.setCurrentItem(minute,true);
  61. }
  62. }
  63. });
  64. }
  65. /**
  66. * Adds changing listener for wheel that updates the wheel label
  67. * @param wheel the wheel
  68. * @param label the wheel label
  69. */
  70. privatevoid addChangingListener(final WheelView wheel, final String label) {
  71. wheel.addChangingListener(new OnWheelChangedListener() {
  72. publicvoid onChanged(WheelView wheel, int oldValue, int newValue) {
  73. wheel.setLabel(newValue !=1 ? label +"s" : label);
  74. }
  75. });
  76. }
  77. }

看一下,里面调用WheelView的方法有 setAdapter()、 setLabel("mins")、 setCyclic(true)、setCurrentItem()、getCurrentItem()、addChangingListener()、addScrollingListener()这些方法,其中setAapter设置数据适配器,setCyclic()设置是否是循环,setCurrentItem和getCurrentItem分别是设置现在选择的item和返回现在选择的item。后面两个设置监听的方法中,需要重写两个接口:

[java] view plaincopy
  1. /**
  2. * Wheel scrolled listener interface.
  3. */
  4. publicinterface OnWheelScrollListener {
  5. /**
  6. * Callback method to be invoked when scrolling started.
  7. * @param wheel the wheel view whose state has changed.
  8. */
  9. void onScrollingStarted(WheelView wheel);
  10. /**
  11. * Callback method to be invoked when scrolling ended.
  12. * @param wheel the wheel view whose state has changed.
  13. */
  14. void onScrollingFinished(WheelView wheel);
  15. }

[java] view plaincopy
  1. publicinterface OnWheelChangedListener {
  2. /**
  3. * Callback method to be invoked when current item changed
  4. * @param wheel the wheel view whose state has changed
  5. * @param oldValue the old value of current item
  6. * @param newValue the new value of current item
  7. */
  8. void onChanged(WheelView wheel, int oldValue, int newValue);
  9. }

在这里使用的是典型的回调方法模式。

然后现在,我们进入WheelView类,看一下他是如何构建,首先,WheelView继承了View类。代码的22行到45行是导入的所需要的类。从54行到135行是声明一些变量和类:

[java] view plaincopy
  1. /** Scrolling duration */
  2. privatestaticfinalint SCROLLING_DURATION = 400;
  3. /** Minimum delta for scrolling */
  4. privatestaticfinalint MIN_DELTA_FOR_SCROLLING = 1;
  5. /** Current value & label text color */
  6. privatestaticfinalint VALUE_TEXT_COLOR = 0xF0000000;
  7. /** Items text color */
  8. privatestaticfinalint ITEMS_TEXT_COLOR = 0xFF000000;
  9. /** Top and bottom shadows colors */
  10. privatestaticfinalint[] SHADOWS_COLORS = newint[] { 0xFF111111,
  11. 0x00AAAAAA,0x00AAAAAA };
  12. /** Additional items height (is added to standard text item height) */
  13. privatestaticfinalint ADDITIONAL_ITEM_HEIGHT = 15;
  14. /** Text size */
  15. privatestaticfinalint TEXT_SIZE = 24;
  16. /** Top and bottom items offset (to hide that) */
  17. privatestaticfinalint ITEM_OFFSET = TEXT_SIZE / 5;
  18. /** Additional width for items layout */
  19. privatestaticfinalint ADDITIONAL_ITEMS_SPACE = 10;
  20. /** Label offset */
  21. privatestaticfinalint LABEL_OFFSET = 8;
  22. /** Left and right padding value */
  23. privatestaticfinalint PADDING = 10;
  24. /** Default count of visible items */
  25. privatestaticfinalint DEF_VISIBLE_ITEMS = 5;
  26. // Wheel Values
  27. private WheelAdapter adapter = null;
  28. privateint currentItem = 0;
  29. // Widths
  30. privateint itemsWidth = 0;
  31. privateint labelWidth = 0;
  32. // Count of visible items
  33. privateint visibleItems = DEF_VISIBLE_ITEMS;
  34. // Item height
  35. privateint itemHeight = 0;
  36. // Text paints
  37. private TextPaint itemsPaint;
  38. private TextPaint valuePaint;
  39. // Layouts
  40. private StaticLayout itemsLayout;
  41. private StaticLayout labelLayout;
  42. private StaticLayout valueLayout;
  43. // Label & background
  44. private String label;
  45. private Drawable centerDrawable;
  46. // Shadows drawables
  47. private GradientDrawable topShadow;
  48. private GradientDrawable bottomShadow;
  49. // Scrolling
  50. privateboolean isScrollingPerformed;
  51. privateint scrollingOffset;
  52. // Scrolling animation
  53. private GestureDetector gestureDetector;
  54. private Scroller scroller;
  55. privateint lastScrollY;
  56. // Cyclic
  57. boolean isCyclic = false;
  58. // Listeners
  59. private List<OnWheelChangedListener> changingListeners = new LinkedList<OnWheelChangedListener>();
  60. private List<OnWheelScrollListener> scrollingListeners = new LinkedList<OnWheelScrollListener>();

在这里面,使用到了StaticLayout,在开发文档中找一下这个类:

[plain] view plaincopy
  1. StaticLayout is a Layout for text that will not be edited after it is laid out. Use DynamicLayout for text that may change.
  2. 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的概述:

[plain] view plaincopy
  1. A Drawable with a color gradient for buttons, backgrounds, etc.
  2. It can be defined in an XML file with the <shape> element. For more information, see the guide to Drawable Resources.

就是说这个类可以为按钮或者背景等提供渐变颜色的绘制。

TextPaint的概述:

[plain] view plaincopy
  1. TextPaint is an extension of Paint that leaves room for some extra data used during text measuring and drawing.
TextPaint是Paint类的一个扩展,主要是用于文本在绘制的过程中为附件的数据留出空间。


GestureDetector:手势检测,看下开发文档中关于该类的概述:

[plain] view plaincopy
  1. 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这个动画接口,我们看下这个接口的概述:

[plain] view plaincopy
  1. 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()方法,看下文档中对该方法的介绍:

[plain] view plaincopy
  1. 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.android仿iPhone滚轮控件实现及源码分析

245行到296行是设置监听,在上面已经简单的说了一下,这里不在累述。

307行到349行是设置正被选中item,就是在那个阴影条框下的那个部分,比较简单。里面主要调用了scroll这个方法:

[java] view plaincopy
  1. /**
  2. * Scroll the wheel
  3. * @param itemsToSkip items to scroll
  4. * @param time scrolling duration
  5. */
  6. publicvoid scroll(int itemsToScroll, int time) {
  7. scroller.forceFinished(true);
  8. lastScrollY = scrollingOffset;
  9. int offset = itemsToScroll * getItemHeight();
  10. scroller.startScroll(0, lastScrollY, 0, offset - lastScrollY, time);
  11. setNextMessage(MESSAGE_SCROLL);
  12. startScrolling();
  13. }


357行到365行是设置item数据能否循环使用。

384行的initResourcesIfNecessary()方法,从字面意思,如果需要的初始化资源。

[java] view plaincopy
  1. privatevoid initResourcesIfNecessary() {
  2. if (itemsPaint == null) {
  3. itemsPaint =new TextPaint(Paint.ANTI_ALIAS_FLAG
  4. | Paint.FAKE_BOLD_TEXT_FLAG);
  5. //itemsPaint.density = getResources().getDisplayMetrics().density;
  6. itemsPaint.setTextSize(TEXT_SIZE);
  7. }
  8. if (valuePaint == null) {
  9. valuePaint =new TextPaint(Paint.ANTI_ALIAS_FLAG
  10. | Paint.FAKE_BOLD_TEXT_FLAG | Paint.DITHER_FLAG);
  11. //valuePaint.density = getResources().getDisplayMetrics().density;
  12. valuePaint.setTextSize(TEXT_SIZE);
  13. valuePaint.setShadowLayer(0.1f,0,0.1f,0xFFC0C0C0);
  14. }
  15. if (centerDrawable == null) {
  16. centerDrawable = getContext().getResources().getDrawable(R.drawable.wheel_val);
  17. }
  18. if (topShadow == null) {
  19. topShadow =new GradientDrawable(Orientation.TOP_BOTTOM, SHADOWS_COLORS);
  20. }
  21. if (bottomShadow == null) {
  22. bottomShadow =new GradientDrawable(Orientation.BOTTOM_TOP, SHADOWS_COLORS);
  23. }
  24. setBackgroundResource(R.drawable.wheel_bg);
  25. }


这个方法就是初始化在532行calculateLayoutWidth()方法中调用了这个方法,同时调用了487行的getMaxTextLength()这个方法。

471行getTextItem(int index)通过一个索引获取该item的文本。


这是第一部分,没有多少有太多意思的地方,重点的地方在以后532行到940行的内容,另起一篇,开始分析,这一篇先到这。

最后是下载地址:

Android仿iPhone滚动控件源码

http://download.csdn.net/detail/aomandeshangxiao/4175719


android仿iPhone滚轮控件实现及源码分析(二)

分类: android小例子429人阅读 评论(8)收藏举报

在上一篇android仿iPhone滚轮控件实现及源码分析(一)简单的说了下架构还有效果图,但是关于图形的绘制各方面的代码在532行到940行,如果写在一篇文章里面,可能会导致文章太长,效果不好,所以自作聪明的分成了两篇android仿iPhone滚轮控件实现及源码分析。闲言碎语不要讲,下面开始正事。

首先,先把代码贴出来:

[java] view plaincopy
  1. /**
  2. * Calculates control width and creates text layouts
  3. * @param widthSize the input layout width
  4. * @param mode the layout mode
  5. * @return the calculated control width
  6. */
  7. privateint calculateLayoutWidth(int widthSize, int mode) {
  8. initResourcesIfNecessary();
  9. int width = widthSize;
  10. int maxLength = getMaxTextLength();
  11. if (maxLength > 0) {
  12. float textWidth = FloatMath.ceil(Layout.getDesiredWidth("0", itemsPaint));
  13. itemsWidth = (int) (maxLength * textWidth);
  14. }else {
  15. itemsWidth =0;
  16. }
  17. itemsWidth += ADDITIONAL_ITEMS_SPACE;// make it some more
  18. labelWidth =0;
  19. if (label != null && label.length() > 0) {
  20. labelWidth = (int) FloatMath.ceil(Layout.getDesiredWidth(label, valuePaint));
  21. }
  22. boolean recalculate = false;
  23. if (mode == MeasureSpec.EXACTLY) {
  24. width = widthSize;
  25. recalculate =true;
  26. }else {
  27. width = itemsWidth + labelWidth +2 * PADDING;
  28. if (labelWidth > 0) {
  29. width += LABEL_OFFSET;
  30. }
  31. // Check against our minimum width
  32. width = Math.max(width, getSuggestedMinimumWidth());
  33. if (mode == MeasureSpec.AT_MOST && widthSize < width) {
  34. width = widthSize;
  35. recalculate =true;
  36. }
  37. }
  38. if (recalculate) {
  39. // recalculate width
  40. int pureWidth = width - LABEL_OFFSET - 2 * PADDING;
  41. if (pureWidth <= 0) {
  42. itemsWidth = labelWidth =0;
  43. }
  44. if (labelWidth > 0) {
  45. double newWidthItems = (double) itemsWidth * pureWidth
  46. / (itemsWidth + labelWidth);
  47. itemsWidth = (int) newWidthItems;
  48. labelWidth = pureWidth - itemsWidth;
  49. }else {
  50. itemsWidth = pureWidth + LABEL_OFFSET;// no label
  51. }
  52. }
  53. if (itemsWidth > 0) {
  54. createLayouts(itemsWidth, labelWidth);
  55. }
  56. return width;
  57. }
  58. /**
  59. * Creates layouts
  60. * @param widthItems width of items layout
  61. * @param widthLabel width of label layout
  62. */
  63. privatevoid createLayouts(int widthItems, int widthLabel) {
  64. if (itemsLayout == null || itemsLayout.getWidth() > widthItems) {
  65. itemsLayout =new StaticLayout(buildText(isScrollingPerformed), itemsPaint, widthItems,
  66. widthLabel >0 ? Layout.Alignment.ALIGN_OPPOSITE : Layout.Alignment.ALIGN_CENTER,
  67. 1, ADDITIONAL_ITEM_HEIGHT, false);
  68. }else {
  69. itemsLayout.increaseWidthTo(widthItems);
  70. }
  71. if (!isScrollingPerformed && (valueLayout == null || valueLayout.getWidth() > widthItems)) {
  72. String text = getAdapter() !=null ? getAdapter().getItem(currentItem) :null;
  73. valueLayout =new StaticLayout(text !=null ? text : "",
  74. valuePaint, widthItems, widthLabel >0 ?
  75. Layout.Alignment.ALIGN_OPPOSITE : Layout.Alignment.ALIGN_CENTER,
  76. 1, ADDITIONAL_ITEM_HEIGHT, false);
  77. }elseif (isScrollingPerformed) {
  78. valueLayout =null;
  79. }else {
  80. valueLayout.increaseWidthTo(widthItems);
  81. }
  82. if (widthLabel > 0) {
  83. if (labelLayout == null || labelLayout.getWidth() > widthLabel) {
  84. labelLayout =new StaticLayout(label, valuePaint,
  85. widthLabel, Layout.Alignment.ALIGN_NORMAL,1,
  86. ADDITIONAL_ITEM_HEIGHT,false);
  87. }else {
  88. labelLayout.increaseWidthTo(widthLabel);
  89. }
  90. }
  91. }
  92. @Override
  93. protectedvoid onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  94. int widthMode = MeasureSpec.getMode(widthMeasureSpec);
  95. int heightMode = MeasureSpec.getMode(heightMeasureSpec);
  96. int widthSize = MeasureSpec.getSize(widthMeasureSpec);
  97. int heightSize = MeasureSpec.getSize(heightMeasureSpec);
  98. int width = calculateLayoutWidth(widthSize, widthMode);
  99. int height;
  100. if (heightMode == MeasureSpec.EXACTLY) {
  101. height = heightSize;
  102. }else {
  103. height = getDesiredHeight(itemsLayout);
  104. if (heightMode == MeasureSpec.AT_MOST) {
  105. height = Math.min(height, heightSize);
  106. }
  107. }
  108. setMeasuredDimension(width, height);
  109. }
  110. @Override
  111. protectedvoid onDraw(Canvas canvas) {
  112. super.onDraw(canvas);
  113. if (itemsLayout == null) {
  114. if (itemsWidth == 0) {
  115. calculateLayoutWidth(getWidth(), MeasureSpec.EXACTLY);
  116. }else {
  117. createLayouts(itemsWidth, labelWidth);
  118. }
  119. }
  120. if (itemsWidth > 0) {
  121. canvas.save();
  122. // Skip padding space and hide a part of top and bottom items
  123. canvas.translate(PADDING, -ITEM_OFFSET);
  124. drawItems(canvas);
  125. drawValue(canvas);
  126. canvas.restore();
  127. }
  128. drawCenterRect(canvas);
  129. drawShadows(canvas);
  130. }
  131. /**
  132. * Draws shadows on top and bottom of control
  133. * @param canvas the canvas for drawing
  134. */
  135. privatevoid drawShadows(Canvas canvas) {
  136. topShadow.setBounds(0,0, getWidth(), getHeight() / visibleItems);
  137. topShadow.draw(canvas);
  138. bottomShadow.setBounds(0, getHeight() - getHeight() / visibleItems,
  139. getWidth(), getHeight());
  140. bottomShadow.draw(canvas);
  141. }
  142. /**
  143. * Draws value and label layout
  144. * @param canvas the canvas for drawing
  145. */
  146. privatevoid drawValue(Canvas canvas) {
  147. valuePaint.setColor(VALUE_TEXT_COLOR);
  148. valuePaint.drawableState = getDrawableState();
  149. Rect bounds =new Rect();
  150. itemsLayout.getLineBounds(visibleItems /2, bounds);
  151. // draw label
  152. if (labelLayout != null) {
  153. canvas.save();
  154. canvas.translate(itemsLayout.getWidth() + LABEL_OFFSET, bounds.top);
  155. labelLayout.draw(canvas);
  156. canvas.restore();
  157. }
  158. // draw current value
  159. if (valueLayout != null) {
  160. canvas.save();
  161. canvas.translate(0, bounds.top + scrollingOffset);
  162. valueLayout.draw(canvas);
  163. canvas.restore();
  164. }
  165. }
  166. /**
  167. * Draws items
  168. * @param canvas the canvas for drawing
  169. */
  170. privatevoid drawItems(Canvas canvas) {
  171. canvas.save();
  172. int top = itemsLayout.getLineTop(1);
  173. canvas.translate(0, - top + scrollingOffset);
  174. itemsPaint.setColor(ITEMS_TEXT_COLOR);
  175. itemsPaint.drawableState = getDrawableState();
  176. itemsLayout.draw(canvas);
  177. canvas.restore();
  178. }
  179. /**
  180. * Draws rect for current value
  181. * @param canvas the canvas for drawing
  182. */
  183. privatevoid drawCenterRect(Canvas canvas) {
  184. int center = getHeight() / 2;
  185. int offset = getItemHeight() / 2;
  186. centerDrawable.setBounds(0, center - offset, getWidth(), center + offset);
  187. centerDrawable.draw(canvas);
  188. }
  189. @Override
  190. publicboolean onTouchEvent(MotionEvent event) {
  191. WheelAdapter adapter = getAdapter();
  192. if (adapter == null) {
  193. returntrue;
  194. }
  195. if (!gestureDetector.onTouchEvent(event) && event.getAction() == MotionEvent.ACTION_UP) {
  196. justify();
  197. }
  198. returntrue;
  199. }
  200. /**
  201. * Scrolls the wheel
  202. * @param delta the scrolling value
  203. */
  204. privatevoid doScroll(int delta) {
  205. scrollingOffset += delta;
  206. int count = scrollingOffset / getItemHeight();
  207. int pos = currentItem - count;
  208. if (isCyclic && adapter.getItemsCount() > 0) {
  209. // fix position by rotating
  210. while (pos < 0) {
  211. pos += adapter.getItemsCount();
  212. }
  213. pos %= adapter.getItemsCount();
  214. }elseif (isScrollingPerformed) {
  215. //
  216. if (pos < 0) {
  217. count = currentItem;
  218. pos =0;
  219. }elseif (pos >= adapter.getItemsCount()) {
  220. count = currentItem - adapter.getItemsCount() +1;
  221. pos = adapter.getItemsCount() -1;
  222. }
  223. }else {
  224. // fix position
  225. pos = Math.max(pos,0);
  226. pos = Math.min(pos, adapter.getItemsCount() -1);
  227. }
  228. int offset = scrollingOffset;
  229. if (pos != currentItem) {
  230. setCurrentItem(pos,false);
  231. }else {
  232. invalidate();
  233. }
  234. // update offset
  235. scrollingOffset = offset - count * getItemHeight();
  236. if (scrollingOffset > getHeight()) {
  237. scrollingOffset = scrollingOffset % getHeight() + getHeight();
  238. }
  239. }
  240. // gesture listener
  241. private SimpleOnGestureListener gestureListener = new SimpleOnGestureListener() {
  242. publicboolean onDown(MotionEvent e) {
  243. if (isScrollingPerformed) {
  244. scroller.forceFinished(true);
  245. clearMessages();
  246. returntrue;
  247. }
  248. returnfalse;
  249. }
  250. publicboolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
  251. startScrolling();
  252. doScroll((int)-distanceY);
  253. returntrue;
  254. }
  255. publicboolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
  256. lastScrollY = currentItem * getItemHeight() + scrollingOffset;
  257. int maxY = isCyclic ? 0x7FFFFFFF : adapter.getItemsCount() * getItemHeight();
  258. int minY = isCyclic ? -maxY : 0;
  259. scroller.fling(0, lastScrollY, 0, (int) -velocityY / 2,0,0, minY, maxY);
  260. setNextMessage(MESSAGE_SCROLL);
  261. returntrue;
  262. }
  263. };
  264. // Messages
  265. privatefinalint MESSAGE_SCROLL = 0;
  266. privatefinalint MESSAGE_JUSTIFY = 1;
  267. /**
  268. * Set next message to queue. Clears queue before.
  269. *
  270. * @param message the message to set
  271. */
  272. privatevoid setNextMessage(int message) {
  273. clearMessages();
  274. animationHandler.sendEmptyMessage(message);
  275. }
  276. /**
  277. * Clears messages from queue
  278. */
  279. privatevoid clearMessages() {
  280. animationHandler.removeMessages(MESSAGE_SCROLL);
  281. animationHandler.removeMessages(MESSAGE_JUSTIFY);
  282. }
  283. // animation handler
  284. private Handler animationHandler = new Handler() {
  285. publicvoid handleMessage(Message msg) {
  286. scroller.computeScrollOffset();
  287. int currY = scroller.getCurrY();
  288. int delta = lastScrollY - currY;
  289. lastScrollY = currY;
  290. if (delta != 0) {
  291. doScroll(delta);
  292. }
  293. // scrolling is not finished when it comes to final Y
  294. // so, finish it manually
  295. if (Math.abs(currY - scroller.getFinalY()) < MIN_DELTA_FOR_SCROLLING) {
  296. currY = scroller.getFinalY();
  297. scroller.forceFinished(true);
  298. }
  299. if (!scroller.isFinished()) {
  300. animationHandler.sendEmptyMessage(msg.what);
  301. }elseif (msg.what == MESSAGE_SCROLL) {
  302. justify();
  303. }else {
  304. finishScrolling();
  305. }
  306. }
  307. };
  308. /**
  309. * Justifies wheel
  310. */
  311. privatevoid justify() {
  312. if (adapter == null) {
  313. return;
  314. }
  315. lastScrollY =0;
  316. int offset = scrollingOffset;
  317. int itemHeight = getItemHeight();
  318. boolean needToIncrease = offset > 0 ? currentItem < adapter.getItemsCount() : currentItem > 0;
  319. if ((isCyclic || needToIncrease) && Math.abs((float) offset) > (float) itemHeight / 2) {
  320. if (offset < 0)
  321. offset += itemHeight + MIN_DELTA_FOR_SCROLLING;
  322. else
  323. offset -= itemHeight + MIN_DELTA_FOR_SCROLLING;
  324. }
  325. if (Math.abs(offset) > MIN_DELTA_FOR_SCROLLING) {
  326. scroller.startScroll(0,0,0, offset, SCROLLING_DURATION);
  327. setNextMessage(MESSAGE_JUSTIFY);
  328. }else {
  329. finishScrolling();
  330. }
  331. }
  332. /**
  333. * Starts scrolling
  334. */
  335. privatevoid startScrolling() {
  336. if (!isScrollingPerformed) {
  337. isScrollingPerformed =true;
  338. notifyScrollingListenersAboutStart();
  339. }
  340. }
  341. /**
  342. * Finishes scrolling
  343. */
  344. void finishScrolling() {
  345. if (isScrollingPerformed) {
  346. notifyScrollingListenersAboutEnd();
  347. isScrollingPerformed =false;
  348. }
  349. invalidateLayouts();
  350. invalidate();
  351. }
  352. /**
  353. * Scroll the wheel
  354. * @param itemsToSkip items to scroll
  355. * @param time scrolling duration
  356. */
  357. publicvoid scroll(int itemsToScroll, int time) {
  358. scroller.forceFinished(true);
  359. lastScrollY = scrollingOffset;
  360. int offset = itemsToScroll * getItemHeight();
  361. scroller.startScroll(0, lastScrollY, 0, offset - lastScrollY, time);
  362. setNextMessage(MESSAGE_SCROLL);
  363. startScrolling();
  364. }

在629行到744行的代码是绘制图形,747行onTouchEvent()里面主要是调用了882行的justify()方法,用于调整画面,

[java] view plaincopy
  1. @Override
  2. publicboolean onTouchEvent(MotionEvent event) {
  3. WheelAdapter adapter = getAdapter();
  4. if (adapter == null) {
  5. returntrue;
  6. }
  7. if (!gestureDetector.onTouchEvent(event) && event.getAction() == MotionEvent.ACTION_UP) {
  8. justify();
  9. }
  10. returntrue;
  11. }


[java] view plaincopy
  1. /**
  2. * Justifies wheel
  3. */
  4. privatevoid justify() {
  5. if (adapter == null) {
  6. return;
  7. }
  8. lastScrollY =0;
  9. int offset = scrollingOffset;
  10. int itemHeight = getItemHeight();
  11. boolean needToIncrease = offset > 0 ? currentItem < adapter.getItemsCount() : currentItem > 0;
  12. if ((isCyclic || needToIncrease) && Math.abs((float) offset) > (float) itemHeight / 2) {
  13. if (offset < 0)
  14. offset += itemHeight + MIN_DELTA_FOR_SCROLLING;
  15. else
  16. offset -= itemHeight + MIN_DELTA_FOR_SCROLLING;
  17. }
  18. if (Math.abs(offset) > MIN_DELTA_FOR_SCROLLING) {
  19. scroller.startScroll(0,0,0, offset, SCROLLING_DURATION);
  20. setNextMessage(MESSAGE_JUSTIFY);
  21. }else {
  22. finishScrolling();
  23. }
  24. }

我们看下重写的系统回调函数onMeasure()(用于测量各个控件距离,父子控件空间大小等):

[java] view plaincopy
  1. @Override
  2. protectedvoid onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  3. int widthMode = MeasureSpec.getMode(widthMeasureSpec);
  4. int heightMode = MeasureSpec.getMode(heightMeasureSpec);
  5. int widthSize = MeasureSpec.getSize(widthMeasureSpec);
  6. int heightSize = MeasureSpec.getSize(heightMeasureSpec);
  7. int width = calculateLayoutWidth(widthSize, widthMode);
  8. int height;
  9. if (heightMode == MeasureSpec.EXACTLY) {
  10. height = heightSize;
  11. }else {
  12. height = getDesiredHeight(itemsLayout);
  13. if (heightMode == MeasureSpec.AT_MOST) {
  14. height = Math.min(height, heightSize);
  15. }
  16. }
  17. setMeasuredDimension(width, height);
  18. }

里面用到了532行calculateLayoutWidth()的方法,就是计算Layout的宽度,在calculateLayoutWidth()这个方法里面调用了

[java] view plaincopy
  1. /**
  2. * Creates layouts
  3. * @param widthItems width of items layout
  4. * @param widthLabel width of label layout
  5. */
  6. privatevoid createLayouts(int widthItems, int widthLabel) {
  7. if (itemsLayout == null || itemsLayout.getWidth() > widthItems) {
  8. itemsLayout =new StaticLayout(buildText(isScrollingPerformed), itemsPaint, widthItems,
  9. widthLabel >0 ? Layout.Alignment.ALIGN_OPPOSITE : Layout.Alignment.ALIGN_CENTER,
  10. 1, ADDITIONAL_ITEM_HEIGHT, false);
  11. }else {
  12. itemsLayout.increaseWidthTo(widthItems);
  13. }
  14. if (!isScrollingPerformed && (valueLayout == null || valueLayout.getWidth() > widthItems)) {
  15. String text = getAdapter() !=null ? getAdapter().getItem(currentItem) :null;
  16. valueLayout =new StaticLayout(text !=null ? text : "",
  17. valuePaint, widthItems, widthLabel >0 ?
  18. Layout.Alignment.ALIGN_OPPOSITE : Layout.Alignment.ALIGN_CENTER,
  19. 1, ADDITIONAL_ITEM_HEIGHT, false);
  20. }elseif (isScrollingPerformed) {
  21. valueLayout =null;
  22. }else {
  23. valueLayout.increaseWidthTo(widthItems);
  24. }
  25. if (widthLabel > 0) {
  26. if (labelLayout == null || labelLayout.getWidth() > widthLabel) {
  27. labelLayout =new StaticLayout(label, valuePaint,
  28. widthLabel, Layout.Alignment.ALIGN_NORMAL,1,
  29. ADDITIONAL_ITEM_HEIGHT,false);
  30. }else {
  31. labelLayout.increaseWidthTo(widthLabel);
  32. }
  33. }
  34. }

然后我们接着看onDraw()方法:

[java] view plaincopy
  1. @Override
  2. protectedvoid onDraw(Canvas canvas) {
  3. super.onDraw(canvas);
  4. if (itemsLayout == null) {
  5. if (itemsWidth == 0) {
  6. calculateLayoutWidth(getWidth(), MeasureSpec.EXACTLY);
  7. }else {
  8. createLayouts(itemsWidth, labelWidth);
  9. }
  10. }
  11. if (itemsWidth > 0) {
  12. canvas.save();
  13. // Skip padding space and hide a part of top and bottom items
  14. canvas.translate(PADDING, -ITEM_OFFSET);
  15. drawItems(canvas);
  16. drawValue(canvas);
  17. canvas.restore();
  18. }
  19. drawCenterRect(canvas);
  20. drawShadows(canvas);
  21. }

在onDraw方法中,也调用了CreateLayout()方法,然后在后面调用drawCenterRect()、drawItems()、drawValue()、绘制阴影drawShadows()两个方法:

[java] view plaincopy
  1. /**
  2. * Draws shadows on top and bottom of control
  3. * @param canvas the canvas for drawing
  4. */
  5. privatevoid drawShadows(Canvas canvas) {
  6. topShadow.setBounds(0,0, getWidth(), getHeight() / visibleItems);
  7. topShadow.draw(canvas);
  8. bottomShadow.setBounds(0, getHeight() - getHeight() / visibleItems,
  9. getWidth(), getHeight());
  10. bottomShadow.draw(canvas);
  11. }
  12. /**
  13. * Draws value and label layout
  14. * @param canvas the canvas for drawing
  15. */
  16. privatevoid drawValue(Canvas canvas) {
  17. valuePaint.setColor(VALUE_TEXT_COLOR);
  18. valuePaint.drawableState = getDrawableState();
  19. Rect bounds =new Rect();
  20. itemsLayout.getLineBounds(visibleItems /2, bounds);
  21. // draw label
  22. if (labelLayout != null) {
  23. canvas.save();
  24. canvas.translate(itemsLayout.getWidth() + LABEL_OFFSET, bounds.top);
  25. labelLayout.draw(canvas);
  26. canvas.restore();
  27. }
  28. // draw current value
  29. if (valueLayout != null) {
  30. canvas.save();
  31. canvas.translate(0, bounds.top + scrollingOffset);
  32. valueLayout.draw(canvas);
  33. canvas.restore();
  34. }
  35. }
  36. /**
  37. * Draws items
  38. * @param canvas the canvas for drawing
  39. */
  40. privatevoid drawItems(Canvas canvas) {
  41. canvas.save();
  42. int top = itemsLayout.getLineTop(1);
  43. canvas.translate(0, - top + scrollingOffset);
  44. itemsPaint.setColor(ITEMS_TEXT_COLOR);
  45. itemsPaint.drawableState = getDrawableState();
  46. itemsLayout.draw(canvas);
  47. canvas.restore();
  48. }
  49. /**
  50. * Draws rect for current value
  51. * @param canvas the canvas for drawing
  52. */
  53. privatevoid drawCenterRect(Canvas canvas) {
  54. int center = getHeight() / 2;
  55. int offset = getItemHeight() / 2;
  56. centerDrawable.setBounds(0, center - offset, getWidth(), center + offset);
  57. centerDrawable.draw(canvas);
  58. }


主要就是通过canvas类进行图形的绘制。


最后,我们看下840行定义的手势监听:

[java] view plaincopy
  1. // gesture listener
  2. private SimpleOnGestureListener gestureListener = new SimpleOnGestureListener() {
  3. publicboolean onDown(MotionEvent e) {
  4. if (isScrollingPerformed) {
  5. scroller.forceFinished(true);
  6. clearMessages();
  7. returntrue;
  8. }
  9. returnfalse;
  10. }
  11. publicboolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
  12. startScrolling();
  13. doScroll((int)-distanceY);
  14. returntrue;
  15. }
  16. publicboolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
  17. lastScrollY = currentItem * getItemHeight() + scrollingOffset;
  18. int maxY = isCyclic ? 0x7FFFFFFF : adapter.getItemsCount() * getItemHeight();
  19. int minY = isCyclic ? -maxY : 0;
  20. scroller.fling(0, lastScrollY, 0, (int) -velocityY / 2,0,0, minY, maxY);
  21. setNextMessage(MESSAGE_SCROLL);
  22. returntrue;
  23. }
  24. };

里面主要调用的方法:clearMessages()、startScrolling()、doScroll()、setNextMessage(),先看下中间的两个方法开始滑动和滑动

[java] view plaincopy
  1. /**
  2. * Scrolls the wheel
  3. * @param delta the scrolling value
  4. */
  5. privatevoid doScroll(int delta) {
  6. scrollingOffset += delta;
  7. int count = scrollingOffset / getItemHeight();
  8. int pos = currentItem - count;
  9. if (isCyclic && adapter.getItemsCount() > 0) {
  10. // fix position by rotating
  11. while (pos < 0) {
  12. pos += adapter.getItemsCount();
  13. }
  14. pos %= adapter.getItemsCount();
  15. }elseif (isScrollingPerformed) {
  16. //
  17. if (pos < 0) {
  18. count = currentItem;
  19. pos =0;
  20. }elseif (pos >= adapter.getItemsCount()) {
  21. count = currentItem - adapter.getItemsCount() +1;
  22. pos = adapter.getItemsCount() -1;
  23. }
  24. }else {
  25. // fix position
  26. pos = Math.max(pos,0);
  27. pos = Math.min(pos, adapter.getItemsCount() -1);
  28. }
  29. int offset = scrollingOffset;
  30. if (pos != currentItem) {
  31. setCurrentItem(pos,false);
  32. }else {
  33. invalidate();
  34. }
  35. // update offset
  36. scrollingOffset = offset - count * getItemHeight();
  37. if (scrollingOffset > getHeight()) {
  38. scrollingOffset = scrollingOffset % getHeight() + getHeight();
  39. }
  40. }

[java] view plaincopy
  1. /**
  2. * Starts scrolling
  3. */
  4. privatevoid startScrolling() {
  5. if (!isScrollingPerformed) {
  6. isScrollingPerformed =true;
  7. notifyScrollingListenersAboutStart();
  8. }
  9. }

在startScrolling方法里面有287行的notifyScrollingListenersAboutStart函数。

再看clearMessages()、setMessageNext()

[java] view plaincopy
  1. privatevoid setNextMessage(int message) {
  2. clearMessages();
  3. animationHandler.sendEmptyMessage(message);
  4. }
  5. /**
  6. * Clears messages from queue
  7. */
  8. privatevoid clearMessages() {
  9. animationHandler.removeMessages(MESSAGE_SCROLL);
  10. animationHandler.removeMessages(MESSAGE_JUSTIFY);
  11. }

里面使用到了animationHandler,用来传递动画有段的操作:

[java] view plaincopy
  1. // animation handler
  2. private Handler animationHandler = new Handler() {
  3. publicvoid handleMessage(Message msg) {
  4. scroller.computeScrollOffset();
  5. int currY = scroller.getCurrY();
  6. int delta = lastScrollY - currY;
  7. lastScrollY = currY;
  8. if (delta != 0) {
  9. doScroll(delta);
  10. }
  11. // scrolling is not finished when it comes to final Y
  12. // so, finish it manually
  13. if (Math.abs(currY - scroller.getFinalY()) < MIN_DELTA_FOR_SCROLLING) {
  14. currY = scroller.getFinalY();
  15. scroller.forceFinished(true);
  16. }
  17. if (!scroller.isFinished()) {
  18. animationHandler.sendEmptyMessage(msg.what);
  19. }elseif (msg.what == MESSAGE_SCROLL) {
  20. justify();
  21. }else {
  22. finishScrolling();
  23. }
  24. }
  25. };

里面调用了finishScrolling()

[java] view plaincopy
  1. /**
  2. * Finishes scrolling
  3. */
  4. void finishScrolling() {
  5. if (isScrollingPerformed) {
  6. notifyScrollingListenersAboutEnd();
  7. isScrollingPerformed =false;
  8. }
  9. invalidateLayouts();
  10. invalidate();
  11. }