-
Notifications
You must be signed in to change notification settings - Fork 0
/
SlidingLayer.java
1530 lines (1260 loc) · 50.7 KB
/
SlidingLayer.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
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* SlidingLayer.java
*
* Copyright (C) 2015 6 Wunderkinder GmbH.
*
* @author Jose L Ugia - @Jl_Ugia
* @author Antonio Consuegra - @aconsuegra
* @author Cesar Valiente - @CesarValiente
* @version 1.2.0
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.symphonyrecords.mediacomp.slidinglayer;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.animation.Interpolator;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.Scroller;
import androidx.core.view.ViewCompat;
import com.symphonyrecords.mediacomp.R;
import com.symphonyrecords.mediacomp.design.Views.SRToast;
import com.symphonyrecords.mediacomp.mediaEditor.videoEditor.HgLVideoTrimmer;
import org.jetbrains.annotations.NotNull;
/**
* https://github.com/wunderlist/android-sliding-layer-lib
*/
@SuppressLint("ObsoleteSdkInt")
@SuppressWarnings({"UnusedAssignment", "unused"})
public class SlidingLayer extends FrameLayout {
public static final int LOCK_MODE_UNLOCKED = 7;
public static final int LOCK_MODE_LOCKED = 9;
private int lock_mode = LOCK_MODE_UNLOCKED;
private static final String STATE_KEY = "state";
/**
* Special value for the position of the layer. STICK_TO_RIGHT means that
* the view shall be attached to the right side of the screen, and come from
* there into the viewable area.
*/
public static final int STICK_TO_RIGHT = -1;
/**
* Special value for the position of the layer. STICK_TO_LEFT means that the
* view shall be attached to the left side of the screen, and come from
* there into the viewable area.
*/
public static final int STICK_TO_LEFT = -2;
/**
* Special value for the position of the layer. STICK_TO_TOP means that the view will stay attached to the top
* part of the screen, and come from there into the viewable area.
*/
public static final int STICK_TO_TOP = -3;
/**
* Special value for the position of the layer. STICK_TO_BOTTOM means that the view will stay attached to the
* bottom part of the screen, and come from there into the viewable area.
*/
public static final int STICK_TO_BOTTOM = -4;
private static final int HORIZONTAL = 0;
private static final int VERTICAL = 1;
private static final int HIGH_VELOCITY = 9000;
private static final int MAX_SCROLLING_DURATION = 600; // in ms
private static final int MIN_DISTANCE_FOR_FLING = 10; // in dip
private static final Interpolator sMenuInterpolator = t -> {
t -= 1.0f;
return (float) Math.pow(t, 5) + 1.0f;
};
/**
* Sentinel value for no current active pointer. Used by {@link #mActivePointerId}.
*/
private static final int INVALID_VALUE = -1;
protected int mActivePointerId = INVALID_VALUE;
protected VelocityTracker mVelocityTracker;
protected int mMaximumVelocity;
protected Bundle mState;
private Scroller mScroller;
private int mShadowSize;
private Drawable mShadowDrawable;
private boolean mForceLayout;
/**
* The size of the panel that sticks out when closed
*/
private int mOffsetDistance;
private boolean mDrawingCacheEnabled;
private int mScreenSide;
/**
* If the user taps the layer then we will switch state it if enabled.
*/
private boolean changeStateOnTap = true;
/**
* The size of the panel in preview mode
*/
private int mPreviewOffsetDistance = INVALID_VALUE;
private boolean mEnabled = true;
private boolean mSlidingFromShadowEnabled = true;
private boolean mIsDragging;
private boolean mIsUnableToDrag;
private int mTouchSlop;
private float mLastX = INVALID_VALUE;
private float mLastY = INVALID_VALUE;
private float mInitialX = INVALID_VALUE;
private float mInitialY = INVALID_VALUE;
private float mInitialRawX = INVALID_VALUE;
private float mInitialRawY = INVALID_VALUE;
/**
* Flags to determine the state of the layer
*/
private static final int STATE_CLOSED = 0;
private static final int STATE_PREVIEW = 1;
private static final int STATE_OPENED = 2;
private int mCurrentState;
private boolean mScrolling;
private OnInteractListener mOnInteractListener;
/**
* Optional callback to notify client when scroll position has changed
*/
private OnScrollListener mOnScrollListener;
private int mMinimumVelocity;
private int mFlingDistance;
private LayerTransformer mLayerTransformer;
public SlidingLayer(Context context) {
this(context, null);
}
public SlidingLayer(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
/**
* Constructor for the sliding layer.<br>
* By default this panel will
* <ol>
* <li>{@link #setStickTo(int)} with param {@link #STICK_TO_RIGHT}</li>
* <li>Use no shadow drawable. (i.e. with size of 0)</li>
* <li>Close when the panel is tapped</li>
* <li>Open when the offset is tapped, but will have an offset of 0</li>
* </ol>
*
* @param context a reference to an existing context
* @param attrs attribute set constructed from attributes set in android .xml file
* @param defStyle style res id
*/
public SlidingLayer(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// Style
final TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.SlidingLayer);
// Set the side of the screen
setStickTo(ta.getInt(R.styleable.SlidingLayer_stickTo, STICK_TO_RIGHT));
// Sets the shadow drawable
int shadowRes = ta.getResourceId(R.styleable.SlidingLayer_shadowDrawable, INVALID_VALUE);
if (shadowRes != INVALID_VALUE) {
setShadowDrawable(shadowRes);
}
boolean openLayer = ta.getBoolean(R.styleable.SlidingLayer_openLayer, true);
if (openLayer) {
openLayer(false);
} else {
closeLayer(false);
}
// Sets the shadow size
mShadowSize = (int) ta.getDimension(R.styleable.SlidingLayer_shadowSize, 0);
// Sets the ability to open or close the layer by tapping in any empty space
changeStateOnTap = ta.getBoolean(R.styleable.SlidingLayer_changeStateOnTap, true);
// How much of the view sticks out when closed
mOffsetDistance = ta.getDimensionPixelOffset(R.styleable.SlidingLayer_offsetDistance, 0);
// Sets the size of the preview summary, if any
mPreviewOffsetDistance = ta.getDimensionPixelOffset(R.styleable.SlidingLayer_previewOffsetDistance, INVALID_VALUE);
// If showing offset is greater than preview mode offset dimension, exception is thrown
checkPreviewModeConsistency();
ta.recycle();
init();
}
private void init() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
setLayerType(LAYER_TYPE_HARDWARE, null);
}
setWillNotDraw(false);
setDescendantFocusability(FOCUS_AFTER_DESCENDANTS);
setFocusable(true);
final Context context = getContext();
mScroller = new Scroller(context, sMenuInterpolator);
final ViewConfiguration configuration = ViewConfiguration.get(context);
mTouchSlop = configuration.getScaledPagingTouchSlop();
mMinimumVelocity = configuration.getScaledMinimumFlingVelocity();
mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
final float density = context.getResources().getDisplayMetrics().density;
mFlingDistance = (int) (MIN_DISTANCE_FOR_FLING * density);
}
/**
* Method exposing the state of the panel
*
* @return returns the state of the panel (@link STATE_OPENED, STATE_CLOSED or STATE_PREVIEW). Please note
* that if the panel was opened with smooth animation this method is not guaranteed to return
* its final value until the panel has reached its final position.
*/
private int getCurrentState() {
return mCurrentState;
}
public boolean isOpened() {
return mCurrentState == STATE_OPENED;
}
public boolean isInPreviewMode() {
return mCurrentState == STATE_PREVIEW;
}
public boolean isClosed() {
return mCurrentState == STATE_CLOSED;
}
public void openLayer(final boolean smoothAnimation) {
setLayerState(STATE_OPENED, smoothAnimation);
}
public void openPreview(final boolean smoothAnimation) {
if (mPreviewOffsetDistance == INVALID_VALUE) {
throw new IllegalStateException("A value offset for the preview has to be specified in order to open " +
"the layer in preview mode. Use setPreviewOffsetDistance or set its associated XML property ");
}
setLayerState(STATE_PREVIEW, smoothAnimation);
}
public void closeLayer(final boolean smoothAnimation) {
setLayerState(STATE_CLOSED, smoothAnimation);
}
private void setLayerState(final int state, final boolean smoothAnimation) {
setLayerState(state, smoothAnimation, false);
}
private void setLayerState(final int state, final boolean smoothAnimation, boolean force) {
setLayerState(state, smoothAnimation, force, 0, 0);
}
private void setLayerState(final int state, final boolean smoothAnimation, final boolean force, final int velocityX, final int velocityY) {
if (!force && mCurrentState == state) {
setDrawingCacheEnabled(false);
return;
}
if (mOnInteractListener != null) {
notifyActionStartedForState(state);
}
final int[] pos = getDestScrollPosForState(state);
if (smoothAnimation) {
int velocity = allowedDirection() == HORIZONTAL ? velocityX : velocityY;
smoothScrollTo(pos[0], pos[1], velocity);
} else {
completeScroll();
scrollToAndNotify(pos[0], pos[1]);
}
mCurrentState = state;
}
/**
* Sets the listener to be invoked after a switch change
* {@link OnInteractListener}.
*
* @param listener Listener to set
*/
public void setOnInteractListener(OnInteractListener listener) {
mOnInteractListener = listener;
}
/**
* Sets the listener to be invoked when the layer is being scrolled
* {@link OnScrollListener}.
*
* @param listener Listener to set
*/
public void setOnScrollListener(OnScrollListener listener) {
mOnScrollListener = listener;
}
/**
* Sets the transformer to use when the layer is being scrolled
* {@link LayerTransformer}.
*
* @param layerTransformer Transformer to adopt
*/
public void setLayerTransformer(LayerTransformer layerTransformer) {
mLayerTransformer = layerTransformer;
}
/**
* Sets the shadow of the size which will be included within the view by
* using padding since it's on the left of the view in this case
*
* @param shadowSize Desired size of the shadow
* @see #getShadowSize()
* @see #setShadowDrawable(Drawable)
* @see #setShadowDrawable(int)
*/
public void setShadowSize(final int shadowSize) {
mShadowSize = shadowSize;
invalidate(getLeft(), getTop(), getRight(), getBottom());
}
/**
* Sets the shadow size by the value of a resource.
*
* @param resId The dimension resource id to be set as the shadow size.
*/
public void setShadowSizeRes(int resId) {
setShadowSize((int) getResources().getDimension(resId));
}
/**
* Return the current size of the shadow.
*
* @return The size of the shadow in pixels
*/
public int getShadowSize() {
return mShadowSize;
}
/**
* Sets a drawable that will be used to create the shadow for the layer.
*
* @param d Drawable append as a shadow
*/
public void setShadowDrawable(final Drawable d) {
mShadowDrawable = d;
refreshDrawableState();
setWillNotDraw(false);
invalidate(getLeft(), getTop(), getRight(), getBottom());
}
/**
* Sets a drawable resource that will be used to create the shadow for the
* layer.
*
* @param resId Resource ID of a drawable
*/
public void setShadowDrawable(int resId) {
setShadowDrawable(getContext().getResources().getDrawable(resId));
}
/**
* Sets the offset distance of the panel by using a dimension resource.
*
* @param resId The dimension resource id to be set as the offset.
*/
public void setOffsetDistanceRes(int resId) {
setOffsetDistance((int) getResources().getDimension(resId));
}
/**
* Sets the offset distance of the panel. How much sticks out when off screen.
*
* @param offsetDistance Size of the offset in pixels
* @see #getOffsetDistance()
*/
public void setOffsetDistance(int offsetDistance) {
mOffsetDistance = offsetDistance;
checkPreviewModeConsistency();
invalidate(getLeft(), getTop(), getRight(), getBottom());
}
/**
* @return returns the number of pixels that are visible when the panel is closed
*/
public int getOffsetDistance() {
return mOffsetDistance;
}
/**
* Sets the offset distance of the preview panel by using a dimension resource.
*
* @param resId The dimension resource id to be set as the size of the preview mode.
*/
public void setPreviewOffsetDistanceRes(int resId) {
setPreviewOffsetDistance((int) getResources().getDimension(resId));
}
/**
* Sets the size of the panel when in preview mode.
*
* @param previewOffsetDistance Size of the offset in pixels
* @see #getOffsetDistance()
*/
public void setPreviewOffsetDistance(int previewOffsetDistance) {
mPreviewOffsetDistance = previewOffsetDistance;
checkPreviewModeConsistency();
invalidate(getLeft(), getTop(), getRight(), getBottom());
if (mCurrentState == STATE_PREVIEW) {
smoothScrollToCurrentPosition();
}
}
private void checkPreviewModeConsistency() {
if (isPreviewModeEnabled() && mOffsetDistance > mPreviewOffsetDistance) {
throw new IllegalStateException("The showing offset of the layer can never be greater than the " +
"offset dimension of the preview mode");
}
}
/**
* @return true if the preview mode is enabled
*/
private boolean isPreviewModeEnabled() {
return mPreviewOffsetDistance != INVALID_VALUE;
}
@Override
protected boolean verifyDrawable(@NotNull Drawable who) {
return super.verifyDrawable(who) || who == mShadowDrawable;
}
@Override
protected void drawableStateChanged() {
super.drawableStateChanged();
final Drawable d = mShadowDrawable;
if (d != null && d.isStateful()) {
d.setState(getDrawableState());
}
}
public boolean isSlidingEnabled() {
return mEnabled;
}
public void setSlidingEnabled(boolean _enabled) {
mEnabled = _enabled;
}
public boolean isSlidingFromShadowEnabled() {
return mSlidingFromShadowEnabled;
}
public void setSlidingFromShadowEnabled(boolean _slidingShadow) {
mSlidingFromShadowEnabled = _slidingShadow;
}
@Override
protected Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
SavedState state = new SavedState(superState);
if (mState == null) {
mState = new Bundle();
}
mState.putInt(STATE_KEY, mCurrentState);
state.mState = mState;
return state;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
SavedState savedState = (SavedState) state;
super.onRestoreInstanceState(savedState.getSuperState());
restoreState(savedState.mState);
}
public void restoreState(Parcelable in) {
mState = (Bundle) in;
int state = mState.getInt(STATE_KEY);
setLayerState(state, true);
}
private float getViewX(MotionEvent event) {
return event.getRawX();
}
private float getViewY(MotionEvent event) {
return event.getRawY();
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (lock_mode == LOCK_MODE_LOCKED) {
return false;
} else {
if (!mEnabled) {
return false;
}
final int action = ev.getAction() & MotionEvent.ACTION_MASK;
if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) {
mIsDragging = false;
mIsUnableToDrag = false;
mActivePointerId = INVALID_VALUE;
if (mVelocityTracker != null) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
return false;
}
if (action != MotionEvent.ACTION_DOWN) {
if (mIsDragging) {
return true;
} else if (mIsUnableToDrag) {
return false;
}
}
switch (action) {
case MotionEvent.ACTION_MOVE:
final int activePointerId = mActivePointerId;
if (activePointerId == INVALID_VALUE) {
break;
}
final int pointerIndex = ev.findPointerIndex(activePointerId);
final float x = getViewX(ev);
final float dx = x - mLastX;
final float xDiff = Math.abs(dx);
final float y = getViewY(ev);
final float dy = y - mLastY;
final float yDiff = Math.abs(dy);
if ((dx != 0 || dy != 0) &&
canScroll(this, false, (int) dx, (int) dy, (int) x, (int) y)) {
mLastX = mInitialRawX = x;
mLastY = mInitialRawY = y;
mInitialX = ev.getX(pointerIndex);
mInitialY = ev.getY(pointerIndex);
return false;
}
final boolean validHorizontalDrag = xDiff > mTouchSlop && xDiff > yDiff;
final boolean validVerticalDrag = yDiff > mTouchSlop && yDiff > xDiff;
if (validHorizontalDrag) {
mLastX = x;
} else if (validVerticalDrag) {
mLastY = y;
}
if (validHorizontalDrag || validVerticalDrag) {
mIsDragging = true;
setDrawingCacheEnabled(true);
}
break;
case MotionEvent.ACTION_DOWN:
mLastX = mInitialRawX = getViewX(ev);
mLastY = mInitialRawY = getViewY(ev);
mInitialX = ev.getX(0);
mInitialY = ev.getY(0);
mActivePointerId = ev.getPointerId(0);
if (touchPointIsWithinBounds(ev.getX(), ev.getY())) {
mIsDragging = false;
mIsUnableToDrag = false;
// We don't want to do anything, send the event up
return super.onInterceptTouchEvent(ev);
} else {
completeScroll();
mIsDragging = false;
mIsUnableToDrag = true;
}
break;
case MotionEvent.ACTION_POINTER_UP:
onSecondaryPointerUp(ev);
break;
}
if (!mIsDragging) {
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(ev);
}
return mIsDragging;
}
}
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (lock_mode == LOCK_MODE_LOCKED) {
return false;
} else {
if (ev.getAction() == MotionEvent.ACTION_DOWN && ev.getEdgeFlags() != 0) {
return false;
}
if (!mEnabled || !mIsDragging && !touchPointIsWithinBounds(mInitialX, mInitialY)) {
return false;
}
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(ev);
final int action = ev.getAction();
switch (action & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN: {
completeScroll();
// Remember where the motion event started
mLastX = mInitialRawX = getViewX(ev);
mLastY = mInitialRawY = getViewY(ev);
mInitialX = ev.getX();
mInitialY = ev.getY();
mActivePointerId = ev.getPointerId(0);
break;
}
case MotionEvent.ACTION_MOVE: {
final int pointerIndex = ev.findPointerIndex(mActivePointerId);
if (!touchPointIsWithinBounds(ev.getX(), ev.getY(), false)) return false;
final float x = getViewX(ev);
final float y = getViewY(ev);
final float deltaX = mLastX - x;
final float deltaY = mLastY - y;
mLastX = x;
mLastY = y;
if (!mIsDragging) {
final float xDiff = Math.abs(x - mInitialRawX);
final float yDiff = Math.abs(y - mInitialRawY);
final boolean validHorizontalDrag = xDiff > mTouchSlop && xDiff > yDiff;
final boolean validVerticalDrag = yDiff > mTouchSlop && yDiff > xDiff;
if (validHorizontalDrag || validVerticalDrag) {
mIsDragging = true;
setDrawingCacheEnabled(true);
}
}
if (mIsDragging) {
final float oldScrollX = getScrollX();
final float oldScrollY = getScrollY();
float scrollX = oldScrollX + deltaX;
float scrollY = oldScrollY + deltaY;
// Log.d("Layer", String.format("Layer scrollX[%f],scrollY[%f]", scrollX, scrollY));
final float leftBound, rightBound;
final float bottomBound, topBound;
switch (mScreenSide) {
case STICK_TO_LEFT:
topBound = bottomBound = rightBound = 0;
leftBound = getWidth(); // How far left we can scroll
break;
case STICK_TO_RIGHT:
rightBound = -getWidth();
topBound = bottomBound = leftBound = 0;
break;
case STICK_TO_TOP:
topBound = getHeight();
bottomBound = rightBound = leftBound = 0;
break;
case STICK_TO_BOTTOM:
bottomBound = -getHeight();
topBound = rightBound = leftBound = 0;
break;
default:
topBound = bottomBound = rightBound = leftBound = 0;
break;
}
if (scrollX > leftBound) {
scrollX = leftBound;
} else if (scrollX < rightBound) {
scrollX = rightBound;
}
if (scrollY > topBound) {
scrollY = topBound;
} else if (scrollY < bottomBound) {
scrollY = bottomBound;
}
// Keep the precision
mLastX += scrollX - (int) scrollX;
mLastY += scrollY - (int) scrollY;
scrollToAndNotify((int) scrollX, (int) scrollY);
}
break;
}
case MotionEvent.ACTION_UP: {
if (mIsDragging) {
final VelocityTracker velocityTracker = mVelocityTracker;
velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
final int initialVelocityX = (int) velocityTracker.getXVelocity(mActivePointerId);
final int initialVelocityY = (int) velocityTracker.getYVelocity(mActivePointerId);
final int scrollX = getScrollX();
final int scrollY = getScrollY();
final int pointerIndex = ev.findPointerIndex(mActivePointerId);
final float x = getViewX(ev);
final float y = getViewY(ev);
int nextState = determineNextStateForDrag(scrollX, scrollY, initialVelocityX, initialVelocityY,
(int) mInitialRawX, (int) mInitialRawY, (int) x, (int) y);
setLayerState(nextState, true, true, initialVelocityX, initialVelocityY);
mActivePointerId = INVALID_VALUE;
endDrag();
} else if (changeStateOnTap) {
int nextState = determineNextStateAfterTap();
setLayerState(nextState, true, true);
}
break;
}
case MotionEvent.ACTION_CANCEL:
if (mIsDragging) {
setLayerState(mCurrentState, true, true);
mActivePointerId = INVALID_VALUE;
endDrag();
}
break;
case MotionEvent.ACTION_POINTER_DOWN: {
final int pointerIndex = ev.getActionIndex();
mActivePointerId = ev.getPointerId(pointerIndex);
mLastX = getViewX(ev);
mLastY = getViewY(ev);
break;
}
case MotionEvent.ACTION_POINTER_UP: {
onSecondaryPointerUp(ev);
final int pointerIndex = ev.findPointerIndex(mActivePointerId);
mLastX = getViewX(ev);
mLastY = getViewY(ev);
break;
}
}
return true;
}
}
/**
* Checks if it's allowed to slide from the given position.
*
* @param touchX where the touch event started
* @param touchY where the touch event started.
* @return true if you can drag this view, false otherwise
*/
private boolean touchPointIsWithinBounds(final float touchX, final float touchY) {
return touchPointIsWithinBounds(touchX, touchY, true);
}
private boolean touchPointIsWithinBounds(final float touchX, final float touchY, boolean withinLayer) {
int scroll = 0;
float touch;
if (allowedDirection() == HORIZONTAL) {
if (withinLayer) scroll = getScrollX();
touch = touchX;
} else {
if (withinLayer) scroll = getScrollY();
touch = touchY;
}
switch (mScreenSide) {
case STICK_TO_RIGHT:
case STICK_TO_BOTTOM:
return touch >= -scroll;
case STICK_TO_LEFT:
return touch <= getWidth() - scroll;
case STICK_TO_TOP:
return touch <= getHeight() - scroll;
default:
throw new IllegalStateException("The layer has to be stuck to one of the sides of the screen. " +
"Current value is: " + mScreenSide);
}
}
protected boolean canScroll(View v, boolean checkV, int dx, int dy, int x, int y) {
if (v instanceof ViewGroup) {
final ViewGroup group = (ViewGroup) v;
final int scrollX = v.getScrollX();
final int scrollY = v.getScrollY();
final int count = group.getChildCount();
// Count backwards - let topmost views consume scroll distance first.
for (int i = count - 1; i >= 0; i--) {
// TODO: Add versioned support here for transformed views.
// This will not work for transformed views in Honeycomb+
final View child = group.getChildAt(i);
if (x + scrollX >= child.getLeft()
&& x + scrollX < child.getRight()
&& y + scrollY >= child.getTop()
&& y + scrollY < child.getBottom()
&& canScroll(child, true, dx, dy, x + scrollX - child.getLeft(), y + scrollY - child.getTop())) {
return true;
}
}
}
return checkV && ((allowedDirection() == HORIZONTAL && v.canScrollHorizontally(-dx) || allowedDirection() == VERTICAL && v.canScrollVertically(-dy)));
}
/**
* Based on the position and velocity of the layer we calculate what the next state should be.
*
* @param velocityX velocityX
* @param velocityY velocityY
* @param initialX initialX
* @param initialY initialY
* @param currentX currentX
* @param currentY currentY
* @return the state of the panel (@link STATE_OPENED, STATE_CLOSED or STATE_PREVIEW).
*/
private int determineNextStateForDrag(final int scrollX, final int scrollY, final int velocityX,
final int velocityY, final int initialX, final int initialY,
final int currentX, final int currentY) {
int panelOffset;
int panelSize;
int relativeVelocity;
int absoluteDelta;
if (allowedDirection() == HORIZONTAL) {
panelSize = getWidth();
panelOffset = Math.abs(panelSize - Math.abs(scrollX));
absoluteDelta = Math.abs(currentX - initialX);
relativeVelocity = velocityX * (mScreenSide == STICK_TO_LEFT ? 1 : -1);
} else {
panelSize = getHeight();
panelOffset = Math.abs(panelSize - Math.abs(scrollY));
absoluteDelta = Math.abs(currentY - initialY);
relativeVelocity = velocityY * (mScreenSide == STICK_TO_TOP ? 1 : -1);
}
final int absoluteVelocity = Math.abs(relativeVelocity);
final boolean isOverThreshold = absoluteDelta > mFlingDistance && absoluteVelocity > mMinimumVelocity;
if (isOverThreshold) {
if (relativeVelocity > 0) {
return STATE_OPENED;
} else {
boolean goesToPreview = isPreviewModeEnabled()
&& panelOffset > mPreviewOffsetDistance
&& absoluteVelocity < HIGH_VELOCITY;
if (goesToPreview) {
return STATE_PREVIEW;
} else {
return STATE_CLOSED;
}
}
} else {
int openedThreshold = (panelSize + (isPreviewModeEnabled() ? mPreviewOffsetDistance : 0)) / 2;
if (panelOffset > openedThreshold) {
return STATE_OPENED;
} else if (isPreviewModeEnabled() && panelOffset > mPreviewOffsetDistance / 2) {
return STATE_PREVIEW;
} else {
return STATE_CLOSED;
}
}
}
/**
* Based on the current state of the panel, this method returns the next state after tapping.
*
* @return the state of the panel (@link STATE_OPENED, STATE_CLOSED or STATE_PREVIEW).
*/
private int determineNextStateAfterTap() {
switch (mCurrentState) {
case STATE_CLOSED:
return isPreviewModeEnabled() ? STATE_PREVIEW : STATE_OPENED;
case STATE_PREVIEW:
return STATE_OPENED;
case STATE_OPENED:
return isPreviewModeEnabled() ? STATE_PREVIEW : STATE_CLOSED;
}
return STATE_CLOSED;
}
/**
* Like {@link View#scrollBy}, but scroll smoothly instead of immediately.
*
* @param x the number of pixels to scroll by on the X axis
* @param y the number of pixels to scroll by on the Y axis
*/
void smoothScrollTo(int x, int y) {
smoothScrollTo(x, y, 0);
}
/**
* Like {@link View#scrollBy}, but scroll smoothly instead of immediately.
*
* @param x the number of pixels to scroll by on the X axis
* @param y the number of pixels to scroll by on the Y axis
* @param velocity the velocity associated with a fling, if applicable. (0
* otherwise)