【Android 应用开发】 自定义组件 宽高适配方法, 手势监听器操作组件, 回调接口维护策略, 绘制方法分析 -- 基于 WheelView 组件分析自定义组件

来源:互联网 发布:php 构造函数 编辑:程序博客网 时间:2024/05/17 06:03
 4952人阅读 评论(4) 收藏 举报
WheelView

目录(?)[+]


博客地址 http://blog.csdn.net/shulianghan/article/details/41520569


代码下载 : 

-- GitHub : https://github.com/han1202012/WheelViewDemo.git 

-- CSDN : http://download.csdn.net/detail/han1202012/8208997 ;



博客总结 :

 

博文内容 : 本文完整地分析了 WheelView 所有的源码, 包括其适配器类型两种回调接口 (选中条目改变回调, 和开始结束滚动回调), 以及详细的分析了 WheelView 主题源码, 其中 组件宽高测量手势监听器添加, 以及精准的绘图方法是主要目的, 花了将近1周时间, 感觉很值, 在这里分享给大家;


WheelView 使用方法 创建 WheelView 组件 --> 设置显示条目数 --> 设置循环 --> 设置适配器 --> 设置监听器 ;


自定义组件宽高获取策略 : MeasureSpec 最大模式 取 默认值 和 给定值中较小的那个未定义模式取默认值精准模式取 给定值;


自定义组件维护各种回调监听器策略 : 维护集合, 将监听器置于集合中, 回调接口时遍历集合元素, 回调每个元素的接口方法;


自定义组件手势监听器添加方法 : 创建手势监听器, 将手势监听器传入手势探测器, 在 onTouchEvent() 方法中回调手势监听器的 onTouchEvent()方法;



一. WheelView 简介



1. WheelView 效果


在 Android 中实现类似与 IOS 的 WheelView 控件 : 如图 




2. WheelView 使用流程



(1) 基本流程简介

 

获取组件 --> 设置显示条目数 --> 设置循环 --> 设置适配器 --> 设置条目改变监听器 --> 设置滚动监听器


a. 创建 WheelView 组件 : 使用 构造方法 或者 从布局文件获取 WheelView 组件;

b. 设置显示条目数 : 调用 WheelView 组件对象的 setVisibleItems 方法 设置;

c. 设置是否循环 : 设置 WheelView 是否循环, 调用 setCyclic() 方法设置;

d. 设置适配器 : 调用 WheelView 组件的 setAdapter() 方法设置;

e. 设置条目改变监听器 : 调用 WheelView 组件对象的 addChangingListener() 方法设置;

f. 设置滚动监听器 : 调用 WheelView 组件对象的 addScrollingListener() 方法设置;



(2) 代码实例


a. 创建 WheelView 对象 : 

[java] view plaincopy
  1. //创建 WheelView 组件  
  2. final WheelView wheelLeft = new WheelView(context);  

b. 设置 WheelView 显示条目数 : 

[java] view plaincopy
  1. //设置 WheelView 组件最多显示 5 个元素  
  2. wheelLeft.setVisibleItems(5);  

c. 设置 WheelView 是否滚动循环 : 

[java] view plaincopy
  1. //设置 WheelView 元素是否循环滚动  
  2. wheelLeft.setCyclic(false);  

d. 设置 WheelView 适配器 

[java] view plaincopy
  1. //设置 WheelView 适配器  
  2. wheelLeft.setAdapter(new ArrayWheelAdapter<String>(left));  

e. 设置条目改变监听器 : 

[java] view plaincopy
  1. //为左侧的 WheelView 设置条目改变监听器  
  2. wheelLeft.addChangingListener(new OnWheelChangedListener() {  
  3.     @Override  
  4.     public void onChanged(WheelView wheel, int oldValue, int newValue) {  
  5.         //设置右侧的 WheelView 的适配器  
  6.         wheelRight.setAdapter(new ArrayWheelAdapter<String>(right[newValue]));  
  7.         wheelRight.setCurrentItem(right[newValue].length / 2);  
  8.     }  
  9. });  

f. 设置滚动监听器 : 

[java] view plaincopy
  1.      wheelLeft.addScrollingListener(new OnWheelScrollListener() {  
  2.   
  3. @Override  
  4. public void onScrollingStarted(WheelView wheel) {  
  5.     // TODO Auto-generated method stub  
  6.       
  7. }  
  8.   
  9. @Override  
  10. public void onScrollingFinished(WheelView wheel) {  
  11.     // TODO Auto-generated method stub  
  12.       
  13. }  
  14. );  




二. WheelView  适配器 监听器 相关接口分析



1. 适配器 分析



这里定义了一个适配器接口, 以及两个适配器类, 一个用于任意类型的数据集适配, 一个用于数字适配;


适配器操作 : 在 WheelView.java 中通过 setAdapter(WheelAdapter adapter) 和 getAdapter() 方法设置 获取 适配器;

-- 适配器常用操作 : 在 WheelView 中定义了 getItem(), getItemsCount(), getMaxmiumLength() 方法获取 适配器的相关信息;

[java] view plaincopy
  1. /** 
  2.  * 获取该 WheelView 的适配器 
  3.  *  
  4.  * @return  
  5.  *      返回适配器 
  6.  */  
  7. public WheelAdapter getAdapter() {  
  8.     return adapter;  
  9. }  
  10.   
  11. /** 
  12.  * 设置适配器 
  13.  *  
  14.  * @param adapter 
  15.  *            要设置的适配器 
  16.  */  
  17. public void setAdapter(WheelAdapter adapter) {  
  18.     this.adapter = adapter;  
  19.     invalidateLayouts();  
  20.     invalidate();  
  21. }  




(1) 适配器接口 ( interface WheelAdapter )


适配器接口 : WheelAdapter;

-- 接口作用 : 该接口是所有适配器的接口, 适配器类都需要实现该接口;


接口抽象方法介绍 : 

-- getItemsCount() : 获取适配器数据集合中元素个数;

[java] view plaincopy
  1. /** 
  2.  * 获取条目的个数 
  3.  *  
  4.  * @return  
  5.  *      WheelView 的条目个数 
  6.  */  
  7. public int getItemsCount();  


-- getItem(int index) : 获取适配器集合的中指定索引元素;

[java] view plaincopy
  1. /** 
  2.  * 根据索引位置获取 WheelView 的条目 
  3.  *  
  4.  * @param index 
  5.  *            条目的索引 
  6.  * @return  
  7.  *      WheelView 上显示的条目的值 
  8.  */  
  9. public String getItem(int index);  


-- getMaximumLength() : 获取 WheelView 在界面上的显示宽度;

[java] view plaincopy
  1. /** 
  2.  * 获取条目的最大长度. 用来定义 WheelView 的宽度. 如果返回 -1, 就会使用默认宽度 
  3.  *  
  4.  * @return  
  5.  *      条目的最大宽度 或者 -1 
  6.  */  
  7. public int getMaximumLength();  



(2) 数组适配器 ( class ArrayWheelAdapter<T> implements WheelAdapter )


适配器作用 : 该适配器可以传入任何数据类型的数组, 可以是 字符串数组, 也可以是任何对象的数组, 传入的数组作为适配器的数据源;


成员变量分析 

-- 数据源 

[java] view plaincopy
  1. /** 适配器的数据源 */  
  2. private T items[];  


-- WheelView 最大宽度 

[java] view plaincopy
  1. /** WheelView 的宽度 */  
  2. private int length;  



构造方法分析 

-- ArrayWheelAdapter(T items[], int length) : 传入 T 类型 对象数组, 以及 WheelView 的宽度;

[java] view plaincopy
  1. /** 
  2.  * 构造方法 
  3.  *  
  4.  * @param items 
  5.  *            适配器数据源 集合 T 类型的数组 
  6.  * @param length 
  7.  *            适配器数据源 集合 T 数组长度 
  8.  */  
  9. public ArrayWheelAdapter(T items[], int length) {  
  10.     this.items = items;  
  11.     this.length = length;  
  12. }  


-- ArrayWheelAdapter(T items[]) : 传入 T 类型对象数组, 宽度使用默认的宽度;

[java] view plaincopy
  1. /** 
  2.  * 构造方法 
  3.  *  
  4.  * @param items 
  5.  *            适配器数据源集合 T 类型数组 
  6.  */  
  7. public ArrayWheelAdapter(T items[]) {  
  8.     this(items, DEFAULT_LENGTH);  
  9. }  


实现的父类方法分析 :

--  getItem(int index) : 根据索引获取数组中对应位置的对象的字符串类型;

[java] view plaincopy
  1. @Override  
  2. public String getItem(int index) {  
  3.     //如果这个索引值合法, 就返回 item 数组对应的元素的字符串形式  
  4.     if (index >= 0 && index < items.length) {  
  5.         return items[index].toString();  
  6.     }  
  7.     return null;  
  8. }  


-- getItemsCount() : 获取数据集广大小, 直接返回数组大小;

[java] view plaincopy
  1. @Override  
  2. public int getItemsCount() {  
  3.     //返回 item 数组的长度  
  4.     return items.length;  
  5. }  


-- getMaximumLength() : 获取 WheelView 的最大宽度;

[java] view plaincopy
  1. @Override  
  2. public int getMaximumLength() {  
  3.     //返回 item 元素的宽度  
  4.     return length;  
  5. }  



(3) 数字适配器 ( class NumericWheelAdapter implements WheelAdapter )


NumericWheelAdapter 适配器作用 : 数字作为 WheelView 适配器的显示值;



成员变量分析 : 

-- 最小值 : WheelView 数值显示的最小值;

[java] view plaincopy
  1. /** 设置的最小值 */  
  2. private int minValue;  


-- 最大值 : WheelView 数值显示的最大值;

[java] view plaincopy
  1. /** 设置的最大值 */  
  2. private int maxValue;  

-- 格式化字符串 : 用于字符串的格式化;

[java] view plaincopy
  1. /** 格式化字符串, 用于格式化 货币, 科学计数, 十六进制 等格式 */  
  2. private String format;  


构造方法分析 : 

-- NumericWheelAdapter() : 默认的构造方法, 使用默认的最大最小值;

[java] view plaincopy
  1. /** 
  2.  * 默认的构造方法, 使用默认的最大最小值 
  3.  */  
  4. public NumericWheelAdapter() {  
  5.     this(DEFAULT_MIN_VALUE, DEFAULT_MAX_VALUE);  
  6. }  


-- NumericWheelAdapter(int minValue, int maxValue) : 传入一个最大最小值;

[java] view plaincopy
  1. /** 
  2.  * 构造方法 
  3.  *  
  4.  * @param minValue 
  5.  *            最小值 
  6.  * @param maxValue 
  7.  *            最大值 
  8.  */  
  9. public NumericWheelAdapter(int minValue, int maxValue) {  
  10.     this(minValue, maxValue, null);  
  11. }  


-- NumericWheelAdapter(int minValue, int maxValue, String format) : 传入最大最小值, 以及数字格式化方式;

[java] view plaincopy
  1. /** 
  2.  * 构造方法 
  3.  *  
  4.  * @param minValue 
  5.  *            最小值 
  6.  * @param maxValue 
  7.  *            最大值 
  8.  * @param format 
  9.  *            格式化字符串 
  10.  */  
  11. public NumericWheelAdapter(int minValue, int maxValue, String format) {  
  12.     this.minValue = minValue;  
  13.     this.maxValue = maxValue;  
  14.     this.format = format;  
  15. }  


实现的父类方法 : 

-- 获取条目 : 如果需要格式化, 先进行格式化;

[java] view plaincopy
  1. @Override  
  2. public String getItem(int index) {  
  3.     String result = "";  
  4.     if (index >= 0 && index < getItemsCount()) {  
  5.         int value = minValue + index;  
  6.         //如果 format 不为 null, 那么格式化字符串, 如果为 null, 直接返回数字  
  7.         if(format != null){  
  8.             result = String.format(format, value);  
  9.         }else{  
  10.             result = Integer.toString(value);  
  11.         }  
  12.         return result;  
  13.     }  
  14.     return null;  
  15. }  

-- 获取元素个数 : 

[java] view plaincopy
  1. @Override  
  2. public int getItemsCount() {  
  3.     //返回数字总个数  
  4.     return maxValue - minValue + 1;  
  5. }  

-- 获取 WheelView 最大宽度 

[java] view plaincopy
  1. @Override  
  2. public int getMaximumLength() {  
  3.     //获取 最大值 和 最小值 中的 较大的数字  
  4.     int max = Math.max(Math.abs(maxValue), Math.abs(minValue));  
  5.     //获取这个数字 的 字符串形式的 字符串长度  
  6.     int maxLen = Integer.toString(max).length();  
  7.     if (minValue < 0) {  
  8.         maxLen++;  
  9.     }  
  10.     return maxLen;  
  11. }  



2. 监听器相关接口



(1) 条目改变监听器 ( interface OnWheelChangedListener )


监听器作用 : 在 WheelView 条目改变的时候, 回调该监听器的接口方法, 执行条目改变对应的操作;


接口方法介绍 : 

-- onChanged(WheelView wheel, int oldValue, int newValue) : 传入 WheelView 组件对象, 以及 旧的 和 新的 条目值索引;

[java] view plaincopy
  1. /** 
  2.  * 当前条目改变时回调该方法 
  3.  *  
  4.  * @param wheel 
  5.  *            条目改变的 WheelView 对象 
  6.  * @param oldValue 
  7.  *            WheelView 旧的条目值 
  8.  * @param newValue 
  9.  *            WheelView 新的条目值 
  10.  */  
  11. void onChanged(WheelView wheel, int oldValue, int newValue);  



(2) 滚动监听器 ( interface OnWheelScrollListener )


滚动监听器作用 : 在 WheelView 滚动动作 开始 和 结束的时候回调对应的方法, 在对应方法中进行相应的操作;



接口方法介绍 

-- 开始滚动方法 : 在滚动开始的时候回调该方法;

[java] view plaincopy
  1. /** 
  2.  * 在 WheelView 滚动开始的时候回调该接口 
  3.  *  
  4.  * @param wheel 
  5.  *            开始滚动的 WheelView 对象 
  6.  */  
  7. void onScrollingStarted(WheelView wheel);  


-- 停止滚动方法 : 在滚动结束的时候回调该方法;

[java] view plaincopy
  1. /** 
  2.  * 在 WheelView 滚动结束的时候回调该接口 
  3.  *  
  4.  * @param wheel 
  5.  *            结束滚动的 WheelView 对象 
  6.  */  
  7. void onScrollingFinished(WheelView wheel);  



三. WheelView 解析



1. 触摸 点击 手势 动作操作控制组件 模块



(1) 创建手势监听器


手势监听器创建及对应方法 : 

-- onDown(MotionEvent e) : 在按下的时候回调该方法, e 参数是按下的事件;

-- onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) : 滚动的时候回调该方法, e1 滚动第一次按下事件, e2 当前滚动的触摸事件, X 上一次滚动到这一次滚动 x 轴距离, Y 上一次滚动到这一次滚动 y 轴距离;

-- onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) : 快速急冲滚动时回调的方法, e1 e2 与上面参数相同, velocityX 是手势在 x 轴的速度, velocityY 是手势在 y 轴的速度;

-- 代码示例 : 

[java] view plaincopy
  1.     /* 
  2.      * 手势监听器监听到 滚动操作后回调 
  3.      *  
  4.      * 参数解析 :  
  5.      * MotionEvent e1 : 触发滚动时第一次按下的事件 
  6.      * MotionEvent e2 : 触发当前滚动的移动事件 
  7.      * float distanceX : 自从上一次调用 该方法 到这一次 x 轴滚动的距离,  
  8.      *              注意不是 e1 到 e2 的距离, e1 到 e2 的距离是从开始滚动到现在的滚动距离 
  9.      * float distanceY : 自从上一次回调该方法到这一次 y 轴滚动的距离 
  10.      *  
  11.      * 返回值 : 如果事件成功触发, 执行完了方法中的操作, 返回true, 否则返回 false  
  12.      * (non-Javadoc) 
  13.      * @see android.view.GestureDetector.SimpleOnGestureListener#onScroll(android.view.MotionEvent, android.view.MotionEvent, float, float) 
  14.      */  
  15.     public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {  
  16.         //开始滚动, 并回调滚动监听器集合中监听器的 开始滚动方法  
  17.         startScrolling();  
  18.         doScroll((int) -distanceY);  
  19.         return true;  
  20.     }  
  21.   
  22.     /* 
  23.      * 当一个急冲手势发生后 回调该方法, 会计算出该手势在 x 轴 y 轴的速率 
  24.      *  
  25.      * 参数解析 :  
  26.      * -- MotionEvent e1 : 急冲动作的第一次触摸事件; 
  27.      * -- MotionEvent e2 : 急冲动作的移动发生的时候的触摸事件; 
  28.      * -- float velocityX : x 轴的速率 
  29.      * -- float velocityY : y 轴的速率 
  30.      *  
  31.      * 返回值 : 如果执行完毕返回 true, 否则返回false, 这个就是自己定义的 
  32.      *  
  33.      * (non-Javadoc) 
  34.      * @see android.view.GestureDetector.SimpleOnGestureListener#onFling(android.view.MotionEvent, android.view.MotionEvent, float, float) 
  35.      */  
  36.     public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {  
  37.         //计算上一次的 y 轴位置, 当前的条目高度 加上 剩余的 不够一行高度的那部分  
  38.         lastScrollY = currentItem * getItemHeight() + scrollingOffset;  
  39.         //如果可以循环最大值是无限大, 不能循环就是条目数的高度值  
  40.         int maxY = isCyclic ? 0x7FFFFFFF : adapter.getItemsCount() * getItemHeight();  
  41.         int minY = isCyclic ? -maxY : 0;  
  42.         /* 
  43.          * Scroll 开始根据一个急冲手势滚动, 滚动的距离与初速度有关 
  44.          * 参数介绍 :  
  45.          * -- int startX : 开始时的 X轴位置 
  46.          * -- int startY : 开始时的 y轴位置 
  47.          * -- int velocityX : 急冲手势的 x 轴的初速度, 单位 px/s 
  48.          * -- int velocityY : 急冲手势的 y 轴的初速度, 单位 px/s 
  49.          * -- int minX : x 轴滚动的最小值 
  50.          * -- int maxX : x 轴滚动的最大值 
  51.          * -- int minY : y 轴滚动的最小值 
  52.          * -- int maxY : y 轴滚动的最大值 
  53.          */  
  54.         scroller.fling(0, lastScrollY, 0, (int) -velocityY / 200, minY, maxY);  
  55.         setNextMessage(MESSAGE_SCROLL);  
  56.         return true;  
  57.     }  
  58. };  



(2) 创建手势探测器


手势探测器创建 : 调用 其构造函数, 传入 上下文对象 和 手势监听器对象;

-- 禁止长按操作 : 调用 setIsLongpressEnabled(false) 方法, 禁止长按操作, 因为 长按操作会屏蔽滚动事件;

[java] view plaincopy
  1. //创建一个手势处理  
  2.    gestureDetector = new GestureDetector(context, gestureListener);  
  3.    /* 
  4.     * 是否允许长按操作,  
  5.     * 如果设置为 true 用户按下不松开, 会返回一个长按事件,  
  6.     * 如果设置为 false, 按下不松开滑动的话 会收到滚动事件. 
  7.     */  
  8.    gestureDetector.setIsLongpressEnabled(false);  



(3) 将手势探测器 与 组件结合


关联手势探测器 与 组件 : 在组件的 onTouchEvent(MotionEvent event) 方法中, 调用手势探测器的 gestureDetector.onTouchEvent(event) 方法即可;

[java] view plaincopy
  1. /* 
  2.  * 继承自 View 的触摸事件, 当出现触摸事件的时候, 就会回调该方法 
  3.  * (non-Javadoc) 
  4.  * @see android.view.View#onTouchEvent(android.view.MotionEvent) 
  5.  */  
  6. @Override  
  7. public boolean onTouchEvent(MotionEvent event) {  
  8.     //获取适配器  
  9.     WheelAdapter adapter = getAdapter();  
  10.     if (adapter == null) {  
  11.         return true;  
  12.     }  
  13.   
  14.     /* 
  15.      * gestureDetector.onTouchEvent(event) : 分析给定的动作, 如果可用, 调用 手势检测器的 onTouchEvent 方法 
  16.      * -- 参数解析 : ev , 触摸事件 
  17.      * -- 返回值 : 如果手势监听器成功执行了该方法, 返回true, 如果执行出现意外 返回 false; 
  18.      */  
  19.     if (!gestureDetector.onTouchEvent(event) && event.getAction() == MotionEvent.ACTION_UP) {  
  20.         justify();  
  21.     }  
  22.     return true;  
  23. }  




2. Scroller 简介



(1) Scroller 简介 


Scroller 通用作用 : Scroller 组件并不是一个布局组件, 该组件是运行在后台的, 通过一些方法设定 Scroller 对象 的操作 或者 动画, 然后让 Scroller 运行在后台中 用于模拟滚动操作, 在适当的时机 获取该对象的坐标信息, 这些信息是在后台运算出来的;


Scroller 在本 View 中作用 : Android 的这个自定义的 WheelView 组件, 可以平滑的滚动, 当我们做一个加速滑动时, 会根据速度计算出滑动的距离, 这些数据都是在 Scroller 中计算出来的;



(2) 设定 Scroller 对象的动作参数 


终止滚动 : 

-- 终止滚动 跳转到目标位置 : 终止平缓的动画, 直接跳转到最终的 x y 轴的坐标位置;

[java] view plaincopy
  1. public void abortAnimation()  

-- 终止滚动 停止在当前位置 : 强行结束 Scroll 的滚动;

[java] view plaincopy
  1. public final void forceFinished(boolean finished)  


设置滚动参数 : 

-- 设置最终 x 轴坐标 : 

[java] view plaincopy
  1. public void setFinalX(int newX)  

-- 设置最终 y 轴坐标 : 

[java] view plaincopy
  1. public void setFinalY(int newY)  

-- 设置滚动摩擦力 : 

[java] view plaincopy
  1. public final void setFriction(float friction)  


设置动作 

-- 开始滚动 : 传入参数 开始 x 位置, 开始 y 位置, x 轴滚动距离, y 轴滚动距离;

[java] view plaincopy
  1. public void startScroll(int startX, int startY, int dx, int dy)  
-- 开始滚动 设定时间 : 最后一个参数是时间, 单位是 ms;

[java] view plaincopy
  1. public void startScroll(int startX, int startY, int dx, int dy, int duration)  
-- 急冲滚动 : 根据一个 急冲 手势进行滚动, 传入参数 : x轴开始位置, y轴开始位置, x 轴速度, y 轴速度, x 轴最小速度, x 轴最大速度, y 轴最小速度, y 轴最大速度;

[java] view plaincopy
  1. public void fling(int startX, int startY, int velocityX, int velocityY,  
  2.             int minX, int maxX, int minY, int maxY)  


延长滚动时间 : 延长滚动的时间, 让滚动滚的更远一些;

[java] view plaincopy
  1. public void extendDuration(int extend)  



(3) 获取 Scroll 后台运行参数 



获取当前数据 : 

-- 获取当前 x 轴坐标 : 

[java] view plaincopy
  1. public final int getCurrX()  

-- 获取当前 y 轴坐标 : 

[java] view plaincopy
  1. public final int getCurrY()  

-- 获取当前速度 : 

[java] view plaincopy
  1. public float getCurrVelocity()  


获取开始结束时的数据  : 

-- 获取开始 x 轴坐标 : 

[java] view plaincopy
  1. public final int getStartX()  

-- 获取开始 y 轴坐标 : 

[java] view plaincopy
  1. public final int getStartY()  

-- 获取最终 x 轴坐标 : 该参数只在急冲滚动时有效;

[java] view plaincopy
  1. public final int getFinalX()  

-- 获取最终 y 轴坐标 : 该参数只在急冲滚动时有效;

[java] view plaincopy
  1. public final int getFinalY()  


查看是否滚动完毕 : 

[java] view plaincopy
  1. public final boolean isFinished()  


获取从开始滚动到现在的时间 : 

[java] view plaincopy
  1. public int timePassed()  


获取新位置 : 调用该方法可以获取新位置, 如果返回 true 说明动画还没执行完毕;

[java] view plaincopy
  1. public boolean computeScrollOffset()  



(4) Scroll 在 WheelView 中的运用


Scroller 创建 

[java] view plaincopy
  1. //使用默认的 时间 和 插入器 创建一个滚动器  
  2. scroller = new Scroller(context);  


手势监听器 SimpleOnGestureListener 对象中的 onDown() 方法 : 如果滚动还在执行, 那么强行停止 Scroller 滚动;

[java] view plaincopy
  1. //按下操作  
  2.    public boolean onDown(MotionEvent e) {  
  3.     //如果滚动在执行  
  4.        if (isScrollingPerformed) {  
  5.         //滚动强制停止, 按下的时候不能继续滚动  
  6.            scroller.forceFinished(true);  
  7.            //清理信息  
  8.            clearMessages();  
  9.            return true;  
  10.        }  
  11.        return false;  
  12.    }  


当手势监听器 SimpleOnGestureListener 对象中有急冲动作时 onFling() 方法中 : 手势监听器监听到了 急冲动作, 那么 Scroller 也进行对应操作;

[java] view plaincopy
  1. public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {  
  2.     //计算上一次的 y 轴位置, 当前的条目高度 加上 剩余的 不够一行高度的那部分  
  3.     lastScrollY = currentItem * getItemHeight() + scrollingOffset;  
  4.     //如果可以循环最大值是无限大, 不能循环就是条目数的高度值  
  5.     int maxY = isCyclic ? 0x7FFFFFFF : adapter.getItemsCount() * getItemHeight();  
  6.     int minY = isCyclic ? -maxY : 0;  
  7.     /* 
  8.      * Scroll 开始根据一个急冲手势滚动, 滚动的距离与初速度有关 
  9.      * 参数介绍 :  
  10.      * -- int startX : 开始时的 X轴位置 
  11.      * -- int startY : 开始时的 y轴位置 
  12.      * -- int velocityX : 急冲手势的 x 轴的初速度, 单位 px/s 
  13.      * -- int velocityY : 急冲手势的 y 轴的初速度, 单位 px/s 
  14.      * -- int minX : x 轴滚动的最小值 
  15.      * -- int maxX : x 轴滚动的最大值 
  16.      * -- int minY : y 轴滚动的最小值 
  17.      * -- int maxY : y 轴滚动的最大值 
  18.      */  
  19.     scroller.fling(0, lastScrollY, 0, (int) -velocityY / 200, minY, maxY);  
  20.     setNextMessage(MESSAGE_SCROLL);  
  21.     return true;  
  22. }  


动画控制 Handler 中 : 

-- 滚动 : 获取当前 Scroller 的 y 轴位置, 与上一次的 y 轴位置对比, 如果 间距 delta 不为0, 就滚动;  

-- 查看是否停止 : 如果现在距离 到 最终距离 小于最小滚动距离, 强制停止;

-- 执行 msg.what 指令 : 如果需要停止, 强制停止, 否则调整坐标;

[java] view plaincopy
  1. /** 
  2.  * 动画控制器 
  3.  *  animation handler 
  4.  *   
  5.  *  可能会造成内存泄露 : 添加注解 HandlerLeak 
  6.  *  Handler 类应该应该为static类型,否则有可能造成泄露。 
  7.  *  在程序消息队列中排队的消息保持了对目标Handler类的应用。 
  8.  *  如果Handler是个内部类,那 么它也会保持它所在的外部类的引用。 
  9.  *  为了避免泄露这个外部类,应该将Handler声明为static嵌套类,并且使用对外部类的弱应用。 
  10.  */  
  11. @SuppressLint("HandlerLeak")  
  12. vate Handler animationHandler = new Handler() {  
  13.     public void handleMessage(Message msg) {  
  14.         //回调该方法获取当前位置, 如果返回true, 说明动画还没有执行完毕  
  15.         scroller.computeScrollOffset();  
  16.         //获取当前 y 位置  
  17.         int currY = scroller.getCurrY();  
  18.         //获取已经滚动了的位置, 使用上一次位置 减去 当前位置  
  19.         int delta = lastScrollY - currY;  
  20.         lastScrollY = currY;  
  21.         if (delta != 0) {  
  22.             //改变值不为 0 , 继续滚动  
  23.             doScroll(delta);  
  24.         }  
  25.   
  26.         /* 
  27.          * 如果滚动到了指定的位置, 滚动还没有停止 
  28.          * 这时需要强制停止 
  29.          */  
  30.         if (Math.abs(currY - scroller.getFinalY()) < MIN_DELTA_FOR_SCROLLING) {  
  31.             currY = scroller.getFinalY();  
  32.             scroller.forceFinished(true);  
  33.         }  
  34.           
  35.         /* 
  36.          * 如果滚动没有停止 
  37.          * 再向 Handler 发送一个停止 
  38.          */  
  39.         if (!scroller.isFinished()) {  
  40.             animationHandler.sendEmptyMessage(msg.what);  
  41.         } else if (msg.what == MESSAGE_SCROLL) {  
  42.             justify();  
  43.         } else {  
  44.             finishScrolling();  
  45.         }  
  46.     }  
  47. };  




3. StaticLayout 布局容器



(1) StaticLayout 解析


StaticLayout 解析 : 该组件用于显示文本, 一旦该文本被显示后, 就不能再编辑, 如果想要修改文本, 使用 DynamicLayout 布局即可; 

-- 使用场景 : 一般情况下不会使用该组件, 当想要自定义组件 或者 想要使用 Canvas 绘制文本时 才使用该布局;



常用方法解析 : 

-- 获取底部 Padding : 获取底部 到最后一行文字的 间隔, 单位是 px;

[java] view plaincopy
  1. public int getBottomPadding()  

-- 获取顶部 Padding : 

[java] view plaincopy
  1. public int getTopPadding()  

-- 获取省略个数 : 获取某一行需要省略的字符个数;

[java] view plaincopy
  1. public int getEllipsisCount(int line)  
-- 获取省略开始位置 : 获取某一行要省略的字符串的第一个位置索引;

[java] view plaincopy
  1. public int getEllipsisStart(int line)  
-- 获取省略的宽度 : 获取某一行省略字符串的宽度, 单位 px;

[java] view plaincopy
  1. public int getEllipsisStart(int line)  
-- 获取是否处理特殊符号 : 

[java] view plaincopy
  1. public boolean getLineContainsTab(int line)  
-- 获取文字的行数 : 

[java] view plaincopy
  1. public int getLineCount()  
-- 获取顶部位置 : 获取某一行顶部的位置;

[java] view plaincopy
  1. public int getLineTop(int line)  
-- 获取某一行底部位置 : 

[java] view plaincopy
  1. public int getLineDescent(int line)  
-- 获取行的方向 : 字符串从左至右 还是从右至左;

[java] view plaincopy
  1. public final Directions getLineDirections(int line)  
-- 获取某行第一个字符索引 : 获取的是 某一行 第一个字符 在整个字符串的索引;

[java] view plaincopy
  1. public int getLineStart(int line)  
-- 获取该行段落方向 : 获取该行文字方向, 左至右 或者 右至左;

[java] view plaincopy
  1. public int getParagraphDirection(int line)  
-- 获取某个垂直位置显示的行数 : 

[java] view plaincopy
  1. public int getLineForVertical(int vertical)  



(2) 布局显示


布局创建 : 

-- 三种布局 : WheelView 中涉及到了三种 StaticLayout 布局, 普通条目布局 itemLayout, 选中条目布局 valueLayout, 标签布局 labelLayout;

-- 创建时机 : 在 View 组件 每次 onMeasure() 和 onDraw() 方法中都要重新创建对应布局;

-- 创建布局源码 : 

[java] view plaincopy
  1. /** 
  2.  * 创建布局 
  3.  *  
  4.  * @param widthItems 
  5.  *            布局条目宽度 
  6.  * @param widthLabel 
  7.  *            label 宽度 
  8.  */  
  9. private void createLayouts(int widthItems, int widthLabel) {  
  10.     /* 
  11.      * 创建普通条目布局 
  12.      * 如果 普通条目布局 为 null 或者 普通条目布局的宽度 大于 传入的宽度, 这时需要重新创建布局 
  13.      * 如果 普通条目布局存在, 并且其宽度小于传入的宽度, 此时需要将 
  14.      */  
  15.     if (itemsLayout == null || itemsLayout.getWidth() > widthItems) {  
  16.           
  17.         /* 
  18.          * android.text.StaticLayout.StaticLayout( 
  19.          * CharSequence source, TextPaint paint,  
  20.          * int width, Alignment align,  
  21.          * float spacingmult, float spacingadd, boolean includepad) 
  22.          * 传入参数介绍 :  
  23.          * CharSequence source : 需要分行显示的字符串 
  24.          * TextPaint paint : 绘制字符串的画笔 
  25.          * int width : 条目的宽度 
  26.          * Alignment align : Layout 的对齐方式, ALIGN_CENTER 居中对齐, ALIGN_NORMAL 左对齐, Alignment.ALIGN_OPPOSITE 右对齐 
  27.          * float spacingmult : 行间距, 1.5f 代表 1.5 倍字体高度 
  28.          * float spacingadd : 基础行距上增加多少 , 真实行间距 等于 spacingmult 和 spacingadd 的和 
  29.          * boolean includepad :  
  30.          */  
  31.         itemsLayout = new StaticLayout(buildText(isScrollingPerformed), itemsPaint, widthItems,  
  32.                 widthLabel > 0 ? Layout.Alignment.ALIGN_OPPOSITE : Layout.Alignment.ALIGN_CENTER, 1,  
  33.                 ADDITIONAL_ITEM_HEIGHT, false);  
  34.     } else {  
  35.         //调用 Layout 内置的方法 increaseWidthTo 将宽度提升到指定的宽度  
  36.         itemsLayout.increaseWidthTo(widthItems);  
  37.     }  
  38.   
  39.     /* 
  40.      * 创建选中条目 
  41.      */  
  42.     if (!isScrollingPerformed && (valueLayout == null || valueLayout.getWidth() > widthItems)) {  
  43.         String text = getAdapter() != null ? getAdapter().getItem(currentItem) : null;  
  44.         valueLayout = new StaticLayout(text != null ? text : "", valuePaint, widthItems,  
  45.                 widthLabel > 0 ? Layout.Alignment.ALIGN_OPPOSITE : Layout.Alignment.ALIGN_CENTER, 1,  
  46.                 ADDITIONAL_ITEM_HEIGHT, false);  
  47.     } else if (isScrollingPerformed) {  
  48.         valueLayout = null;  
  49.     } else {  
  50.         valueLayout.increaseWidthTo(widthItems);  
  51.     }  
  52.   
  53.     /* 
  54.      * 创建标签条目 
  55.      */  
  56.     if (widthLabel > 0) {  
  57.         if (labelLayout == null || labelLayout.getWidth() > widthLabel) {  
  58.             labelLayout = new StaticLayout(label, valuePaint, widthLabel, Layout.Alignment.ALIGN_NORMAL, 1,  
  59.                     ADDITIONAL_ITEM_HEIGHT, false);  
  60.         } else {  
  61.             labelLayout.increaseWidthTo(widthLabel);  
  62.         }  
  63.     }  
  64. }  



4. 监听器管理



监听器集合维护 

-- 定义监听器集合 : 在 View 组件中 定义一个 List 集合, 集合中存放 监听器元素;

[java] view plaincopy
  1. /** 条目改变监听器集合  封装了条目改变方法, 当条目改变时回调 */  
  2. private List<OnWheelChangedListener> changingListeners = new LinkedList<OnWheelChangedListener>();  
  3. /** 条目滚动监听器集合, 该监听器封装了 开始滚动方法, 结束滚动方法 */  
  4. private List<OnWheelScrollListener> scrollingListeners = new LinkedList<OnWheelScrollListener>();  


-- 提供对监听器集合的添加删除接口 : 提供 对集合 进行 添加 和 删除的接口;

[java] view plaincopy
  1. /** 
  2.  * 添加 WheelView 选择的元素改变监听器 
  3.  *  
  4.  * @param listener 
  5.  *            the listener 
  6.  */  
  7. public void addChangingListener(OnWheelChangedListener listener) {  
  8.     changingListeners.add(listener);  
  9. }  
  10.   
  11. /** 
  12.  * 移除 WheelView 元素改变监听器 
  13.  *  
  14.  * @param listener 
  15.  *            the listener 
  16.  */  
  17. public void removeChangingListener(OnWheelChangedListener listener) {  
  18.     changingListeners.remove(listener);  
  19. }  

-- 调用监听器接口 : 

[java] view plaincopy
  1. /** 
  2.  * 回调元素改变监听器集合的元素改变监听器元素的元素改变方法 
  3.  *  
  4.  * @param oldValue 
  5.  *            旧的 WheelView选中的值 
  6.  * @param newValue 
  7.  *            新的 WheelView选中的值 
  8.  */  
  9. protected void notifyChangingListeners(int oldValue, int newValue) {  
  10.     for (OnWheelChangedListener listener : changingListeners) {  
  11.         listener.onChanged(this, oldValue, newValue);  
  12.     }  
  13. }  



5. 自定义 View 对象的宽高 



(1) onMeasure 方法 MeasureSpec 模式解析


常规处理方法 : 组件的宽高有三种情况, widthMeasureSpec 有三种模式 最大模式, 精准模式, 未定义模式;

-- 最大模式 : 在 组件的宽或高 warp_content 属性时, 会使用最大模式;

-- 精准模式 : 当给组件宽 或者高 定义一个值 或者 使用 match_parent 时, 会使用精准模式;


处理宽高的常规代码 

[java] view plaincopy
  1. @Override  
  2. protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {  
  3.     super.onMeasure(widthMeasureSpec, heightMeasureSpec);  
  4.       
  5.     //获取宽度 和 高度的模式 和 大小  
  6.        int widthMode = MeasureSpec.getMode(widthMeasureSpec);  
  7.        int heightMode = MeasureSpec.getMode(heightMeasureSpec);  
  8.        int widthSize = MeasureSpec.getSize(widthMeasureSpec);  
  9.        int heightSize = MeasureSpec.getSize(heightMeasureSpec);  
  10.          
  11.        Log.i(TAG, "宽度 : widthMode : " + getMode(widthMode) + " , widthSize : " + widthSize + "\n"   
  12.             + "高度 : heightMode : " + getMode(heightMode) + " , heightSize : " + heightSize);  
  13.          
  14.        int width = 0;  
  15.        int height = 0;  
  16.        /* 
  17.         * 精准模式 
  18.         *       精准模式下 高度就是精确的高度 
  19.         */  
  20.        if (heightMode == MeasureSpec.EXACTLY) {  
  21.            height = heightSize;  
  22.        //未定义模式 和 最大模式  
  23.        } else {  
  24.         //未定义模式下 获取布局需要的高度  
  25.            height = 100;  
  26.   
  27.            //最大模式下 获取 布局高度 和 布局所需高度的最小值  
  28.            if (heightMode == MeasureSpec.AT_MOST) {  
  29.                height = Math.min(height, heightSize);  
  30.            }  
  31.        }  
  32.          
  33.        if (widthMode == MeasureSpec.EXACTLY) {  
  34.            width = widthSize;  
  35.        } else {  
  36.            width = 100;  
  37.            if (heightMode == MeasureSpec.AT_MOST) {  
  38.                width = Math.min(width, widthSize);  
  39.            }  
  40.        }  
  41.   
  42.        Log.i(TAG, "最终结果 : 宽度 : " + width + " , 高度 : " + height);  
  43.          
  44.        setMeasuredDimension(width, height);  
  45.       
  46. }  
  47.   
  48.   
  49. public String getMode(int mode) {  
  50.     String modeName = "";  
  51.     if(mode == MeasureSpec.EXACTLY){  
  52.         modeName = "精准模式";  
  53.     }else if(mode == MeasureSpec.AT_MOST){  
  54.         modeName = "最大模式";  
  55.     }else if(mode == MeasureSpec.UNSPECIFIED){  
  56.         modeName = "未定义模式";  
  57.     }  
  58.           
  59.     return modeName;  
  60. }  



(2) 测试上述代码


使用下面的自定义组件测试 : 

[java] view plaincopy
  1. package cn.org.octopus.wheelview;  
  2.   
  3. import android.content.Context;  
  4. import android.graphics.Canvas;  
  5. import android.graphics.Color;  
  6. import android.util.AttributeSet;  
  7. import android.util.Log;  
  8. import android.view.View;  
  9.   
  10. public class MyView extends View {  
  11.   
  12.     public static final String TAG = "octopus.my.view";  
  13.       
  14.     public MyView(Context context, AttributeSet attrs) {  
  15.         super(context, attrs);  
  16.     }  
  17.   
  18.     public MyView(Context context) {  
  19.         super(context);  
  20.     }  
  21.   
  22.     public MyView(Context context, AttributeSet attrs, int defStyle) {  
  23.         super(context, attrs, defStyle);  
  24.     }  
  25.       
  26.       
  27.       
  28.       
  29.     @Override  
  30.     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {  
  31.         super.onMeasure(widthMeasureSpec, heightMeasureSpec);  
  32.           
  33.         //获取宽度 和 高度的模式 和 大小  
  34.         int widthMode = MeasureSpec.getMode(widthMeasureSpec);  
  35.         int heightMode = MeasureSpec.getMode(heightMeasureSpec);  
  36.         int widthSize = MeasureSpec.getSize(widthMeasureSpec);  
  37.         int heightSize = MeasureSpec.getSize(heightMeasureSpec);  
  38.           
  39.         Log.i(TAG, "宽度 : widthMode : " + getMode(widthMode) + " , widthSize : " + widthSize + "\n"   
  40.                 + "高度 : heightMode : " + getMode(heightMode) + " , heightSize : " + heightSize);  
  41.           
  42.         int width = 0;  
  43.         int height = 0;  
  44.         /* 
  45.          * 精准模式 
  46.          *      精准模式下 高度就是精确的高度 
  47.          */  
  48.         if (heightMode == MeasureSpec.EXACTLY) {  
  49.             height = heightSize;  
  50.         //未定义模式 和 最大模式  
  51.         } else {  
  52.             //未定义模式下 获取布局需要的高度  
  53.             height = 100;  
  54.   
  55.             //最大模式下 获取 布局高度 和 布局所需高度的最小值  
  56.             if (heightMode == MeasureSpec.AT_MOST) {  
  57.                 height = Math.min(height, heightSize);  
  58.             }  
  59.         }  
  60.           
  61.         if (widthMode == MeasureSpec.EXACTLY) {  
  62.             width = widthSize;  
  63.         } else {  
  64.             width = 100;  
  65.             if (heightMode == MeasureSpec.AT_MOST) {  
  66.                 width = Math.min(width, widthSize);  
  67.             }  
  68.         }  
  69.   
  70.         Log.i(TAG, "最终结果 : 宽度 : " + width + " , 高度 : " + height);  
  71.           
  72.         setMeasuredDimension(width, height);  
  73.           
  74.     }  
  75.       
  76.       
  77.     public String getMode(int mode) {  
  78.         String modeName = "";  
  79.         if(mode == MeasureSpec.EXACTLY){  
  80.             modeName = "精准模式";  
  81.         }else if(mode == MeasureSpec.AT_MOST){  
  82.             modeName = "最大模式";  
  83.         }else if(mode == MeasureSpec.UNSPECIFIED){  
  84.             modeName = "未定义模式";  
  85.         }  
  86.               
  87.         return modeName;  
  88.     }  
  89.       
  90.     @Override  
  91.     protected void onDraw(Canvas canvas) {  
  92.         super.onDraw(canvas);  
  93.           
  94.         canvas.drawColor(Color.BLUE);  
  95.     }  
  96.   
  97. }  



给定具体值情况 : 

-- 组件信息 : 

[html] view plaincopy
  1. <cn.org.octopus.wheelview.MyView  
  2.     android:layout_width="300dip"  
  3.     android:layout_height="300dip"/>  
-- 日志信息 : 

[plain] view plaincopy
  1. 11-30 01:40:24.304: I/octopus.my.view(2609): 宽度 : widthMode : 精准模式 , widthSize : 450  
  2. 11-30 01:40:24.304: I/octopus.my.view(2609): 高度 : heightMode : 最大模式 , heightSize : 850  
  3. 11-30 01:40:24.304: I/octopus.my.view(2609): 最终结果 : 宽度 : 450 , 高度 : 100  
  4. 11-30 01:40:24.304: I/octopus.my.view(2609): 宽度 : widthMode : 精准模式 , widthSize : 450  
  5. 11-30 01:40:24.304: I/octopus.my.view(2609): 高度 : heightMode : 精准模式 , heightSize : 450  
  6. 11-30 01:40:24.304: I/octopus.my.view(2609): 最终结果 : 宽度 : 450 , 高度 : 450  
  7. 11-30 01:40:24.335: I/octopus.my.view(2609): 宽度 : widthMode : 精准模式 , widthSize : 450  
  8. 11-30 01:40:24.335: I/octopus.my.view(2609): 高度 : heightMode : 最大模式 , heightSize : 850  
  9. 11-30 01:40:24.335: I/octopus.my.view(2609): 最终结果 : 宽度 : 450 , 高度 : 100  
  10. 11-30 01:40:24.335: I/octopus.my.view(2609): 宽度 : widthMode : 精准模式 , widthSize : 450  
  11. 11-30 01:40:24.335: I/octopus.my.view(2609): 高度 : heightMode : 精准模式 , heightSize : 450  
  12. 11-30 01:40:24.335: I/octopus.my.view(2609): 最终结果 : 宽度 : 450 , 高度 : 450  



warp_content 情况 : 

-- 组件信息 : 

[html] view plaincopy
  1. <cn.org.octopus.wheelview.MyView  
  2.     android:layout_width="wrap_content"  
  3.     android:layout_height="wrap_content"/>  
-- 日志信息 : 

[html] view plaincopy
  1. 11-30 01:37:47.351: I/octopus.my.view(1803): 宽度 : widthMode : 最大模式 , widthSize : 492  
  2. 11-30 01:37:47.351: I/octopus.my.view(1803): 高度 : heightMode : 最大模式 , heightSize : 850  
  3. 11-30 01:37:47.351: I/octopus.my.view(1803): 最终结果 : 宽度 : 100 , 高度 : 100  
  4. 11-30 01:37:47.351: I/octopus.my.view(1803): 宽度 : widthMode : 精准模式 , widthSize : 100  
  5. 11-30 01:37:47.351: I/octopus.my.view(1803): 高度 : heightMode : 最大模式 , heightSize : 802  
  6. 11-30 01:37:47.351: I/octopus.my.view(1803): 最终结果 : 宽度 : 100 , 高度 : 100  
  7. 11-30 01:37:47.390: I/octopus.my.view(1803): 宽度 : widthMode : 最大模式 , widthSize : 492  
  8. 11-30 01:37:47.390: I/octopus.my.view(1803): 高度 : heightMode : 最大模式 , heightSize : 850  
  9. 11-30 01:37:47.390: I/octopus.my.view(1803): 最终结果 : 宽度 : 100 , 高度 : 100  
  10. 11-30 01:37:47.390: I/octopus.my.view(1803): 宽度 : widthMode : 精准模式 , widthSize : 100  
  11. 11-30 01:37:47.390: I/octopus.my.view(1803): 高度 : heightMode : 最大模式 , heightSize : 802  
  12. 11-30 01:37:47.390: I/octopus.my.view(1803): 最终结果 : 宽度 : 100 , 高度 : 100  



match_parent 情况 : 

-- 组件信息 : 

[html] view plaincopy
  1. <cn.org.octopus.wheelview.MyView  
  2.     android:layout_width="match_parent"  
  3.     android:layout_height="match_parent"/>  

-- 日志信息 : 

[html] view plaincopy
  1. 11-30 01:39:08.296: I/octopus.my.view(2249): 宽度 : widthMode : 精准模式 , widthSize : 492  
  2. 11-30 01:39:08.296: I/octopus.my.view(2249): 高度 : heightMode : 精准模式 , heightSize : 850  
  3. 11-30 01:39:08.296: I/octopus.my.view(2249): 最终结果 : 宽度 : 492 , 高度 : 850  
  4. 11-30 01:39:08.296: I/octopus.my.view(2249): 宽度 : widthMode : 精准模式 , widthSize : 492  
  5. 11-30 01:39:08.296: I/octopus.my.view(2249): 高度 : heightMode : 精准模式 , heightSize : 802  
  6. 11-30 01:39:08.296: I/octopus.my.view(2249): 最终结果 : 宽度 : 492 , 高度 : 802  
  7. 11-30 01:39:08.328: I/octopus.my.view(2249): 宽度 : widthMode : 精准模式 , widthSize : 492  
  8. 11-30 01:39:08.328: I/octopus.my.view(2249): 高度 : heightMode : 精准模式 , heightSize : 850  
  9. 11-30 01:39:08.328: I/octopus.my.view(2249): 最终结果 : 宽度 : 492 , 高度 : 850  
  10. 11-30 01:39:08.328: I/octopus.my.view(2249): 宽度 : widthMode : 精准模式 , widthSize : 492  
  11. 11-30 01:39:08.328: I/octopus.my.view(2249): 高度 : heightMode : 精准模式 , heightSize : 802  
  12. 11-30 01:39:08.328: I/octopus.my.view(2249): 最终结果 : 宽度 : 492 , 高度 : 802  


博客地址 http://blog.csdn.net/shulianghan/article/details/41520569#t17


代码下载 : 

-- GitHub : https://github.com/han1202012/WheelViewDemo.git 

-- CSDN : http://download.csdn.net/detail/han1202012/8208997 ;




四. 详细代码 



1. WheelAdapter


[java] view plaincopy
  1. package cn.org.octopus.wheelview.widget;  
  2.   
  3. /** 
  4.  * WheelView 适配器接口 
  5.  * @author han_shuliang(octopus_truth@163.com) 
  6.  * 
  7.  */  
  8. public interface WheelAdapter {  
  9.     /** 
  10.      * 获取条目的个数 
  11.      *  
  12.      * @return  
  13.      *      WheelView 的条目个数 
  14.      */  
  15.     public int getItemsCount();  
  16.   
  17.     /** 
  18.      * 根据索引位置获取 WheelView 的条目 
  19.      *  
  20.      * @param index 
  21.      *            条目的索引 
  22.      * @return  
  23.      *      WheelView 上显示的条目的值 
  24.      */  
  25.     public String getItem(int index);  
  26.   
  27.     /** 
  28.      * 获取条目的最大长度. 用来定义 WheelView 的宽度. 如果返回 -1, 就会使用默认宽度 
  29.      *  
  30.      * @return  
  31.      *      条目的最大宽度 或者 -1 
  32.      */  
  33.     public int getMaximumLength();  
  34. }  



2. ArrayWheelAdapter



[java] view plaincopy
  1. package cn.org.octopus.wheelview.widget;  
  2.   
  3. /** 
  4.  * WheelView 的适配器类 
  5.  *  
  6.  * @param <T> 
  7.  *            元素类型 
  8.  */  
  9. public class ArrayWheelAdapter<T> implements WheelAdapter {  
  10.   
  11.     /** 适配器的 元素集合(数据源) 默认长度为 -1 */  
  12.     public static final int DEFAULT_LENGTH = -1;  
  13.   
  14.     /** 适配器的数据源 */  
  15.     private T items[];  
  16.     /** WheelView 的宽度 */  
  17.     private int length;  
  18.   
  19.     /** 
  20.      * 构造方法 
  21.      *  
  22.      * @param items 
  23.      *            适配器数据源 集合 T 类型的数组 
  24.      * @param length 
  25.      *            适配器数据源 集合 T 数组长度 
  26.      */  
  27.     public ArrayWheelAdapter(T items[], int length) {  
  28.         this.items = items;  
  29.         this.length = length;  
  30.     }  
  31.   
  32.     /** 
  33.      * 构造方法 
  34.      *  
  35.      * @param items 
  36.      *            适配器数据源集合 T 类型数组 
  37.      */  
  38.     public ArrayWheelAdapter(T items[]) {  
  39.         this(items, DEFAULT_LENGTH);  
  40.     }  
  41.   
  42.       
  43.     @Override  
  44.     public String getItem(int index) {  
  45.         //如果这个索引值合法, 就返回 item 数组对应的元素的字符串形式  
  46.         if (index >= 0 && index < items.length) {  
  47.             return items[index].toString();  
  48.         }  
  49.         return null;  
  50.     }  
  51.   
  52.     @Override  
  53.     public int getItemsCount() {  
  54.         //返回 item 数组的长度  
  55.         return items.length;  
  56.     }  
  57.   
  58.     @Override  
  59.     public int getMaximumLength() {  
  60.         //返回 item 元素的宽度  
  61.         return length;  
  62.     }  
  63.   
  64. }  


3. NumericWheelAdapter


[java] view plaincopy
  1. package cn.org.octopus.wheelview.widget;  
  2.   
  3. /** 
  4.  * 显示数字的 WheelAdapter 
  5.  */  
  6. public class NumericWheelAdapter implements WheelAdapter {  
  7.   
  8.     /** 默认最小值 */  
  9.     public static final int DEFAULT_MAX_VALUE = 9;  
  10.   
  11.     /** 默认最大值 */  
  12.     private static final int DEFAULT_MIN_VALUE = 0;  
  13.   
  14.     /** 设置的最小值 */  
  15.     private int minValue;  
  16.     /** 设置的最大值 */  
  17.     private int maxValue;  
  18.   
  19.     /** 格式化字符串, 用于格式化 货币, 科学计数, 十六进制 等格式 */  
  20.     private String format;  
  21.   
  22.     /** 
  23.      * 默认的构造方法, 使用默认的最大最小值 
  24.      */  
  25.     public NumericWheelAdapter() {  
  26.         this(DEFAULT_MIN_VALUE, DEFAULT_MAX_VALUE);  
  27.     }  
  28.   
  29.     /** 
  30.      * 构造方法 
  31.      *  
  32.      * @param minValue 
  33.      *            最小值 
  34.      * @param maxValue 
  35.      *            最大值 
  36.      */  
  37.     public NumericWheelAdapter(int minValue, int maxValue) {  
  38.         this(minValue, maxValue, null);  
  39.     }  
  40.   
  41.     /** 
  42.      * 构造方法 
  43.      *  
  44.      * @param minValue 
  45.      *            最小值 
  46.      * @param maxValue 
  47.      *            最大值 
  48.      * @param format 
  49.      *            格式化字符串 
  50.      */  
  51.     public NumericWheelAdapter(int minValue, int maxValue, String format) {  
  52.         this.minValue = minValue;  
  53.         this.maxValue = maxValue;  
  54.         this.format = format;  
  55.     }  
  56.   
  57.     @Override  
  58.     public String getItem(int index) {  
  59.         String result = "";  
  60.         if (index >= 0 && index < getItemsCount()) {  
  61.             int value = minValue + index;  
  62.             //如果 format 不为 null, 那么格式化字符串, 如果为 null, 直接返回数字  
  63.             if(format != null){  
  64.                 result = String.format(format, value);  
  65.             }else{  
  66.                 result = Integer.toString(value);  
  67.             }  
  68.             return result;  
  69.         }  
  70.         return null;  
  71.     }  
  72.   
  73.     @Override  
  74.     public int getItemsCount() {  
  75.         //返回数字总个数  
  76.         return maxValue - minValue + 1;  
  77.     }  
  78.   
  79.     @Override  
  80.     public int getMaximumLength() {  
  81.         //获取 最大值 和 最小值 中的 较大的数字  
  82.         int max = Math.max(Math.abs(maxValue), Math.abs(minValue));  
  83.         //获取这个数字 的 字符串形式的 字符串长度  
  84.         int maxLen = Integer.toString(max).length();  
  85.         if (minValue < 0) {  
  86.             maxLen++;  
  87.         }  
  88.         return maxLen;  
  89.     }  
  90. }  



4. OnWheelChangedListener


[java] view plaincopy
  1. package cn.org.octopus.wheelview.widget;  
  2.   
  3. /** 
  4.  * 条目改变监听器 
  5.  */  
  6. public interface OnWheelChangedListener {  
  7.     /** 
  8.      * 当前条目改变时回调该方法 
  9.      *  
  10.      * @param wheel 
  11.      *            条目改变的 WheelView 对象 
  12.      * @param oldValue 
  13.      *            WheelView 旧的条目值 
  14.      * @param newValue 
  15.      *            WheelView 新的条目值 
  16.      */  
  17.     void onChanged(WheelView wheel, int oldValue, int newValue);  
  18. }  




5. OnWheelScrollListener



[java] view plaincopy
  1. package cn.org.octopus.wheelview.widget;  
  2.   
  3. /** 
  4.  * WheelView 滚动监听器 
  5.  */  
  6. public interface OnWheelScrollListener {  
  7.     /** 
  8.      * 在 WheelView 滚动开始的时候回调该接口 
  9.      *  
  10.      * @param wheel 
  11.      *            开始滚动的 WheelView 对象 
  12.      */  
  13.     void onScrollingStarted(WheelView wheel);  
  14.   
  15.     /** 
  16.      * 在 WheelView 滚动结束的时候回调该接口 
  17.      *  
  18.      * @param wheel 
  19.      *            结束滚动的 WheelView 对象 
  20.      */  
  21.     void onScrollingFinished(WheelView wheel);  
  22. }  



6. WheelView


[java] view plaincopy
  1. package cn.org.octopus.wheelview.widget;  
  2.   
  3. import java.util.LinkedList;  
  4. import java.util.List;  
  5.   
  6. import cn.org.octopus.wheelview.R;  
  7. import android.annotation.SuppressLint;  
  8. import android.content.Context;  
  9. import android.graphics.Canvas;  
  10. import android.graphics.Paint;  
  11. import android.graphics.Rect;  
  12. import android.graphics.drawable.Drawable;  
  13. import android.graphics.drawable.GradientDrawable;  
  14. import android.graphics.drawable.GradientDrawable.Orientation;  
  15. import android.os.Handler;  
  16. import android.os.Message;  
  17. import android.text.Layout;  
  18. import android.text.StaticLayout;  
  19. import android.text.TextPaint;  
  20. import android.util.AttributeSet;  
  21. import android.view.GestureDetector;  
  22. import android.view.GestureDetector.SimpleOnGestureListener;  
  23. import android.view.MotionEvent;  
  24. import android.view.View;  
  25. import android.view.animation.Interpolator;  
  26. import android.widget.Scroller;  
  27.   
  28. /** 
  29.  * WheelView 主对象 
  30.  */  
  31. public class WheelView extends View {  
  32.     /** 滚动花费时间 Scrolling duration */  
  33.     private static final int SCROLLING_DURATION = 400;  
  34.   
  35.     /** 最小的滚动值, 每次最少滚动一个单位 */  
  36.     private static final int MIN_DELTA_FOR_SCROLLING = 1;  
  37.   
  38.     /** 当前条目中的文字颜色 */  
  39.     private static final int VALUE_TEXT_COLOR = 0xF0FF6347;  
  40.   
  41.     /** 非当前条目的文字颜色 */  
  42.     private static final int ITEMS_TEXT_COLOR = 0xFF000000;  
  43.   
  44.     /** 顶部和底部的阴影颜色 */  
  45.     //private static final int[] SHADOWS_COLORS = new int[] { 0xFF5436EE, 0x0012CEAE, 0x0012CEAE };  
  46.     private static final int[] SHADOWS_COLORS = new int[] { 0xFF1111110x00AAAAAA0x00AAAAAA };  
  47.   
  48.     /** 额外的条目高度 Additional items height (is added to standard text item height) */  
  49.     private static final int ADDITIONAL_ITEM_HEIGHT = 15;  
  50.   
  51.     /** 字体大小 */  
  52.     private static final int TEXT_SIZE = 24;  
  53.   
  54.     /** 顶部 和 底部 条目的隐藏大小,  
  55.      * 如果是正数 会隐藏一部份,  
  56.      * 0 顶部 和 底部的字正好紧贴 边缘,  
  57.      * 负数时 顶部和底部 与 字有一定间距 */  
  58.     private static final int ITEM_OFFSET = TEXT_SIZE / 5;  
  59.   
  60.     /** Additional width for items layout */  
  61.     private static final int ADDITIONAL_ITEMS_SPACE = 10;  
  62.   
  63.     /** Label offset */  
  64.     private static final int LABEL_OFFSET = 8;  
  65.   
  66.     /** Left and right padding value */  
  67.     private static final int PADDING = 10;  
  68.   
  69.     /** 默认的可显示的条目数 */  
  70.     private static final int DEF_VISIBLE_ITEMS = 5;  
  71.   
  72.     /** WheelView 适配器 */  
  73.     private WheelAdapter adapter = null;  
  74.     /** 当前显示的条目索引 */  
  75.     private int currentItem = 0;  
  76.   
  77.     /** 条目宽度 */  
  78.     private int itemsWidth = 0;  
  79.     /** 标签宽度 */  
  80.     private int labelWidth = 0;  
  81.   
  82.     /** 可见的条目数 */  
  83.     private int visibleItems = DEF_VISIBLE_ITEMS;  
  84.   
  85.     /** 条目高度 */  
  86.     private int itemHeight = 0;  
  87.   
  88.     /** 绘制普通条目画笔 */  
  89.     private TextPaint itemsPaint;  
  90.     /** 绘制选中条目画笔 */  
  91.     private TextPaint valuePaint;  
  92.   
  93.     /** 普通条目布局 
  94.      * StaticLayout 布局用于控制 TextView 组件, 一般情况下不会直接使用该组件,  
  95.      * 除非你自定义一个组件 或者 想要直接调用  Canvas.drawText() 方法 
  96.      *  */  
  97.     private StaticLayout itemsLayout;  
  98.     private StaticLayout labelLayout;  
  99.     /** 选中条目布局 */  
  100.     private StaticLayout valueLayout;  
  101.   
  102.     /** 标签 在选中条目的右边出现 */  
  103.     private String label;  
  104.     /** 选中条目的背景图片 */  
  105.     private Drawable centerDrawable;  
  106.   
  107.     /** 顶部阴影图片 */  
  108.     private GradientDrawable topShadow;  
  109.     /** 底部阴影图片 */  
  110.     private GradientDrawable bottomShadow;  
  111.   
  112.     /** 是否在滚动 */  
  113.     private boolean isScrollingPerformed;  
  114.     /** 滚动的位置 */  
  115.     private int scrollingOffset;  
  116.   
  117.     /** 手势检测器 */  
  118.     private GestureDetector gestureDetector;  
  119.     /**  
  120.      * Scroll 类封装了滚动动作.  
  121.      * 开发者可以使用 Scroll 或者 Scroll 实现类 去收集产生一个滚动动画所需要的数据, 返回一个急冲滑动的手势. 
  122.      * 该对象可以追踪随着时间推移滚动的偏移量, 但是这些对象不会自动向 View 对象提供这些位置. 
  123.      * 如果想要使滚动动画看起来比较平滑, 开发者需要在适当的时机  获取 和 使用新的坐标;  
  124.      *  */  
  125.     private Scroller scroller;  
  126.     /** 之前所在的 y 轴位置 */  
  127.     private int lastScrollY;  
  128.   
  129.     /** 是否循环 */  
  130.     boolean isCyclic = false;  
  131.   
  132.     /** 条目改变监听器集合  封装了条目改变方法, 当条目改变时回调 */  
  133.     private List<OnWheelChangedListener> changingListeners = new LinkedList<OnWheelChangedListener>();  
  134.     /** 条目滚动监听器集合, 该监听器封装了 开始滚动方法, 结束滚动方法 */  
  135.     private List<OnWheelScrollListener> scrollingListeners = new LinkedList<OnWheelScrollListener>();  
  136.   
  137.     /** 
  138.      * 构造方法 
  139.      */  
  140.     public WheelView(Context context, AttributeSet attrs, int defStyle) {  
  141.         super(context, attrs, defStyle);  
  142.         initData(context);  
  143.     }  
  144.   
  145.     /** 
  146.      * 构造方法 
  147.      */  
  148.     public WheelView(Context context, AttributeSet attrs) {  
  149.         super(context, attrs);  
  150.         initData(context);  
  151.     }  
  152.   
  153.     /** 
  154.      * 构造方法 
  155.      */  
  156.     public WheelView(Context context) {  
  157.         super(context);  
  158.         initData(context);  
  159.     }  
  160.   
  161.     /** 
  162.      * 初始化数据 
  163.      *  
  164.      * @param context 
  165.      *            上下文对象 
  166.      */  
  167.     private void initData(Context context) {  
  168.         //创建一个手势处理  
  169.         gestureDetector = new GestureDetector(context, gestureListener);  
  170.         /* 
  171.          * 是否允许长按操作,  
  172.          * 如果设置为 true 用户按下不松开, 会返回一个长按事件,  
  173.          * 如果设置为 false, 按下不松开滑动的话 会收到滚动事件. 
  174.          */  
  175.         gestureDetector.setIsLongpressEnabled(false);  
  176.           
  177.         //使用默认的 时间 和 插入器 创建一个滚动器  
  178.         scroller = new Scroller(context);  
  179.     }  
  180.   
  181.     /** 
  182.      * 获取该 WheelView 的适配器 
  183.      *  
  184.      * @return  
  185.      *      返回适配器 
  186.      */  
  187.     public WheelAdapter getAdapter() {  
  188.         return adapter;  
  189.     }  
  190.   
  191.     /** 
  192.      * 设置适配器 
  193.      *  
  194.      * @param adapter 
  195.      *            要设置的适配器 
  196.      */  
  197.     public void setAdapter(WheelAdapter adapter) {  
  198.         this.adapter = adapter;  
  199.         invalidateLayouts();  
  200.         invalidate();  
  201.     }  
  202.   
  203.     /** 
  204.      * 设置 Scroll 的插入器 
  205.      *  
  206.      * @param interpolator 
  207.      *            the interpolator 
  208.      */  
  209.     public void setInterpolator(Interpolator interpolator) {  
  210.         //强制停止滚动  
  211.         scroller.forceFinished(true);  
  212.         //创建一个 Scroll 对象  
  213.         scroller = new Scroller(getContext(), interpolator);  
  214.     }  
  215.   
  216.     /** 
  217.      * 获取课件条目数 
  218.      *  
  219.      * @return the count of visible items 
  220.      */  
  221.     public int getVisibleItems() {  
  222.         return visibleItems;  
  223.     }  
  224.   
  225.     /** 
  226.      * 设置可见条目数 
  227.      *  
  228.      * @param count 
  229.      *            the new count 
  230.      */  
  231.     public void setVisibleItems(int count) {  
  232.         visibleItems = count;  
  233.         invalidate();  
  234.     }  
  235.   
  236.     /** 
  237.      * 获取标签 
  238.      *  
  239.      * @return the label 
  240.      */  
  241.     public String getLabel() {  
  242.         return label;  
  243.     }  
  244.   
  245.     /** 
  246.      * 设置标签 
  247.      *  
  248.      * @param newLabel 
  249.      *            the label to set 
  250.      */  
  251.     public void setLabel(String newLabel) {  
  252.         if (label == null || !label.equals(newLabel)) {  
  253.             label = newLabel;  
  254.             labelLayout = null;  
  255.             invalidate();  
  256.         }  
  257.     }  
  258.   
  259.     /** 
  260.      * 添加 WheelView 选择的元素改变监听器 
  261.      *  
  262.      * @param listener 
  263.      *            the listener 
  264.      */  
  265.     public void addChangingListener(OnWheelChangedListener listener) {  
  266.         changingListeners.add(listener);  
  267.     }  
  268.   
  269.     /** 
  270.      * 移除 WheelView 元素改变监听器 
  271.      *  
  272.      * @param listener 
  273.      *            the listener 
  274.      */  
  275.     public void removeChangingListener(OnWheelChangedListener listener) {  
  276.         changingListeners.remove(listener);  
  277.     }  
  278.   
  279.     /** 
  280.      * 回调元素改变监听器集合的元素改变监听器元素的元素改变方法 
  281.      *  
  282.      * @param oldValue 
  283.      *            旧的 WheelView选中的值 
  284.      * @param newValue 
  285.      *            新的 WheelView选中的值 
  286.      */  
  287.     protected void notifyChangingListeners(int oldValue, int newValue) {  
  288.         for (OnWheelChangedListener listener : changingListeners) {  
  289.             listener.onChanged(this, oldValue, newValue);  
  290.         }  
  291.     }  
  292.   
  293.     /** 
  294.      * 添加 WheelView 滚动监听器 
  295.      *  
  296.      * @param listener 
  297.      *            the listener 
  298.      */  
  299.     public void addScrollingListener(OnWheelScrollListener listener) {  
  300.         scrollingListeners.add(listener);  
  301.     }  
  302.   
  303.     /** 
  304.      * 移除 WheelView 滚动监听器 
  305.      *  
  306.      * @param listener 
  307.      *            the listener 
  308.      */  
  309.     public void removeScrollingListener(OnWheelScrollListener listener) {  
  310.         scrollingListeners.remove(listener);  
  311.     }  
  312.   
  313.     /** 
  314.      * 通知监听器开始滚动 
  315.      */  
  316.     protected void notifyScrollingListenersAboutStart() {  
  317.         for (OnWheelScrollListener listener : scrollingListeners) {  
  318.             //回调开始滚动方法  
  319.             listener.onScrollingStarted(this);  
  320.         }  
  321.     }  
  322.   
  323.     /** 
  324.      * 通知监听器结束滚动 
  325.      */  
  326.     protected void notifyScrollingListenersAboutEnd() {  
  327.         for (OnWheelScrollListener listener : scrollingListeners) {  
  328.             //回调滚动结束方法  
  329.             listener.onScrollingFinished(this);  
  330.         }  
  331.     }  
  332.   
  333.     /** 
  334.      * 获取当前选中元素的索引 
  335.      *  
  336.      * @return  
  337.      *      当前元素索引 
  338.      */  
  339.     public int getCurrentItem() {  
  340.         return currentItem;  
  341.     }  
  342.   
  343.     /** 
  344.      * 设置当前元素的位置, 如果索引是错误的 不进行任何操作 
  345.      * -- 需要考虑该 WheelView 是否能循环 
  346.      * -- 根据是否需要滚动动画来确定是 ①滚动到目的位置 还是 ②晴空所有条目然后重绘 
  347.      *  
  348.      * @param index 
  349.      *            要设置的元素索引值 
  350.      * @param animated 
  351.      *            动画标志位 
  352.      */  
  353.     public void setCurrentItem(int index, boolean animated) {  
  354.         //如果没有适配器或者元素个数为0 直接返回  
  355.         if (adapter == null || adapter.getItemsCount() == 0) {  
  356.             return// throw?  
  357.         }  
  358.         //目标索引小于 0 或者大于 元素索引最大值(个数 -1)  
  359.         if (index < 0 || index >= adapter.getItemsCount()) {  
  360.             //入股WheelView 可循环, 修正索引值, 如果不可循环直接返回  
  361.             if (isCyclic) {  
  362.                 while (index < 0) {  
  363.                     index += adapter.getItemsCount();  
  364.                 }  
  365.                 index %= adapter.getItemsCount();  
  366.             } else {  
  367.                 return// throw?  
  368.             }  
  369.         }  
  370.           
  371.         //如果当前的索引不是传入的 索引  
  372.         if (index != currentItem) {  
  373.               
  374.             /* 
  375.              * 如果需要动画, 就滚动到目标位置 
  376.              * 如果不需要动画, 重新设置布局 
  377.              */  
  378.             if (animated) {  
  379.                 /* 
  380.                  * 开始滚动, 每个元素滚动间隔 400 ms, 滚动次数是 目标索引值 减去 当前索引值, 这是滚动的真实方法 
  381.                  */  
  382.                 scroll(index - currentItem, SCROLLING_DURATION);  
  383.             } else {  
  384.                 //所有布局设置为 null, 滚动位置设置为 0  
  385.                 invalidateLayouts();  
  386.   
  387.                 int old = currentItem;  
  388.                 currentItem = index;  
  389.   
  390.                 //便利回调元素改变监听器集合中的监听器元素中的元素改变方法  
  391.                 notifyChangingListeners(old, currentItem);  
  392.   
  393.                 //重绘  
  394.                 invalidate();  
  395.             }  
  396.         }  
  397.     }  
  398.   
  399.     /** 
  400.      * 设置当前选中的条目, 没有动画, 当索引出错不做任何操作 
  401.      *  
  402.      * @param index 
  403.      *            要设置的索引 
  404.      */  
  405.     public void setCurrentItem(int index) {  
  406.         setCurrentItem(index, false);  
  407.     }  
  408.   
  409.     /** 
  410.      * 获取 WheelView 是否可以循环 
  411.      * -- 如果可循环 : 第一个之前是最后一个, 最后一个之后是第一个; 
  412.      * -- 如果不可循环 : 到第一个就不能上翻, 最后一个不能下翻  
  413.      *  
  414.      * @return 
  415.      */  
  416.     public boolean isCyclic() {  
  417.         return isCyclic;  
  418.     }  
  419.   
  420.     /** 
  421.      * 设置 WheelView 循环标志 
  422.      *  
  423.      * @param isCyclic 
  424.      *            the flag to set 
  425.      */  
  426.     public void setCyclic(boolean isCyclic) {  
  427.         this.isCyclic = isCyclic;  
  428.   
  429.         invalidate();  
  430.         invalidateLayouts();  
  431.     }  
  432.   
  433.     /** 
  434.      * 使布局无效 
  435.      * 将 选中条目 和 普通条目设置为 null, 滚动位置设置为0 
  436.      */  
  437.     private void invalidateLayouts() {  
  438.         itemsLayout = null;  
  439.         valueLayout = null;  
  440.         scrollingOffset = 0;  
  441.     }  
  442.   
  443.     /** 
  444.      * 初始化资源 
  445.      */  
  446.     private void initResourcesIfNecessary() {  
  447.         /* 
  448.          * 设置绘制普通条目的画笔, 允许抗拒齿, 允许 fake-bold 
  449.          * 设置文字大小为 24 
  450.          */  
  451.         if (itemsPaint == null) {  
  452.             itemsPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG | Paint.FAKE_BOLD_TEXT_FLAG);  
  453.             itemsPaint.setTextSize(TEXT_SIZE);  
  454.         }  
  455.   
  456.         /* 
  457.          * 设置绘制选中条目的画笔 
  458.          * 设置文字大小 24 
  459.          */  
  460.         if (valuePaint == null) {  
  461.             valuePaint = new TextPaint(Paint.ANTI_ALIAS_FLAG | Paint.FAKE_BOLD_TEXT_FLAG | Paint.DITHER_FLAG);  
  462.             valuePaint.setTextSize(TEXT_SIZE);  
  463.             valuePaint.setShadowLayer(0.1f, 00.1f, 0xFFC0C0C0);  
  464.         }  
  465.   
  466.         //选中的条目背景  
  467.         if (centerDrawable == null) {  
  468.             centerDrawable = getContext().getResources().getDrawable(R.drawable.wheel_val);  
  469.         }  
  470.   
  471.         //创建顶部阴影图片  
  472.         if (topShadow == null) {  
  473.             /* 
  474.              * 构造方法中传入颜色渐变方向 
  475.              * 阴影颜色 
  476.              */  
  477.             topShadow = new GradientDrawable(Orientation.TOP_BOTTOM, SHADOWS_COLORS);  
  478.         }  
  479.   
  480.         //创建底部阴影图片  
  481.         if (bottomShadow == null) {  
  482.             bottomShadow = new GradientDrawable(Orientation.BOTTOM_TOP, SHADOWS_COLORS);  
  483.         }  
  484.   
  485.         /* 
  486.          * 设置 View 组件的背景 
  487.          */  
  488.         setBackgroundResource(R.drawable.wheel_bg);  
  489.     }  
  490.   
  491.     /** 
  492.      * 计算布局期望的高度 
  493.      *  
  494.      * @param layout 
  495.      *      组件的布局的 
  496.      * @return  
  497.      *      布局需要的高度 
  498.      */  
  499.     private int getDesiredHeight(Layout layout) {  
  500.         if (layout == null) {  
  501.             return 0;  
  502.         }  
  503.   
  504.         /* 
  505.          * 布局需要的高度是 条目个数 * 可见条目数 减去 顶部和底部隐藏的一部份 减去 额外的条目高度 
  506.          */  
  507.         int desired = getItemHeight() * visibleItems - ITEM_OFFSET * 2 - ADDITIONAL_ITEM_HEIGHT;  
  508.   
  509.         // 将计算的布局高度 与 最小高度比较, 取最大值  
  510.         desired = Math.max(desired, getSuggestedMinimumHeight());  
  511.   
  512.         return desired;  
  513.     }  
  514.   
  515.     /** 
  516.      * 根据条目获取字符串 
  517.      *  
  518.      * @param index 
  519.      *            条目索引 
  520.      * @return  
  521.      *      条目显示的字符串 
  522.      */  
  523.     private String getTextItem(int index) {  
  524.         if (adapter == null || adapter.getItemsCount() == 0) {  
  525.             return null;  
  526.         }  
  527.         //适配器显示的字符串个数  
  528.         int count = adapter.getItemsCount();  
  529.           
  530.         //考虑 index 小于 0 的情况  
  531.         if ((index < 0 || index >= count) && !isCyclic) {  
  532.             return null;  
  533.         } else {  
  534.             while (index < 0) {  
  535.                 index = count + index;  
  536.             }  
  537.         }  
  538.   
  539.         //index 大于 0  
  540.         index %= count;  
  541.         return adapter.getItem(index);  
  542.     }  
  543.   
  544.     /** 
  545.      * 根据当前值创建 字符串 
  546.      *  
  547.      * @param useCurrentValue 
  548.      *      是否在滚动 
  549.      * @return the text 
  550.      *      生成的字符串 
  551.      */  
  552.     private String buildText(boolean useCurrentValue) {  
  553.         //创建字符串容器  
  554.         StringBuilder itemsText = new StringBuilder();  
  555.         //计算出显示的条目相对位置, 例如显示 5个, 第 3 个是正中见选中的布局  
  556.         int addItems = visibleItems / 2 + 1;  
  557.   
  558.         /* 
  559.          * 遍历显示的条目 
  560.          * 获取当前显示条目 上下 各 addItems 个文本, 将该文本添加到显示文本中去 
  561.          * 如果不是最后一个 都加上回车 
  562.          */  
  563.         for (int i = currentItem - addItems; i <= currentItem + addItems; i++) {  
  564.             //如果在滚动  
  565.             if (useCurrentValue || i != currentItem) {  
  566.                 String text = getTextItem(i);  
  567.                 if (text != null) {  
  568.                     itemsText.append(text);  
  569.                 }  
  570.             }  
  571.             if (i < currentItem + addItems) {  
  572.                 itemsText.append("\n");  
  573.             }  
  574.         }  
  575.   
  576.         return itemsText.toString();  
  577.     }  
  578.   
  579.     /** 
  580.      * 返回 条目的字符串 
  581.      *  
  582.      * @return  
  583.      *      条目最大宽度 
  584.      */  
  585.     private int getMaxTextLength() {  
  586.         WheelAdapter adapter = getAdapter();  
  587.         if (adapter == null) {  
  588.             return 0;  
  589.         }  
  590.   
  591.         //如果获取的最大条目宽度不为 -1, 可以直接返回该条目宽度  
  592.         int adapterLength = adapter.getMaximumLength();  
  593.         if (adapterLength > 0) {  
  594.             return adapterLength;  
  595.         }  
  596.   
  597.         String maxText = null;  
  598.         int addItems = visibleItems / 2;  
  599.         /* 
  600.          * 遍历当前显示的条目, 获取字符串长度最长的那个, 返回这个最长的字符串长度 
  601.          */  
  602.         for (int i = Math.max(currentItem - addItems, 0); i < Math.min(currentItem + visibleItems,  
  603.                 adapter.getItemsCount()); i++) {  
  604.             String text = adapter.getItem(i);  
  605.             if (text != null && (maxText == null || maxText.length() < text.length())) {  
  606.                 maxText = text;  
  607.             }  
  608.         }  
  609.   
  610.         return maxText != null ? maxText.length() : 0;  
  611.     }  
  612.   
  613.     /** 
  614.      * 获取每个条目的高度 
  615.      *  
  616.      * @return  
  617.      *      条目的高度 
  618.      */  
  619.     private int getItemHeight() {  
  620.         //如果条目高度不为 0, 直接返回  
  621.         if (itemHeight != 0) {  
  622.             return itemHeight;  
  623.         //如果条目的高度为 0, 并且普通条目布局不为null, 条目个数大于 2   
  624.         } else if (itemsLayout != null && itemsLayout.getLineCount() > 2) {  
  625.             /* 
  626.              * itemsLayout.getLineTop(2) : 获取顶部第二行上面的垂直(y轴)位置, 如果行数等于 
  627.              */  
  628.             itemHeight = itemsLayout.getLineTop(2) - itemsLayout.getLineTop(1);  
  629.             return itemHeight;  
  630.         }  
  631.   
  632.         //如果上面都不符合, 使用整体高度处以 显示条目数  
  633.         return getHeight() / visibleItems;  
  634.     }  
  635.   
  636.     /** 
  637.      * 计算宽度并创建文字布局 
  638.      *  
  639.      * @param widthSize 
  640.      *            输入的布局宽度 
  641.      * @param mode 
  642.      *            布局模式 
  643.      * @return  
  644.      *      计算的宽度 
  645.      */  
  646.     private int calculateLayoutWidth(int widthSize, int mode) {  
  647.         initResourcesIfNecessary();  
  648.   
  649.         int width = widthSize;  
  650.   
  651.         //获取最长的条目显示字符串字符个数  
  652.         int maxLength = getMaxTextLength();  
  653.           
  654.         if (maxLength > 0) {  
  655.             /* 
  656.              * 使用方法 FloatMath.ceil() 方法有以下警告 
  657.              * Use java.lang.Math#ceil instead of android.util.FloatMath#ceil() since it is faster as of API 8 
  658.              */  
  659.             //float textWidth = FloatMath.ceil(Layout.getDesiredWidth("0", itemsPaint));  
  660.             //向上取整  计算一个字符串宽度  
  661.             float textWidth = (float) Math.ceil(Layout.getDesiredWidth("0", itemsPaint));  
  662.               
  663.             //获取字符串总的宽度  
  664.             itemsWidth = (int) (maxLength * textWidth);  
  665.         } else {  
  666.             itemsWidth = 0;  
  667.         }  
  668.           
  669.         //总宽度加上一些间距  
  670.         itemsWidth += ADDITIONAL_ITEMS_SPACE; // make it some more  
  671.   
  672.         //计算 label 的长度  
  673.         labelWidth = 0;  
  674.         if (label != null && label.length() > 0) {  
  675.             labelWidth = (int) Math.ceil(Layout.getDesiredWidth(label, valuePaint));  
  676.             //labelWidth = (int) FloatMath.ceil(Layout.getDesiredWidth(label, valuePaint));  
  677.         }  
  678.   
  679.         boolean recalculate = false;  
  680.         //精准模式  
  681.         if (mode == MeasureSpec.EXACTLY) {  
  682.             //精准模式下, 宽度就是给定的宽度  
  683.             width = widthSize;  
  684.             recalculate = true;  
  685.         } else {  
  686.             //未定义模式  
  687.             width = itemsWidth + labelWidth + 2 * PADDING;  
  688.             if (labelWidth > 0) {  
  689.                 width += LABEL_OFFSET;  
  690.             }  
  691.   
  692.             // 获取 ( 计算出来的宽度 与 最小宽度的 ) 最大值  
  693.             width = Math.max(width, getSuggestedMinimumWidth());  
  694.   
  695.             //最大模式 如果 给定的宽度 小于 计算出来的宽度, 那么使用最小的宽度 ( 给定宽度 | 计算出来的宽度 )  
  696.             if (mode == MeasureSpec.AT_MOST && widthSize < width) {  
  697.                 width = widthSize;  
  698.                 recalculate = true;  
  699.             }  
  700.         }  
  701.   
  702.         /* 
  703.          * 重新计算宽度 , 如果宽度是给定的宽度, 不是我们计算出来的宽度, 需要重新进行计算 
  704.          * 重新计算的宽度是用于 
  705.          *  
  706.          * 计算 itemsWidth , 这个与返回的 宽度无关, 与创建布局有关 
  707.          */  
  708.         if (recalculate) {  
  709.             int pureWidth = width - LABEL_OFFSET - 2 * PADDING;  
  710.             if (pureWidth <= 0) {  
  711.                 itemsWidth = labelWidth = 0;  
  712.             }  
  713.             if (labelWidth > 0) {  
  714.                 double newWidthItems = (double) itemsWidth * pureWidth / (itemsWidth + labelWidth);  
  715.                 itemsWidth = (int) newWidthItems;  
  716.                 labelWidth = pureWidth - itemsWidth;  
  717.             } else {  
  718.                 itemsWidth = pureWidth + LABEL_OFFSET; // no label  
  719.             }  
  720.         }  
  721.   
  722.         if (itemsWidth > 0) {  
  723.             //创建布局  
  724.             createLayouts(itemsWidth, labelWidth);  
  725.         }  
  726.   
  727.         return width;  
  728.     }  
  729.   
  730.     /** 
  731.      * 创建布局 
  732.      *  
  733.      * @param widthItems 
  734.      *            布局条目宽度 
  735.      * @param widthLabel 
  736.      *            label 宽度 
  737.      */  
  738.     private void createLayouts(int widthItems, int widthLabel) {  
  739.         /* 
  740.          * 创建普通条目布局 
  741.          * 如果 普通条目布局 为 null 或者 普通条目布局的宽度 大于 传入的宽度, 这时需要重新创建布局 
  742.          * 如果 普通条目布局存在, 并且其宽度小于传入的宽度, 此时需要将 
  743.          */  
  744.         if (itemsLayout == null || itemsLayout.getWidth() > widthItems) {  
  745.               
  746.             /* 
  747.              * android.text.StaticLayout.StaticLayout( 
  748.              * CharSequence source, TextPaint paint,  
  749.              * int width, Alignment align,  
  750.              * float spacingmult, float spacingadd, boolean includepad) 
  751.              * 传入参数介绍 :  
  752.              * CharSequence source : 需要分行显示的字符串 
  753.              * TextPaint paint : 绘制字符串的画笔 
  754.              * int width : 条目的宽度 
  755.              * Alignment align : Layout 的对齐方式, ALIGN_CENTER 居中对齐, ALIGN_NORMAL 左对齐, Alignment.ALIGN_OPPOSITE 右对齐 
  756.              * float spacingmult : 行间距, 1.5f 代表 1.5 倍字体高度 
  757.              * float spacingadd : 基础行距上增加多少 , 真实行间距 等于 spacingmult 和 spacingadd 的和 
  758.              * boolean includepad :  
  759.              */  
  760.             itemsLayout = new StaticLayout(buildText(isScrollingPerformed), itemsPaint, widthItems,  
  761.                     widthLabel > 0 ? Layout.Alignment.ALIGN_OPPOSITE : Layout.Alignment.ALIGN_CENTER, 1,  
  762.                     ADDITIONAL_ITEM_HEIGHT, false);  
  763.         } else {  
  764.             //调用 Layout 内置的方法 increaseWidthTo 将宽度提升到指定的宽度  
  765.             itemsLayout.increaseWidthTo(widthItems);  
  766.         }  
  767.   
  768.         /* 
  769.          * 创建选中条目 
  770.          */  
  771.         if (!isScrollingPerformed && (valueLayout == null || valueLayout.getWidth() > widthItems)) {  
  772.             String text = getAdapter() != null ? getAdapter().getItem(currentItem) : null;  
  773.             valueLayout = new StaticLayout(text != null ? text : "", valuePaint, widthItems,  
  774.                     widthLabel > 0 ? Layout.Alignment.ALIGN_OPPOSITE : Layout.Alignment.ALIGN_CENTER, 1,  
  775.                     ADDITIONAL_ITEM_HEIGHT, false);  
  776.         } else if (isScrollingPerformed) {  
  777.             valueLayout = null;  
  778.         } else {  
  779.             valueLayout.increaseWidthTo(widthItems);  
  780.         }  
  781.   
  782.         /* 
  783.          * 创建标签条目 
  784.          */  
  785.         if (widthLabel > 0) {  
  786.             if (labelLayout == null || labelLayout.getWidth() > widthLabel) {  
  787.                 labelLayout = new StaticLayout(label, valuePaint, widthLabel, Layout.Alignment.ALIGN_NORMAL, 1,  
  788.                         ADDITIONAL_ITEM_HEIGHT, false);  
  789.             } else {  
  790.                 labelLayout.increaseWidthTo(widthLabel);  
  791.             }  
  792.         }  
  793.     }  
  794.   
  795.     /* 
  796.      * 测量组件大小 
  797.      * (non-Javadoc) 
  798.      * @see android.view.View#onMeasure(int, int) 
  799.      */  
  800.     @Override  
  801.     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {  
  802.         //获取宽度 和 高度的模式 和 大小  
  803.         int widthMode = MeasureSpec.getMode(widthMeasureSpec);  
  804.         int heightMode = MeasureSpec.getMode(heightMeasureSpec);  
  805.         int widthSize = MeasureSpec.getSize(widthMeasureSpec);  
  806.         int heightSize = MeasureSpec.getSize(heightMeasureSpec);  
  807.   
  808.         //宽度就是 计算的布局的宽度  
  809.         int width = calculateLayoutWidth(widthSize, widthMode);  
  810.   
  811.         int height;  
  812.         /* 
  813.          * 精准模式 
  814.          *      精准模式下 高度就是精确的高度 
  815.          */  
  816.         if (heightMode == MeasureSpec.EXACTLY) {  
  817.             height = heightSize;  
  818.           
  819.         //未定义模式 和 最大模式  
  820.         } else {  
  821.             //未定义模式下 获取布局需要的高度  
  822.             height = getDesiredHeight(itemsLayout);  
  823.   
  824.             //最大模式下 获取 布局高度 和 布局所需高度的最小值  
  825.             if (heightMode == MeasureSpec.AT_MOST) {  
  826.                 height = Math.min(height, heightSize);  
  827.             }  
  828.         }  
  829.   
  830.         //设置组件的宽和高  
  831.         setMeasuredDimension(width, height);  
  832.     }  
  833.   
  834.     /* 
  835.      * 绘制组件 
  836.      * (non-Javadoc) 
  837.      * @see android.view.View#onDraw(android.graphics.Canvas) 
  838.      */  
  839.     @Override  
  840.     protected void onDraw(Canvas canvas) {  
  841.         super.onDraw(canvas);  
  842.   
  843.         //如果条目布局为 null, 就创建该布局  
  844.         if (itemsLayout == null) {  
  845.             /* 
  846.              * 如果 条目宽度为0, 说明该宽度没有计算, 先计算, 计算完之后会创建布局 
  847.              * 如果 条目宽度 大于 0, 说明已经计算过宽度了, 直接创建布局 
  848.              */  
  849.             if (itemsWidth == 0) {  
  850.                 calculateLayoutWidth(getWidth(), MeasureSpec.EXACTLY);  
  851.             } else {  
  852.                 //创建普通条目布局, 选中条目布局, 标签条目布局  
  853.                 createLayouts(itemsWidth, labelWidth);  
  854.             }  
  855.         }  
  856.   
  857.         //如果条目宽度大于0  
  858.         if (itemsWidth > 0) {  
  859.             canvas.save();  
  860.             // 使用平移方法忽略 填充的空间 和 顶部底部隐藏的一部份条目  
  861.             canvas.translate(PADDING, -ITEM_OFFSET);  
  862.             //绘制普通条目  
  863.             drawItems(canvas);  
  864.             //绘制选中条目  
  865.             drawValue(canvas);  
  866.             canvas.restore();  
  867.         }  
  868.   
  869.         //在中心位置绘制  
  870.         drawCenterRect(canvas);  
  871.         //绘制阴影  
  872.         drawShadows(canvas);  
  873.     }  
  874.   
  875.     /** 
  876.      * Draws shadows on top and bottom of control 
  877.      *  
  878.      * @param canvas 
  879.      *            the canvas for drawing 
  880.      */  
  881.     private void drawShadows(Canvas canvas) {  
  882.         topShadow.setBounds(00, getWidth(), getHeight() / visibleItems);  
  883.         topShadow.draw(canvas);  
  884.   
  885.         bottomShadow.setBounds(0, getHeight() - getHeight() / visibleItems, getWidth(), getHeight());  
  886.         bottomShadow.draw(canvas);  
  887.     }  
  888.   
  889.     /** 
  890.      * 绘制选中条目 
  891.      *  
  892.      * @param canvas 
  893.      *            画布 
  894.      */  
  895.     private void drawValue(Canvas canvas) {  
  896.         valuePaint.setColor(VALUE_TEXT_COLOR);  
  897.           
  898.         //将当前 View 状态属性值 转为整型集合, 赋值给 普通条目布局的绘制属性  
  899.         valuePaint.drawableState = getDrawableState();  
  900.   
  901.         Rect bounds = new Rect();  
  902.         //获取选中条目布局的边界  
  903.         itemsLayout.getLineBounds(visibleItems / 2, bounds);  
  904.   
  905.         // 绘制标签  
  906.         if (labelLayout != null) {  
  907.             canvas.save();  
  908.             canvas.translate(itemsLayout.getWidth() + LABEL_OFFSET, bounds.top);  
  909.             labelLayout.draw(canvas);  
  910.             canvas.restore();  
  911.         }  
  912.   
  913.         // 绘制选中条目  
  914.         if (valueLayout != null) {  
  915.             canvas.save();  
  916.             canvas.translate(0, bounds.top + scrollingOffset);  
  917.             valueLayout.draw(canvas);  
  918.             canvas.restore();  
  919.         }  
  920.     }  
  921.   
  922.     /** 
  923.      * 绘制普通条目 
  924.      *  
  925.      * @param canvas 
  926.      *            画布 
  927.      */  
  928.     private void drawItems(Canvas canvas) {  
  929.         canvas.save();  
  930.   
  931.         //获取 y 轴 定点高度  
  932.         int top = itemsLayout.getLineTop(1);  
  933.         canvas.translate(0, -top + scrollingOffset);  
  934.   
  935.         //设置画笔颜色  
  936.         itemsPaint.setColor(ITEMS_TEXT_COLOR);  
  937.         //将当前 View 状态属性值 转为整型集合, 赋值给 普通条目布局的绘制属性  
  938.         itemsPaint.drawableState = getDrawableState();  
  939.         //将布局绘制到画布上  
  940.         itemsLayout.draw(canvas);  
  941.   
  942.         canvas.restore();  
  943.     }  
  944.   
  945.     /** 
  946.      * 绘制当前选中条目的背景图片 
  947.      *  
  948.      * @param canvas 
  949.      *            画布 
  950.      */  
  951.     private void drawCenterRect(Canvas canvas) {  
  952.         int center = getHeight() / 2;  
  953.         int offset = getItemHeight() / 2;  
  954.         centerDrawable.setBounds(0, center - offset, getWidth(), center + offset);  
  955.         centerDrawable.draw(canvas);  
  956.     }  
  957.   
  958.     /* 
  959.      * 继承自 View 的触摸事件, 当出现触摸事件的时候, 就会回调该方法 
  960.      * (non-Javadoc) 
  961.      * @see android.view.View#onTouchEvent(android.view.MotionEvent) 
  962.      */  
  963.     @Override  
  964.     public boolean onTouchEvent(MotionEvent event) {  
  965.         //获取适配器  
  966.         WheelAdapter adapter = getAdapter();  
  967.         if (adapter == null) {  
  968.             return true;  
  969.         }  
  970.   
  971.         /* 
  972.          * gestureDetector.onTouchEvent(event) : 分析给定的动作, 如果可用, 调用 手势检测器的 onTouchEvent 方法 
  973.          * -- 参数解析 : ev , 触摸事件 
  974.          * -- 返回值 : 如果手势监听器成功执行了该方法, 返回true, 如果执行出现意外 返回 false; 
  975.          */  
  976.         if (!gestureDetector.onTouchEvent(event) && event.getAction() == MotionEvent.ACTION_UP) {  
  977.             justify();  
  978.         }  
  979.         return true;  
  980.     }  
  981.   
  982.     /** 
  983.      * 滚动 WheelView 
  984.      *  
  985.      * @param delta 
  986.      *            滚动的值 
  987.      */  
  988.     private void doScroll(int delta) {  
  989.         scrollingOffset += delta;  
  990.           
  991.         //计算滚动的条目数, 使用滚动的值 处于 单个条目高度, 注意计算整数值  
  992.         int count = scrollingOffset / getItemHeight();  
  993.         /* 
  994.          * pos 是滚动后的目标元素索引 
  995.          * 计算当前位置, 当前条目数 减去 滚动的条目数 
  996.          * 注意 滚动条目数可正 可负 
  997.          */  
  998.         int pos = currentItem - count;  
  999.         //如果是可循环的, 并且条目数大于0  
  1000.         if (isCyclic && adapter.getItemsCount() > 0) {  
  1001.             //设置循环, 如果位置小于0, 那么该位置就显示最后一个元素  
  1002.             while (pos < 0) {  
  1003.                 pos += adapter.getItemsCount();  
  1004.             }  
  1005.             //如果位置正无限大, 模条目数 取余  
  1006.             pos %= adapter.getItemsCount();  
  1007.               
  1008.         // (前提 : 不可循环  条目数大于0, 可循环 条目数小于0, 条目数小于0, 不可循环) , 如果滚动在执行  
  1009.         } else if (isScrollingPerformed) {  
  1010.             //位置一旦小于0, 计算的位置就赋值为 0, 条目滚动数为0  
  1011.             if (pos < 0) {  
  1012.                 count = currentItem;  
  1013.                 pos = 0;  
  1014.                   
  1015.             //位置大于条目数的时候, 当前位置等于(条目数 - 1), 条目滚动数等于 当前位置 减去 (条目数 - 1)  
  1016.             } else if (pos >= adapter.getItemsCount()) {  
  1017.                 count = currentItem - adapter.getItemsCount() + 1;  
  1018.                 pos = adapter.getItemsCount() - 1;  
  1019.             }  
  1020.           
  1021.         } else {  
  1022.             // fix position  
  1023.             pos = Math.max(pos, 0);  
  1024.             pos = Math.min(pos, adapter.getItemsCount() - 1);  
  1025.         }  
  1026.   
  1027.         //滚动的高度  
  1028.         int offset = scrollingOffset;  
  1029.           
  1030.         /* 
  1031.          * 如果当前位置不是滚动后的目标位置, 就将当前位置设置为目标位置 
  1032.          * 否则就重绘组件 
  1033.          */  
  1034.         if (pos != currentItem) {  
  1035.             setCurrentItem(pos, false);  
  1036.         } else {  
  1037.             //重绘组件  
  1038.             invalidate();  
  1039.         }  
  1040.   
  1041.         // 将滚动后剩余的小数部分保存  
  1042.         scrollingOffset = offset - count * getItemHeight();  
  1043.         if (scrollingOffset > getHeight()) {  
  1044.             scrollingOffset = scrollingOffset % getHeight() + getHeight();  
  1045.         }  
  1046.     }  
  1047.   
  1048.     /** 
  1049.      * 手势监听器 
  1050.      */  
  1051.     private SimpleOnGestureListener gestureListener = new SimpleOnGestureListener() {  
  1052.           
  1053.         //按下操作  
  1054.         public boolean onDown(MotionEvent e) {  
  1055.             //如果滚动在执行  
  1056.             if (isScrollingPerformed) {  
  1057.                 //滚动强制停止, 按下的时候不能继续滚动  
  1058.                 scroller.forceFinished(true);  
  1059.                 //清理信息  
  1060.                 clearMessages();  
  1061.                 return true;  
  1062.             }  
  1063.             return false;  
  1064.         }  
  1065.   
  1066.         /* 
  1067.          * 手势监听器监听到 滚动操作后回调 
  1068.          *  
  1069.          * 参数解析 :  
  1070.          * MotionEvent e1 : 触发滚动时第一次按下的事件 
  1071.          * MotionEvent e2 : 触发当前滚动的移动事件 
  1072.          * float distanceX : 自从上一次调用 该方法 到这一次 x 轴滚动的距离,  
  1073.          *              注意不是 e1 到 e2 的距离, e1 到 e2 的距离是从开始滚动到现在的滚动距离 
  1074.          * float distanceY : 自从上一次回调该方法到这一次 y 轴滚动的距离 
  1075.          *  
  1076.          * 返回值 : 如果事件成功触发, 执行完了方法中的操作, 返回true, 否则返回 false  
  1077.          * (non-Javadoc) 
  1078.          * @see android.view.GestureDetector.SimpleOnGestureListener#onScroll(android.view.MotionEvent, android.view.MotionEvent, float, float) 
  1079.          */  
  1080.         public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {  
  1081.             //开始滚动, 并回调滚动监听器集合中监听器的 开始滚动方法  
  1082.             startScrolling();  
  1083.             doScroll((int) -distanceY);  
  1084.             return true;  
  1085.         }  
  1086.   
  1087.         /* 
  1088.          * 当一个急冲手势发生后 回调该方法, 会计算出该手势在 x 轴 y 轴的速率 
  1089.          *  
  1090.          * 参数解析 :  
  1091.          * -- MotionEvent e1 : 急冲动作的第一次触摸事件; 
  1092.          * -- MotionEvent e2 : 急冲动作的移动发生的时候的触摸事件; 
  1093.          * -- float velocityX : x 轴的速率 
  1094.          * -- float velocityY : y 轴的速率 
  1095.          *  
  1096.          * 返回值 : 如果执行完毕返回 true, 否则返回false, 这个就是自己定义的 
  1097.          *  
  1098.          * (non-Javadoc) 
  1099.          * @see android.view.GestureDetector.SimpleOnGestureListener#onFling(android.view.MotionEvent, android.view.MotionEvent, float, float) 
  1100.          */  
  1101.         public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {  
  1102.             //计算上一次的 y 轴位置, 当前的条目高度 加上 剩余的 不够一行高度的那部分  
  1103.             lastScrollY = currentItem * getItemHeight() + scrollingOffset;  
  1104.             //如果可以循环最大值是无限大, 不能循环就是条目数的高度值  
  1105.             int maxY = isCyclic ? 0x7FFFFFFF : adapter.getItemsCount() * getItemHeight();  
  1106.             int minY = isCyclic ? -maxY : 0;  
  1107.             /* 
  1108.              * Scroll 开始根据一个急冲手势滚动, 滚动的距离与初速度有关 
  1109.              * 参数介绍 :  
  1110.              * -- int startX : 开始时的 X轴位置 
  1111.              * -- int startY : 开始时的 y轴位置 
  1112.              * -- int velocityX : 急冲手势的 x 轴的初速度, 单位 px/s 
  1113.              * -- int velocityY : 急冲手势的 y 轴的初速度, 单位 px/s 
  1114.              * -- int minX : x 轴滚动的最小值 
  1115.              * -- int maxX : x 轴滚动的最大值 
  1116.              * -- int minY : y 轴滚动的最小值 
  1117.              * -- int maxY : y 轴滚动的最大值 
  1118.              */  
  1119.             scroller.fling(0, lastScrollY, 0, (int) -velocityY / 200, minY, maxY);  
  1120.             setNextMessage(MESSAGE_SCROLL);  
  1121.             return true;  
  1122.         }  
  1123.     };  
  1124.   
  1125.     // Handler 中的  Message 信息  
  1126.     /** 滚动信息 */  
  1127.     private final int MESSAGE_SCROLL = 0;  
  1128.     /** 调整信息 */  
  1129.     private final int MESSAGE_JUSTIFY = 1;  
  1130.   
  1131.     /** 
  1132.      * 清空之前的 Handler 队列, 发送下一个消息到 Handler 中 
  1133.      *  
  1134.      * @param message 
  1135.      *            要发送的消息 
  1136.      */  
  1137.     private void setNextMessage(int message) {  
  1138.         //清空 Handler 队列中的  what 消息  
  1139.         clearMessages();  
  1140.         //发送消息到 Handler 中  
  1141.         animationHandler.sendEmptyMessage(message);  
  1142.     }  
  1143.   
  1144.     /** 
  1145.      * 清空队列中的信息 
  1146.      */  
  1147.     private void clearMessages() {  
  1148.         //删除 Handler 执行队列中的滚动操作  
  1149.         animationHandler.removeMessages(MESSAGE_SCROLL);  
  1150.         animationHandler.removeMessages(MESSAGE_JUSTIFY);  
  1151.     }  
  1152.   
  1153.     /** 
  1154.      * 动画控制器 
  1155.      *  animation handler 
  1156.      *   
  1157.      *  可能会造成内存泄露 : 添加注解 HandlerLeak 
  1158.      *  Handler 类应该应该为static类型,否则有可能造成泄露。 
  1159.      *  在程序消息队列中排队的消息保持了对目标Handler类的应用。 
  1160.      *  如果Handler是个内部类,那 么它也会保持它所在的外部类的引用。 
  1161.      *  为了避免泄露这个外部类,应该将Handler声明为static嵌套类,并且使用对外部类的弱应用。 
  1162.      */  
  1163.     @SuppressLint("HandlerLeak")  
  1164.     private Handler animationHandler = new Handler() {  
  1165.         public void handleMessage(Message msg) {  
  1166.             //回调该方法获取当前位置, 如果返回true, 说明动画还没有执行完毕  
  1167.             scroller.computeScrollOffset();  
  1168.             //获取当前 y 位置  
  1169.             int currY = scroller.getCurrY();  
  1170.             //获取已经滚动了的位置, 使用上一次位置 减去 当前位置  
  1171.             int delta = lastScrollY - currY;  
  1172.             lastScrollY = currY;  
  1173.             if (delta != 0) {  
  1174.                 //改变值不为 0 , 继续滚动  
  1175.                 doScroll(delta);  
  1176.             }  
  1177.   
  1178.             /* 
  1179.              * 如果滚动到了指定的位置, 滚动还没有停止 
  1180.              * 这时需要强制停止 
  1181.              */  
  1182.             if (Math.abs(currY - scroller.getFinalY()) < MIN_DELTA_FOR_SCROLLING) {  
  1183.                 currY = scroller.getFinalY();  
  1184.                 scroller.forceFinished(true);  
  1185.             }  
  1186.               
  1187.             /* 
  1188.              * 如果滚动没有停止 
  1189.              * 再向 Handler 发送一个停止 
  1190.              */  
  1191.             if (!scroller.isFinished()) {  
  1192.                 animationHandler.sendEmptyMessage(msg.what);  
  1193.             } else if (msg.what == MESSAGE_SCROLL) {  
  1194.                 justify();  
  1195.             } else {  
  1196.                 finishScrolling();  
  1197.             }  
  1198.         }  
  1199.     };  
  1200.   
  1201.     /** 
  1202.      * 调整 WheelView 
  1203.      */  
  1204.     private void justify() {  
  1205.         if (adapter == null) {  
  1206.             return;  
  1207.         }  
  1208.         //上一次的 y 轴的位置为 0  
  1209.         lastScrollY = 0;  
  1210.         int offset = scrollingOffset;  
  1211.         int itemHeight = getItemHeight();  
  1212.         /* 
  1213.          * 当滚动补偿 大于 0, 说明还有没有滚动的部分,  needToIncrease 是 当前条目是否小于条目数 
  1214.          * 如果 滚动补偿不大于 0,  needToIncrease 是当前条目是否大于 0 
  1215.          */  
  1216.         boolean needToIncrease = offset > 0 ? currentItem < adapter.getItemsCount() : currentItem > 0;  
  1217.         if ((isCyclic || needToIncrease) && Math.abs((float) offset) > (float) itemHeight / 2) {  
  1218.             if (offset < 0)  
  1219.                 offset += itemHeight + MIN_DELTA_FOR_SCROLLING;  
  1220.             else  
  1221.                 offset -= itemHeight + MIN_DELTA_FOR_SCROLLING;  
  1222.         }  
  1223.         if (Math.abs(offset) > MIN_DELTA_FOR_SCROLLING) {  
  1224.             scroller.startScroll(000, offset, SCROLLING_DURATION);  
  1225.             setNextMessage(MESSAGE_JUSTIFY);  
  1226.         } else {  
  1227.             finishScrolling();  
  1228.         }  
  1229.     }  
  1230.   
  1231.     /** 
  1232.      * WheelView 开始滚动 
  1233.      */  
  1234.     private void startScrolling() {  
  1235.         //如果没有滚动, 将滚动状态 isScrollingPerformed 设为 true  
  1236.         if (!isScrollingPerformed) {  
  1237.             isScrollingPerformed = true;  
  1238.             //通知监听器开始滚动 回调所有的 滚动监听集合中 的 开始滚动方法  
  1239.             notifyScrollingListenersAboutStart();  
  1240.         }  
  1241.     }  
  1242.   
  1243.     /** 
  1244.      * 结束滚动 
  1245.      *  设置滚动状态为 false, 回调滚动监听器的停止滚动方法 
  1246.      */  
  1247.     void finishScrolling() {  
  1248.         if (isScrollingPerformed) {  
  1249.             notifyScrollingListenersAboutEnd();  
  1250.             isScrollingPerformed = false;  
  1251.         }  
  1252.         //设置布局无效  
  1253.         invalidateLayouts();  
  1254.         //重绘布局  
  1255.         invalidate();  
  1256.     }  
  1257.   
  1258.     /** 
  1259.      * 滚动 WheelView 
  1260.      *  
  1261.      * @param itemsToSkip 
  1262.      *            滚动的元素个数 
  1263.      * @param time 
  1264.      *            每次滚动的间隔 
  1265.      */  
  1266.     public void scroll(int itemsToScroll, int time) {  
  1267.         //如果有滚动强制停止  
  1268.         scroller.forceFinished(true);  
  1269.   
  1270.         lastScrollY = scrollingOffset;  
  1271.         int offset = itemsToScroll * getItemHeight();  
  1272.   
  1273.         /* 
  1274.          * 给定 一个开始点, 滚动距离, 滚动间隔, 开始滚动 
  1275.          *  
  1276.          * 参数解析 :  
  1277.          * 1. 开始的 x 轴位置 
  1278.          * 2. 开始的 y 轴位置 
  1279.          * 3. 要滚动 x 轴距离 
  1280.          * 4. 要滚动 y 轴距离 
  1281.          * 5. 滚动花费的时间 
  1282.          */  
  1283.         scroller.startScroll(0, lastScrollY, 0, offset - lastScrollY, time);  
  1284.         setNextMessage(MESSAGE_SCROLL);  
  1285.   
  1286.         //设置开始滚动状态, 并回调滚动监听器方法  
  1287.         startScrolling();  
  1288.     }  
  1289.   
  1290. }  



7. Activity 主界面 


[java] view plaincopy
  1. package cn.org.octopus.wheelview;  
  2.   
  3. import android.app.Activity;  
  4. import android.app.AlertDialog;  
  5. import android.app.Fragment;  
  6. import android.content.Context;  
  7. import android.content.DialogInterface;  
  8. import android.os.Bundle;  
  9. import android.view.Gravity;  
  10. import android.view.LayoutInflater;  
  11. import android.view.Menu;  
  12. import android.view.MenuItem;  
  13. import android.view.View;  
  14. import android.view.ViewGroup;  
  15. import android.view.ViewGroup.LayoutParams;  
  16. import android.widget.Button;  
  17. import android.widget.LinearLayout;  
  18. import cn.org.octopus.wheelview.widget.ArrayWheelAdapter;  
  19. import cn.org.octopus.wheelview.widget.OnWheelChangedListener;  
  20. import cn.org.octopus.wheelview.widget.OnWheelScrollListener;  
  21. import cn.org.octopus.wheelview.widget.WheelView;  
  22.   
  23. public class MainActivity extends Activity{  
  24.   
  25.     public static final String TAG = "octopus.activity";  
  26.       
  27.     private static Button bt_click;  
  28.       
  29.     public String province[] = new String[] { "  河北省  ""  山西省  ""  内蒙古  ""  辽宁省  ""  吉林省  ""  黑龙江  ""  江苏省  " };  
  30.   
  31.     public String city[][] = new String[][] {  
  32.             new String[] {"  石家庄  ""唐山""秦皇岛""邯郸""邢台""保定""张家口""承德""沧州""廊坊""衡水"},  
  33.             new String[] {"太原""大同""阳泉""长治""晋城""朔州""晋中""运城""忻州""临汾""吕梁"},  
  34.             new String[] {"呼和浩特""包头""乌海""赤峰""通辽""鄂尔多斯""呼伦贝尔""巴彦淖尔""乌兰察布""兴安""锡林郭勒""阿拉善"},  
  35.             new String[] {"沈阳""大连""鞍山""抚顺""本溪""丹东""锦州""营口""阜新""辽阳""盘锦""铁岭""朝阳""葫芦岛"},  
  36.             new String[] {"长春""吉林""四平""辽源""通化""白山""松原""白城""延边"},  
  37.             new String[] {"哈尔滨""齐齐哈尔""鸡西""鹤岗""双鸭山""大庆""伊春""佳木斯""七台河""牡丹江""黑河""绥化""大兴安岭"},  
  38.             new String[] {"南京""无锡""徐州""常州""苏州""南通""连云港""淮安""盐城""扬州""镇江""泰州""宿迁"} };  
  39.       
  40.     @Override  
  41.     protected void onCreate(Bundle savedInstanceState) {  
  42.         super.onCreate(savedInstanceState);  
  43.         setContentView(R.layout.activity_main);  
  44.   
  45.         if (savedInstanceState == null) {  
  46.             getFragmentManager().beginTransaction()  
  47.                     .add(R.id.container, new PlaceholderFragment()).commit();  
  48.         }  
  49.     }  
  50.       
  51.     /* 
  52.      * 点击事件 
  53.      */  
  54.     public void onClick(View view) {  
  55.         showSelectDialog(this"选择地点", province, city);  
  56.     }  
  57.   
  58.       
  59.     private void showSelectDialog(Context context, String title, final String[] left, final String[][] right) {  
  60.         //创建对话框  
  61.         AlertDialog dialog = new AlertDialog.Builder(context).create();  
  62.         //为对话框设置标题  
  63.         dialog.setTitle(title);  
  64.         //创建对话框内容, 创建一个 LinearLayout   
  65.         LinearLayout llContent = new LinearLayout(context);  
  66.         //将创建的 LinearLayout 设置成横向的  
  67.         llContent.setOrientation(LinearLayout.HORIZONTAL);  
  68.         //创建 WheelView 组件  
  69.         final WheelView wheelLeft = new WheelView(context);  
  70.         //设置 WheelView 组件最多显示 5 个元素  
  71.         wheelLeft.setVisibleItems(5);  
  72.         //设置 WheelView 元素是否循环滚动  
  73.         wheelLeft.setCyclic(false);  
  74.         //设置 WheelView 适配器  
  75.         wheelLeft.setAdapter(new ArrayWheelAdapter<String>(left));  
  76.         //设置右侧的 WheelView  
  77.         final WheelView wheelRight = new WheelView(context);  
  78.         //设置右侧 WheelView 显示个数  
  79.         wheelRight.setVisibleItems(5);  
  80.         //设置右侧 WheelView 元素是否循环滚动  
  81.         wheelRight.setCyclic(true);  
  82.         //设置右侧 WheelView 的元素适配器  
  83.         wheelRight.setAdapter(new ArrayWheelAdapter<String>(right[0]));  
  84.         //设置 LinearLayout 的布局参数  
  85.         LinearLayout.LayoutParams paramsLeft = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,  
  86.                 LayoutParams.WRAP_CONTENT, 4);  
  87.         paramsLeft.gravity = Gravity.LEFT;  
  88.         LinearLayout.LayoutParams paramsRight = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,  
  89.                 LayoutParams.WRAP_CONTENT, 6);  
  90.         paramsRight.gravity = Gravity.RIGHT;  
  91.         //将 WheelView 对象放到左侧 LinearLayout 中  
  92.         llContent.addView(wheelLeft, paramsLeft);  
  93.         //将 WheelView 对象放到 右侧 LinearLayout 中  
  94.         llContent.addView(wheelRight, paramsRight);  
  95.           
  96.         //为左侧的 WheelView 设置条目改变监听器  
  97.         wheelLeft.addChangingListener(new OnWheelChangedListener() {  
  98.             @Override  
  99.             public void onChanged(WheelView wheel, int oldValue, int newValue) {  
  100.                 //设置右侧的 WheelView 的适配器  
  101.                 wheelRight.setAdapter(new ArrayWheelAdapter<String>(right[newValue]));  
  102.                 wheelRight.setCurrentItem(right[newValue].length / 2);  
  103.             }  
  104.         });  
  105.           
  106.         wheelLeft.addScrollingListener(new OnWheelScrollListener() {  
  107.               
  108.             @Override  
  109.             public void onScrollingStarted(WheelView wheel) {  
  110.                 // TODO Auto-generated method stub  
  111.                   
  112.             }  
  113.               
  114.             @Override  
  115.             public void onScrollingFinished(WheelView wheel) {  
  116.                 // TODO Auto-generated method stub  
  117.                   
  118.             }  
  119.         });  
  120.           
  121.         //设置对话框点击事件 积极  
  122.         dialog.setButton(AlertDialog.BUTTON_POSITIVE, "确定"new DialogInterface.OnClickListener() {  
  123.             @Override  
  124.             public void onClick(DialogInterface dialog, int which) {  
  125.                 int leftPosition = wheelLeft.getCurrentItem();  
  126.                 String vLeft = left[leftPosition];  
  127.                 String vRight = right[leftPosition][wheelRight.getCurrentItem()];  
  128.                 bt_click.setText(vLeft + "-" + vRight);  
  129.                 dialog.dismiss();  
  130.             }  
  131.         });  
  132.           
  133.         //设置对话框点击事件 消极  
  134.         dialog.setButton(AlertDialog.BUTTON_NEGATIVE, "取消"new DialogInterface.OnClickListener() {  
  135.             @Override  
  136.             public void onClick(DialogInterface dialog, int which) {  
  137.                 dialog.dismiss();  
  138.             }  
  139.         });  
  140.         //将 LinearLayout 设置到 对话框中  
  141.         dialog.setView(llContent);  
  142.         //显示对话框  
  143.         if (!dialog.isShowing()) {  
  144.             dialog.show();  
  145.         }  
  146.     }  
  147.       
  148.       
  149.     @Override  
  150.     public boolean onCreateOptionsMenu(Menu menu) {  
  151.   
  152.         // Inflate the menu; this adds items to the action bar if it is present.  
  153.         getMenuInflater().inflate(R.menu.main, menu);  
  154.         return true;  
  155.     }  
  156.   
  157.     @Override  
  158.     public boolean onOptionsItemSelected(MenuItem item) {  
  159.         // Handle action bar item clicks here. The action bar will  
  160.         // automatically handle clicks on the Home/Up button, so long  
  161.         // as you specify a parent activity in AndroidManifest.xml.  
  162.         int id = item.getItemId();  
  163.         if (id == R.id.action_settings) {  
  164.             return true;  
  165.         }  
  166.         return super.onOptionsItemSelected(item);  
  167.     }  
  168.   
  169.     /** 
  170.      * A placeholder fragment containing a simple view. 
  171.      */  
  172.     public static class PlaceholderFragment extends Fragment {  
  173.   
  174.         public PlaceholderFragment() {  
  175.         }  
  176.   
  177.         @Override  
  178.         public View onCreateView(LayoutInflater inflater, ViewGroup container,  
  179.                 Bundle savedInstanceState) {  
  180.             View rootView = inflater.inflate(R.layout.fragment_main, container,  
  181.                     false);  
  182.             bt_click = (Button)rootView.findViewById(R.id.bt_click);  
  183.             return rootView;  
  184.         }  
  185.     }  
  186.   
  187. }  


博客地址 http://blog.csdn.net/shulianghan/article/details/41520569#t17


代码下载 : 

-- GitHub : https://github.com/han1202012/WheelViewDemo.git 

-- CSDN : http://download.csdn.net/detail/han1202012/8208997 ;



代码下载 : 

-- GitHub : https://github.com/han1202012/WheelViewDemo.git 

-- CSDN : http://download.csdn.net/detail/han1202012/8208997 ;


博客地址 http://blog.csdn.net/shulianghan/article/details/41520569#t17


代码下载 : 

-- GitHub : https://github.com/han1202012/WheelViewDemo.git 

-- CSDN : http://download.csdn.net/detail/han1202012/8208997 ;

博客地址 http://blog.csdn.net/shulianghan/article/details/41520569#t17


代码下载 : 

-- GitHub : https://github.com/han1202012/WheelViewDemo.git 

-- CSDN : http://download.csdn.net/detail/han1202012/8208997 ;

0 0
原创粉丝点击