-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathStackLayoutManager.java
613 lines (526 loc) · 20.9 KB
/
StackLayoutManager.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
package com.hirayclay;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import static android.support.v7.widget.RecyclerView.NO_POSITION;
import static com.hirayclay.Align.BOTTOM;
import static com.hirayclay.Align.LEFT;
import static com.hirayclay.Align.RIGHT;
import static com.hirayclay.Align.TOP;
/**
* Created by CJJ on 2017/5/17.
* my thought is simple:we assume the first item in the initial state is the base position ,
* we only need to calculate the appropriate position{@link #left(int index)}for the given item
* index with the given offset{@link #mTotalOffset}.After solve this thinking confusion ,this
* layoutManager is easy to implement
*
* @author CJJ
*/
class StackLayoutManager extends RecyclerView.LayoutManager {
private static final String TAG = "StackLayoutManager";
//the space unit for the stacked item
private int mSpace = 60;
/**
* the offset unit,deciding current position(the sum of {@link #mItemWidth} and {@link #mSpace})
*/
private int mUnit;
//item width
private int mItemWidth;
private int mItemHeight;
//the counting variable ,record the total offset including parallex
private int mTotalOffset;
//record the total offset without parallex
private int mRealOffset;
private ObjectAnimator animator;
private int animateValue;
private int duration = 300;
private RecyclerView.Recycler recycler;
private int lastAnimateValue;
//the max stacked item count;
private int maxStackCount = 4;
//initial stacked item
private int initialStackCount = 4;
private float secondaryScale = 0.8f;
private float scaleRatio = 0.4f;
private float parallex = 1f;
private int initialOffset;
private boolean initial;
private int mMinVelocityX;
private VelocityTracker mVelocityTracker = VelocityTracker.obtain();
private int pointerId;
private Align direction = LEFT;
private RecyclerView mRV;
private Method sSetScrollState;
private int mPendingScrollPosition = NO_POSITION;
StackLayoutManager(Config config) {
this();
this.maxStackCount = config.maxStackCount;
this.mSpace = config.space;
this.initialStackCount = config.initialStackCount;
this.secondaryScale = config.secondaryScale;
this.scaleRatio = config.scaleRatio;
this.direction = config.align;
this.parallex = config.parallex;
}
@SuppressWarnings("unused")
public StackLayoutManager() {
setAutoMeasureEnabled(true);
}
@Override
public boolean isAutoMeasureEnabled() {
return true;
}
@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
if (getItemCount() <= 0)
return;
this.recycler = recycler;
detachAndScrapAttachedViews(recycler);
//got the mUnit basing on the first child,of course we assume that all the item has the same size
View anchorView = recycler.getViewForPosition(0);
measureChildWithMargins(anchorView, 0, 0);
mItemWidth = anchorView.getMeasuredWidth();
mItemHeight = anchorView.getMeasuredHeight();
if (canScrollHorizontally())
mUnit = mItemWidth + mSpace;
else mUnit = mItemHeight + mSpace;
//because this method will be called twice
initialOffset = resolveInitialOffset();
mMinVelocityX = ViewConfiguration.get(anchorView.getContext()).getScaledMinimumFlingVelocity();
fill(recycler, 0);
}
//we need take direction into account when calc initialOffset
private int resolveInitialOffset() {
int offset = initialStackCount * mUnit;
if (mPendingScrollPosition != NO_POSITION) {
offset = mPendingScrollPosition * mUnit;
mPendingScrollPosition = NO_POSITION;
}
if (direction == LEFT)
return offset;
if (direction == RIGHT)
return -offset;
if (direction == TOP)
return offset;
else return offset;
}
@Override
public void onLayoutCompleted(RecyclerView.State state) {
super.onLayoutCompleted(state);
if (getItemCount()<=0)
return;
if (!initial) {
fill(recycler, initialOffset, false);
initial = true;
}
}
@Override
public void onAdapterChanged(RecyclerView.Adapter oldAdapter, RecyclerView.Adapter newAdapter) {
initial = false;
mTotalOffset = mRealOffset = 0;
}
/**
* the magic function :).all the work including computing ,recycling,and layout is done here
*
* @param recycler ...
*/
private int fill(RecyclerView.Recycler recycler, int dy, boolean apply) {
int delta = direction.layoutDirection * dy;
// multiply the parallex factor
if (apply)
delta = (int) (delta * parallex);
if (direction == LEFT)
return fillFromLeft(recycler, delta);
if (direction == RIGHT)
return fillFromRight(recycler, delta);
if (direction == TOP)
return fillFromTop(recycler, delta);
else return dy;//bottom alignment is not necessary,we don't support that
}
public int fill(RecyclerView.Recycler recycler, int dy) {
return fill(recycler, dy, true);
}
private int fillFromTop(RecyclerView.Recycler recycler, int dy) {
if (mTotalOffset + dy < 0 || (mTotalOffset + dy + 0f) / mUnit > getItemCount() - 1)
return 0;
detachAndScrapAttachedViews(recycler);
mTotalOffset += direction.layoutDirection * dy;
int count = getChildCount();
//removeAndRecycle views
for (int i = 0; i < count; i++) {
View child = getChildAt(i);
if (recycleVertically(child, dy))
removeAndRecycleView(child, recycler);
}
int currPos = mTotalOffset / mUnit;
int leavingSpace = getHeight() - (left(currPos) + mUnit);
int itemCountAfterBaseItem = leavingSpace / mUnit + 2;
int e = currPos + itemCountAfterBaseItem;
int start = currPos - maxStackCount >= 0 ? currPos - maxStackCount : 0;
int end = e >= getItemCount() ? getItemCount() - 1 : e;
int left = getWidth() / 2 - mItemWidth / 2;
//layout views
for (int i = start; i <= end; i++) {
View view = recycler.getViewForPosition(i);
float scale = scale(i);
float alpha = alpha(i);
addView(view);
measureChildWithMargins(view, 0, 0);
int top = (int) (left(i) - (1 - scale) * view.getMeasuredHeight() / 2);
int right = view.getMeasuredWidth() + left;
int bottom = view.getMeasuredHeight() + top;
layoutDecoratedWithMargins(view, left, top, right, bottom);
view.setAlpha(alpha);
view.setScaleY(scale);
view.setScaleX(scale);
}
return dy;
}
private int fillFromRight(RecyclerView.Recycler recycler, int dy) {
if (mTotalOffset + dy < 0 || (mTotalOffset + dy + 0f) / mUnit > getItemCount() - 1)
return 0;
detachAndScrapAttachedViews(recycler);
mTotalOffset += dy;
int count = getChildCount();
//removeAndRecycle views
for (int i = 0; i < count; i++) {
View child = getChildAt(i);
if (recycleHorizontally(child, dy))
removeAndRecycleView(child, recycler);
}
int currPos = mTotalOffset / mUnit;
int leavingSpace = left(currPos);
int itemCountAfterBaseItem = leavingSpace / mUnit + 2;
int e = currPos + itemCountAfterBaseItem;
int start = currPos - maxStackCount <= 0 ? 0 : currPos - maxStackCount;
int end = e >= getItemCount() ? getItemCount() - 1 : e;
//layout view
for (int i = start; i <= end; i++) {
View view = recycler.getViewForPosition(i);
float scale = scale(i);
float alpha = alpha(i);
addView(view);
measureChildWithMargins(view, 0, 0);
int left = (int) (left(i) - (1 - scale) * view.getMeasuredWidth() / 2);
int top = 0;
int right = left + view.getMeasuredWidth();
int bottom = view.getMeasuredHeight();
layoutDecoratedWithMargins(view, left, top, right, bottom);
view.setAlpha(alpha);
view.setScaleY(scale);
view.setScaleX(scale);
}
return dy;
}
private int fillFromLeft(RecyclerView.Recycler recycler, int dy) {
if (mTotalOffset + dy < 0 || (mTotalOffset + dy + 0f) / mUnit > getItemCount() - 1)
return 0;
detachAndScrapAttachedViews(recycler);
mTotalOffset += direction.layoutDirection * dy;
int count = getChildCount();
//removeAndRecycle views
for (int i = 0; i < count; i++) {
View child = getChildAt(i);
if (recycleHorizontally(child, dy))
removeAndRecycleView(child, recycler);
}
int currPos = mTotalOffset / mUnit;
int leavingSpace = getWidth() - (left(currPos) + mUnit);
int itemCountAfterBaseItem = leavingSpace / mUnit + 2;
int e = currPos + itemCountAfterBaseItem;
int start = currPos - maxStackCount >= 0 ? currPos - maxStackCount : 0;
int end = e >= getItemCount() ? getItemCount() - 1 : e;
//layout view
for (int i = start; i <= end; i++) {
View view = recycler.getViewForPosition(i);
float scale = scale(i);
float alpha = alpha(i);
addView(view);
measureChildWithMargins(view, 0, 0);
int left = (int) (left(i) - (1 - scale) * view.getMeasuredWidth() / 2);
int top = 0;
int right = left + view.getMeasuredWidth();
int bottom = top + view.getMeasuredHeight();
layoutDecoratedWithMargins(view, left, top, right, bottom);
view.setAlpha(alpha);
view.setScaleY(scale);
view.setScaleX(scale);
}
return dy;
}
private View.OnTouchListener mTouchListener = new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
mVelocityTracker.addMovement(event);
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (animator != null && animator.isRunning())
animator.cancel();
pointerId = event.getPointerId(0);
}
if (event.getAction() == MotionEvent.ACTION_UP) {
if (v.isPressed()) v.performClick();
mVelocityTracker.computeCurrentVelocity(1000, 14000);
float xVelocity = mVelocityTracker.getXVelocity(pointerId);
int o = mTotalOffset % mUnit;
int scrollX;
if (Math.abs(xVelocity) < mMinVelocityX && o != 0) {
if (o >= mUnit / 2)
scrollX = mUnit - o;
else scrollX = -o;
int dur = (int) (Math.abs((scrollX + 0f) / mUnit) * duration);
Log.i(TAG, "onTouch: ======BREW===");
brewAndStartAnimator(dur, scrollX);
}
}
return false;
}
};
private RecyclerView.OnFlingListener mOnFlingListener = new RecyclerView.OnFlingListener() {
@Override
public boolean onFling(int velocityX, int velocityY) {
int o = mTotalOffset % mUnit;
int s = mUnit - o;
int scrollX;
int vel = absMax(velocityX, velocityY);
if (vel * direction.layoutDirection > 0) {
scrollX = s;
} else
scrollX = -o;
int dur = computeSettleDuration(Math.abs(scrollX), Math.abs(vel));
brewAndStartAnimator(dur, scrollX);
setScrollStateIdle();
return true;
}
};
private int absMax(int a, int b) {
if (Math.abs(a) > Math.abs(b))
return a;
else return b;
}
@Override
public void onAttachedToWindow(RecyclerView view) {
super.onAttachedToWindow(view);
mRV = view;
//check when raise finger and settle to the appropriate item
view.setOnTouchListener(mTouchListener);
view.setOnFlingListener(mOnFlingListener);
}
private int computeSettleDuration(int distance, float xvel) {
float sWeight = 0.5f * distance / mUnit;
float velWeight = xvel > 0 ? 0.5f * mMinVelocityX / xvel : 0;
return (int) ((sWeight + velWeight) * duration);
}
private void brewAndStartAnimator(int dur, int finalXorY) {
animator = ObjectAnimator.ofInt(StackLayoutManager.this, "animateValue", 0, finalXorY);
animator.setDuration(dur);
animator.start();
animator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
lastAnimateValue = 0;
}
@Override
public void onAnimationCancel(Animator animation) {
lastAnimateValue = 0;
}
});
}
/******************************precise math method*******************************/
private float alpha(int position) {
float alpha;
int currPos = mTotalOffset / mUnit;
float n = (mTotalOffset + .0f) / mUnit;
if (position > currPos)
alpha = 1.0f;
else {
//temporary linear map,barely ok
alpha = 1 - (n - position) / maxStackCount;
}
//for precise checking,oh may be kind of dummy
return alpha <= 0.001f ? 0 : alpha;
}
private float scale(int position) {
switch (direction) {
default:
case LEFT:
case RIGHT:
return scaleDefault(position);
}
}
private float scaleDefault(int position) {
float scale;
int currPos = this.mTotalOffset / mUnit;
float n = (mTotalOffset + .0f) / mUnit;
float x = n - currPos;
// position >= currPos+1;
if (position >= currPos) {
if (position == currPos)
scale = 1 - scaleRatio * (n - currPos) / maxStackCount;
else if (position == currPos + 1)
//let the item's (index:position+1) scale be 1 when the item slide 1/2 mUnit,
// this have better visual effect
{
// scale = 0.8f + (0.4f * x >= 0.2f ? 0.2f : 0.4f * x);
scale = secondaryScale + (x > 0.5f ? 1 - secondaryScale : 2 * (1 - secondaryScale) * x);
} else scale = secondaryScale;
} else {//position <= currPos
if (position < currPos - maxStackCount)
scale = 0f;
else {
scale = 1f - scaleRatio * (n - currPos + currPos - position) / maxStackCount;
}
}
return scale;
}
/**
* @param position the index of the item in the adapter
* @return the accurate left position for the given item
*/
private int left(int position) {
int currPos = mTotalOffset / mUnit;
int tail = mTotalOffset % mUnit;
float n = (mTotalOffset + .0f) / mUnit;
float x = n - currPos;
switch (direction) {
default:
case LEFT:
case TOP:
//from left to right or top to bottom
//these two scenario are actually same
return ltr(position, currPos, tail, x);
case RIGHT:
return rtl(position, currPos, tail, x);
}
}
/**
* @param position ..
* @param currPos ..
* @param tail .. change
* @param x ..
* @return the left position for given item
*/
private int rtl(int position, int currPos, int tail, float x) {
//虽然是做对称变换,但是必须考虑到scale给 对称变换带来的影响
float scale = scale(position);
int ltr = ltr(position, currPos, tail, x);
return (int) (getWidth() - ltr - (mItemWidth) * scale);
}
private int ltr(int position, int currPos, int tail, float x) {
int left;
if (position <= currPos) {
if (position == currPos) {
left = (int) (mSpace * (maxStackCount - x));
} else {
left = (int) (mSpace * (maxStackCount - x - (currPos - position)));
}
} else {
if (position == currPos + 1)
left = mSpace * maxStackCount + mUnit - tail;
else {
float closestBaseItemScale = scale(currPos + 1);
//调整因为scale导致的left误差
// left = (int) (mSpace * maxStackCount + (position - currPos) * mUnit - tail
// -(position - currPos)*(mItemWidth) * (1 - closestBaseItemScale));
int baseStart = (int) (mSpace * maxStackCount + mUnit - tail + closestBaseItemScale * (mUnit - mSpace) + mSpace);
left = (int) (baseStart + (position - currPos - 2) * mUnit - (position - currPos - 2) * (1 - secondaryScale) * (mUnit - mSpace));
if (BuildConfig.DEBUG)
Log.i(TAG, "ltr: currPos " + currPos
+ " pos:" + position
+ " left:" + left
+ " baseStart" + baseStart
+ " currPos+1:" + left(currPos + 1));
}
left = left <= 0 ? 0 : left;
}
return left;
}
@SuppressWarnings("unused")
public void setAnimateValue(int animateValue) {
this.animateValue = animateValue;
int dy = this.animateValue - lastAnimateValue;
fill(recycler, direction.layoutDirection * dy, false);
lastAnimateValue = animateValue;
}
@SuppressWarnings("unused")
public int getAnimateValue() {
return animateValue;
}
/**
* should recycle view with the given dy or say check if the
* view is out of the bound after the dy is applied
*
* @param view ..
* @param dy ..
* @return ..
*/
private boolean recycleHorizontally(View view/*int position*/, int dy) {
return view != null && (view.getLeft() - dy < 0 || view.getRight() - dy > getWidth());
}
private boolean recycleVertically(View view, int dy) {
return view != null && (view.getTop() - dy < 0 || view.getBottom() - dy > getHeight());
}
@Override
public int scrollHorizontallyBy(int dx, RecyclerView.Recycler recycler, RecyclerView.State state) {
return fill(recycler, dx);
}
@Override
public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state) {
return fill(recycler, dy);
}
@Override
public boolean canScrollHorizontally() {
return direction == LEFT || direction == RIGHT;
}
@Override
public boolean canScrollVertically() {
return direction == TOP || direction == BOTTOM;
}
@Override
public RecyclerView.LayoutParams generateDefaultLayoutParams() {
return new RecyclerView.LayoutParams(RecyclerView.LayoutParams.WRAP_CONTENT, RecyclerView.LayoutParams.WRAP_CONTENT);
}
/**
* we need to set scrollstate to {@link RecyclerView#SCROLL_STATE_IDLE} idle
* stop RV from intercepting the touch event which block the item click
*/
private void setScrollStateIdle() {
try {
if (sSetScrollState == null)
sSetScrollState = RecyclerView.class.getDeclaredMethod("setScrollState", int.class);
sSetScrollState.setAccessible(true);
sSetScrollState.invoke(mRV, RecyclerView.SCROLL_STATE_IDLE);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
@Override
public void scrollToPosition(int position) {
if (position > getItemCount() - 1) {
Log.i(TAG, "position is " + position + " but itemCount is " + getItemCount());
return;
}
int currPosition = mTotalOffset / mUnit;
int distance = (position - currPosition) * mUnit;
int dur = computeSettleDuration(Math.abs(distance), 0);
brewAndStartAnimator(dur, distance);
}
@Override
public void requestLayout() {
super.requestLayout();
initial = false;
}
@SuppressWarnings("unused")
public interface CallBack {
float scale(int totalOffset, int position);
float alpha(int totalOffset, int position);
float left(int totalOffset, int position);
}
}