This repository has been archived by the owner on Nov 8, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6.2k
/
ViewGroup.java
9479 lines (8500 loc) · 363 KB
/
ViewGroup.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
/*
* Copyright (C) 2006 The Android Open Source Project
*
* 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 android.view;
import static android.os.Build.VERSION_CODES.JELLY_BEAN_MR1;
import static android.view.WindowInsetsAnimation.Callback.DISPATCH_MODE_CONTINUE_ON_SUBTREE;
import static android.view.WindowInsetsAnimation.Callback.DISPATCH_MODE_STOP;
import android.animation.LayoutTransition;
import android.annotation.CallSuper;
import android.annotation.IdRes;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.TestApi;
import android.annotation.UiThread;
import android.compat.annotation.UnsupportedAppUsage;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Insets;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Region;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.util.IntArray;
import android.util.Log;
import android.util.Pools;
import android.util.Pools.SynchronizedPool;
import android.util.SparseArray;
import android.util.SparseBooleanArray;
import android.view.WindowInsetsAnimation.Bounds;
import android.view.WindowInsetsAnimation.Callback.DispatchMode;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityManager;
import android.view.accessibility.AccessibilityNodeInfo;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
import android.view.animation.Transformation;
import android.view.autofill.AutofillId;
import android.view.autofill.AutofillManager;
import android.view.autofill.Helper;
import android.view.inspector.InspectableProperty;
import android.view.inspector.InspectableProperty.EnumEntry;
import android.view.translation.TranslationCapability;
import android.view.translation.TranslationSpec.DataFormat;
import android.view.translation.ViewTranslationRequest;
import android.webkit.WebView;
import android.window.OnBackInvokedDispatcher;
import com.android.internal.R;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Predicate;
/**
* <p>
* A <code>ViewGroup</code> is a special view that can contain other views
* (called children.) The view group is the base class for layouts and views
* containers. This class also defines the
* {@link android.view.ViewGroup.LayoutParams} class which serves as the base
* class for layouts parameters.
* </p>
*
* <p>
* Also see {@link LayoutParams} for layout attributes.
* </p>
*
* <div class="special reference">
* <h3>Developer Guides</h3>
* <p>For more information about creating user interface layouts, read the
* <a href="{@docRoot}guide/topics/ui/declaring-layout.html">XML Layouts</a> developer
* guide.</p></div>
*
* <p>Here is a complete implementation of a custom ViewGroup that implements
* a simple {@link android.widget.FrameLayout} along with the ability to stack
* children in left and right gutters.</p>
*
* {@sample development/samples/ApiDemos/src/com/example/android/apis/view/CustomLayout.java
* Complete}
*
* <p>If you are implementing XML layout attributes as shown in the example, this is the
* corresponding definition for them that would go in <code>res/values/attrs.xml</code>:</p>
*
* {@sample development/samples/ApiDemos/res/values/attrs.xml CustomLayout}
*
* <p>Finally the layout manager can be used in an XML layout like so:</p>
*
* {@sample development/samples/ApiDemos/res/layout/custom_layout.xml Complete}
*
* @attr ref android.R.styleable#ViewGroup_clipChildren
* @attr ref android.R.styleable#ViewGroup_clipToPadding
* @attr ref android.R.styleable#ViewGroup_layoutAnimation
* @attr ref android.R.styleable#ViewGroup_animationCache
* @attr ref android.R.styleable#ViewGroup_persistentDrawingCache
* @attr ref android.R.styleable#ViewGroup_alwaysDrawnWithCache
* @attr ref android.R.styleable#ViewGroup_addStatesFromChildren
* @attr ref android.R.styleable#ViewGroup_descendantFocusability
* @attr ref android.R.styleable#ViewGroup_animateLayoutChanges
* @attr ref android.R.styleable#ViewGroup_splitMotionEvents
* @attr ref android.R.styleable#ViewGroup_layoutMode
*/
@UiThread
public abstract class ViewGroup extends View implements ViewParent, ViewManager {
private static final String TAG = "ViewGroup";
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
private static final boolean DBG = false;
/**
* Views which have been hidden or removed which need to be animated on
* their way out.
* This field should be made private, so it is hidden from the SDK.
* {@hide}
*/
@UnsupportedAppUsage
protected ArrayList<View> mDisappearingChildren;
/**
* Listener used to propagate events indicating when children are added
* and/or removed from a view group.
* This field should be made private, so it is hidden from the SDK.
* {@hide}
*/
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 123768704)
protected OnHierarchyChangeListener mOnHierarchyChangeListener;
// The view contained within this ViewGroup that has or contains focus.
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
private View mFocused;
// The view contained within this ViewGroup (excluding nested keyboard navigation clusters)
// that is or contains a default-focus view.
private View mDefaultFocus;
// The last child of this ViewGroup which held focus within the current cluster
View mFocusedInCluster;
/**
* A Transformation used when drawing children, to
* apply on the child being drawn.
*/
private Transformation mChildTransformation;
/**
* Used to track the current invalidation region.
*/
RectF mInvalidateRegion;
/**
* A Transformation used to calculate a correct
* invalidation area when the application is autoscaled.
*/
Transformation mInvalidationTransformation;
// Current frontmost child that can accept drag and lies under the drag location.
// Used only to generate ENTER/EXIT events for pre-Nougat aps.
private View mCurrentDragChild;
// Metadata about the ongoing drag
private DragEvent mCurrentDragStartEvent;
private boolean mIsInterestedInDrag;
private HashSet<View> mChildrenInterestedInDrag;
// Used during drag dispatch
private PointF mLocalPoint;
// Lazily-created holder for point computations.
private float[] mTempPosition;
// Lazily-created holder for point computations.
private Point mTempPoint;
// Lazily created Rect for dispatch to children
private Rect mTempRect;
// Lazily created int[2] for dispatch to children
private int[] mTempLocation;
// Layout animation
private LayoutAnimationController mLayoutAnimationController;
private Animation.AnimationListener mAnimationListener;
// First touch target in the linked list of touch targets.
@UnsupportedAppUsage
private TouchTarget mFirstTouchTarget;
// For debugging only. You can see these in hierarchyviewer.
@SuppressWarnings({"FieldCanBeLocal", "UnusedDeclaration"})
@ViewDebug.ExportedProperty(category = "events")
private long mLastTouchDownTime;
@ViewDebug.ExportedProperty(category = "events")
private int mLastTouchDownIndex = -1;
@SuppressWarnings({"FieldCanBeLocal", "UnusedDeclaration"})
@ViewDebug.ExportedProperty(category = "events")
private float mLastTouchDownX;
@SuppressWarnings({"FieldCanBeLocal", "UnusedDeclaration"})
@ViewDebug.ExportedProperty(category = "events")
private float mLastTouchDownY;
// First hover target in the linked list of hover targets.
// The hover targets are children which have received ACTION_HOVER_ENTER.
// They might not have actually handled the hover event, but we will
// continue sending hover events to them as long as the pointer remains over
// their bounds and the view group does not intercept hover.
private HoverTarget mFirstHoverTarget;
// True if the view group itself received a hover event.
// It might not have actually handled the hover event.
private boolean mHoveredSelf;
// The child capable of showing a tooltip and currently under the pointer.
private View mTooltipHoverTarget;
// True if the view group is capable of showing a tooltip and the pointer is directly
// over the view group but not one of its child views.
private boolean mTooltipHoveredSelf;
/**
* Internal flags.
*
* This field should be made private, so it is hidden from the SDK.
* {@hide}
*/
@ViewDebug.ExportedProperty(flagMapping = {
@ViewDebug.FlagToString(mask = FLAG_CLIP_CHILDREN, equals = FLAG_CLIP_CHILDREN,
name = "CLIP_CHILDREN"),
@ViewDebug.FlagToString(mask = FLAG_CLIP_TO_PADDING, equals = FLAG_CLIP_TO_PADDING,
name = "CLIP_TO_PADDING"),
@ViewDebug.FlagToString(mask = FLAG_PADDING_NOT_NULL, equals = FLAG_PADDING_NOT_NULL,
name = "PADDING_NOT_NULL")
}, formatToHexString = true)
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 123769411)
protected int mGroupFlags;
/**
* Either {@link #LAYOUT_MODE_CLIP_BOUNDS} or {@link #LAYOUT_MODE_OPTICAL_BOUNDS}.
*/
private int mLayoutMode = LAYOUT_MODE_UNDEFINED;
/**
* NOTE: If you change the flags below make sure to reflect the changes
* the DisplayList class
*/
// When set, ViewGroup invalidates only the child's rectangle
// Set by default
static final int FLAG_CLIP_CHILDREN = 0x1;
// When set, ViewGroup excludes the padding area from the invalidate rectangle
// Set by default
private static final int FLAG_CLIP_TO_PADDING = 0x2;
// When set, dispatchDraw() will invoke invalidate(); this is set by drawChild() when
// a child needs to be invalidated and FLAG_OPTIMIZE_INVALIDATE is set
static final int FLAG_INVALIDATE_REQUIRED = 0x4;
// When set, dispatchDraw() will run the layout animation and unset the flag
private static final int FLAG_RUN_ANIMATION = 0x8;
// When set, there is either no layout animation on the ViewGroup or the layout
// animation is over
// Set by default
static final int FLAG_ANIMATION_DONE = 0x10;
// If set, this ViewGroup has padding; if unset there is no padding and we don't need
// to clip it, even if FLAG_CLIP_TO_PADDING is set
private static final int FLAG_PADDING_NOT_NULL = 0x20;
/** @deprecated - functionality removed */
@Deprecated
private static final int FLAG_ANIMATION_CACHE = 0x40;
// When set, this ViewGroup converts calls to invalidate(Rect) to invalidate() during a
// layout animation; this avoid clobbering the hierarchy
// Automatically set when the layout animation starts, depending on the animation's
// characteristics
static final int FLAG_OPTIMIZE_INVALIDATE = 0x80;
// When set, the next call to drawChild() will clear mChildTransformation's matrix
static final int FLAG_CLEAR_TRANSFORMATION = 0x100;
// When set, this ViewGroup invokes mAnimationListener.onAnimationEnd() and removes
// the children's Bitmap caches if necessary
// This flag is set when the layout animation is over (after FLAG_ANIMATION_DONE is set)
private static final int FLAG_NOTIFY_ANIMATION_LISTENER = 0x200;
/**
* When set, the drawing method will call {@link #getChildDrawingOrder(int, int)}
* to get the index of the child to draw for that iteration.
*
* @hide
*/
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 123769377)
protected static final int FLAG_USE_CHILD_DRAWING_ORDER = 0x400;
/**
* When set, this ViewGroup supports static transformations on children; this causes
* {@link #getChildStaticTransformation(View, android.view.animation.Transformation)} to be
* invoked when a child is drawn.
*
* Any subclass overriding
* {@link #getChildStaticTransformation(View, android.view.animation.Transformation)} should
* set this flags in {@link #mGroupFlags}.
*
* {@hide}
*/
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 123769647)
protected static final int FLAG_SUPPORT_STATIC_TRANSFORMATIONS = 0x800;
// UNUSED FLAG VALUE: 0x1000;
/**
* When set, this ViewGroup's drawable states also include those
* of its children.
*/
private static final int FLAG_ADD_STATES_FROM_CHILDREN = 0x2000;
/** @deprecated functionality removed */
@Deprecated
private static final int FLAG_ALWAYS_DRAWN_WITH_CACHE = 0x4000;
/** @deprecated functionality removed */
@Deprecated
private static final int FLAG_CHILDREN_DRAWN_WITH_CACHE = 0x8000;
/**
* When set, this group will go through its list of children to notify them of
* any drawable state change.
*/
private static final int FLAG_NOTIFY_CHILDREN_ON_DRAWABLE_STATE_CHANGE = 0x10000;
private static final int FLAG_MASK_FOCUSABILITY = 0x60000;
/**
* This view will get focus before any of its descendants.
*/
public static final int FOCUS_BEFORE_DESCENDANTS = 0x20000;
/**
* This view will get focus only if none of its descendants want it.
*/
public static final int FOCUS_AFTER_DESCENDANTS = 0x40000;
/**
* This view will block any of its descendants from getting focus, even
* if they are focusable.
*/
public static final int FOCUS_BLOCK_DESCENDANTS = 0x60000;
/**
* Used to map between enum in attrubutes and flag values.
*/
private static final int[] DESCENDANT_FOCUSABILITY_FLAGS =
{FOCUS_BEFORE_DESCENDANTS, FOCUS_AFTER_DESCENDANTS,
FOCUS_BLOCK_DESCENDANTS};
/**
* When set, this ViewGroup should not intercept touch events.
* {@hide}
*/
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 123983692)
protected static final int FLAG_DISALLOW_INTERCEPT = 0x80000;
/**
* When set, this ViewGroup will split MotionEvents to multiple child Views when appropriate.
*/
private static final int FLAG_SPLIT_MOTION_EVENTS = 0x200000;
/**
* When set, this ViewGroup will not dispatch onAttachedToWindow calls
* to children when adding new views. This is used to prevent multiple
* onAttached calls when a ViewGroup adds children in its own onAttached method.
*/
private static final int FLAG_PREVENT_DISPATCH_ATTACHED_TO_WINDOW = 0x400000;
/**
* When true, indicates that a layoutMode has been explicitly set, either with
* an explicit call to {@link #setLayoutMode(int)} in code or from an XML resource.
* This distinguishes the situation in which a layout mode was inherited from
* one of the ViewGroup's ancestors and cached locally.
*/
private static final int FLAG_LAYOUT_MODE_WAS_EXPLICITLY_SET = 0x800000;
static final int FLAG_IS_TRANSITION_GROUP = 0x1000000;
static final int FLAG_IS_TRANSITION_GROUP_SET = 0x2000000;
/**
* When set, focus will not be permitted to enter this group if a touchscreen is present.
*/
static final int FLAG_TOUCHSCREEN_BLOCKS_FOCUS = 0x4000000;
/**
* When true, indicates that a call to startActionModeForChild was made with the type parameter
* and should not be ignored. This helps in backwards compatibility with the existing method
* without a type.
*
* @see #startActionModeForChild(View, android.view.ActionMode.Callback)
* @see #startActionModeForChild(View, android.view.ActionMode.Callback, int)
*/
private static final int FLAG_START_ACTION_MODE_FOR_CHILD_IS_TYPED = 0x8000000;
/**
* When true, indicates that a call to startActionModeForChild was made without the type
* parameter. This helps in backwards compatibility with the existing method
* without a type.
*
* @see #startActionModeForChild(View, android.view.ActionMode.Callback)
* @see #startActionModeForChild(View, android.view.ActionMode.Callback, int)
*/
private static final int FLAG_START_ACTION_MODE_FOR_CHILD_IS_NOT_TYPED = 0x10000000;
/**
* When set, indicates that a call to showContextMenuForChild was made with explicit
* coordinates within the initiating child view.
*/
private static final int FLAG_SHOW_CONTEXT_MENU_WITH_COORDS = 0x20000000;
/**
* Indicates which types of drawing caches are to be kept in memory.
* This field should be made private, so it is hidden from the SDK.
* {@hide}
*/
@UnsupportedAppUsage
protected int mPersistentDrawingCache;
/**
* Used to indicate that no drawing cache should be kept in memory.
*
* @deprecated The view drawing cache was largely made obsolete with the introduction of
* hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
* layers are largely unnecessary and can easily result in a net loss in performance due to the
* cost of creating and updating the layer. In the rare cases where caching layers are useful,
* such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
* rendering. For software-rendered snapshots of a small part of the View hierarchy or
* individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
* {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
* software-rendered usages are discouraged and have compatibility issues with hardware-only
* rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
* bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
* reports or unit testing the {@link PixelCopy} API is recommended.
*/
@Deprecated
public static final int PERSISTENT_NO_CACHE = 0x0;
/**
* Used to indicate that the animation drawing cache should be kept in memory.
*
* @deprecated The view drawing cache was largely made obsolete with the introduction of
* hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
* layers are largely unnecessary and can easily result in a net loss in performance due to the
* cost of creating and updating the layer. In the rare cases where caching layers are useful,
* such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
* rendering. For software-rendered snapshots of a small part of the View hierarchy or
* individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
* {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
* software-rendered usages are discouraged and have compatibility issues with hardware-only
* rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
* bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
* reports or unit testing the {@link PixelCopy} API is recommended.
*/
@Deprecated
public static final int PERSISTENT_ANIMATION_CACHE = 0x1;
/**
* Used to indicate that the scrolling drawing cache should be kept in memory.
*
* @deprecated The view drawing cache was largely made obsolete with the introduction of
* hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
* layers are largely unnecessary and can easily result in a net loss in performance due to the
* cost of creating and updating the layer. In the rare cases where caching layers are useful,
* such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
* rendering. For software-rendered snapshots of a small part of the View hierarchy or
* individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
* {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
* software-rendered usages are discouraged and have compatibility issues with hardware-only
* rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
* bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
* reports or unit testing the {@link PixelCopy} API is recommended.
*/
@Deprecated
public static final int PERSISTENT_SCROLLING_CACHE = 0x2;
/**
* Used to indicate that all drawing caches should be kept in memory.
*
* @deprecated The view drawing cache was largely made obsolete with the introduction of
* hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
* layers are largely unnecessary and can easily result in a net loss in performance due to the
* cost of creating and updating the layer. In the rare cases where caching layers are useful,
* such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
* rendering. For software-rendered snapshots of a small part of the View hierarchy or
* individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
* {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
* software-rendered usages are discouraged and have compatibility issues with hardware-only
* rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
* bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
* reports or unit testing the {@link PixelCopy} API is recommended.
*/
@Deprecated
public static final int PERSISTENT_ALL_CACHES = 0x3;
// Layout Modes
private static final int LAYOUT_MODE_UNDEFINED = -1;
/**
* This constant is a {@link #setLayoutMode(int) layoutMode}.
* Clip bounds are the raw values of {@link #getLeft() left}, {@link #getTop() top},
* {@link #getRight() right} and {@link #getBottom() bottom}.
*/
public static final int LAYOUT_MODE_CLIP_BOUNDS = 0;
/**
* This constant is a {@link #setLayoutMode(int) layoutMode}.
* Optical bounds describe where a widget appears to be. They sit inside the clip
* bounds which need to cover a larger area to allow other effects,
* such as shadows and glows, to be drawn.
*/
public static final int LAYOUT_MODE_OPTICAL_BOUNDS = 1;
/** @hide */
public static int LAYOUT_MODE_DEFAULT = LAYOUT_MODE_CLIP_BOUNDS;
/**
* We clip to padding when FLAG_CLIP_TO_PADDING and FLAG_PADDING_NOT_NULL
* are set at the same time.
*/
protected static final int CLIP_TO_PADDING_MASK = FLAG_CLIP_TO_PADDING | FLAG_PADDING_NOT_NULL;
// Index of the child's left position in the mLocation array
private static final int CHILD_LEFT_INDEX = 0;
// Index of the child's top position in the mLocation array
private static final int CHILD_TOP_INDEX = 1;
// Child views of this ViewGroup
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
private View[] mChildren;
// Number of valid children in the mChildren array, the rest should be null or not
// considered as children
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
private int mChildrenCount;
// Whether layout calls are currently being suppressed, controlled by calls to
// suppressLayout()
boolean mSuppressLayout = false;
// Whether any layout calls have actually been suppressed while mSuppressLayout
// has been true. This tracks whether we need to issue a requestLayout() when
// layout is later re-enabled.
private boolean mLayoutCalledWhileSuppressed = false;
private static final int ARRAY_INITIAL_CAPACITY = 12;
private static final int ARRAY_CAPACITY_INCREMENT = 12;
private static float[] sDebugLines;
// Used to draw cached views
Paint mCachePaint;
// Used to animate add/remove changes in layout
private LayoutTransition mTransition;
// The set of views that are currently being transitioned. This list is used to track views
// being removed that should not actually be removed from the parent yet because they are
// being animated.
private ArrayList<View> mTransitioningViews;
// List of children changing visibility. This is used to potentially keep rendering
// views during a transition when they otherwise would have become gone/invisible
private ArrayList<View> mVisibilityChangingChildren;
// Temporary holder of presorted children, only used for
// input/software draw dispatch for correctly Z ordering.
private ArrayList<View> mPreSortedChildren;
// Indicates how many of this container's child subtrees contain transient state
@ViewDebug.ExportedProperty(category = "layout")
private int mChildCountWithTransientState = 0;
/**
* Currently registered axes for nested scrolling. Flag set consisting of
* {@link #SCROLL_AXIS_HORIZONTAL} {@link #SCROLL_AXIS_VERTICAL} or {@link #SCROLL_AXIS_NONE}
* for null.
*/
private int mNestedScrollAxes;
// Used to manage the list of transient views, added by addTransientView()
private IntArray mTransientIndices = null;
private List<View> mTransientViews = null;
/**
* Keeps track of how many child views have UnhandledKeyEventListeners. This should only be
* updated on the UI thread so shouldn't require explicit synchronization.
*/
int mChildUnhandledKeyListeners = 0;
/**
* Current dispatch mode of animation events
*
* @see WindowInsetsAnimation.Callback#getDispatchMode()
*/
private @DispatchMode int mInsetsAnimationDispatchMode = DISPATCH_MODE_CONTINUE_ON_SUBTREE;
/**
* Empty ActionMode used as a sentinel in recursive entries to startActionModeForChild.
*
* @see #startActionModeForChild(View, android.view.ActionMode.Callback)
* @see #startActionModeForChild(View, android.view.ActionMode.Callback, int)
*/
private static final ActionMode SENTINEL_ACTION_MODE = new ActionMode() {
@Override
public void setTitle(CharSequence title) {}
@Override
public void setTitle(int resId) {}
@Override
public void setSubtitle(CharSequence subtitle) {}
@Override
public void setSubtitle(int resId) {}
@Override
public void setCustomView(View view) {}
@Override
public void invalidate() {}
@Override
public void finish() {}
@Override
public Menu getMenu() {
return null;
}
@Override
public CharSequence getTitle() {
return null;
}
@Override
public CharSequence getSubtitle() {
return null;
}
@Override
public View getCustomView() {
return null;
}
@Override
public MenuInflater getMenuInflater() {
return null;
}
};
public ViewGroup(Context context) {
this(context, null);
}
public ViewGroup(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public ViewGroup(Context context, AttributeSet attrs, int defStyleAttr) {
this(context, attrs, defStyleAttr, 0);
}
public ViewGroup(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
initViewGroup();
initFromAttributes(context, attrs, defStyleAttr, defStyleRes);
}
private void initViewGroup() {
// ViewGroup doesn't draw by default
if (!isShowingLayoutBounds()) {
setFlags(WILL_NOT_DRAW, DRAW_MASK);
}
mGroupFlags |= FLAG_CLIP_CHILDREN;
mGroupFlags |= FLAG_CLIP_TO_PADDING;
mGroupFlags |= FLAG_ANIMATION_DONE;
mGroupFlags |= FLAG_ANIMATION_CACHE;
mGroupFlags |= FLAG_ALWAYS_DRAWN_WITH_CACHE;
if (mContext.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.HONEYCOMB) {
mGroupFlags |= FLAG_SPLIT_MOTION_EVENTS;
}
setDescendantFocusability(FOCUS_BEFORE_DESCENDANTS);
mChildren = new View[ARRAY_INITIAL_CAPACITY];
mChildrenCount = 0;
mPersistentDrawingCache = PERSISTENT_SCROLLING_CACHE;
}
private void initFromAttributes(
Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ViewGroup,
defStyleAttr, defStyleRes);
saveAttributeDataForStyleable(context, R.styleable.ViewGroup, attrs, a, defStyleAttr,
defStyleRes);
final int N = a.getIndexCount();
for (int i = 0; i < N; i++) {
int attr = a.getIndex(i);
switch (attr) {
case R.styleable.ViewGroup_clipChildren:
setClipChildren(a.getBoolean(attr, true));
break;
case R.styleable.ViewGroup_clipToPadding:
setClipToPadding(a.getBoolean(attr, true));
break;
case R.styleable.ViewGroup_animationCache:
setAnimationCacheEnabled(a.getBoolean(attr, true));
break;
case R.styleable.ViewGroup_persistentDrawingCache:
setPersistentDrawingCache(a.getInt(attr, PERSISTENT_SCROLLING_CACHE));
break;
case R.styleable.ViewGroup_addStatesFromChildren:
setAddStatesFromChildren(a.getBoolean(attr, false));
break;
case R.styleable.ViewGroup_alwaysDrawnWithCache:
setAlwaysDrawnWithCacheEnabled(a.getBoolean(attr, true));
break;
case R.styleable.ViewGroup_layoutAnimation:
int id = a.getResourceId(attr, -1);
if (id > 0) {
setLayoutAnimation(AnimationUtils.loadLayoutAnimation(mContext, id));
}
break;
case R.styleable.ViewGroup_descendantFocusability:
setDescendantFocusability(DESCENDANT_FOCUSABILITY_FLAGS[a.getInt(attr, 0)]);
break;
case R.styleable.ViewGroup_splitMotionEvents:
setMotionEventSplittingEnabled(a.getBoolean(attr, false));
break;
case R.styleable.ViewGroup_animateLayoutChanges:
boolean animateLayoutChanges = a.getBoolean(attr, false);
if (animateLayoutChanges) {
setLayoutTransition(new LayoutTransition());
}
break;
case R.styleable.ViewGroup_layoutMode:
setLayoutMode(a.getInt(attr, LAYOUT_MODE_UNDEFINED));
break;
case R.styleable.ViewGroup_transitionGroup:
setTransitionGroup(a.getBoolean(attr, false));
break;
case R.styleable.ViewGroup_touchscreenBlocksFocus:
setTouchscreenBlocksFocus(a.getBoolean(attr, false));
break;
}
}
a.recycle();
}
/**
* Gets the descendant focusability of this view group. The descendant
* focusability defines the relationship between this view group and its
* descendants when looking for a view to take focus in
* {@link #requestFocus(int, android.graphics.Rect)}.
*
* @return one of {@link #FOCUS_BEFORE_DESCENDANTS}, {@link #FOCUS_AFTER_DESCENDANTS},
* {@link #FOCUS_BLOCK_DESCENDANTS}.
*/
@ViewDebug.ExportedProperty(category = "focus", mapping = {
@ViewDebug.IntToString(from = FOCUS_BEFORE_DESCENDANTS, to = "FOCUS_BEFORE_DESCENDANTS"),
@ViewDebug.IntToString(from = FOCUS_AFTER_DESCENDANTS, to = "FOCUS_AFTER_DESCENDANTS"),
@ViewDebug.IntToString(from = FOCUS_BLOCK_DESCENDANTS, to = "FOCUS_BLOCK_DESCENDANTS")
})
@InspectableProperty(enumMapping = {
@EnumEntry(value = FOCUS_BEFORE_DESCENDANTS, name = "beforeDescendants"),
@EnumEntry(value = FOCUS_AFTER_DESCENDANTS, name = "afterDescendants"),
@EnumEntry(value = FOCUS_BLOCK_DESCENDANTS, name = "blocksDescendants")
})
public int getDescendantFocusability() {
return mGroupFlags & FLAG_MASK_FOCUSABILITY;
}
/**
* Set the descendant focusability of this view group. This defines the relationship
* between this view group and its descendants when looking for a view to
* take focus in {@link #requestFocus(int, android.graphics.Rect)}.
*
* @param focusability one of {@link #FOCUS_BEFORE_DESCENDANTS}, {@link #FOCUS_AFTER_DESCENDANTS},
* {@link #FOCUS_BLOCK_DESCENDANTS}.
*/
public void setDescendantFocusability(int focusability) {
switch (focusability) {
case FOCUS_BEFORE_DESCENDANTS:
case FOCUS_AFTER_DESCENDANTS:
case FOCUS_BLOCK_DESCENDANTS:
break;
default:
throw new IllegalArgumentException("must be one of FOCUS_BEFORE_DESCENDANTS, "
+ "FOCUS_AFTER_DESCENDANTS, FOCUS_BLOCK_DESCENDANTS");
}
mGroupFlags &= ~FLAG_MASK_FOCUSABILITY;
mGroupFlags |= (focusability & FLAG_MASK_FOCUSABILITY);
}
@Override
void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
if (mFocused != null) {
mFocused.unFocus(this);
mFocused = null;
mFocusedInCluster = null;
}
super.handleFocusGainInternal(direction, previouslyFocusedRect);
}
@Override
public void requestChildFocus(View child, View focused) {
if (DBG) {
System.out.println(this + " requestChildFocus()");
}
if (getDescendantFocusability() == FOCUS_BLOCK_DESCENDANTS) {
return;
}
// Unfocus us, if necessary
super.unFocus(focused);
// We had a previous notion of who had focus. Clear it.
if (mFocused != child) {
if (mFocused != null) {
mFocused.unFocus(focused);
}
mFocused = child;
}
if (mParent != null) {
mParent.requestChildFocus(this, focused);
}
}
void setDefaultFocus(View child) {
// Stop at any higher view which is explicitly focused-by-default
if (mDefaultFocus != null && mDefaultFocus.isFocusedByDefault()) {
return;
}
mDefaultFocus = child;
if (mParent instanceof ViewGroup) {
((ViewGroup) mParent).setDefaultFocus(this);
}
}
/**
* Clears the default-focus chain from {@param child} up to the first parent which has another
* default-focusable branch below it or until there is no default-focus chain.
*
* @param child
*/
void clearDefaultFocus(View child) {
// Stop at any higher view which is explicitly focused-by-default
if (mDefaultFocus != child && mDefaultFocus != null
&& mDefaultFocus.isFocusedByDefault()) {
return;
}
mDefaultFocus = null;
// Search child siblings for default focusables.
for (int i = 0; i < mChildrenCount; ++i) {
View sibling = mChildren[i];
if (sibling.isFocusedByDefault()) {
mDefaultFocus = sibling;
return;
} else if (mDefaultFocus == null && sibling.hasDefaultFocus()) {
mDefaultFocus = sibling;
}
}
if (mParent instanceof ViewGroup) {
((ViewGroup) mParent).clearDefaultFocus(this);
}
}
@Override
boolean hasDefaultFocus() {
return mDefaultFocus != null || super.hasDefaultFocus();
}
/**
* Removes {@code child} (and associated focusedInCluster chain) from the cluster containing
* it.
* <br>
* This is intended to be run on {@code child}'s immediate parent. This is necessary because
* the chain is sometimes cleared after {@code child} has been detached.
*/
void clearFocusedInCluster(View child) {
if (mFocusedInCluster != child) {
return;
}
clearFocusedInCluster();
}
/**
* Removes the focusedInCluster chain from this up to the cluster containing it.
*/
void clearFocusedInCluster() {
View top = findKeyboardNavigationCluster();
ViewParent parent = this;
do {
((ViewGroup) parent).mFocusedInCluster = null;
if (parent == top) {
break;
}
parent = parent.getParent();
} while (parent instanceof ViewGroup);
}
@Override
public void focusableViewAvailable(View v) {
if (mParent != null
// shortcut: don't report a new focusable view if we block our descendants from
// getting focus or if we're not visible
&& (getDescendantFocusability() != FOCUS_BLOCK_DESCENDANTS)
&& ((mViewFlags & VISIBILITY_MASK) == VISIBLE)
&& (isFocusableInTouchMode() || !shouldBlockFocusForTouchscreen())
// shortcut: don't report a new focusable view if we already are focused
// (and we don't prefer our descendants)
//
// note: knowing that mFocused is non-null is not a good enough reason
// to break the traversal since in that case we'd actually have to find
// the focused view and make sure it wasn't FOCUS_AFTER_DESCENDANTS and
// an ancestor of v; this will get checked for at ViewAncestor
&& !(isFocused() && getDescendantFocusability() != FOCUS_AFTER_DESCENDANTS)) {
mParent.focusableViewAvailable(v);
}
}
@Override
public boolean showContextMenuForChild(View originalView) {
if (isShowingContextMenuWithCoords()) {
// We're being called for compatibility. Return false and let the version
// with coordinates recurse up.
return false;
}
return mParent != null && mParent.showContextMenuForChild(originalView);
}
/**
* @hide used internally for compatibility with existing app code only
*/
public final boolean isShowingContextMenuWithCoords() {
return (mGroupFlags & FLAG_SHOW_CONTEXT_MENU_WITH_COORDS) != 0;
}
@Override
public boolean showContextMenuForChild(View originalView, float x, float y) {
try {
mGroupFlags |= FLAG_SHOW_CONTEXT_MENU_WITH_COORDS;
if (showContextMenuForChild(originalView)) {
return true;
}
} finally {
mGroupFlags &= ~FLAG_SHOW_CONTEXT_MENU_WITH_COORDS;
}