敬告:由于本文代码较多,可以下下载文章下方的代码,打开参考本文查看,效果更好!
首先,先看下效果图:
这三张图分别是使用滚动控件实现城市,随机数和时间三个简单的例子,当然,界面有点简陋,下面我们就以时间这个为例,开始解析一下。
首先,先看下布局文件:
- xml version="1.0" encoding="utf-8"?>
-
- <LinearLayout xmlns:android=""
- android:layout_height="wrap_content"
- android:layout_width="fill_parent"
- android:layout_marginTop="12dp"
- android:orientation="vertical"
- android:background="@drawable/layout_bg">
-
- <LinearLayout xmlns:android=""
- android:layout_height="wrap_content"
- android:layout_width="fill_parent"
- android:layout_gravity="center_horizontal"
- android:paddingLeft="12dp"
- android:paddingRight="12dp"
- android:paddingTop="10dp">
-
- <kankan.wheel.widget.WheelView android:id="@+id/hour"
- android:layout_height="wrap_content"
- android:layout_width="fill_parent"
- android:layout_weight="1"/>
- <kankan.wheel.widget.WheelView android:id="@+id/mins"
- android:layout_height="wrap_content"
- android:layout_width="fill_parent"
- android:layout_weight="1"/>
- LinearLayout>
-
- <TimePicker android:id="@+id/time"
- android:layout_marginTop="12dp"
- android:layout_height="wrap_content"
- android:layout_width="fill_parent"
- android:layout_weight="1"/>
-
- LinearLayout>
里面只有三个控件,两个自定义的WheelView,还有一个TimePicker,然后进入代码里面看一下:
- public class TimeActivity extends Activity {
-
- private boolean timeChanged = false;
-
-
- private boolean timeScrolled = false;
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
-
- setContentView(R.layout.time_layout);
-
- final WheelView hours = (WheelView) findViewById(R.id.hour);
- hours.setAdapter(new NumericWheelAdapter(0, 23));
- hours.setLabel("hours");
-
- final WheelView mins = (WheelView) findViewById(R.id.mins);
- mins.setAdapter(new NumericWheelAdapter(0, 59, "%02d"));
- mins.setLabel("mins");
- mins.setCyclic(true);
-
- final TimePicker picker = (TimePicker) findViewById(R.id.time);
- picker.setIs24HourView(true);
-
-
- Calendar c = Calendar.getInstance();
- int curHours = c.get(Calendar.HOUR_OF_DAY);
- int curMinutes = c.get(Calendar.MINUTE);
-
- hours.setCurrentItem(curHours);
- mins.setCurrentItem(curMinutes);
-
- picker.setCurrentHour(curHours);
- picker.setCurrentMinute(curMinutes);
-
-
- addChangingListener(mins, "min");
- addChangingListener(hours, "hour");
-
- OnWheelChangedListener wheelListener = new OnWheelChangedListener() {
- public void onChanged(WheelView wheel, int oldValue, int newValue) {
- if (!timeScrolled) {
- timeChanged = true;
- picker.setCurrentHour(hours.getCurrentItem());
- picker.setCurrentMinute(mins.getCurrentItem());
- timeChanged = false;
- }
- }
- };
-
- hours.addChangingListener(wheelListener);
- mins.addChangingListener(wheelListener);
-
- OnWheelScrollListener scrollListener = new OnWheelScrollListener() {
- public void onScrollingStarted(WheelView wheel) {
- timeScrolled = true;
- }
- public void onScrollingFinished(WheelView wheel) {
- timeScrolled = false;
- timeChanged = true;
- picker.setCurrentHour(hours.getCurrentItem());
- picker.setCurrentMinute(mins.getCurrentItem());
- timeChanged = false;
- }
- };
-
- hours.addScrollingListener(scrollListener);
- mins.addScrollingListener(scrollListener);
-
- picker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
- public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
- if (!timeChanged) {
- hours.setCurrentItem(hourOfDay, true);
- mins.setCurrentItem(minute, true);
- }
- }
- });
- }
-
-
-
-
-
-
- private void addChangingListener(final WheelView wheel, final String label) {
- wheel.addChangingListener(new OnWheelChangedListener() {
- public void onChanged(WheelView wheel, int oldValue, int newValue) {
- wheel.setLabel(newValue != 1 ? label + "s" : label);
- }
- });
- }
- }
看一下,里面调用WheelView的方法有setAdapter()、setLabel("mins")、setCyclic(true)、setCurrentItem()、getCurrentItem()、addChangingListener()、addScrollingListener()这些方法,其中setAapter设置数据适配器,setCyclic()设置是否是循环,setCurrentItem和getCurrentItem分别是设置现在选择的item和返回现在选择的item。后面两个设置监听的方法中,需要重写两个接口:
-
-
-
- public interface OnWheelScrollListener {
-
-
-
-
- void onScrollingStarted(WheelView wheel);
-
-
-
-
-
- void onScrollingFinished(WheelView wheel);
- }
和
- public interface OnWheelChangedListener {
-
-
-
-
-
-
- void onChanged(WheelView wheel, int oldValue, int newValue);
- }
在这里使用的是典型的回调方法模式。
然后现在,我们进入WheelView类,看一下他是如何构建,首先,WheelView继承了View类。代码的22行到45行是导入的所需要的类。从54行到135行是声明一些变量和类:
-
- private static final int SCROLLING_DURATION = 400;
-
-
- private static final int MIN_DELTA_FOR_SCROLLING = 1;
-
-
- private static final int VALUE_TEXT_COLOR = 0xF0000000;
-
-
- private static final int ITEMS_TEXT_COLOR = 0xFF000000;
-
-
- private static final int[] SHADOWS_COLORS = new int[] { 0xFF111111,
- 0x00AAAAAA, 0x00AAAAAA };
-
-
- private static final int ADDITIONAL_ITEM_HEIGHT = 15;
-
-
- private static final int TEXT_SIZE = 24;
-
-
- private static final int ITEM_OFFSET = TEXT_SIZE / 5;
-
-
- private static final int ADDITIONAL_ITEMS_SPACE = 10;
-
-
- private static final int LABEL_OFFSET = 8;
-
-
- private static final int PADDING = 10;
-
-
- private static final int DEF_VISIBLE_ITEMS = 5;
-
-
- private WheelAdapter adapter = null;
- private int currentItem = 0;
-
-
- private int itemsWidth = 0;
- private int labelWidth = 0;
-
-
- private int visibleItems = DEF_VISIBLE_ITEMS;
-
-
- private int itemHeight = 0;
-
-
- private TextPaint itemsPaint;
- private TextPaint valuePaint;
-
-
- private StaticLayout itemsLayout;
- private StaticLayout labelLayout;
- private StaticLayout valueLayout;
-
-
- private String label;
- private Drawable centerDrawable;
-
-
- private GradientDrawable topShadow;
- private GradientDrawable bottomShadow;
-
-
- private boolean isScrollingPerformed;
- private int scrollingOffset;
-
-
- private GestureDetector gestureDetector;
- private Scroller scroller;
- private int lastScrollY;
-
-
- boolean isCyclic = false;
-
-
- private List changingListeners = new LinkedList();
- private List scrollingListeners = new LinkedList();
在这里面,使用到了StaticLayout,在开发文档中找一下这个类:
- StaticLayout is a Layout for text that will not be edited after it is laid out. Use DynamicLayout for text that may change.
-
- This is used by widgets to control text layout. You should not need to use this class directly unless you are implementing your own widget or custom display object, or would be tempted to call Canvas.drawText() directly.
staticLayout被创建以后就不能被修改了,通常被用于控制文本组件布局。
还使用到了Drawable、Text'Paint、GradientDrawable、GestureDetector、Scroller类,在开发文档中,GradientDrawable的概述:
- A Drawable with a color gradient for buttons, backgrounds, etc.
-
- It can be defined in an XML file with the element. For more information, see the guide to Drawable Resources.
就是说这个类可以为按钮或者背景等提供渐变颜色的绘制。
TextPaint的概述:
- TextPaint is an extension of Paint that leaves room for some extra data used during text measuring and drawing.
TextPaint是Paint类的一个扩展,主要是用于文本在绘制的过程中为附件的数据留出空间。
GestureDetector:手势检测,看下开发文档中关于该类的概述:
- Detects various gestures and events using the supplied MotionEvents. The GestureDetector.OnGestureListener callback will notify users when a particular motion event has occurred. This class should only be used with MotionEvents reported via touch (don't use for trackball events).
为各种手势和事件提供MotionEvents。当一个具体的事件发生时会调用回调函数GestureDetector.OnGestureListener。这个类应该只适用于MotionEvents通过触摸触发的事件(不要使用追踪事件)。
140行到156行是构造方法,175到183行是set和getAdapter。在193行,setInterpolator()方法,设置interPolator这个动画接口,我们看下这个接口的概述:
- An interpolator defines the rate of change of an animation. This allows the basic animation effects (alpha, scale, translate, rotate) to be accelerated, decelerated, repeated, etc.
定义了一种基于变率的一个动画。这使得基本的动画效果(alpha, scale, translate, rotate)是加速,减慢,重复等。这个方法在随机数这个例子中被使用。
203行到213行设置显示的item条数。在setVisibleItems()方法里面调用了View的invalidate()方法,看下文档中对该方法的介绍:
- Invalidate the whole view. If the view is visible, onDraw(android.graphics.Canvas) will be called at some point in the future. This must be called from a UI thread. To call from a non-UI thread, call postInvalidate().
使全部视图失效,如果View视图是可见的,会在UI线程里面从新调用onDraw()方法。
223行到233行是设置Label,既后面图片中的hours.
245行到296行是设置监听,在上面已经简单的说了一下,这里不在累述。
307行到349行是设置正被选中item,就是在那个阴影条框下的那个部分,比较简单。
357行到365行是设置item数据能否循环使用。
384行的initResourcesIfNecessary()方法,从字面意思,如果需要的初始化资源。
- private void initResourcesIfNecessary() {
- if (itemsPaint == null) {
- itemsPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG
- | Paint.FAKE_BOLD_TEXT_FLAG);
-
- itemsPaint.setTextSize(TEXT_SIZE);
- }
-
- if (valuePaint == null) {
- valuePaint = new TextPaint(Paint.ANTI_ALIAS_FLAG
- | Paint.FAKE_BOLD_TEXT_FLAG | Paint.DITHER_FLAG);
-
- valuePaint.setTextSize(TEXT_SIZE);
- valuePaint.setShadowLayer(0.1f, 0, 0.1f, 0xFFC0C0C0);
- }
-
- if (centerDrawable == null) {
- centerDrawable = getContext().getResources().getDrawable(R.drawable.wheel_val);
- }
-
- if (topShadow == null) {
- topShadow = new GradientDrawable(Orientation.TOP_BOTTOM, SHADOWS_COLORS);
- }
-
- if (bottomShadow == null) {
- bottomShadow = new GradientDrawable(Orientation.BOTTOM_TOP, SHADOWS_COLORS);
- }
-
- setBackgroundResource(R.drawable.wheel_bg);
- }
这个方法就是初始化在532行calculateLayoutWidth()方法中调用了这个方法,同时调用了487行的getMaxTextLength()这个方法。
471行getTextItem(int index)通过一个索引获取该item的文本。
这是第一部分,没有多少有太多意思的地方,重点的地方在以后532行到940行的内容,另起一篇,开始分析,这一篇先到这。
最后是下载地址:
Android仿iPhone滚动控件源码