-
Notifications
You must be signed in to change notification settings - Fork 1
/
DirFastScroller.java
717 lines (549 loc) · 22.5 KB
/
DirFastScroller.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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
package net.sf.fakenames.fddemo.view;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.support.annotation.NonNull;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.OnScrollListener;
import android.util.AttributeSet;
import android.view.ContextThemeWrapper;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import net.sf.fakenames.fddemo.R;
import java.io.File;
/**
* Defines a basic widget that will allow for fast scrolling a RecyclerView using
* the basic paradigm of a handle and a bar.
*/
public final class DirFastScroller extends ViewGroup {
private static final int[] STYLEABLE = R.styleable.AbsRecyclerViewFastScroller;
// The handle that signifies the user's progress in the list
private View thumb;
// The long bar along which a handle travels
private View track;
private RecyclerView recycler;
private OnScrollListener onScrollListener;
private RecyclerView.AdapterDataObserver adapterDataObserver;
private VerticalScreenPositionCalculator screenPositionCalculator;
private final ViewDrugHelper drugHelper;
private final GestureDetectorCompat trackHandler;
private final OnLayoutChangeListener layoutListener = (v, l, t, r, b, l0, t0, r0, b0) -> makeNewObserver();
private final Runnable delayed = new Runnable() {
@Override
public void run() {
if (canComputeFastScroll) {
onCreateScrollProgressCalculator();
moveHandleToPosition();
}
}
};
private void makeNewObserver() {
removeCallbacks(delayed);
post(delayed);
}
public DirFastScroller(Context context) {
this(context, null, 0);
}
public DirFastScroller(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public DirFastScroller(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray attributes = getContext().getTheme().obtainStyledAttributes(attrs, STYLEABLE, defStyleAttr, R.style.FastScrollerDefault);
try {
int layoutResource = attributes.getResourceId(R.styleable.AbsRecyclerViewFastScroller_rfs_fast_scroller_layout, 0);
if (layoutResource != 0) {
final Context themed = new ContextThemeWrapper(context, R.style.FastScrollerDefault);
LayoutInflater.from(themed).inflate(layoutResource, this, true);
}
} finally {
attributes.recycle();
}
drugHelper = ViewDrugHelper.create(this, new DragCallback());
trackHandler = new GestureDetectorCompat(getContext(), new TrackEventHandler());
}
@Override
public void onViewAdded(View child) {
super.onViewAdded(child);
switch (child.getId()) {
case R.id.scroll_bar:
track = child;
track.setOnTouchListener((v, event) -> trackHandler.onTouchEvent(event));
track.addOnLayoutChangeListener(layoutListener);
break;
case R.id.scroll_handle:
thumb = child;
thumb.setOnTouchListener((v, event) -> thumbTouched(event));
break;
}
}
@Override
public void onViewRemoved(View child) {
super.onViewRemoved(child);
switch (child.getId()) {
case R.id.scroll_bar:
track = null;
child.setOnTouchListener(null);
child.removeOnLayoutChangeListener(layoutListener);
break;
case R.id.scroll_handle:
thumb = null;
child.setOnTouchListener(null);
break;
}
}
private boolean thumbTouched(MotionEvent event) {
switch (MotionEventCompat.getActionMasked(event)) {
case MotionEventCompat.ACTION_POINTER_DOWN:
case MotionEvent.ACTION_DOWN:
if (recycler != null) {
recycler.stopScroll();
}
}
return false;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return drugHelper.shouldInterceptTouchEvent(ev) || super.onInterceptTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
drugHelper.processTouchEvent(event);
return super.onTouchEvent(event);
}
@Override
public boolean isImportantForAccessibility() {
return false;
}
public void setRecyclerView(RecyclerView recycler) {
this.recycler = recycler;
checkValidity();
}
private int getListPositionFromScrollProgress(float scrollProgress) {
if (!canComputeFastScroll) {
return -1;
}
int itemCount = recycler.getAdapter().getItemCount();
int pos = (int) (itemCount * scrollProgress);
// limit in case scrollProgress is exactly 1
if (pos >= itemCount) {
pos = itemCount - 1;
}
return pos;
}
@NonNull
public OnScrollListener getOnScrollListener() {
if (onScrollListener == null) {
onScrollListener = new RecyclerViewScrollListener();
}
return onScrollListener;
}
@NonNull
public RecyclerView.AdapterDataObserver getAdapterDataObserver() {
if (adapterDataObserver == null) {
adapterDataObserver = new AdapterObserver();
}
return adapterDataObserver;
}
// poor-man's smooth animation done android way
public void moveHandleToPosition() {
// do not engage in meaningless work here
if (getVisibility() != VISIBLE) {
return;
}
if (screenPositionCalculator == null) {
// not laid out yet, ignore the call
return;
}
if (!canComputeFastScroll) {
return;
}
if (drugHelper.getViewDragState() != ViewDrugHelper.STATE_IDLE) {
// do not interfere with user-initiated dragging...
return;
}
// ...but quickly abort ongoing animations, if currently settling
drugHelper.release();
final int trackLength = recycler.computeVerticalScrollRange();
final int extra = recycler.computeVerticalScrollExtent();
final int thumbTop = recycler.computeVerticalScrollOffset();
if (trackLength <= 0 || thumbTop < 0 || trackLength == thumbTop) {
canComputeFastScroll = false;
return;
}
float scrollProgress = thumbTop / ((float) trackLength - extra);
final View child = thumb;
final FastScrollerLayoutParams position = (FastScrollerLayoutParams) child.getLayoutParams();
position.ratio = scrollProgress;
final int newTop = screenPositionCalculator.getYPositionFromScrollProgress(scrollProgress);
position.y = newTop;
final int oldTop = child.getTop();
final int oldBottom = child.getBottom();
ViewCompat.offsetTopAndBottom(child, newTop - oldTop);
postInvalidateOnAnimation(0, Math.min(newTop, oldTop),
getMeasuredWidth(), Math.max(oldBottom, newTop + child.getMeasuredHeight()));
}
private int maxWidth;
private int maxHeight;
private int childState;
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
maxWidth = 0; maxHeight = 0; childState = 0;
measureChildren(widthMeasureSpec, heightMeasureSpec);
maxWidth += getPaddingLeft() + getPaddingRight();
maxHeight += getPaddingTop() + getPaddingBottom();
maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight());
maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());
setMeasuredDimension(
resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
resolveSizeAndState(maxHeight, heightMeasureSpec, childState << MEASURED_HEIGHT_STATE_SHIFT));
}
@Override
protected void measureChild(View child, int parentWidthMeasureSpec, int parentHeightMeasureSpec) {
super.measureChildWithMargins(child, parentWidthMeasureSpec, 0, parentHeightMeasureSpec, 0);
final FastScrollerLayoutParams lp = (FastScrollerLayoutParams) child.getLayoutParams();
maxWidth = Math.max(maxWidth, child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin);
maxHeight = Math.max(maxHeight, child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin);
childState = combineMeasuredStates(childState, child.getMeasuredState());
}
// unlike code above this _actually_ moves thumb in specific position
@Override
@SuppressLint("RtlHardcoded")
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
final int count = getChildCount();
final int parentLeft = getPaddingLeft();
final int parentRight = right - left - getPaddingRight();
final int parentTop = getPaddingTop();
final int parentBottom = bottom - top - getPaddingBottom();
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {
final FastScrollerLayoutParams lp = (FastScrollerLayoutParams) child.getLayoutParams();
final int width = child.getMeasuredWidth();
final int height = child.getMeasuredHeight();
int childLeft;
int childTop;
int gravity = lp.gravity;
if (gravity == -1) {
gravity = Gravity.TOP | Gravity.START;
}
final int layoutDirection = getLayoutDirection();
final int absoluteGravity = Gravity.getAbsoluteGravity(gravity, layoutDirection);
final int verticalGravity = gravity & Gravity.VERTICAL_GRAVITY_MASK;
switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
case Gravity.CENTER_HORIZONTAL:
childLeft = parentLeft + (parentRight - parentLeft - width) / 2 +
lp.leftMargin - lp.rightMargin;
break;
case Gravity.RIGHT:
childLeft = parentRight - width - lp.rightMargin;
break;
case Gravity.LEFT:
default:
childLeft = parentLeft + lp.leftMargin;
}
switch (verticalGravity) {
case Gravity.TOP:
childTop = parentTop + lp.topMargin;
break;
case Gravity.CENTER_VERTICAL:
childTop = parentTop + (parentBottom - parentTop - height) / 2 +
lp.topMargin - lp.bottomMargin;
break;
case Gravity.BOTTOM:
childTop = parentBottom - height - lp.bottomMargin;
break;
default:
childTop = parentTop + lp.topMargin;
}
if (child == thumb) {
checkValidity();
if (canComputeFastScroll) {
if (lp.isPositionSet()) {
childTop = lp.y;
}
}
child.layout(childLeft, childTop, childLeft + width, childTop + height);
if (canComputeFastScroll) {
if (screenPositionCalculator == null) {
makeNewObserver();
}
}
} else {
child.layout(childLeft, childTop, childLeft + width, childTop + height);
}
}
}
}
@Override
protected void dispatchDraw(Canvas canvas) {
if (!canComputeFastScroll) {
return;
}
super.dispatchDraw(canvas);
}
protected void onCreateScrollProgressCalculator() {
VerticalScrollBoundsProvider boundsProvider = new VerticalScrollBoundsProvider();
//scrollProgressCalculator = new ScrollProgressCalculator(boundsProvider);
screenPositionCalculator = new VerticalScreenPositionCalculator(boundsProvider);
}
@Override
public void computeScroll() {
super.computeScroll();
if (drugHelper.continueSettling(true)) {
ViewCompat.postInvalidateOnAnimation(this);
}
}
// if you use this with LinearLayoutManager, consider using scrollToPositionWithOffset instead
protected void scrollListToPosition(int listPosition) {
recycler.scrollToPosition(listPosition);
}
final class TrackEventHandler extends GestureDetector.SimpleOnGestureListener {
final int[] tempLoc = new int[2];
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
if (track != null && thumb != null) {
track.getLocationOnScreen(tempLoc);
int offset = (int) (tempLoc[1] + e.getRawY());
drugHelper.release();
final FastScrollerLayoutParams position = (FastScrollerLayoutParams) thumb.getLayoutParams();
position.y = offset;
position.ratio = screenPositionCalculator.getScrollRatio(offset);
ViewCompat.offsetTopAndBottom(track, offset - thumb.getTop());
ViewCompat.postInvalidateOnAnimation(DirFastScroller.this);
return true;
}
return false;
}
}
final class DragCallback extends ViewDrugHelper.Callback {
@Override
public boolean tryCaptureView(View child, int pointerId) {
return child == thumb && canScroll();
}
@Override
public void onViewCaptured(View capturedChild, int activePointerId) {
recycler.stopScroll();
capturedChild.post(() -> capturedChild.setPressed(true));
}
@Override
public void onViewDragStateChanged(int state) {
if (state != ViewDrugHelper.STATE_DRAGGING) {
thumb.setPressed(false);
}
}
@Override
public void onViewReleased(View releasedChild, float xvel, float yvel) {
if (yvel != 0) {
drugHelper.flingCapturedView(0, track.getTop(), 0, track.getBottom() - thumb.getHeight());
ViewCompat.postInvalidateOnAnimation(DirFastScroller.this);
}
}
@Override
public int getViewVerticalDragRange(View child) {
return child == thumb && screenPositionCalculator != null ? screenPositionCalculator.getDragRange() : 0;
}
@Override
public int getViewHorizontalDragRange(View child) {
return 0;
}
@Override
public int clampViewPositionHorizontal(View child, int left, int dx) {
return 0;
}
@Override
public int clampViewPositionVertical(View child, int top, int dy) {
return child == thumb && screenPositionCalculator != null ? screenPositionCalculator.clamp(top) : 0;
}
@Override
public void onViewPositionChanged(View child, int left, int top, int dx, int dy) {
if (drugHelper.getViewDragState() == ViewDrugHelper.STATE_IDLE) {
// we are being dragged by code (likely from within RecyclerView itself!)
return;
}
final FastScrollerLayoutParams position = (FastScrollerLayoutParams) child.getLayoutParams();
position.y = top;
position.ratio = screenPositionCalculator.getScrollRatio(top);
int listPosition = getListPositionFromScrollProgress(position.ratio);
if (listPosition != -1) {
scrollListToPosition(listPosition);
}
}
}
final class RecyclerViewScrollListener extends OnScrollListener {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
moveHandleToPosition();
}
}
final class VerticalScrollBoundsProvider {
private final int mMinimumScrollY;
private final int mMaximumScrollY;
private final int scrollRange;
VerticalScrollBoundsProvider() {
mMinimumScrollY = track.getTop();
mMaximumScrollY = track.getBottom() - thumb.getHeight();
scrollRange = track.getBottom() - track.getTop();
}
int getMinimumScrollY() {
return mMinimumScrollY;
}
int getMaximumScrollY() {
return mMaximumScrollY;
}
int getScrollRange() {
return scrollRange;
}
}
@Override
protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
return p.getClass() == FastScrollerLayoutParams.class;
}
@Override
public boolean shouldDelayChildPressedState() {
return true;
}
@Override
public FastScrollerLayoutParams generateLayoutParams(AttributeSet attrs) {
return new FastScrollerLayoutParams(new FrameLayout.LayoutParams(getContext(), attrs));
}
@Override
protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
return FastScrollerLayoutParams.from(p);
}
@Override
protected LayoutParams generateDefaultLayoutParams() {
return new FastScrollerLayoutParams();
}
static final class FastScrollerLayoutParams extends FrameLayout.LayoutParams {
float ratio = Float.NaN;
int y = Integer.MIN_VALUE;
FastScrollerLayoutParams() {
//noinspection ResourceType
super(WRAP_CONTENT, WRAP_CONTENT);
}
FastScrollerLayoutParams(FrameLayout.LayoutParams p) {
super(p);
}
FastScrollerLayoutParams(MarginLayoutParams p) {
super(p);
}
FastScrollerLayoutParams(ViewGroup.LayoutParams p) {
super(p);
}
static FastScrollerLayoutParams from(ViewGroup.LayoutParams p) {
if (p.getClass() == FrameLayout.LayoutParams.class || p instanceof FrameLayout.LayoutParams) {
return new FastScrollerLayoutParams((FrameLayout.LayoutParams) p);
}
if (p instanceof MarginLayoutParams) {
return new FastScrollerLayoutParams((MarginLayoutParams) p);
}
return new FastScrollerLayoutParams(p);
}
boolean isPositionSet() {
return y != Integer.MIN_VALUE;
}
}
static final class VerticalScreenPositionCalculator {
private final VerticalScrollBoundsProvider mVerticalScrollBoundsProvider;
VerticalScreenPositionCalculator(VerticalScrollBoundsProvider scrollBoundsProvider) {
mVerticalScrollBoundsProvider = scrollBoundsProvider;
}
int getYPositionFromScrollProgress(float scrollProgress) {
int absScroll = mVerticalScrollBoundsProvider.getMinimumScrollY() +
(int) (scrollProgress * mVerticalScrollBoundsProvider.getScrollRange());
return Math.max(
mVerticalScrollBoundsProvider.getMinimumScrollY(),
Math.min(mVerticalScrollBoundsProvider.getMaximumScrollY(), absScroll)
);
}
float getScrollRatio(int y) {
if (y == mVerticalScrollBoundsProvider.getMinimumScrollY()) {
return 0f;
} else if (y == mVerticalScrollBoundsProvider.getMaximumScrollY()) {
return 1f;
} else {
return y / (float) mVerticalScrollBoundsProvider.getScrollRange();
}
}
int getDragRange() {
return mVerticalScrollBoundsProvider.getMaximumScrollY() - mVerticalScrollBoundsProvider.getMinimumScrollY();
}
int clamp(int newTop) {
final int bottomLimit = mVerticalScrollBoundsProvider.getMaximumScrollY();
if (newTop >= bottomLimit) {
return bottomLimit;
}
final int topLimit = mVerticalScrollBoundsProvider.getMinimumScrollY();
if (newTop <= mVerticalScrollBoundsProvider.getMinimumScrollY()) {
return topLimit;
}
return newTop;
}
}
final class AdapterObserver extends RecyclerView.AdapterDataObserver {
@Override
public void onChanged() {
checkValidity();
}
@Override
public void onItemRangeInserted(int positionStart, int itemCount) {
checkValidity();
}
@Override
public void onItemRangeRemoved(int positionStart, int itemCount) {
checkValidity();
}
@Override
public void onItemRangeChanged(int positionStart, int itemCount) {
}
@Override
public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {
}
}
private boolean canComputeFastScroll;
private void checkValidity() {
boolean canComputeFastScroll = canShowThumb();
if (canComputeFastScroll != this.canComputeFastScroll) {
this.canComputeFastScroll = canComputeFastScroll;
if (!ViewCompat.isInLayout(this)) {
requestLayout();
}
}
}
public boolean canShowThumb() {
if (thumb == null || track == null) {
return false;
}
if (recycler == null || !ViewCompat.isLaidOut(recycler)) {
return false;
}
final RecyclerView.Adapter<?> adapter = recycler.getAdapter();
if (adapter == null) {
return false;
}
final int itemCount = adapter.getItemCount();
if (itemCount <= 0 || itemCount == Integer.MAX_VALUE) {
return false;
}
return true;
}
public boolean canScroll() {
if (!canShowThumb()) return false;
final int range = recycler.computeVerticalScrollRange();
if (range <= 0) {
return false;
}
final int extent = recycler.computeVerticalScrollExtent();
return extent * 1.5 < range;
}
}