forked from brucetoo/PickView
/
WheelView.java
569 lines (454 loc) · 20 KB
/
WheelView.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
package io.blackbox_vision.wheelview.view;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import io.blackbox_vision.wheelview.data.ItemMapper;
import io.blackbox_vision.wheelview.R;
import static android.view.GestureDetector.SimpleOnGestureListener;
public final class WheelView extends View {
private static final String TAG = WheelView.class.getSimpleName();
public static final int MSG_INVALIDATE = 1000;
public static final int MSG_SCROLL_LOOP = 2000;
public static final int MSG_SELECTED_ITEM = 3000;
@NonNull
private final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
private ScheduledFuture<?> scheduledFuture;
@NonNull
private final List<OnLoopScrollListener> listeners = new ArrayList<>();
@NonNull
private final SimpleOnGestureListener onGestureListener = new WheelViewGestureListener();
private GestureDetector gestureDetector;
private final Paint topBottomTextPaint = new Paint(); //paint that draw top and bottom text
private final Paint centerTextPaint = new Paint(); // paint that draw center text
private final Paint centerLinePaint = new Paint(); // paint that draw line besides center text
private List items;
private ItemMapper itemMapper;
private String[] itemCount;
private float lineSpacingMultiplier;
private float itemHeight;
private boolean canLoop;
private int totalScrollY;
private int selectedIndex;
private int textSize;
private int maxTextWidth;
private int maxTextHeight;
private int overflowTextColor;
private int contentTextColor;
private int lineColor;
private int topLineY;
private int bottomLineY;
private int currentIndex;
private int initialPosition;
private int paddingLeftRight;
private int paddingTopBottom;
private int drawItemsCount;
private int circularDiameter;
private int widgetHeight;
private int circularRadius;
private int widgetWidth;
public Handler handler = new Handler(msg -> {
switch (msg.what) {
case MSG_INVALIDATE:
invalidate();
break;
case MSG_SCROLL_LOOP:
startSmoothScrollTo();
break;
case MSG_SELECTED_ITEM:
itemSelected();
break;
}
return false;
});
public WheelView(Context context) {
this(context, null);
}
public WheelView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public WheelView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
if (!isInEditMode()) {
initView(attrs);
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public WheelView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
if (!isInEditMode()) {
initView(attrs);
}
}
private void initView(@NonNull AttributeSet attrs) {
final TypedArray array = getContext().obtainStyledAttributes(attrs, R.styleable.WheelView);
try {
if (null != array) {
overflowTextColor = array.getColor(R.styleable.WheelView_wheelViewOverflowTextColor, 0xffafafaf);
contentTextColor = array.getColor(R.styleable.WheelView_wheelViewContentTextColor, 0xff313131);
lineColor = array.getColor(R.styleable.WheelView_wheelViewLineColor, 0xffc5c5c5);
canLoop = array.getBoolean(R.styleable.WheelView_wheelViewIsLoopEnabled, false);
initialPosition = array.getInt(R.styleable.WheelView_wheelViewInitialPosition, -1);
textSize = array.getDimensionPixelSize(R.styleable.WheelView_wheelViewTextSize, sp2px(getContext(), 16));
drawItemsCount = array.getInt(R.styleable.WheelView_wheelViewDrawItemCount, 7);
}
} finally {
if (null != array) {
array.recycle();
}
}
lineSpacingMultiplier = 2.0F;
if (Build.VERSION.SDK_INT >= 11) {
setLayerType(LAYER_TYPE_SOFTWARE, null);
}
itemMapper = item -> (String) item;
itemCount = new String[drawItemsCount];
gestureDetector = new GestureDetector(getContext(), onGestureListener);
gestureDetector.setIsLongpressEnabled(false);
}
private void initData() {
if (null == items) {
throw new IllegalArgumentException("items list must not be null!");
}
topBottomTextPaint.setColor(overflowTextColor);
topBottomTextPaint.setAntiAlias(true);
topBottomTextPaint.setTypeface(Typeface.MONOSPACE);
topBottomTextPaint.setTextSize(textSize);
centerTextPaint.setColor(contentTextColor);
centerTextPaint.setAntiAlias(true);
centerTextPaint.setTextScaleX(1.05F);
centerTextPaint.setTypeface(Typeface.MONOSPACE);
centerTextPaint.setTextSize(textSize);
centerLinePaint.setColor(lineColor);
centerLinePaint.setAntiAlias(true);
centerLinePaint.setTypeface(Typeface.MONOSPACE);
centerLinePaint.setTextSize(textSize);
measureTextWidthHeight();
//计算半圆周 -- maxTextHeight * lineSpacingMultiplier 表示每个item的高度 drawItemsCount = 7
//实际显示5个,留两个是在圆周的上下面
//lineSpacingMultiplier是指text上下的距离的值和maxTextHeight一样的意思 所以 = 2
//drawItemsCount - 1 代表圆周的上下两面各被剪切了一半 相当于高度少了一个 maxTextHeight
int mHalfCircumference = (int) (maxTextHeight * lineSpacingMultiplier * (drawItemsCount - 1));
//the diameter of circular 2πr = cir, 2r = height
circularDiameter = (int) ((mHalfCircumference * 2) / Math.PI);
//the radius of circular
circularRadius = (int) (mHalfCircumference / Math.PI);
// FIXME: 7/8/16 通过控件的高度来计算圆弧的周长
if (initialPosition == -1) {
initialPosition = canLoop ? (items.size() + 1) / 2 : 0;
}
currentIndex = initialPosition;
invalidate();
}
private void measureTextWidthHeight() {
final Rect rect = new Rect();
for (int i = 0; i < items.size(); i++) {
final String s1 = (String) items.get(i);
centerTextPaint.getTextBounds(s1, 0, s1.length(), rect);
int textWidth = rect.width();
int textHeight = rect.height();
maxTextWidth = (textWidth > maxTextWidth) ? textWidth : maxTextWidth;
maxTextHeight = (textHeight > maxTextHeight) ? textHeight : maxTextHeight;
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
widgetWidth = getMeasuredWidth();
widgetHeight = MeasureSpec.getSize(heightMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
Log.i(TAG, "onMeasure -> heightMode:" + heightMode);
itemHeight = lineSpacingMultiplier * maxTextHeight;
//auto calculate the text's left/right value when draw
paddingLeftRight = (widgetWidth - maxTextWidth) / 2;
paddingTopBottom = (widgetHeight - circularDiameter) / 2;
//topLineY = diameter/2 - itemHeight(itemHeight)/2 + paddingTopBottom
topLineY = (int) ((circularDiameter - itemHeight) / 2.0F) + paddingTopBottom;
bottomLineY = (int) ((circularDiameter + itemHeight) / 2.0F) + paddingTopBottom;
}
@Override
protected void onDraw(Canvas canvas) {
if (items == null) {
super.onDraw(canvas);
return;
}
super.onDraw(canvas);
//the length of single item is itemHeight
int mChangingItem = (int) (totalScrollY / (itemHeight));
currentIndex = initialPosition + mChangingItem % items.size();
if (!canLoop) { // can loop
currentIndex = (currentIndex < 0) ? 0 : currentIndex;
currentIndex = (currentIndex > items.size() - 1) ? items.size() - 1 : currentIndex;
} else { //can not loop
currentIndex = (currentIndex < 0) ? currentIndex + items.size() : currentIndex;
currentIndex = (currentIndex > items.size() - 1) ? currentIndex - items.size() : currentIndex;
}
int count = 0;
//reconfirm each item's value from dataList according to currentIndex,
while (count < drawItemsCount) {
int templateItem = currentIndex - (drawItemsCount / 2 - count);
if (canLoop) {
templateItem = (templateItem < 0) ? templateItem + items.size() : templateItem;
templateItem = (templateItem > items.size() - 1) ? templateItem - items.size() : templateItem;
itemCount[count] = itemMapper.map(items.get(templateItem));
} else if (templateItem < 0 || templateItem > items.size() - 1) {
itemCount[count] = "";
} else {
itemCount[count] = itemMapper.map(items.get(templateItem));
}
count++;
}
//draw top and bottom line
canvas.drawLine(0.0F, topLineY, widgetWidth, topLineY, centerLinePaint);
canvas.drawLine(0.0F, bottomLineY, widgetWidth, bottomLineY, centerLinePaint);
int changingLeftY = (int) (totalScrollY % (itemHeight));
count = 0;
while (count < drawItemsCount) {
canvas.save();
// L= å * r -> å = rad
float itemHeight = maxTextHeight * lineSpacingMultiplier;
//get radian L = (itemHeight * count - changingLeftY),r = circularRadius
double radian = (itemHeight * count - changingLeftY) / circularRadius;
// a = rad * 180 / π
//get angle
float angle = (float) (radian * 180 / Math.PI);
//when angle >= 180 || angle <= 0 don't draw
if (angle >= 180F || angle <= 0F) {
canvas.restore();
} else {
// translateY = r - r*cos(å) -
//(Math.sin(radian) * maxTextHeight) / 2 this is text offset
int translateY = (int) (circularRadius - Math.cos(radian) * circularRadius - (Math.sin(radian) * maxTextHeight) / 2) + paddingTopBottom;
canvas.translate(0.0F, translateY);
//scale offset = Math.sin(radian) -> 0 - 1
canvas.scale(1.0F, (float) Math.sin(radian));
if (translateY <= topLineY || maxTextHeight + translateY >= bottomLineY) {
final int diff = (translateY <= topLineY) ? topLineY - translateY : bottomLineY - translateY;
final Paint topBottomPaint = (translateY <= topLineY) ? topBottomTextPaint : centerTextPaint;
final Paint centerPaint = (translateY <= topLineY) ? centerTextPaint : topBottomTextPaint;
//draw text y between 0 -> topLineY,include incomplete text
canvas.save();
canvas.clipRect(0, 0, widgetWidth, diff);
canvas.drawText(itemCount[count], paddingLeftRight, maxTextHeight, topBottomPaint);
canvas.restore();
canvas.save();
canvas.clipRect(0, diff, widgetWidth, (int) (itemHeight));
canvas.drawText(itemCount[count], paddingLeftRight, maxTextHeight, centerPaint);
canvas.restore();
} else if (translateY >= topLineY && maxTextHeight + translateY <= bottomLineY) {
//draw center complete text
canvas.clipRect(0, 0, widgetWidth, (int) (itemHeight));
canvas.drawText(itemCount[count], paddingLeftRight, maxTextHeight, centerTextPaint);
//center one indicate selected item
selectedIndex = items.indexOf(itemCount[count]);
}
canvas.restore();
}
count++;
}
}
@Override
public boolean onTouchEvent(MotionEvent motionevent) {
switch (motionevent.getAction()) {
case MotionEvent.ACTION_UP:
default:
if (!gestureDetector.onTouchEvent(motionevent)) {
startSmoothScrollTo();
}
}
return true;
}
public WheelView setContentTextColor(int centerTextColor) {
this.contentTextColor = centerTextColor;
return this;
}
public WheelView setOverflowTextColor(int topBottomTextColor) {
this.overflowTextColor = topBottomTextColor;
return this;
}
public WheelView setLineColor(int centerLineColor) {
this.lineColor = centerLineColor;
return this;
}
public final void setIsLoopEnabled(boolean canLoop) {
this.canLoop = canLoop;
invalidate();
}
public final void setTextSize(float size) {
if (size > 0) {
textSize = sp2px(getContext(), size);
}
}
public void setInitialPosition(int initialPosition) {
this.initialPosition = initialPosition;
invalidate();
}
public void addOnLoopScrollListener(@Nullable OnLoopScrollListener loopScrollListener) {
listeners.add(loopScrollListener);
invalidate();
}
public void setOnLoopScrollListener(@Nullable OnLoopScrollListener loopScrollListener) {
listeners.add(loopScrollListener);
invalidate();
}
public void setItemMapper(@NonNull ItemMapper mapper) {
this.itemMapper = mapper;
}
public void setItems(@NonNull List items) {
this.items = items;
initData();
}
private void itemSelected() {
postDelayed(this::onItemSelected, 200L);
}
private void onItemSelected() {
for (OnLoopScrollListener onLoopScrollListener: listeners) {
onLoopScrollListener.onLoopScrollFinish(items.get(selectedIndex), items.indexOf(items.get(selectedIndex)));
}
}
private void cancelSchedule() {
if (null != scheduledFuture && !scheduledFuture.isCancelled()) {
scheduledFuture.cancel(true);
scheduledFuture = null;
}
}
private void startSmoothScrollTo() {
int offset = (int) (totalScrollY % (itemHeight));
cancelSchedule();
scheduledFuture = executorService.scheduleWithFixedDelay(new HalfHeightRunnable(offset), 0, 10, TimeUnit.MILLISECONDS);
}
private void startSmoothScrollTo(float velocityY) {
cancelSchedule();
int velocityFling = 20;
scheduledFuture = executorService.scheduleWithFixedDelay(new FlingRunnable(velocityY), 0, velocityFling, TimeUnit.MILLISECONDS);
}
class WheelViewGestureListener extends SimpleOnGestureListener {
@Override
public final boolean onDown(MotionEvent motionevent) {
cancelSchedule();
Log.i(TAG, "WheelViewGestureListener -> onDown");
return true;
}
@Override
public final boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
startSmoothScrollTo(velocityY);
Log.i(TAG, "WheelViewGestureListener -> onFling");
return true;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
Log.i(TAG, "WheelViewGestureListener -> onScroll");
totalScrollY = (int) ((float) totalScrollY + distanceY);
if (!canLoop) {
final int circleLength = (int) ((float) (items.size() - 1 - initialPosition) * (itemHeight));
final int initPositionCircleLength = (int) (initialPosition * (itemHeight));
final int initPositionStartY = -1 * initPositionCircleLength;
totalScrollY = (totalScrollY < initPositionStartY) ? initPositionStartY : totalScrollY;
totalScrollY = (totalScrollY >= circleLength) ? circleLength : totalScrollY;
}
invalidate();
return true;
}
}
public int sp2px(Context context, float spValue) {
final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return (int) (spValue * fontScale + 0.5f);
}
/**
* Use in ACTION_UP
*/
class HalfHeightRunnable implements Runnable {
int realTotalOffset;
int realOffset;
int offset;
HalfHeightRunnable(int offset) {
this.offset = offset;
realTotalOffset = Integer.MAX_VALUE;
realOffset = 0;
}
@Override
public void run() {
//first in
if (realTotalOffset == Integer.MAX_VALUE) {
if ((float) offset > itemHeight / 2.0F) {
//move to next item
realTotalOffset = (int) (itemHeight - (float) offset);
} else {
//move to pre item
realTotalOffset = -offset;
}
}
realOffset = (int) ((float) realTotalOffset * 0.1F);
if (realOffset == 0) {
realOffset = (realTotalOffset < 0) ? -1 : 1;
}
if (Math.abs(realTotalOffset) <= 0) {
cancelSchedule();
handler.sendEmptyMessage(MSG_SELECTED_ITEM);
} else {
totalScrollY = totalScrollY + realOffset;
handler.sendEmptyMessage(MSG_INVALIDATE);
realTotalOffset = realTotalOffset - realOffset;
}
}
}
class FlingRunnable implements Runnable {
float velocity;
final float velocityY;
FlingRunnable(float velocityY) {
this.velocityY = velocityY;
velocity = Integer.MAX_VALUE;
}
@Override
public void run() {
if (velocity == Integer.MAX_VALUE) {
if (Math.abs(velocityY) > 2000F) {
velocity = (velocityY > 0.0F) ? 2000F : - 2000F;
} else {
velocity = velocityY;
}
}
Log.i(TAG, "velocity -> " + velocity);
if (Math.abs(velocity) >= 0.0F && Math.abs(velocity) <= 20F) {
cancelSchedule();
handler.sendEmptyMessage(MSG_SCROLL_LOOP);
return;
}
int i = (int) ((velocity * 10F) / 1000F);
totalScrollY = totalScrollY - i;
if (!canLoop) {
float itemHeight = lineSpacingMultiplier * maxTextHeight;
if (totalScrollY <= (int) ((float) (-initialPosition) * itemHeight)) {
velocity = 40F;
totalScrollY = (int) ((float) (-initialPosition) * itemHeight);
} else if (totalScrollY >= (int) ((float) (items.size() - 1 - initialPosition) * itemHeight)) {
totalScrollY = (int) ((float) (items.size() - 1 - initialPosition) * itemHeight);
velocity = -40F;
}
}
velocity = (velocity < 0.0F) ? velocity + 20F : velocity - 20F;
handler.sendEmptyMessage(MSG_INVALIDATE);
}
}
public interface OnLoopScrollListener {
void onLoopScrollFinish(@NonNull Object item, int position);
}
}