Debian Codegraph @

core/java/android/view/View.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package android.view;
18
19 import static android.content.res.Resources.ID_NULL;
20 import static android.view.ContentInfo.SOURCE_DRAG_AND_DROP;
21 import static android.view.accessibility.AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED;
22 import static android.view.displayhash.DisplayHashResultCallback.DISPLAY_HASH_ERROR_INVALID_BOUNDS;
23 import static android.view.displayhash.DisplayHashResultCallback.DISPLAY_HASH_ERROR_MISSING_WINDOW;
24 import static android.view.displayhash.DisplayHashResultCallback.DISPLAY_HASH_ERROR_NOT_VISIBLE_ON_SCREEN;
25 import static android.view.displayhash.DisplayHashResultCallback.DISPLAY_HASH_ERROR_UNKNOWN;
26 import static android.view.displayhash.DisplayHashResultCallback.EXTRA_DISPLAY_HASH;
27 import static android.view.displayhash.DisplayHashResultCallback.EXTRA_DISPLAY_HASH_ERROR_CODE;
28
29 import static com.android.internal.util.FrameworkStatsLog.TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__DEEP_PRESS;
30 import static com.android.internal.util.FrameworkStatsLog.TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__LONG_PRESS;
31 import static com.android.internal.util.FrameworkStatsLog.TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__SINGLE_TAP;
32 import static com.android.internal.util.FrameworkStatsLog.TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__UNKNOWN_CLASSIFICATION;
33
34 import static java.lang.Math.max;
35
36 import android.animation.AnimatorInflater;
37 import android.animation.StateListAnimator;
38 import android.annotation.AttrRes;
39 import android.annotation.CallSuper;
40 import android.annotation.ColorInt;
41 import android.annotation.DrawableRes;
42 import android.annotation.FloatRange;
43 import android.annotation.IdRes;
44 import android.annotation.IntDef;
45 import android.annotation.IntRange;
46 import android.annotation.LayoutRes;
47 import android.annotation.NonNull;
48 import android.annotation.Nullable;
49 import android.annotation.RequiresPermission;
50 import android.annotation.Size;
51 import android.annotation.StyleRes;
52 import android.annotation.SuppressLint;
53 import android.annotation.SystemApi;
54 import android.annotation.TestApi;
55 import android.annotation.UiContext;
56 import android.annotation.UiThread;
57 import android.compat.annotation.UnsupportedAppUsage;
58 import android.content.AutofillOptions;
59 import android.content.ClipData;
60 import android.content.ClipDescription;
61 import android.content.Context;
62 import android.content.ContextWrapper;
63 import android.content.Intent;
64 import android.content.res.ColorStateList;
65 import android.content.res.Configuration;
66 import android.content.res.Resources;
67 import android.content.res.TypedArray;
68 import android.graphics.Bitmap;
69 import android.graphics.BlendMode;
70 import android.graphics.Canvas;
71 import android.graphics.Color;
72 import android.graphics.Insets;
73 import android.graphics.Interpolator;
74 import android.graphics.LinearGradient;
75 import android.graphics.Matrix;
76 import android.graphics.Outline;
77 import android.graphics.Paint;
78 import android.graphics.PixelFormat;
79 import android.graphics.Point;
80 import android.graphics.PorterDuff;
81 import android.graphics.PorterDuffXfermode;
82 import android.graphics.RecordingCanvas;
83 import android.graphics.Rect;
84 import android.graphics.RectF;
85 import android.graphics.Region;
86 import android.graphics.RenderEffect;
87 import android.graphics.RenderNode;
88 import android.graphics.Shader;
89 import android.graphics.drawable.ColorDrawable;
90 import android.graphics.drawable.Drawable;
91 import android.graphics.drawable.GradientDrawable;
92 import android.hardware.display.DisplayManagerGlobal;
93 import android.net.Uri;
94 import android.os.Build;
95 import android.os.Bundle;
96 import android.os.Handler;
97 import android.os.IBinder;
98 import android.os.Message;
99 import android.os.Parcel;
100 import android.os.Parcelable;
101 import android.os.RemoteCallback;
102 import android.os.RemoteException;
103 import android.os.SystemClock;
104 import android.os.Trace;
105 import android.sysprop.DisplayProperties;
106 import android.text.InputType;
107 import android.text.TextUtils;
108 import android.util.AttributeSet;
109 import android.util.FloatProperty;
110 import android.util.LayoutDirection;
111 import android.util.Log;
112 import android.util.LongSparseArray;
113 import android.util.LongSparseLongArray;
114 import android.util.Pair;
115 import android.util.Pools.SynchronizedPool;
116 import android.util.Property;
117 import android.util.SparseArray;
118 import android.util.SparseIntArray;
119 import android.util.StateSet;
120 import android.util.SuperNotCalledException;
121 import android.util.TypedValue;
122 import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
123 import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
124 import android.view.AccessibilityIterators.TextSegmentIterator;
125 import android.view.AccessibilityIterators.WordTextSegmentIterator;
126 import android.view.ContextMenu.ContextMenuInfo;
127 import android.view.InputDevice.InputSourceClass;
128 import android.view.Window.OnContentApplyWindowInsetsListener;
129 import android.view.WindowInsets.Type;
130 import android.view.WindowInsetsAnimation.Bounds;
131 import android.view.WindowManager.LayoutParams;
132 import android.view.accessibility.AccessibilityEvent;
133 import android.view.accessibility.AccessibilityEventSource;
134 import android.view.accessibility.AccessibilityManager;
135 import android.view.accessibility.AccessibilityNodeIdManager;
136 import android.view.accessibility.AccessibilityNodeInfo;
137 import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction;
138 import android.view.accessibility.AccessibilityNodeProvider;
139 import android.view.accessibility.AccessibilityWindowInfo;
140 import android.view.animation.Animation;
141 import android.view.animation.AnimationUtils;
142 import android.view.animation.Transformation;
143 import android.view.autofill.AutofillId;
144 import android.view.autofill.AutofillManager;
145 import android.view.autofill.AutofillValue;
146 import android.view.contentcapture.ContentCaptureContext;
147 import android.view.contentcapture.ContentCaptureManager;
148 import android.view.contentcapture.ContentCaptureSession;
149 import android.view.displayhash.DisplayHash;
150 import android.view.displayhash.DisplayHashManager;
151 import android.view.displayhash.DisplayHashResultCallback;
152 import android.view.inputmethod.EditorInfo;
153 import android.view.inputmethod.InputConnection;
154 import android.view.inspector.InspectableProperty;
155 import android.view.inspector.InspectableProperty.EnumEntry;
156 import android.view.inspector.InspectableProperty.FlagEntry;
157 import android.view.translation.TranslationCapability;
158 import android.view.translation.TranslationSpec.DataFormat;
159 import android.view.translation.ViewTranslationCallback;
160 import android.view.translation.ViewTranslationRequest;
161 import android.view.translation.ViewTranslationResponse;
162 import android.widget.Checkable;
163 import android.widget.FrameLayout;
164 import android.widget.ScrollBarDrawable;
165 import android.window.OnBackInvokedDispatcher;
166
167 import com.android.internal.R;
168 import com.android.internal.util.ArrayUtils;
169 import com.android.internal.util.FrameworkStatsLog;
170 import com.android.internal.util.Preconditions;
171 import com.android.internal.view.ScrollCaptureInternal;
172 import com.android.internal.view.TooltipPopup;
173 import com.android.internal.view.menu.MenuBuilder;
174 import com.android.internal.widget.ScrollBarUtils;
175
176 import com.google.android.collect.Lists;
177 import com.google.android.collect.Maps;
178
179 import java.io.PrintWriter;
180 import java.lang.annotation.Retention;
181 import java.lang.annotation.RetentionPolicy;
182 import java.lang.ref.WeakReference;
183 import java.lang.reflect.Field;
184 import java.lang.reflect.InvocationTargetException;
185 import java.lang.reflect.Method;
186 import java.lang.reflect.Modifier;
187 import java.util.ArrayList;
188 import java.util.Arrays;
189 import java.util.Calendar;
190 import java.util.Collection;
191 import java.util.Collections;
192 import java.util.HashMap;
193 import java.util.List;
194 import java.util.Locale;
195 import java.util.Map;
196 import java.util.concurrent.CopyOnWriteArrayList;
197 import java.util.concurrent.Executor;
198 import java.util.concurrent.atomic.AtomicInteger;
199 import java.util.function.Consumer;
200 import java.util.function.Predicate;
201
202 /**
203 * <p>
204 * This class represents the basic building block for user interface components. A View
205 * occupies a rectangular area on the screen and is responsible for drawing and
206 * event handling. View is the base class for <em>widgets</em>, which are
207 * used to create interactive UI components (buttons, text fields, etc.). The
208 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
209 * are invisible containers that hold other Views (or other ViewGroups) and define
210 * their layout properties.
211 * </p>
212 *
213 * <div class="special reference">
214 * <h3>Developer Guides</h3>
215 * <p>For information about using this class to develop your application's user interface,
216 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
217 * </div>
218 *
219 * <a name="Using"></a>
220 * <h3>Using Views</h3>
221 * <p>
222 * All of the views in a window are arranged in a single tree. You can add views
223 * either from code or by specifying a tree of views in one or more XML layout
224 * files. There are many specialized subclasses of views that act as controls or
225 * are capable of displaying text, images, or other content.
226 * </p>
227 * <p>
228 * Once you have created a tree of views, there are typically a few types of
229 * common operations you may wish to perform:
230 * <ul>
231 * <li><strong>Set properties:</strong> for example setting the text of a
232 * {@link android.widget.TextView}. The available properties and the methods
233 * that set them will vary among the different subclasses of views. Note that
234 * properties that are known at build time can be set in the XML layout
235 * files.</li>
236 * <li><strong>Set focus:</strong> The framework will handle moving focus in
237 * response to user input. To force focus to a specific view, call
238 * {@link #requestFocus}.</li>
239 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
240 * that will be notified when something interesting happens to the view. For
241 * example, all views will let you set a listener to be notified when the view
242 * gains or loses focus. You can register such a listener using
243 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
244 * Other view subclasses offer more specialized listeners. For example, a Button
245 * exposes a listener to notify clients when the button is clicked.</li>
246 * <li><strong>Set visibility:</strong> You can hide or show views using
247 * {@link #setVisibility(int)}.</li>
248 * </ul>
249 * </p>
250 * <p><em>
251 * Note: The Android framework is responsible for measuring, laying out and
252 * drawing views. You should not call methods that perform these actions on
253 * views yourself unless you are actually implementing a
254 * {@link android.view.ViewGroup}.
255 * </em></p>
256 *
257 * <a name="Lifecycle"></a>
258 * <h3>Implementing a Custom View</h3>
259 *
260 * <p>
261 * To implement a custom view, you will usually begin by providing overrides for
262 * some of the standard methods that the framework calls on all views. You do
263 * not need to override all of these methods. In fact, you can start by just
264 * overriding {@link #onDraw(android.graphics.Canvas)}.
265 * <table border="2" width="85%" align="center" cellpadding="5">
266 * <thead>
267 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
268 * </thead>
269 *
270 * <tbody>
271 * <tr>
272 * <td rowspan="2">Creation</td>
273 * <td>Constructors</td>
274 * <td>There is a form of the constructor that are called when the view
275 * is created from code and a form that is called when the view is
276 * inflated from a layout file. The second form should parse and apply
277 * any attributes defined in the layout file.
278 * </td>
279 * </tr>
280 * <tr>
281 * <td><code>{@link #onFinishInflate()}</code></td>
282 * <td>Called after a view and all of its children has been inflated
283 * from XML.</td>
284 * </tr>
285 *
286 * <tr>
287 * <td rowspan="3">Layout</td>
288 * <td><code>{@link #onMeasure(int, int)}</code></td>
289 * <td>Called to determine the size requirements for this view and all
290 * of its children.
291 * </td>
292 * </tr>
293 * <tr>
294 * <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
295 * <td>Called when this view should assign a size and position to all
296 * of its children.
297 * </td>
298 * </tr>
299 * <tr>
300 * <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
301 * <td>Called when the size of this view has changed.
302 * </td>
303 * </tr>
304 *
305 * <tr>
306 * <td>Drawing</td>
307 * <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
308 * <td>Called when the view should render its content.
309 * </td>
310 * </tr>
311 *
312 * <tr>
313 * <td rowspan="4">Event processing</td>
314 * <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
315 * <td>Called when a new hardware key event occurs.
316 * </td>
317 * </tr>
318 * <tr>
319 * <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
320 * <td>Called when a hardware key up event occurs.
321 * </td>
322 * </tr>
323 * <tr>
324 * <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
325 * <td>Called when a trackball motion event occurs.
326 * </td>
327 * </tr>
328 * <tr>
329 * <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
330 * <td>Called when a touch screen motion event occurs.
331 * </td>
332 * </tr>
333 *
334 * <tr>
335 * <td rowspan="2">Focus</td>
336 * <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
337 * <td>Called when the view gains or loses focus.
338 * </td>
339 * </tr>
340 *
341 * <tr>
342 * <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
343 * <td>Called when the window containing the view gains or loses focus.
344 * </td>
345 * </tr>
346 *
347 * <tr>
348 * <td rowspan="3">Attaching</td>
349 * <td><code>{@link #onAttachedToWindow()}</code></td>
350 * <td>Called when the view is attached to a window.
351 * </td>
352 * </tr>
353 *
354 * <tr>
355 * <td><code>{@link #onDetachedFromWindow}</code></td>
356 * <td>Called when the view is detached from its window.
357 * </td>
358 * </tr>
359 *
360 * <tr>
361 * <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
362 * <td>Called when the visibility of the window containing the view
363 * has changed.
364 * </td>
365 * </tr>
366 * </tbody>
367 *
368 * </table>
369 * </p>
370 *
371 * <a name="IDs"></a>
372 * <h3>IDs</h3>
373 * Views may have an integer id associated with them. These ids are typically
374 * assigned in the layout XML files, and are used to find specific views within
375 * the view tree. A common pattern is to:
376 * <ul>
377 * <li>Define a Button in the layout file and assign it a unique ID.
378 * <pre>
379 * &lt;Button
380 * android:id="@+id/my_button"
381 * android:layout_width="wrap_content"
382 * android:layout_height="wrap_content"
383 * android:text="@string/my_button_text"/&gt;
384 * </pre></li>
385 * <li>From the onCreate method of an Activity, find the Button
386 * <pre class="prettyprint">
387 * Button myButton = findViewById(R.id.my_button);
388 * </pre></li>
389 * </ul>
390 * <p>
391 * View IDs need not be unique throughout the tree, but it is good practice to
392 * ensure that they are at least unique within the part of the tree you are
393 * searching.
394 * </p>
395 *
396 * <a name="Position"></a>
397 * <h3>Position</h3>
398 * <p>
399 * The geometry of a view is that of a rectangle. A view has a location,
400 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
401 * two dimensions, expressed as a width and a height. The unit for location
402 * and dimensions is the pixel.
403 * </p>
404 *
405 * <p>
406 * It is possible to retrieve the location of a view by invoking the methods
407 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
408 * coordinate of the rectangle representing the view. The latter returns the
409 * top, or Y, coordinate of the rectangle representing the view. These methods
410 * both return the location of the view relative to its parent. For instance,
411 * when getLeft() returns 20, that means the view is located 20 pixels to the
412 * right of the left edge of its direct parent.
413 * </p>
414 *
415 * <p>
416 * In addition, several convenience methods are offered to avoid unnecessary
417 * computations, namely {@link #getRight()} and {@link #getBottom()}.
418 * These methods return the coordinates of the right and bottom edges of the
419 * rectangle representing the view. For instance, calling {@link #getRight()}
420 * is similar to the following computation: <code>getLeft() + getWidth()</code>
421 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
422 * </p>
423 *
424 * <a name="SizePaddingMargins"></a>
425 * <h3>Size, padding and margins</h3>
426 * <p>
427 * The size of a view is expressed with a width and a height. A view actually
428 * possess two pairs of width and height values.
429 * </p>
430 *
431 * <p>
432 * The first pair is known as <em>measured width</em> and
433 * <em>measured height</em>. These dimensions define how big a view wants to be
434 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
435 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
436 * and {@link #getMeasuredHeight()}.
437 * </p>
438 *
439 * <p>
440 * The second pair is simply known as <em>width</em> and <em>height</em>, or
441 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
442 * dimensions define the actual size of the view on screen, at drawing time and
443 * after layout. These values may, but do not have to, be different from the
444 * measured width and height. The width and height can be obtained by calling
445 * {@link #getWidth()} and {@link #getHeight()}.
446 * </p>
447 *
448 * <p>
449 * To measure its dimensions, a view takes into account its padding. The padding
450 * is expressed in pixels for the left, top, right and bottom parts of the view.
451 * Padding can be used to offset the content of the view by a specific amount of
452 * pixels. For instance, a left padding of 2 will push the view's content by
453 * 2 pixels to the right of the left edge. Padding can be set using the
454 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
455 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
456 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
457 * {@link #getPaddingEnd()}.
458 * </p>
459 *
460 * <p>
461 * Even though a view can define a padding, it does not provide any support for
462 * margins. However, view groups provide such a support. Refer to
463 * {@link android.view.ViewGroup} and
464 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
465 * </p>
466 *
467 * <a name="Layout"></a>
468 * <h3>Layout</h3>
469 * <p>
470 * Layout is a two pass process: a measure pass and a layout pass. The measuring
471 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
472 * of the view tree. Each view pushes dimension specifications down the tree
473 * during the recursion. At the end of the measure pass, every view has stored
474 * its measurements. The second pass happens in
475 * {@link #layout(int,int,int,int)} and is also top-down. During
476 * this pass each parent is responsible for positioning all of its children
477 * using the sizes computed in the measure pass.
478 * </p>
479 *
480 * <p>
481 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
482 * {@link #getMeasuredHeight()} values must be set, along with those for all of
483 * that view's descendants. A view's measured width and measured height values
484 * must respect the constraints imposed by the view's parents. This guarantees
485 * that at the end of the measure pass, all parents accept all of their
486 * children's measurements. A parent view may call measure() more than once on
487 * its children. For example, the parent may measure each child once with
488 * unspecified dimensions to find out how big they want to be, then call
489 * measure() on them again with actual numbers if the sum of all the children's
490 * unconstrained sizes is too big or too small.
491 * </p>
492 *
493 * <p>
494 * The measure pass uses two classes to communicate dimensions. The
495 * {@link MeasureSpec} class is used by views to tell their parents how they
496 * want to be measured and positioned. The base LayoutParams class just
497 * describes how big the view wants to be for both width and height. For each
498 * dimension, it can specify one of:
499 * <ul>
500 * <li> an exact number
501 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
502 * (minus padding)
503 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
504 * enclose its content (plus padding).
505 * </ul>
506 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
507 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
508 * an X and Y value.
509 * </p>
510 *
511 * <p>
512 * MeasureSpecs are used to push requirements down the tree from parent to
513 * child. A MeasureSpec can be in one of three modes:
514 * <ul>
515 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
516 * of a child view. For example, a LinearLayout may call measure() on its child
517 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
518 * tall the child view wants to be given a width of 240 pixels.
519 * <li>EXACTLY: This is used by the parent to impose an exact size on the
520 * child. The child must use this size, and guarantee that all of its
521 * descendants will fit within this size.
522 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
523 * child. The child must guarantee that it and all of its descendants will fit
524 * within this size.
525 * </ul>
526 * </p>
527 *
528 * <p>
529 * To initiate a layout, call {@link #requestLayout}. This method is typically
530 * called by a view on itself when it believes that it can no longer fit within
531 * its current bounds.
532 * </p>
533 *
534 * <a name="Drawing"></a>
535 * <h3>Drawing</h3>
536 * <p>
537 * Drawing is handled by walking the tree and recording the drawing commands of
538 * any View that needs to update. After this, the drawing commands of the
539 * entire tree are issued to screen, clipped to the newly damaged area.
540 * </p>
541 *
542 * <p>
543 * The tree is largely recorded and drawn in order, with parents drawn before
544 * (i.e., behind) their children, with siblings drawn in the order they appear
545 * in the tree. If you set a background drawable for a View, then the View will
546 * draw it before calling back to its <code>onDraw()</code> method. The child
547 * drawing order can be overridden with
548 * {@link ViewGroup#setChildrenDrawingOrderEnabled(boolean) custom child drawing order}
549 * in a ViewGroup, and with {@link #setZ(float)} custom Z values} set on Views.
550 * </p>
551 *
552 * <p>
553 * To force a view to draw, call {@link #invalidate()}.
554 * </p>
555 *
556 * <a name="EventHandlingThreading"></a>
557 * <h3>Event Handling and Threading</h3>
558 * <p>
559 * The basic cycle of a view is as follows:
560 * <ol>
561 * <li>An event comes in and is dispatched to the appropriate view. The view
562 * handles the event and notifies any listeners.</li>
563 * <li>If in the course of processing the event, the view's bounds may need
564 * to be changed, the view will call {@link #requestLayout()}.</li>
565 * <li>Similarly, if in the course of processing the event the view's appearance
566 * may need to be changed, the view will call {@link #invalidate()}.</li>
567 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
568 * the framework will take care of measuring, laying out, and drawing the tree
569 * as appropriate.</li>
570 * </ol>
571 * </p>
572 *
573 * <p><em>Note: The entire view tree is single threaded. You must always be on
574 * the UI thread when calling any method on any view.</em>
575 * If you are doing work on other threads and want to update the state of a view
576 * from that thread, you should use a {@link Handler}.
577 * </p>
578 *
579 * <a name="FocusHandling"></a>
580 * <h3>Focus Handling</h3>
581 * <p>
582 * The framework will handle routine focus movement in response to user input.
583 * This includes changing the focus as views are removed or hidden, or as new
584 * views become available. Views indicate their willingness to take focus
585 * through the {@link #isFocusable} method. To change whether a view can take
586 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below)
587 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
588 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
589 * </p>
590 * <p>
591 * Focus movement is based on an algorithm which finds the nearest neighbor in a
592 * given direction. In rare cases, the default algorithm may not match the
593 * intended behavior of the developer. In these situations, you can provide
594 * explicit overrides by using these XML attributes in the layout file:
595 * <pre>
596 * nextFocusDown
597 * nextFocusLeft
598 * nextFocusRight
599 * nextFocusUp
600 * </pre>
601 * </p>
602 *
603 *
604 * <p>
605 * To get a particular view to take focus, call {@link #requestFocus()}.
606 * </p>
607 *
608 * <a name="TouchMode"></a>
609 * <h3>Touch Mode</h3>
610 * <p>
611 * When a user is navigating a user interface via directional keys such as a D-pad, it is
612 * necessary to give focus to actionable items such as buttons so the user can see
613 * what will take input. If the device has touch capabilities, however, and the user
614 * begins interacting with the interface by touching it, it is no longer necessary to
615 * always highlight, or give focus to, a particular view. This motivates a mode
616 * for interaction named 'touch mode'.
617 * </p>
618 * <p>
619 * For a touch capable device, once the user touches the screen, the device
620 * will enter touch mode. From this point onward, only views for which
621 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
622 * Other views that are touchable, like buttons, will not take focus when touched; they will
623 * only fire the on click listeners.
624 * </p>
625 * <p>
626 * Any time a user hits a directional key, such as a D-pad direction, the view device will
627 * exit touch mode, and find a view to take focus, so that the user may resume interacting
628 * with the user interface without touching the screen again.
629 * </p>
630 * <p>
631 * The touch mode state is maintained across {@link android.app.Activity}s. Call
632 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
633 * </p>
634 *
635 * <a name="Scrolling"></a>
636 * <h3>Scrolling</h3>
637 * <p>
638 * The framework provides basic support for views that wish to internally
639 * scroll their content. This includes keeping track of the X and Y scroll
640 * offset as well as mechanisms for drawing scrollbars. See
641 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
642 * {@link #awakenScrollBars()} for more details.
643 * </p>
644 *
645 * <a name="Tags"></a>
646 * <h3>Tags</h3>
647 * <p>
648 * Unlike IDs, tags are not used to identify views. Tags are essentially an
649 * extra piece of information that can be associated with a view. They are most
650 * often used as a convenience to store data related to views in the views
651 * themselves rather than by putting them in a separate structure.
652 * </p>
653 * <p>
654 * Tags may be specified with character sequence values in layout XML as either
655 * a single tag using the {@link android.R.styleable#View_tag android:tag}
656 * attribute or multiple tags using the {@code <tag>} child element:
657 * <pre>
658 * &lt;View ...
659 * android:tag="@string/mytag_value" /&gt;
660 * &lt;View ...&gt;
661 * &lt;tag android:id="@+id/mytag"
662 * android:value="@string/mytag_value" /&gt;
663 * &lt;/View>
664 * </pre>
665 * </p>
666 * <p>
667 * Tags may also be specified with arbitrary objects from code using
668 * {@link #setTag(Object)} or {@link #setTag(int, Object)}.
669 * </p>
670 *
671 * <a name="Themes"></a>
672 * <h3>Themes</h3>
673 * <p>
674 * By default, Views are created using the theme of the Context object supplied
675 * to their constructor; however, a different theme may be specified by using
676 * the {@link android.R.styleable#View_theme android:theme} attribute in layout
677 * XML or by passing a {@link ContextThemeWrapper} to the constructor from
678 * code.
679 * </p>
680 * <p>
681 * When the {@link android.R.styleable#View_theme android:theme} attribute is
682 * used in XML, the specified theme is applied on top of the inflation
683 * context's theme (see {@link LayoutInflater}) and used for the view itself as
684 * well as any child elements.
685 * </p>
686 * <p>
687 * In the following example, both views will be created using the Material dark
688 * color scheme; however, because an overlay theme is used which only defines a
689 * subset of attributes, the value of
690 * {@link android.R.styleable#Theme_colorAccent android:colorAccent} defined on
691 * the inflation context's theme (e.g. the Activity theme) will be preserved.
692 * <pre>
693 * &lt;LinearLayout
694 * ...
695 * android:theme="@android:theme/ThemeOverlay.Material.Dark"&gt;
696 * &lt;View ...&gt;
697 * &lt;/LinearLayout&gt;
698 * </pre>
699 * </p>
700 *
701 * <a name="Properties"></a>
702 * <h3>Properties</h3>
703 * <p>
704 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
705 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
706 * available both in the {@link Property} form as well as in similarly-named setter/getter
707 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
708 * be used to set persistent state associated with these rendering-related properties on the view.
709 * The properties and methods can also be used in conjunction with
710 * {@link android.animation.Animator Animator}-based animations, described more in the
711 * <a href="#Animation">Animation</a> section.
712 * </p>
713 *
714 * <a name="Animation"></a>
715 * <h3>Animation</h3>
716 * <p>
717 * Starting with Android 3.0, the preferred way of animating views is to use the
718 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
719 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
720 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
721 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
722 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
723 * makes animating these View properties particularly easy and efficient.
724 * </p>
725 * <p>
726 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
727 * You can attach an {@link Animation} object to a view using
728 * {@link #setAnimation(Animation)} or
729 * {@link #startAnimation(Animation)}. The animation can alter the scale,
730 * rotation, translation and alpha of a view over time. If the animation is
731 * attached to a view that has children, the animation will affect the entire
732 * subtree rooted by that node. When an animation is started, the framework will
733 * take care of redrawing the appropriate views until the animation completes.
734 * </p>
735 *
736 * <a name="Security"></a>
737 * <h3>Security</h3>
738 * <p>
739 * Sometimes it is essential that an application be able to verify that an action
740 * is being performed with the full knowledge and consent of the user, such as
741 * granting a permission request, making a purchase or clicking on an advertisement.
742 * Unfortunately, a malicious application could try to spoof the user into
743 * performing these actions, unaware, by concealing the intended purpose of the view.
744 * As a remedy, the framework offers a touch filtering mechanism that can be used to
745 * improve the security of views that provide access to sensitive functionality.
746 * </p><p>
747 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
748 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework
749 * will discard touches that are received whenever the view's window is obscured by
750 * another visible window at the touched location. As a result, the view will not receive touches
751 * whenever the touch passed through a toast, dialog or other window that appears above the view's
752 * window.
753 * </p><p>
754 * For more fine-grained control over security, consider overriding the
755 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
756 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
757 * </p>
758 *
759 * @attr ref android.R.styleable#View_accessibilityHeading
760 * @attr ref android.R.styleable#View_allowClickWhenDisabled
761 * @attr ref android.R.styleable#View_alpha
762 * @attr ref android.R.styleable#View_background
763 * @attr ref android.R.styleable#View_clickable
764 * @attr ref android.R.styleable#View_clipToOutline
765 * @attr ref android.R.styleable#View_contentDescription
766 * @attr ref android.R.styleable#View_drawingCacheQuality
767 * @attr ref android.R.styleable#View_duplicateParentState
768 * @attr ref android.R.styleable#View_id
769 * @attr ref android.R.styleable#View_requiresFadingEdge
770 * @attr ref android.R.styleable#View_fadeScrollbars
771 * @attr ref android.R.styleable#View_fadingEdgeLength
772 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
773 * @attr ref android.R.styleable#View_fitsSystemWindows
774 * @attr ref android.R.styleable#View_isScrollContainer
775 * @attr ref android.R.styleable#View_focusable
776 * @attr ref android.R.styleable#View_focusableInTouchMode
777 * @attr ref android.R.styleable#View_focusedByDefault
778 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
779 * @attr ref android.R.styleable#View_keepScreenOn
780 * @attr ref android.R.styleable#View_keyboardNavigationCluster
781 * @attr ref android.R.styleable#View_layerType
782 * @attr ref android.R.styleable#View_layoutDirection
783 * @attr ref android.R.styleable#View_longClickable
784 * @attr ref android.R.styleable#View_minHeight
785 * @attr ref android.R.styleable#View_minWidth
786 * @attr ref android.R.styleable#View_nextClusterForward
787 * @attr ref android.R.styleable#View_nextFocusDown
788 * @attr ref android.R.styleable#View_nextFocusLeft
789 * @attr ref android.R.styleable#View_nextFocusRight
790 * @attr ref android.R.styleable#View_nextFocusUp
791 * @attr ref android.R.styleable#View_onClick
792 * @attr ref android.R.styleable#View_outlineSpotShadowColor
793 * @attr ref android.R.styleable#View_outlineAmbientShadowColor
794 * @attr ref android.R.styleable#View_padding
795 * @attr ref android.R.styleable#View_paddingHorizontal
796 * @attr ref android.R.styleable#View_paddingVertical
797 * @attr ref android.R.styleable#View_paddingBottom
798 * @attr ref android.R.styleable#View_paddingLeft
799 * @attr ref android.R.styleable#View_paddingRight
800 * @attr ref android.R.styleable#View_paddingTop
801 * @attr ref android.R.styleable#View_paddingStart
802 * @attr ref android.R.styleable#View_paddingEnd
803 * @attr ref android.R.styleable#View_saveEnabled
804 * @attr ref android.R.styleable#View_rotation
805 * @attr ref android.R.styleable#View_rotationX
806 * @attr ref android.R.styleable#View_rotationY
807 * @attr ref android.R.styleable#View_scaleX
808 * @attr ref android.R.styleable#View_scaleY
809 * @attr ref android.R.styleable#View_scrollX
810 * @attr ref android.R.styleable#View_scrollY
811 * @attr ref android.R.styleable#View_scrollbarSize
812 * @attr ref android.R.styleable#View_scrollbarStyle
813 * @attr ref android.R.styleable#View_scrollbars
814 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
815 * @attr ref android.R.styleable#View_scrollbarFadeDuration
816 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
817 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
818 * @attr ref android.R.styleable#View_scrollbarThumbVertical
819 * @attr ref android.R.styleable#View_scrollbarTrackVertical
820 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
821 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
822 * @attr ref android.R.styleable#View_stateListAnimator
823 * @attr ref android.R.styleable#View_transitionName
824 * @attr ref android.R.styleable#View_soundEffectsEnabled
825 * @attr ref android.R.styleable#View_tag
826 * @attr ref android.R.styleable#View_textAlignment
827 * @attr ref android.R.styleable#View_textDirection
828 * @attr ref android.R.styleable#View_transformPivotX
829 * @attr ref android.R.styleable#View_transformPivotY
830 * @attr ref android.R.styleable#View_translationX
831 * @attr ref android.R.styleable#View_translationY
832 * @attr ref android.R.styleable#View_translationZ
833 * @attr ref android.R.styleable#View_visibility
834 * @attr ref android.R.styleable#View_theme
835 *
836 * @see android.view.ViewGroup
837 */
838 @UiThread
839 public class View implements Drawable.Callback, KeyEvent.Callback,
840 AccessibilityEventSource {
841 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
842 private static final boolean DBG = false;
843
844 /** @hide */
845 public static boolean DEBUG_DRAW = false;
846
847 /**
848 * The logging tag used by this class with android.util.Log.
849 */
850 protected static final String VIEW_LOG_TAG = "View";
851
852 /**
853 * The logging tag used by this class when logging verbose, autofill-related messages.
854 */
855 // NOTE: We cannot use android.view.autofill.Helper.sVerbose because that variable is not
856 // set if a session is not started.
857 private static final String AUTOFILL_LOG_TAG = "View.Autofill";
858
859 /**
860 * The logging tag used by this class when logging content capture-related messages.
861 */
862 private static final String CONTENT_CAPTURE_LOG_TAG = "View.ContentCapture";
863
864 private static final boolean DEBUG_CONTENT_CAPTURE = false;
865
866 /**
867 * When set to true, this view will save its attribute data.
868 *
869 * @hide
870 */
871 public static boolean sDebugViewAttributes = false;
872
873 /**
874 * When set to this application package view will save its attribute data.
875 *
876 * @hide
877 */
878 public static String sDebugViewAttributesApplicationPackage;
879
880 /**
881 * Used to mark a View that has no ID.
882 */
883 public static final int NO_ID = -1;
884
885 /**
886 * Last ID that is given to Views that are no part of activities.
887 *
888 * {@hide}
889 */
890 public static final int LAST_APP_AUTOFILL_ID = Integer.MAX_VALUE / 2;
891
892 /**
893 * Attribute to find the autofilled highlight
894 *
895 * @see #getAutofilledDrawable()
896 */
897 private static final int[] AUTOFILL_HIGHLIGHT_ATTR =
898 new int[]{android.R.attr.autofilledHighlight};
899
900 /**
901 * Signals that compatibility booleans have been initialized according to
902 * target SDK versions.
903 */
904 private static boolean sCompatibilityDone = false;
905
906 /**
907 * Use the old (broken) way of building MeasureSpecs.
908 */
909 private static boolean sUseBrokenMakeMeasureSpec = false;
910
911 /**
912 * Always return a size of 0 for MeasureSpec values with a mode of UNSPECIFIED
913 */
914 static boolean sUseZeroUnspecifiedMeasureSpec = false;
915
916 /**
917 * Ignore any optimizations using the measure cache.
918 */
919 private static boolean sIgnoreMeasureCache = false;
920
921 /**
922 * Ignore an optimization that skips unnecessary EXACTLY layout passes.
923 */
924 private static boolean sAlwaysRemeasureExactly = false;
925
926 /**
927 * Allow setForeground/setBackground to be called (and ignored) on a textureview,
928 * without throwing
929 */
930 static boolean sTextureViewIgnoresDrawableSetters = false;
931
932 /**
933 * Prior to N, some ViewGroups would not convert LayoutParams properly even though both extend
934 * MarginLayoutParams. For instance, converting LinearLayout.LayoutParams to
935 * RelativeLayout.LayoutParams would lose margin information. This is fixed on N but target API
936 * check is implemented for backwards compatibility.
937 *
938 * {@hide}
939 */
940 protected static boolean sPreserveMarginParamsInLayoutParamConversion;
941
942 /**
943 * Prior to N, when drag enters into child of a view that has already received an
944 * ACTION_DRAG_ENTERED event, the parent doesn't get a ACTION_DRAG_EXITED event.
945 * ACTION_DRAG_LOCATION and ACTION_DROP were delivered to the parent of a view that returned
946 * false from its event handler for these events.
947 * Starting from N, the parent will get ACTION_DRAG_EXITED event before the child gets its
948 * ACTION_DRAG_ENTERED. ACTION_DRAG_LOCATION and ACTION_DROP are never propagated to the parent.
949 * sCascadedDragDrop is true for pre-N apps for backwards compatibility implementation.
950 */
951 static boolean sCascadedDragDrop;
952
953 /**
954 * Prior to O, auto-focusable didn't exist and widgets such as ListView use hasFocusable
955 * to determine things like whether or not to permit item click events. We can't break
956 * apps that do this just because more things (clickable things) are now auto-focusable
957 * and they would get different results, so give old behavior to old apps.
958 */
959 static boolean sHasFocusableExcludeAutoFocusable;
960
961 /**
962 * Prior to O, auto-focusable didn't exist and views marked as clickable weren't implicitly
963 * made focusable by default. As a result, apps could (incorrectly) change the clickable
964 * setting of views off the UI thread. Now that clickable can effect the focusable state,
965 * changing the clickable attribute off the UI thread will cause an exception (since changing
966 * the focusable state checks). In order to prevent apps from crashing, we will handle this
967 * specific case and just not notify parents on new focusables resulting from marking views
968 * clickable from outside the UI thread.
969 */
970 private static boolean sAutoFocusableOffUIThreadWontNotifyParents;
971
972 /**
973 * Prior to P things like setScaleX() allowed passing float values that were bogus such as
974 * Float.NaN. If the app is targetting P or later then passing these values will result in an
975 * exception being thrown. If the app is targetting an earlier SDK version, then we will
976 * silently clamp these values to avoid crashes elsewhere when the rendering code hits
977 * these bogus values.
978 */
979 private static boolean sThrowOnInvalidFloatProperties;
980
981 /**
982 * Prior to P, {@code #startDragAndDrop} accepts a builder which produces an empty drag shadow.
983 * Currently zero size SurfaceControl cannot be created thus we create a 1x1 surface instead.
984 */
985 private static boolean sAcceptZeroSizeDragShadow;
986
987 /**
988 * Prior to R, {@link #dispatchApplyWindowInsets} had an issue:
989 * <p>The modified insets changed by {@link #onApplyWindowInsets} were passed to the
990 * entire view hierarchy in prefix order, including siblings as well as siblings of parents
991 * further down the hierarchy. This violates the basic concepts of the view hierarchy, and
992 * thus, the hierarchical dispatching mechanism was hard to use for apps.
993 * <p>
994 * In order to make window inset dispatching work properly, we dispatch window insets
995 * in the view hierarchy in a proper hierarchical manner if this flag is set to {@code false}.
996 */
997 static boolean sBrokenInsetsDispatch;
998
999 /**
1000 * Prior to Q, calling
1001 * {@link com.android.internal.policy.DecorView#setBackgroundDrawable(Drawable)}
1002 * did not call update the window format so the opacity of the background was not correctly
1003 * applied to the window. Some applications rely on this misbehavior to work properly.
1004 * <p>
1005 * From Q, {@link com.android.internal.policy.DecorView#setBackgroundDrawable(Drawable)} is
1006 * the same as {@link com.android.internal.policy.DecorView#setWindowBackground(Drawable)}
1007 * which updates the window format.
1008 * @hide
1009 */
1010 protected static boolean sBrokenWindowBackground;
1011
1012 /**
1013 * Prior to R, we were always forcing a layout of the entire hierarchy when insets changed from
1014 * the server. This is inefficient and not all apps use it. Instead, we want to rely on apps
1015 * calling {@link #requestLayout} when they need to relayout based on an insets change.
1016 */
1017 static boolean sForceLayoutWhenInsetsChanged;
1018
1019 /** @hide */
1020 @IntDef({NOT_FOCUSABLE, FOCUSABLE, FOCUSABLE_AUTO})
1021 @Retention(RetentionPolicy.SOURCE)
1022 public @interface Focusable {}
1023
1024 /**
1025 * This view does not want keystrokes.
1026 * <p>
1027 * Use with {@link #setFocusable(int)} and <a href="#attr_android:focusable">{@code
1028 * android:focusable}.
1029 */
1030 public static final int NOT_FOCUSABLE = 0x00000000;
1031
1032 /**
1033 * This view wants keystrokes.
1034 * <p>
1035 * Use with {@link #setFocusable(int)} and <a href="#attr_android:focusable">{@code
1036 * android:focusable}.
1037 */
1038 public static final int FOCUSABLE = 0x00000001;
1039
1040 /**
1041 * This view determines focusability automatically. This is the default.
1042 * <p>
1043 * Use with {@link #setFocusable(int)} and <a href="#attr_android:focusable">{@code
1044 * android:focusable}.
1045 */
1046 public static final int FOCUSABLE_AUTO = 0x00000010;
1047
1048 /**
1049 * Mask for use with setFlags indicating bits used for focus.
1050 */
1051 private static final int FOCUSABLE_MASK = 0x00000011;
1052
1053 /**
1054 * This view will adjust its padding to fit sytem windows (e.g. status bar)
1055 */
1056 private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
1057
1058 /** @hide */
1059 @IntDef({VISIBLE, INVISIBLE, GONE})
1060 @Retention(RetentionPolicy.SOURCE)
1061 public @interface Visibility {}
1062
1063 /**
1064 * This view is visible.
1065 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
1066 * android:visibility}.
1067 */
1068 public static final int VISIBLE = 0x00000000;
1069
1070 /**
1071 * This view is invisible, but it still takes up space for layout purposes.
1072 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
1073 * android:visibility}.
1074 */
1075 public static final int INVISIBLE = 0x00000004;
1076
1077 /**
1078 * This view is invisible, and it doesn't take any space for layout
1079 * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
1080 * android:visibility}.
1081 */
1082 public static final int GONE = 0x00000008;
1083
1084 /**
1085 * Mask for use with setFlags indicating bits used for visibility.
1086 * {@hide}
1087 */
1088 static final int VISIBILITY_MASK = 0x0000000C;
1089
1090 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
1091
1092 /**
1093 * Hint indicating that this view can be autofilled with an email address.
1094 *
1095 * <p>Can be used with either {@link #setAutofillHints(String[])} or
1096 * <a href="#attr_android:autofillHint"> {@code android:autofillHint}</a> (in which case the
1097 * value should be <code>{@value #AUTOFILL_HINT_EMAIL_ADDRESS}</code>).
1098 *
1099 * <p>See {@link #setAutofillHints(String...)} for more info about autofill hints.
1100 */
1101 public static final String AUTOFILL_HINT_EMAIL_ADDRESS = "emailAddress";
1102
1103 /**
1104 * Hint indicating that this view can be autofilled with a user's real name.
1105 *
1106 * <p>Can be used with either {@link #setAutofillHints(String[])} or
1107 * <a href="#attr_android:autofillHint"> {@code android:autofillHint}</a> (in which case the
1108 * value should be <code>{@value #AUTOFILL_HINT_NAME}</code>).
1109 *
1110 * <p>See {@link #setAutofillHints(String...)} for more info about autofill hints.
1111 */
1112 public static final String AUTOFILL_HINT_NAME = "name";
1113
1114 /**
1115 * Hint indicating that this view can be autofilled with a username.
1116 *
1117 * <p>Can be used with either {@link #setAutofillHints(String[])} or
1118 * <a href="#attr_android:autofillHint"> {@code android:autofillHint}</a> (in which case the
1119 * value should be <code>{@value #AUTOFILL_HINT_USERNAME}</code>).
1120 *
1121 * <p>See {@link #setAutofillHints(String...)} for more info about autofill hints.
1122 */
1123 public static final String AUTOFILL_HINT_USERNAME = "username";
1124
1125 /**
1126 * Hint indicating that this view can be autofilled with a password.
1127 *
1128 * <p>Can be used with either {@link #setAutofillHints(String[])} or
1129 * <a href="#attr_android:autofillHint"> {@code android:autofillHint}</a> (in which case the
1130 * value should be <code>{@value #AUTOFILL_HINT_PASSWORD}</code>).
1131 *
1132 * <p>See {@link #setAutofillHints(String...)} for more info about autofill hints.
1133 */
1134 public static final String AUTOFILL_HINT_PASSWORD = "password";
1135
1136 /**
1137 * Hint indicating that this view can be autofilled with a phone number.
1138 *
1139 * <p>Can be used with either {@link #setAutofillHints(String[])} or
1140 * <a href="#attr_android:autofillHint"> {@code android:autofillHint}</a> (in which case the
1141 * value should be <code>{@value #AUTOFILL_HINT_PHONE}</code>).
1142 *
1143 * <p>See {@link #setAutofillHints(String...)} for more info about autofill hints.
1144 */
1145 public static final String AUTOFILL_HINT_PHONE = "phone";
1146
1147 /**
1148 * Hint indicating that this view can be autofilled with a postal address.
1149 *
1150 * <p>Can be used with either {@link #setAutofillHints(String[])} or
1151 * <a href="#attr_android:autofillHint"> {@code android:autofillHint}</a> (in which case the
1152 * value should be <code>{@value #AUTOFILL_HINT_POSTAL_ADDRESS}</code>).
1153 *
1154 * <p>See {@link #setAutofillHints(String...)} for more info about autofill hints.
1155 */
1156 public static final String AUTOFILL_HINT_POSTAL_ADDRESS = "postalAddress";
1157
1158 /**
1159 * Hint indicating that this view can be autofilled with a postal code.
1160 *
1161 * <p>Can be used with either {@link #setAutofillHints(String[])} or
1162 * <a href="#attr_android:autofillHint"> {@code android:autofillHint}</a> (in which case the
1163 * value should be <code>{@value #AUTOFILL_HINT_POSTAL_CODE}</code>).
1164 *
1165 * <p>See {@link #setAutofillHints(String...)} for more info about autofill hints.
1166 */
1167 public static final String AUTOFILL_HINT_POSTAL_CODE = "postalCode";
1168
1169 /**
1170 * Hint indicating that this view can be autofilled with a credit card number.
1171 *
1172 * <p>Can be used with either {@link #setAutofillHints(String[])} or
1173 * <a href="#attr_android:autofillHint"> {@code android:autofillHint}</a> (in which case the
1174 * value should be <code>{@value #AUTOFILL_HINT_CREDIT_CARD_NUMBER}</code>).
1175 *
1176 * <p>See {@link #setAutofillHints(String...)} for more info about autofill hints.
1177 */
1178 public static final String AUTOFILL_HINT_CREDIT_CARD_NUMBER = "creditCardNumber";
1179
1180 /**
1181 * Hint indicating that this view can be autofilled with a credit card security code.
1182 *
1183 * <p>Can be used with either {@link #setAutofillHints(String[])} or
1184 * <a href="#attr_android:autofillHint"> {@code android:autofillHint}</a> (in which case the
1185 * value should be <code>{@value #AUTOFILL_HINT_CREDIT_CARD_SECURITY_CODE}</code>).
1186 *
1187 * <p>See {@link #setAutofillHints(String...)} for more info about autofill hints.
1188 */
1189 public static final String AUTOFILL_HINT_CREDIT_CARD_SECURITY_CODE = "creditCardSecurityCode";
1190
1191 /**
1192 * Hint indicating that this view can be autofilled with a credit card expiration date.
1193 *
1194 * <p>It should be used when the credit card expiration date is represented by just one view;
1195 * if it is represented by more than one (for example, one view for the month and another view
1196 * for the year), then each of these views should use the hint specific for the unit
1197 * ({@link #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DAY},
1198 * {@link #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_MONTH},
1199 * or {@link #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_YEAR}).
1200 *
1201 * <p>Can be used with either {@link #setAutofillHints(String[])} or
1202 * <a href="#attr_android:autofillHint"> {@code android:autofillHint}</a> (in which case the
1203 * value should be <code>{@value #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DATE}</code>).
1204 *
1205 * <p>When annotating a view with this hint, it's recommended to use a date autofill value to
1206 * avoid ambiguity when the autofill service provides a value for it. To understand why a
1207 * value can be ambiguous, consider "April of 2020", which could be represented as either of
1208 * the following options:
1209 *
1210 * <ul>
1211 * <li>{@code "04/2020"}
1212 * <li>{@code "4/2020"}
1213 * <li>{@code "2020/04"}
1214 * <li>{@code "2020/4"}
1215 * <li>{@code "April/2020"}
1216 * <li>{@code "Apr/2020"}
1217 * </ul>
1218 *
1219 * <p>You define a date autofill value for the view by overriding the following methods:
1220 *
1221 * <ol>
1222 * <li>{@link #getAutofillType()} to return {@link #AUTOFILL_TYPE_DATE}.
1223 * <li>{@link #getAutofillValue()} to return a
1224 * {@link AutofillValue#forDate(long) date autofillvalue}.
1225 * <li>{@link #autofill(AutofillValue)} to expect a data autofillvalue.
1226 * </ol>
1227 *
1228 * <p>See {@link #setAutofillHints(String...)} for more info about autofill hints.
1229 */
1230 public static final String AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DATE =
1231 "creditCardExpirationDate";
1232
1233 /**
1234 * Hint indicating that this view can be autofilled with a credit card expiration month.
1235 *
1236 * <p>Can be used with either {@link #setAutofillHints(String[])} or
1237 * <a href="#attr_android:autofillHint"> {@code android:autofillHint}</a> (in which case the
1238 * value should be <code>{@value #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_MONTH}</code>).
1239 *
1240 * <p>When annotating a view with this hint, it's recommended to use a text autofill value
1241 * whose value is the numerical representation of the month, starting on {@code 1} to avoid
1242 * ambiguity when the autofill service provides a value for it. To understand why a
1243 * value can be ambiguous, consider "January", which could be represented as either of
1244 *
1245 * <ul>
1246 * <li>{@code "1"}: recommended way.
1247 * <li>{@code "0"}: if following the {@link Calendar#MONTH} convention.
1248 * <li>{@code "January"}: full name, in English.
1249 * <li>{@code "jan"}: abbreviated name, in English.
1250 * <li>{@code "Janeiro"}: full name, in another language.
1251 * </ul>
1252 *
1253 * <p>Another recommended approach is to use a date autofill value - see
1254 * {@link #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DATE} for more details.
1255 *
1256 * <p>See {@link #setAutofillHints(String...)} for more info about autofill hints.
1257 */
1258 public static final String AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_MONTH =
1259 "creditCardExpirationMonth";
1260
1261 /**
1262 * Hint indicating that this view can be autofilled with a credit card expiration year.
1263 *
1264 * <p>Can be used with either {@link #setAutofillHints(String[])} or
1265 * <a href="#attr_android:autofillHint"> {@code android:autofillHint}</a> (in which case the
1266 * value should be <code>{@value #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_YEAR}</code>).
1267 *
1268 * <p>See {@link #setAutofillHints(String...)} for more info about autofill hints.
1269 */
1270 public static final String AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_YEAR =
1271 "creditCardExpirationYear";
1272
1273 /**
1274 * Hint indicating that this view can be autofilled with a credit card expiration day.
1275 *
1276 * <p>Can be used with either {@link #setAutofillHints(String[])} or
1277 * <a href="#attr_android:autofillHint"> {@code android:autofillHint}</a> (in which case the
1278 * value should be <code>{@value #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DAY}</code>).
1279 *
1280 * <p>See {@link #setAutofillHints(String...)} for more info about autofill hints.
1281 */
1282 public static final String AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DAY = "creditCardExpirationDay";
1283
1284 /**
1285 * A hint indicating that this view can be autofilled with a password.
1286 *
1287 * This is a heuristic-based hint that is meant to be used by UI Toolkit developers when a
1288 * view is a password field but doesn't specify a
1289 * <code>{@value View#AUTOFILL_HINT_PASSWORD}</code>.
1290 * @hide
1291 */
1292 // TODO(229765029): unhide this for UI toolkit
1293 public static final String AUTOFILL_HINT_PASSWORD_AUTO = "passwordAuto";
1294
1295 /**
1296 * Hints for the autofill services that describes the content of the view.
1297 */
1298 private @Nullable String[] mAutofillHints;
1299
1300 /**
1301 * Autofill id, lazily created on calls to {@link #getAutofillId()}.
1302 */
1303 private AutofillId mAutofillId;
1304
1305 /** @hide */
1306 @IntDef(prefix = { "AUTOFILL_TYPE_" }, value = {
1307 AUTOFILL_TYPE_NONE,
1308 AUTOFILL_TYPE_TEXT,
1309 AUTOFILL_TYPE_TOGGLE,
1310 AUTOFILL_TYPE_LIST,
1311 AUTOFILL_TYPE_DATE,
1312 })
1313 @Retention(RetentionPolicy.SOURCE)
1314 public @interface AutofillType {}
1315
1316 /**
1317 * Autofill type for views that cannot be autofilled.
1318 *
1319 * <p>Typically used when the view is read-only; for example, a text label.
1320 *
1321 * @see #getAutofillType()
1322 */
1323 public static final int AUTOFILL_TYPE_NONE = 0;
1324
1325 /**
1326 * Autofill type for a text field, which is filled by a {@link CharSequence}.
1327 *
1328 * <p>{@link AutofillValue} instances for autofilling a {@link View} can be obtained through
1329 * {@link AutofillValue#forText(CharSequence)}, and the value passed to autofill a
1330 * {@link View} can be fetched through {@link AutofillValue#getTextValue()}.
1331 *
1332 * @see #getAutofillType()
1333 */
1334 public static final int AUTOFILL_TYPE_TEXT = 1;
1335
1336 /**
1337 * Autofill type for a togglable field, which is filled by a {@code boolean}.
1338 *
1339 * <p>{@link AutofillValue} instances for autofilling a {@link View} can be obtained through
1340 * {@link AutofillValue#forToggle(boolean)}, and the value passed to autofill a
1341 * {@link View} can be fetched through {@link AutofillValue#getToggleValue()}.
1342 *
1343 * @see #getAutofillType()
1344 */
1345 public static final int AUTOFILL_TYPE_TOGGLE = 2;
1346
1347 /**
1348 * Autofill type for a selection list field, which is filled by an {@code int}
1349 * representing the element index inside the list (starting at {@code 0}).
1350 *
1351 * <p>{@link AutofillValue} instances for autofilling a {@link View} can be obtained through
1352 * {@link AutofillValue#forList(int)}, and the value passed to autofill a
1353 * {@link View} can be fetched through {@link AutofillValue#getListValue()}.
1354 *
1355 * <p>The available options in the selection list are typically provided by
1356 * {@link android.app.assist.AssistStructure.ViewNode#getAutofillOptions()}.
1357 *
1358 * @see #getAutofillType()
1359 */
1360 public static final int AUTOFILL_TYPE_LIST = 3;
1361
1362 /**
1363 * Autofill type for a field that contains a date, which is represented by a long representing
1364 * the number of milliseconds since the standard base time known as "the epoch", namely
1365 * January 1, 1970, 00:00:00 GMT (see {@link java.util.Date#getTime()}.
1366 *
1367 * <p>{@link AutofillValue} instances for autofilling a {@link View} can be obtained through
1368 * {@link AutofillValue#forDate(long)}, and the values passed to
1369 * autofill a {@link View} can be fetched through {@link AutofillValue#getDateValue()}.
1370 *
1371 * @see #getAutofillType()
1372 */
1373 public static final int AUTOFILL_TYPE_DATE = 4;
1374
1375
1376 /** @hide */
1377 @IntDef(prefix = { "IMPORTANT_FOR_AUTOFILL_" }, value = {
1378 IMPORTANT_FOR_AUTOFILL_AUTO,
1379 IMPORTANT_FOR_AUTOFILL_YES,
1380 IMPORTANT_FOR_AUTOFILL_NO,
1381 IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS,
1382 IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS
1383 })
1384 @Retention(RetentionPolicy.SOURCE)
1385 public @interface AutofillImportance {}
1386
1387 /**
1388 * Automatically determine whether a view is important for autofill.
1389 *
1390 * @see #isImportantForAutofill()
1391 * @see #setImportantForAutofill(int)
1392 */
1393 public static final int IMPORTANT_FOR_AUTOFILL_AUTO = 0x0;
1394
1395 /**
1396 * The view is important for autofill, and its children (if any) will be traversed.
1397 *
1398 * @see #isImportantForAutofill()
1399 * @see #setImportantForAutofill(int)
1400 */
1401 public static final int IMPORTANT_FOR_AUTOFILL_YES = 0x1;
1402
1403 /**
1404 * The view is not important for autofill, but its children (if any) will be traversed.
1405 *
1406 * @see #isImportantForAutofill()
1407 * @see #setImportantForAutofill(int)
1408 */
1409 public static final int IMPORTANT_FOR_AUTOFILL_NO = 0x2;
1410
1411 /**
1412 * The view is important for autofill, but its children (if any) will not be traversed.
1413 *
1414 * @see #isImportantForAutofill()
1415 * @see #setImportantForAutofill(int)
1416 */
1417 public static final int IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS = 0x4;
1418
1419 /**
1420 * The view is not important for autofill, and its children (if any) will not be traversed.
1421 *
1422 * @see #isImportantForAutofill()
1423 * @see #setImportantForAutofill(int)
1424 */
1425 public static final int IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS = 0x8;
1426
1427 /** @hide */
1428 @IntDef(flag = true, prefix = { "AUTOFILL_FLAG_" }, value = {
1429 AUTOFILL_FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
1430 })
1431 @Retention(RetentionPolicy.SOURCE)
1432 public @interface AutofillFlags {}
1433
1434 /**
1435 * Flag requesting you to add views that are marked as not important for autofill
1436 * (see {@link #setImportantForAutofill(int)}) to a {@link ViewStructure}.
1437 */
1438 public static final int AUTOFILL_FLAG_INCLUDE_NOT_IMPORTANT_VIEWS = 0x1;
1439
1440 /** @hide */
1441 @IntDef(prefix = { "IMPORTANT_FOR_CONTENT_CAPTURE_" }, value = {
1442 IMPORTANT_FOR_CONTENT_CAPTURE_AUTO,
1443 IMPORTANT_FOR_CONTENT_CAPTURE_YES,
1444 IMPORTANT_FOR_CONTENT_CAPTURE_NO,
1445 IMPORTANT_FOR_CONTENT_CAPTURE_YES_EXCLUDE_DESCENDANTS,
1446 IMPORTANT_FOR_CONTENT_CAPTURE_NO_EXCLUDE_DESCENDANTS
1447 })
1448 @Retention(RetentionPolicy.SOURCE)
1449 public @interface ContentCaptureImportance {}
1450
1451 /**
1452 * Automatically determine whether a view is important for content capture.
1453 *
1454 * @see #isImportantForContentCapture()
1455 * @see #setImportantForContentCapture(int)
1456 */
1457 public static final int IMPORTANT_FOR_CONTENT_CAPTURE_AUTO = 0x0;
1458
1459 /**
1460 * The view is important for content capture, and its children (if any) will be traversed.
1461 *
1462 * @see #isImportantForContentCapture()
1463 * @see #setImportantForContentCapture(int)
1464 */
1465 public static final int IMPORTANT_FOR_CONTENT_CAPTURE_YES = 0x1;
1466
1467 /**
1468 * The view is not important for content capture, but its children (if any) will be traversed.
1469 *
1470 * @see #isImportantForContentCapture()
1471 * @see #setImportantForContentCapture(int)
1472 */
1473 public static final int IMPORTANT_FOR_CONTENT_CAPTURE_NO = 0x2;
1474
1475 /**
1476 * The view is important for content capture, but its children (if any) will not be traversed.
1477 *
1478 * @see #isImportantForContentCapture()
1479 * @see #setImportantForContentCapture(int)
1480 */
1481 public static final int IMPORTANT_FOR_CONTENT_CAPTURE_YES_EXCLUDE_DESCENDANTS = 0x4;
1482
1483 /**
1484 * The view is not important for content capture, and its children (if any) will not be
1485 * traversed.
1486 *
1487 * @see #isImportantForContentCapture()
1488 * @see #setImportantForContentCapture(int)
1489 */
1490 public static final int IMPORTANT_FOR_CONTENT_CAPTURE_NO_EXCLUDE_DESCENDANTS = 0x8;
1491
1492 /** {@hide} */
1493 @IntDef(flag = true, prefix = {"SCROLL_CAPTURE_HINT_"},
1494 value = {
1495 SCROLL_CAPTURE_HINT_AUTO,
1496 SCROLL_CAPTURE_HINT_EXCLUDE,
1497 SCROLL_CAPTURE_HINT_INCLUDE,
1498 SCROLL_CAPTURE_HINT_EXCLUDE_DESCENDANTS
1499 })
1500 @Retention(RetentionPolicy.SOURCE)
1501 public @interface ScrollCaptureHint {}
1502
1503 /**
1504 * The content of this view will be considered for scroll capture if scrolling is possible.
1505 *
1506 * @see #getScrollCaptureHint()
1507 * @see #setScrollCaptureHint(int)
1508 */
1509 public static final int SCROLL_CAPTURE_HINT_AUTO = 0;
1510
1511 /**
1512 * Explicitly exclude this view as a potential scroll capture target. The system will not
1513 * consider it. Mutually exclusive with {@link #SCROLL_CAPTURE_HINT_INCLUDE}, which this flag
1514 * takes precedence over.
1515 *
1516 * @see #getScrollCaptureHint()
1517 * @see #setScrollCaptureHint(int)
1518 */
1519 public static final int SCROLL_CAPTURE_HINT_EXCLUDE = 0x1;
1520
1521 /**
1522 * Explicitly include this view as a potential scroll capture target. When locating a scroll
1523 * capture target, this view will be prioritized before others without this flag. Mutually
1524 * exclusive with {@link #SCROLL_CAPTURE_HINT_EXCLUDE}, which takes precedence.
1525 *
1526 * @see #getScrollCaptureHint()
1527 * @see #setScrollCaptureHint(int)
1528 */
1529 public static final int SCROLL_CAPTURE_HINT_INCLUDE = 0x2;
1530
1531 /**
1532 * Explicitly exclude all children of this view as potential scroll capture targets. This view
1533 * is unaffected. Note: Excluded children are not considered, regardless of {@link
1534 * #SCROLL_CAPTURE_HINT_INCLUDE}.
1535 *
1536 * @see #getScrollCaptureHint()
1537 * @see #setScrollCaptureHint(int)
1538 */
1539 public static final int SCROLL_CAPTURE_HINT_EXCLUDE_DESCENDANTS = 0x4;
1540
1541 /**
1542 * This view is enabled. Interpretation varies by subclass.
1543 * Use with ENABLED_MASK when calling setFlags.
1544 * {@hide}
1545 */
1546 static final int ENABLED = 0x00000000;
1547
1548 /**
1549 * This view is disabled. Interpretation varies by subclass.
1550 * Use with ENABLED_MASK when calling setFlags.
1551 * {@hide}
1552 */
1553 static final int DISABLED = 0x00000020;
1554
1555 /**
1556 * Mask for use with setFlags indicating bits used for indicating whether
1557 * this view is enabled
1558 * {@hide}
1559 */
1560 static final int ENABLED_MASK = 0x00000020;
1561
1562 /**
1563 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
1564 * called and further optimizations will be performed. It is okay to have
1565 * this flag set and a background. Use with DRAW_MASK when calling setFlags.
1566 * {@hide}
1567 */
1568 static final int WILL_NOT_DRAW = 0x00000080;
1569
1570 /**
1571 * Mask for use with setFlags indicating bits used for indicating whether
1572 * this view is will draw
1573 * {@hide}
1574 */
1575 static final int DRAW_MASK = 0x00000080;
1576
1577 /**
1578 * <p>This view doesn't show scrollbars.</p>
1579 * {@hide}
1580 */
1581 static final int SCROLLBARS_NONE = 0x00000000;
1582
1583 /**
1584 * <p>This view shows horizontal scrollbars.</p>
1585 * {@hide}
1586 */
1587 static final int SCROLLBARS_HORIZONTAL = 0x00000100;
1588
1589 /**
1590 * <p>This view shows vertical scrollbars.</p>
1591 * {@hide}
1592 */
1593 static final int SCROLLBARS_VERTICAL = 0x00000200;
1594
1595 /**
1596 * <p>Mask for use with setFlags indicating bits used for indicating which
1597 * scrollbars are enabled.</p>
1598 * {@hide}
1599 */
1600 static final int SCROLLBARS_MASK = 0x00000300;
1601
1602 /**
1603 * Indicates that the view should filter touches when its window is obscured.
1604 * Refer to the class comments for more information about this security feature.
1605 * {@hide}
1606 */
1607 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
1608
1609 /**
1610 * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
1611 * that they are optional and should be skipped if the window has
1612 * requested system UI flags that ignore those insets for layout.
1613 * <p>
1614 * This is only used for support library as of Android R. The framework now uses
1615 * {@link #PFLAG4_FRAMEWORK_OPTIONAL_FITS_SYSTEM_WINDOWS} such that it can skip the legacy
1616 * insets path that loses insets information.
1617 */
1618 static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
1619
1620 /**
1621 * <p>This view doesn't show fading edges.</p>
1622 * {@hide}
1623 */
1624 static final int FADING_EDGE_NONE = 0x00000000;
1625
1626 /**
1627 * <p>This view shows horizontal fading edges.</p>
1628 * {@hide}
1629 */
1630 static final int FADING_EDGE_HORIZONTAL = 0x00001000;
1631
1632 /**
1633 * <p>This view shows vertical fading edges.</p>
1634 * {@hide}
1635 */
1636 static final int FADING_EDGE_VERTICAL = 0x00002000;
1637
1638 /**
1639 * <p>Mask for use with setFlags indicating bits used for indicating which
1640 * fading edges are enabled.</p>
1641 * {@hide}
1642 */
1643 static final int FADING_EDGE_MASK = 0x00003000;
1644
1645 /**
1646 * <p>Indicates this view can be clicked. When clickable, a View reacts
1647 * to clicks by notifying the OnClickListener.<p>
1648 * {@hide}
1649 */
1650 static final int CLICKABLE = 0x00004000;
1651
1652 /**
1653 * <p>Indicates this view is caching its drawing into a bitmap.</p>
1654 * {@hide}
1655 */
1656 static final int DRAWING_CACHE_ENABLED = 0x00008000;
1657
1658 /**
1659 * <p>Indicates that no icicle should be saved for this view.<p>
1660 * {@hide}
1661 */
1662 static final int SAVE_DISABLED = 0x000010000;
1663
1664 /**
1665 * <p>Mask for use with setFlags indicating bits used for the saveEnabled
1666 * property.</p>
1667 * {@hide}
1668 */
1669 static final int SAVE_DISABLED_MASK = 0x000010000;
1670
1671 /**
1672 * <p>Indicates that no drawing cache should ever be created for this view.<p>
1673 * {@hide}
1674 */
1675 static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
1676
1677 /**
1678 * <p>Indicates this view can take / keep focus when int touch mode.</p>
1679 * {@hide}
1680 */
1681 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
1682
1683 /** @hide */
1684 @Retention(RetentionPolicy.SOURCE)
1685 @IntDef(prefix = { "DRAWING_CACHE_QUALITY_" }, value = {
1686 DRAWING_CACHE_QUALITY_LOW,
1687 DRAWING_CACHE_QUALITY_HIGH,
1688 DRAWING_CACHE_QUALITY_AUTO
1689 })
1690 public @interface DrawingCacheQuality {}
1691
1692 /**
1693 * <p>Enables low quality mode for the drawing cache.</p>
1694 *
1695 * @deprecated The view drawing cache was largely made obsolete with the introduction of
1696 * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
1697 * layers are largely unnecessary and can easily result in a net loss in performance due to the
1698 * cost of creating and updating the layer. In the rare cases where caching layers are useful,
1699 * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
1700 * rendering. For software-rendered snapshots of a small part of the View hierarchy or
1701 * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
1702 * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
1703 * software-rendered usages are discouraged and have compatibility issues with hardware-only
1704 * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
1705 * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
1706 * reports or unit testing the {@link PixelCopy} API is recommended.
1707 */
1708 @Deprecated
1709 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
1710
1711 /**
1712 * <p>Enables high quality mode for the drawing cache.</p>
1713 *
1714 * @deprecated The view drawing cache was largely made obsolete with the introduction of
1715 * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
1716 * layers are largely unnecessary and can easily result in a net loss in performance due to the
1717 * cost of creating and updating the layer. In the rare cases where caching layers are useful,
1718 * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
1719 * rendering. For software-rendered snapshots of a small part of the View hierarchy or
1720 * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
1721 * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
1722 * software-rendered usages are discouraged and have compatibility issues with hardware-only
1723 * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
1724 * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
1725 * reports or unit testing the {@link PixelCopy} API is recommended.
1726 */
1727 @Deprecated
1728 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
1729
1730 /**
1731 * <p>Enables automatic quality mode for the drawing cache.</p>
1732 *
1733 * @deprecated The view drawing cache was largely made obsolete with the introduction of
1734 * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
1735 * layers are largely unnecessary and can easily result in a net loss in performance due to the
1736 * cost of creating and updating the layer. In the rare cases where caching layers are useful,
1737 * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
1738 * rendering. For software-rendered snapshots of a small part of the View hierarchy or
1739 * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
1740 * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
1741 * software-rendered usages are discouraged and have compatibility issues with hardware-only
1742 * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
1743 * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
1744 * reports or unit testing the {@link PixelCopy} API is recommended.
1745 */
1746 @Deprecated
1747 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
1748
1749 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
1750 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
1751 };
1752
1753 /**
1754 * <p>Mask for use with setFlags indicating bits used for the cache
1755 * quality property.</p>
1756 * {@hide}
1757 */
1758 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
1759
1760 /**
1761 * <p>
1762 * Indicates this view can be long clicked. When long clickable, a View
1763 * reacts to long clicks by notifying the OnLongClickListener or showing a
1764 * context menu.
1765 * </p>
1766 * {@hide}
1767 */
1768 static final int LONG_CLICKABLE = 0x00200000;
1769
1770 /**
1771 * <p>Indicates that this view gets its drawable states from its direct parent
1772 * and ignores its original internal states.</p>
1773 *
1774 * @hide
1775 */
1776 static final int DUPLICATE_PARENT_STATE = 0x00400000;
1777
1778 /**
1779 * <p>
1780 * Indicates this view can be context clicked. When context clickable, a View reacts to a
1781 * context click (e.g. a primary stylus button press or right mouse click) by notifying the
1782 * OnContextClickListener.
1783 * </p>
1784 * {@hide}
1785 */
1786 static final int CONTEXT_CLICKABLE = 0x00800000;
1787
1788 /** @hide */
1789 @IntDef(prefix = { "SCROLLBARS_" }, value = {
1790 SCROLLBARS_INSIDE_OVERLAY,
1791 SCROLLBARS_INSIDE_INSET,
1792 SCROLLBARS_OUTSIDE_OVERLAY,
1793 SCROLLBARS_OUTSIDE_INSET
1794 })
1795 @Retention(RetentionPolicy.SOURCE)
1796 public @interface ScrollBarStyle {}
1797
1798 /**
1799 * The scrollbar style to display the scrollbars inside the content area,
1800 * without increasing the padding. The scrollbars will be overlaid with
1801 * translucency on the view's content.
1802 */
1803 public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
1804
1805 /**
1806 * The scrollbar style to display the scrollbars inside the padded area,
1807 * increasing the padding of the view. The scrollbars will not overlap the
1808 * content area of the view.
1809 */
1810 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
1811
1812 /**
1813 * The scrollbar style to display the scrollbars at the edge of the view,
1814 * without increasing the padding. The scrollbars will be overlaid with
1815 * translucency.
1816 */
1817 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
1818
1819 /**
1820 * The scrollbar style to display the scrollbars at the edge of the view,
1821 * increasing the padding of the view. The scrollbars will only overlap the
1822 * background, if any.
1823 */
1824 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
1825
1826 /**
1827 * Mask to check if the scrollbar style is overlay or inset.
1828 * {@hide}
1829 */
1830 static final int SCROLLBARS_INSET_MASK = 0x01000000;
1831
1832 /**
1833 * Mask to check if the scrollbar style is inside or outside.
1834 * {@hide}
1835 */
1836 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
1837
1838 /**
1839 * Mask for scrollbar style.
1840 * {@hide}
1841 */
1842 static final int SCROLLBARS_STYLE_MASK = 0x03000000;
1843
1844 /**
1845 * View flag indicating that the screen should remain on while the
1846 * window containing this view is visible to the user. This effectively
1847 * takes care of automatically setting the WindowManager's
1848 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
1849 */
1850 public static final int KEEP_SCREEN_ON = 0x04000000;
1851
1852 /**
1853 * View flag indicating whether this view should have sound effects enabled
1854 * for events such as clicking and touching.
1855 */
1856 public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
1857
1858 /**
1859 * View flag indicating whether this view should have haptic feedback
1860 * enabled for events such as long presses.
1861 */
1862 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
1863
1864 /**
1865 * <p>Indicates that the view hierarchy should stop saving state when
1866 * it reaches this view. If state saving is initiated immediately at
1867 * the view, it will be allowed.
1868 * {@hide}
1869 */
1870 static final int PARENT_SAVE_DISABLED = 0x20000000;
1871
1872 /**
1873 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1874 * {@hide}
1875 */
1876 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1877
1878 private static Paint sDebugPaint;
1879
1880 /**
1881 * <p>Indicates this view can display a tooltip on hover or long press.</p>
1882 * {@hide}
1883 */
1884 static final int TOOLTIP = 0x40000000;
1885
1886 /** @hide */
1887 @IntDef(flag = true, prefix = { "FOCUSABLES_" }, value = {
1888 FOCUSABLES_ALL,
1889 FOCUSABLES_TOUCH_MODE
1890 })
1891 @Retention(RetentionPolicy.SOURCE)
1892 public @interface FocusableMode {}
1893
1894 /**
1895 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1896 * should add all focusable Views regardless if they are focusable in touch mode.
1897 */
1898 public static final int FOCUSABLES_ALL = 0x00000000;
1899
1900 /**
1901 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1902 * should add only Views focusable in touch mode.
1903 */
1904 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1905
1906 /** @hide */
1907 @IntDef(prefix = { "FOCUS_" }, value = {
1908 FOCUS_BACKWARD,
1909 FOCUS_FORWARD,
1910 FOCUS_LEFT,
1911 FOCUS_UP,
1912 FOCUS_RIGHT,
1913 FOCUS_DOWN
1914 })
1915 @Retention(RetentionPolicy.SOURCE)
1916 public @interface FocusDirection {}
1917
1918 /** @hide */
1919 @IntDef(prefix = { "FOCUS_" }, value = {
1920 FOCUS_LEFT,
1921 FOCUS_UP,
1922 FOCUS_RIGHT,
1923 FOCUS_DOWN
1924 })
1925 @Retention(RetentionPolicy.SOURCE)
1926 public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward
1927
1928 /**
1929 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1930 * item.
1931 */
1932 public static final int FOCUS_BACKWARD = 0x00000001;
1933
1934 /**
1935 * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1936 * item.
1937 */
1938 public static final int FOCUS_FORWARD = 0x00000002;
1939
1940 /**
1941 * Use with {@link #focusSearch(int)}. Move focus to the left.
1942 */
1943 public static final int FOCUS_LEFT = 0x00000011;
1944
1945 /**
1946 * Use with {@link #focusSearch(int)}. Move focus up.
1947 */
1948 public static final int FOCUS_UP = 0x00000021;
1949
1950 /**
1951 * Use with {@link #focusSearch(int)}. Move focus to the right.
1952 */
1953 public static final int FOCUS_RIGHT = 0x00000042;
1954
1955 /**
1956 * Use with {@link #focusSearch(int)}. Move focus down.
1957 */
1958 public static final int FOCUS_DOWN = 0x00000082;
1959
1960 /**
1961 * Bits of {@link #getMeasuredWidthAndState()} and
1962 * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1963 */
1964 public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1965
1966 /**
1967 * Bits of {@link #getMeasuredWidthAndState()} and
1968 * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1969 */
1970 public static final int MEASURED_STATE_MASK = 0xff000000;
1971
1972 /**
1973 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1974 * for functions that combine both width and height into a single int,
1975 * such as {@link #getMeasuredState()} and the childState argument of
1976 * {@link #resolveSizeAndState(int, int, int)}.
1977 */
1978 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1979
1980 /**
1981 * Bit of {@link #getMeasuredWidthAndState()} and
1982 * {@link #getMeasuredWidthAndState()} that indicates the measured size
1983 * is smaller that the space the view would like to have.
1984 */
1985 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1986
1987 /**
1988 * Base View state sets
1989 */
1990 // Singles
1991 /**
1992 * Indicates the view has no states set. States are used with
1993 * {@link android.graphics.drawable.Drawable} to change the drawing of the
1994 * view depending on its state.
1995 *
1996 * @see android.graphics.drawable.Drawable
1997 * @see #getDrawableState()
1998 */
1999 protected static final int[] EMPTY_STATE_SET;
2000 /**
2001 * Indicates the view is enabled. States are used with
2002 * {@link android.graphics.drawable.Drawable} to change the drawing of the
2003 * view depending on its state.
2004 *
2005 * @see android.graphics.drawable.Drawable
2006 * @see #getDrawableState()
2007 */
2008 protected static final int[] ENABLED_STATE_SET;
2009 /**
2010 * Indicates the view is focused. States are used with
2011 * {@link android.graphics.drawable.Drawable} to change the drawing of the
2012 * view depending on its state.
2013 *
2014 * @see android.graphics.drawable.Drawable
2015 * @see #getDrawableState()
2016 */
2017 protected static final int[] FOCUSED_STATE_SET;
2018 /**
2019 * Indicates the view is selected. States are used with
2020 * {@link android.graphics.drawable.Drawable} to change the drawing of the
2021 * view depending on its state.
2022 *
2023 * @see android.graphics.drawable.Drawable
2024 * @see #getDrawableState()
2025 */
2026 protected static final int[] SELECTED_STATE_SET;
2027 /**
2028 * Indicates the view is pressed. States are used with
2029 * {@link android.graphics.drawable.Drawable} to change the drawing of the
2030 * view depending on its state.
2031 *
2032 * @see android.graphics.drawable.Drawable
2033 * @see #getDrawableState()
2034 */
2035 protected static final int[] PRESSED_STATE_SET;
2036 /**
2037 * Indicates the view's window has focus. States are used with
2038 * {@link android.graphics.drawable.Drawable} to change the drawing of the
2039 * view depending on its state.
2040 *
2041 * @see android.graphics.drawable.Drawable
2042 * @see #getDrawableState()
2043 */
2044 protected static final int[] WINDOW_FOCUSED_STATE_SET;
2045 // Doubles
2046 /**
2047 * Indicates the view is enabled and has the focus.
2048 *
2049 * @see #ENABLED_STATE_SET
2050 * @see #FOCUSED_STATE_SET
2051 */
2052 protected static final int[] ENABLED_FOCUSED_STATE_SET;
2053 /**
2054 * Indicates the view is enabled and selected.
2055 *
2056 * @see #ENABLED_STATE_SET
2057 * @see #SELECTED_STATE_SET
2058 */
2059 protected static final int[] ENABLED_SELECTED_STATE_SET;
2060 /**
2061 * Indicates the view is enabled and that its window has focus.
2062 *
2063 * @see #ENABLED_STATE_SET
2064 * @see #WINDOW_FOCUSED_STATE_SET
2065 */
2066 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
2067 /**
2068 * Indicates the view is focused and selected.
2069 *
2070 * @see #FOCUSED_STATE_SET
2071 * @see #SELECTED_STATE_SET
2072 */
2073 protected static final int[] FOCUSED_SELECTED_STATE_SET;
2074 /**
2075 * Indicates the view has the focus and that its window has the focus.
2076 *
2077 * @see #FOCUSED_STATE_SET
2078 * @see #WINDOW_FOCUSED_STATE_SET
2079 */
2080 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
2081 /**
2082 * Indicates the view is selected and that its window has the focus.
2083 *
2084 * @see #SELECTED_STATE_SET
2085 * @see #WINDOW_FOCUSED_STATE_SET
2086 */
2087 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
2088 // Triples
2089 /**
2090 * Indicates the view is enabled, focused and selected.
2091 *
2092 * @see #ENABLED_STATE_SET
2093 * @see #FOCUSED_STATE_SET
2094 * @see #SELECTED_STATE_SET
2095 */
2096 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
2097 /**
2098 * Indicates the view is enabled, focused and its window has the focus.
2099 *
2100 * @see #ENABLED_STATE_SET
2101 * @see #FOCUSED_STATE_SET
2102 * @see #WINDOW_FOCUSED_STATE_SET
2103 */
2104 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
2105 /**
2106 * Indicates the view is enabled, selected and its window has the focus.
2107 *
2108 * @see #ENABLED_STATE_SET
2109 * @see #SELECTED_STATE_SET
2110 * @see #WINDOW_FOCUSED_STATE_SET
2111 */
2112 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
2113 /**
2114 * Indicates the view is focused, selected and its window has the focus.
2115 *
2116 * @see #FOCUSED_STATE_SET
2117 * @see #SELECTED_STATE_SET
2118 * @see #WINDOW_FOCUSED_STATE_SET
2119 */
2120 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
2121 /**
2122 * Indicates the view is enabled, focused, selected and its window
2123 * has the focus.
2124 *
2125 * @see #ENABLED_STATE_SET
2126 * @see #FOCUSED_STATE_SET
2127 * @see #SELECTED_STATE_SET
2128 * @see #WINDOW_FOCUSED_STATE_SET
2129 */
2130 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
2131 /**
2132 * Indicates the view is pressed and its window has the focus.
2133 *
2134 * @see #PRESSED_STATE_SET
2135 * @see #WINDOW_FOCUSED_STATE_SET
2136 */
2137 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
2138 /**
2139 * Indicates the view is pressed and selected.
2140 *
2141 * @see #PRESSED_STATE_SET
2142 * @see #SELECTED_STATE_SET
2143 */
2144 protected static final int[] PRESSED_SELECTED_STATE_SET;
2145 /**
2146 * Indicates the view is pressed, selected and its window has the focus.
2147 *
2148 * @see #PRESSED_STATE_SET
2149 * @see #SELECTED_STATE_SET
2150 * @see #WINDOW_FOCUSED_STATE_SET
2151 */
2152 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
2153 /**
2154 * Indicates the view is pressed and focused.
2155 *
2156 * @see #PRESSED_STATE_SET
2157 * @see #FOCUSED_STATE_SET
2158 */
2159 protected static final int[] PRESSED_FOCUSED_STATE_SET;
2160 /**
2161 * Indicates the view is pressed, focused and its window has the focus.
2162 *
2163 * @see #PRESSED_STATE_SET
2164 * @see #FOCUSED_STATE_SET
2165 * @see #WINDOW_FOCUSED_STATE_SET
2166 */
2167 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
2168 /**
2169 * Indicates the view is pressed, focused and selected.
2170 *
2171 * @see #PRESSED_STATE_SET
2172 * @see #SELECTED_STATE_SET
2173 * @see #FOCUSED_STATE_SET
2174 */
2175 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
2176 /**
2177 * Indicates the view is pressed, focused, selected and its window has the focus.
2178 *
2179 * @see #PRESSED_STATE_SET
2180 * @see #FOCUSED_STATE_SET
2181 * @see #SELECTED_STATE_SET
2182 * @see #WINDOW_FOCUSED_STATE_SET
2183 */
2184 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
2185 /**
2186 * Indicates the view is pressed and enabled.
2187 *
2188 * @see #PRESSED_STATE_SET
2189 * @see #ENABLED_STATE_SET
2190 */
2191 protected static final int[] PRESSED_ENABLED_STATE_SET;
2192 /**
2193 * Indicates the view is pressed, enabled and its window has the focus.
2194 *
2195 * @see #PRESSED_STATE_SET
2196 * @see #ENABLED_STATE_SET
2197 * @see #WINDOW_FOCUSED_STATE_SET
2198 */
2199 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
2200 /**
2201 * Indicates the view is pressed, enabled and selected.
2202 *
2203 * @see #PRESSED_STATE_SET
2204 * @see #ENABLED_STATE_SET
2205 * @see #SELECTED_STATE_SET
2206 */
2207 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
2208 /**
2209 * Indicates the view is pressed, enabled, selected and its window has the
2210 * focus.
2211 *
2212 * @see #PRESSED_STATE_SET
2213 * @see #ENABLED_STATE_SET
2214 * @see #SELECTED_STATE_SET
2215 * @see #WINDOW_FOCUSED_STATE_SET
2216 */
2217 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
2218 /**
2219 * Indicates the view is pressed, enabled and focused.
2220 *
2221 * @see #PRESSED_STATE_SET
2222 * @see #ENABLED_STATE_SET
2223 * @see #FOCUSED_STATE_SET
2224 */
2225 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
2226 /**
2227 * Indicates the view is pressed, enabled, focused and its window has the
2228 * focus.
2229 *
2230 * @see #PRESSED_STATE_SET
2231 * @see #ENABLED_STATE_SET
2232 * @see #FOCUSED_STATE_SET
2233 * @see #WINDOW_FOCUSED_STATE_SET
2234 */
2235 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
2236 /**
2237 * Indicates the view is pressed, enabled, focused and selected.
2238 *
2239 * @see #PRESSED_STATE_SET
2240 * @see #ENABLED_STATE_SET
2241 * @see #SELECTED_STATE_SET
2242 * @see #FOCUSED_STATE_SET
2243 */
2244 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
2245 /**
2246 * Indicates the view is pressed, enabled, focused, selected and its window
2247 * has the focus.
2248 *
2249 * @see #PRESSED_STATE_SET
2250 * @see #ENABLED_STATE_SET
2251 * @see #SELECTED_STATE_SET
2252 * @see #FOCUSED_STATE_SET
2253 * @see #WINDOW_FOCUSED_STATE_SET
2254 */
2255 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
2256
2257 static {
2258 EMPTY_STATE_SET = StateSet.get(0);
2259
2260 WINDOW_FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_WINDOW_FOCUSED);
2261
2262 SELECTED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_SELECTED);
2263 SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
2264 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED);
2265
2266 FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_FOCUSED);
2267 FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
2268 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED);
2269 FOCUSED_SELECTED_STATE_SET = StateSet.get(
2270 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED);
2271 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
2272 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
2273 | StateSet.VIEW_STATE_FOCUSED);
2274
2275 ENABLED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_ENABLED);
2276 ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
2277 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED);
2278 ENABLED_SELECTED_STATE_SET = StateSet.get(
2279 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED);
2280 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
2281 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
2282 | StateSet.VIEW_STATE_ENABLED);
2283 ENABLED_FOCUSED_STATE_SET = StateSet.get(
2284 StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED);
2285 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
2286 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
2287 | StateSet.VIEW_STATE_ENABLED);
2288 ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
2289 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
2290 | StateSet.VIEW_STATE_ENABLED);
2291 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
2292 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
2293 | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED);
2294
2295 PRESSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_PRESSED);
2296 PRESSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
2297 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_PRESSED);
2298 PRESSED_SELECTED_STATE_SET = StateSet.get(
2299 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_PRESSED);
2300 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
2301 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
2302 | StateSet.VIEW_STATE_PRESSED);
2303 PRESSED_FOCUSED_STATE_SET = StateSet.get(
2304 StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED);
2305 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
2306 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
2307 | StateSet.VIEW_STATE_PRESSED);
2308 PRESSED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
2309 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
2310 | StateSet.VIEW_STATE_PRESSED);
2311 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
2312 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
2313 | StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED);
2314 PRESSED_ENABLED_STATE_SET = StateSet.get(
2315 StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
2316 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
2317 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED
2318 | StateSet.VIEW_STATE_PRESSED);
2319 PRESSED_ENABLED_SELECTED_STATE_SET = StateSet.get(
2320 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED
2321 | StateSet.VIEW_STATE_PRESSED);
2322 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
2323 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
2324 | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
2325 PRESSED_ENABLED_FOCUSED_STATE_SET = StateSet.get(
2326 StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED
2327 | StateSet.VIEW_STATE_PRESSED);
2328 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
2329 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
2330 | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
2331 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
2332 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
2333 | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
2334 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
2335 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
2336 | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED
2337 | StateSet.VIEW_STATE_PRESSED);
2338 }
2339
2340 /**
2341 * Accessibility event types that are dispatched for text population.
2342 */
2343 private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
2344 AccessibilityEvent.TYPE_VIEW_CLICKED
2345 | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
2346 | AccessibilityEvent.TYPE_VIEW_SELECTED
2347 | AccessibilityEvent.TYPE_VIEW_FOCUSED
2348 | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
2349 | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
2350 | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
2351 | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
2352 | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
2353 | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
2354 | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
2355
2356 static final int DEBUG_CORNERS_COLOR = Color.rgb(63, 127, 255);
2357
2358 static final int DEBUG_CORNERS_SIZE_DIP = 8;
2359
2360 /**
2361 * Temporary Rect currently for use in setBackground(). This will probably
2362 * be extended in the future to hold our own class with more than just
2363 * a Rect. :)
2364 */
2365 static final ThreadLocal<Rect> sThreadLocal = ThreadLocal.withInitial(Rect::new);
2366
2367 /**
2368 * Map used to store views' tags.
2369 */
2370 @UnsupportedAppUsage
2371 private SparseArray<Object> mKeyedTags;
2372
2373 /**
2374 * The next available accessibility id.
2375 */
2376 private static int sNextAccessibilityViewId;
2377
2378 /**
2379 * The animation currently associated with this view.
2380 * @hide
2381 */
2382 protected Animation mCurrentAnimation = null;
2383
2384 /**
2385 * Width as measured during measure pass.
2386 * {@hide}
2387 */
2388 @ViewDebug.ExportedProperty(category = "measurement")
2389 @UnsupportedAppUsage
2390 int mMeasuredWidth;
2391
2392 /**
2393 * Height as measured during measure pass.
2394 * {@hide}
2395 */
2396 @ViewDebug.ExportedProperty(category = "measurement")
2397 @UnsupportedAppUsage
2398 int mMeasuredHeight;
2399
2400 /**
2401 * Flag to indicate that this view was marked INVALIDATED, or had its display list
2402 * invalidated, prior to the current drawing iteration. If true, the view must re-draw
2403 * its display list. This flag, used only when hw accelerated, allows us to clear the
2404 * flag while retaining this information until it's needed (at getDisplayList() time and
2405 * in drawChild(), when we decide to draw a view's children's display lists into our own).
2406 *
2407 * {@hide}
2408 */
2409 @UnsupportedAppUsage
2410 boolean mRecreateDisplayList = false;
2411
2412 /**
2413 * The view's identifier.
2414 * {@hide}
2415 *
2416 * @see #setId(int)
2417 * @see #getId()
2418 */
2419 @IdRes
2420 @ViewDebug.ExportedProperty(resolveId = true)
2421 int mID = NO_ID;
2422
2423 /** The ID of this view for autofill purposes.
2424 * <ul>
2425 * <li>== {@link #NO_ID}: ID has not been assigned yet
2426 * <li>&le; {@link #LAST_APP_AUTOFILL_ID}: View is not part of a activity. The ID is
2427 * unique in the process. This might change
2428 * over activity lifecycle events.
2429 * <li>&gt; {@link #LAST_APP_AUTOFILL_ID}: View is part of a activity. The ID is
2430 * unique in the activity. This stays the same
2431 * over activity lifecycle events.
2432 */
2433 private int mAutofillViewId = NO_ID;
2434
2435 // ID for accessibility purposes. This ID must be unique for every window
2436 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2437 private int mAccessibilityViewId = NO_ID;
2438
2439 private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
2440
2441 /**
2442 * The view's tag.
2443 * {@hide}
2444 *
2445 * @see #setTag(Object)
2446 * @see #getTag()
2447 */
2448 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2449 protected Object mTag = null;
2450
2451 /*
2452 * Masks for mPrivateFlags, as generated by dumpFlags():
2453 *
2454 * |-------|-------|-------|-------|
2455 * 1 PFLAG_WANTS_FOCUS
2456 * 1 PFLAG_FOCUSED
2457 * 1 PFLAG_SELECTED
2458 * 1 PFLAG_IS_ROOT_NAMESPACE
2459 * 1 PFLAG_HAS_BOUNDS
2460 * 1 PFLAG_DRAWN
2461 * 1 PFLAG_DRAW_ANIMATION
2462 * 1 PFLAG_SKIP_DRAW
2463 * 1 PFLAG_REQUEST_TRANSPARENT_REGIONS
2464 * 1 PFLAG_DRAWABLE_STATE_DIRTY
2465 * 1 PFLAG_MEASURED_DIMENSION_SET
2466 * 1 PFLAG_FORCE_LAYOUT
2467 * 1 PFLAG_LAYOUT_REQUIRED
2468 * 1 PFLAG_PRESSED
2469 * 1 PFLAG_DRAWING_CACHE_VALID
2470 * 1 PFLAG_ANIMATION_STARTED
2471 * 1 PFLAG_SAVE_STATE_CALLED
2472 * 1 PFLAG_ALPHA_SET
2473 * 1 PFLAG_SCROLL_CONTAINER
2474 * 1 PFLAG_SCROLL_CONTAINER_ADDED
2475 * 1 PFLAG_DIRTY
2476 * 1 PFLAG_DIRTY_MASK
2477 * 1 PFLAG_OPAQUE_BACKGROUND
2478 * 1 PFLAG_OPAQUE_SCROLLBARS
2479 * 11 PFLAG_OPAQUE_MASK
2480 * 1 PFLAG_PREPRESSED
2481 * 1 PFLAG_CANCEL_NEXT_UP_EVENT
2482 * 1 PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH
2483 * 1 PFLAG_HOVERED
2484 * 1 PFLAG_NOTIFY_AUTOFILL_MANAGER_ON_CLICK
2485 * 1 PFLAG_ACTIVATED
2486 * 1 PFLAG_INVALIDATED
2487 * |-------|-------|-------|-------|
2488 */
2489 /** {@hide} */
2490 static final int PFLAG_WANTS_FOCUS = 0x00000001;
2491 /** {@hide} */
2492 static final int PFLAG_FOCUSED = 0x00000002;
2493 /** {@hide} */
2494 static final int PFLAG_SELECTED = 0x00000004;
2495 /** {@hide} */
2496 static final int PFLAG_IS_ROOT_NAMESPACE = 0x00000008;
2497 /** {@hide} */
2498 static final int PFLAG_HAS_BOUNDS = 0x00000010;
2499 /** {@hide} */
2500 static final int PFLAG_DRAWN = 0x00000020;
2501 /**
2502 * When this flag is set, this view is running an animation on behalf of its
2503 * children and should therefore not cancel invalidate requests, even if they
2504 * lie outside of this view's bounds.
2505 *
2506 * {@hide}
2507 */
2508 static final int PFLAG_DRAW_ANIMATION = 0x00000040;
2509 /** {@hide} */
2510 static final int PFLAG_SKIP_DRAW = 0x00000080;
2511 /** {@hide} */
2512 static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
2513 /** {@hide} */
2514 static final int PFLAG_DRAWABLE_STATE_DIRTY = 0x00000400;
2515 /** {@hide} */
2516 static final int PFLAG_MEASURED_DIMENSION_SET = 0x00000800;
2517 /** {@hide} */
2518 static final int PFLAG_FORCE_LAYOUT = 0x00001000;
2519 /** {@hide} */
2520 static final int PFLAG_LAYOUT_REQUIRED = 0x00002000;
2521
2522 private static final int PFLAG_PRESSED = 0x00004000;
2523
2524 /** {@hide} */
2525 static final int PFLAG_DRAWING_CACHE_VALID = 0x00008000;
2526 /**
2527 * Flag used to indicate that this view should be drawn once more (and only once
2528 * more) after its animation has completed.
2529 * {@hide}
2530 */
2531 static final int PFLAG_ANIMATION_STARTED = 0x00010000;
2532
2533 private static final int PFLAG_SAVE_STATE_CALLED = 0x00020000;
2534
2535 /**
2536 * Indicates that the View returned true when onSetAlpha() was called and that
2537 * the alpha must be restored.
2538 * {@hide}
2539 */
2540 static final int PFLAG_ALPHA_SET = 0x00040000;
2541
2542 /**
2543 * Set by {@link #setScrollContainer(boolean)}.
2544 */
2545 static final int PFLAG_SCROLL_CONTAINER = 0x00080000;
2546
2547 /**
2548 * Set by {@link #setScrollContainer(boolean)}.
2549 */
2550 static final int PFLAG_SCROLL_CONTAINER_ADDED = 0x00100000;
2551
2552 /**
2553 * View flag indicating whether this view was invalidated (fully or partially.)
2554 *
2555 * @hide
2556 */
2557 static final int PFLAG_DIRTY = 0x00200000;
2558
2559 /**
2560 * Mask for {@link #PFLAG_DIRTY}.
2561 *
2562 * @hide
2563 */
2564 static final int PFLAG_DIRTY_MASK = 0x00200000;
2565
2566 /**
2567 * Indicates whether the background is opaque.
2568 *
2569 * @hide
2570 */
2571 static final int PFLAG_OPAQUE_BACKGROUND = 0x00800000;
2572
2573 /**
2574 * Indicates whether the scrollbars are opaque.
2575 *
2576 * @hide
2577 */
2578 static final int PFLAG_OPAQUE_SCROLLBARS = 0x01000000;
2579
2580 /**
2581 * Indicates whether the view is opaque.
2582 *
2583 * @hide
2584 */
2585 static final int PFLAG_OPAQUE_MASK = 0x01800000;
2586
2587 /**
2588 * Indicates a prepressed state;
2589 * the short time between ACTION_DOWN and recognizing
2590 * a 'real' press. Prepressed is used to recognize quick taps
2591 * even when they are shorter than ViewConfiguration.getTapTimeout().
2592 *
2593 * @hide
2594 */
2595 private static final int PFLAG_PREPRESSED = 0x02000000;
2596
2597 /**
2598 * Indicates whether the view is temporarily detached.
2599 *
2600 * @hide
2601 */
2602 static final int PFLAG_CANCEL_NEXT_UP_EVENT = 0x04000000;
2603
2604 /**
2605 * Indicates that we should awaken scroll bars once attached
2606 *
2607 * PLEASE NOTE: This flag is now unused as we now send onVisibilityChanged
2608 * during window attachment and it is no longer needed. Feel free to repurpose it.
2609 *
2610 * @hide
2611 */
2612 private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
2613
2614 /**
2615 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT.
2616 * @hide
2617 */
2618 private static final int PFLAG_HOVERED = 0x10000000;
2619
2620 /**
2621 * Flag set by {@link AutofillManager} if it needs to be notified when this view is clicked.
2622 */
2623 private static final int PFLAG_NOTIFY_AUTOFILL_MANAGER_ON_CLICK = 0x20000000;
2624
2625 /** {@hide} */
2626 static final int PFLAG_ACTIVATED = 0x40000000;
2627
2628 /**
2629 * Indicates that this view was specifically invalidated, not just dirtied because some
2630 * child view was invalidated. The flag is used to determine when we need to recreate
2631 * a view's display list (as opposed to just returning a reference to its existing
2632 * display list).
2633 *
2634 * @hide
2635 */
2636 static final int PFLAG_INVALIDATED = 0x80000000;
2637
2638 /* End of masks for mPrivateFlags */
2639
2640 /*
2641 * Masks for mPrivateFlags2, as generated by dumpFlags():
2642 *
2643 * |-------|-------|-------|-------|
2644 * 1 PFLAG2_DRAG_CAN_ACCEPT
2645 * 1 PFLAG2_DRAG_HOVERED
2646 * 11 PFLAG2_LAYOUT_DIRECTION_MASK
2647 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
2648 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED
2649 * 11 PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
2650 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[1]
2651 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[2]
2652 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[3]
2653 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[4]
2654 * 1 1 PFLAG2_TEXT_DIRECTION_FLAGS[5]
2655 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[6]
2656 * 111 PFLAG2_TEXT_DIRECTION_FLAGS[7]
2657 * 111 PFLAG2_TEXT_DIRECTION_MASK
2658 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED
2659 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
2660 * 111 PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
2661 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
2662 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
2663 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
2664 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
2665 * 1 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
2666 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
2667 * 111 PFLAG2_TEXT_ALIGNMENT_MASK
2668 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED
2669 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
2670 * 111 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
2671 * 111 PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
2672 * 11 PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK
2673 * 1 PFLAG2_ACCESSIBILITY_FOCUSED
2674 * 1 PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED
2675 * 1 PFLAG2_VIEW_QUICK_REJECTED
2676 * 1 PFLAG2_PADDING_RESOLVED
2677 * 1 PFLAG2_DRAWABLE_RESOLVED
2678 * 1 PFLAG2_HAS_TRANSIENT_STATE
2679 * |-------|-------|-------|-------|
2680 */
2681
2682 /**
2683 * Indicates that this view has reported that it can accept the current drag's content.
2684 * Cleared when the drag operation concludes.
2685 * @hide
2686 */
2687 static final int PFLAG2_DRAG_CAN_ACCEPT = 0x00000001;
2688
2689 /**
2690 * Indicates that this view is currently directly under the drag location in a
2691 * drag-and-drop operation involving content that it can accept. Cleared when
2692 * the drag exits the view, or when the drag operation concludes.
2693 * @hide
2694 */
2695 static final int PFLAG2_DRAG_HOVERED = 0x00000002;
2696
2697 /** @hide */
2698 @IntDef(prefix = { "LAYOUT_DIRECTION_" }, value = {
2699 LAYOUT_DIRECTION_LTR,
2700 LAYOUT_DIRECTION_RTL,
2701 LAYOUT_DIRECTION_INHERIT,
2702 LAYOUT_DIRECTION_LOCALE
2703 })
2704 @Retention(RetentionPolicy.SOURCE)
2705 // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection
2706 public @interface LayoutDir {}
2707
2708 /** @hide */
2709 @IntDef(prefix = { "LAYOUT_DIRECTION_" }, value = {
2710 LAYOUT_DIRECTION_LTR,
2711 LAYOUT_DIRECTION_RTL
2712 })
2713 @Retention(RetentionPolicy.SOURCE)
2714 public @interface ResolvedLayoutDir {}
2715
2716 /**
2717 * A flag to indicate that the layout direction of this view has not been defined yet.
2718 * @hide
2719 */
2720 public static final int LAYOUT_DIRECTION_UNDEFINED = LayoutDirection.UNDEFINED;
2721
2722 /**
2723 * Horizontal layout direction of this view is from Left to Right.
2724 * Use with {@link #setLayoutDirection}.
2725 */
2726 public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR;
2727
2728 /**
2729 * Horizontal layout direction of this view is from Right to Left.
2730 * Use with {@link #setLayoutDirection}.
2731 */
2732 public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL;
2733
2734 /**
2735 * Horizontal layout direction of this view is inherited from its parent.
2736 * Use with {@link #setLayoutDirection}.
2737 */
2738 public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT;
2739
2740 /**
2741 * Horizontal layout direction of this view is from deduced from the default language
2742 * script for the locale. Use with {@link #setLayoutDirection}.
2743 */
2744 public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE;
2745
2746 /**
2747 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2748 * @hide
2749 */
2750 static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
2751
2752 /**
2753 * Mask for use with private flags indicating bits used for horizontal layout direction.
2754 * @hide
2755 */
2756 static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2757
2758 /**
2759 * Indicates whether the view horizontal layout direction has been resolved and drawn to the
2760 * right-to-left direction.
2761 * @hide
2762 */
2763 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2764
2765 /**
2766 * Indicates whether the view horizontal layout direction has been resolved.
2767 * @hide
2768 */
2769 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2770
2771 /**
2772 * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
2773 * @hide
2774 */
2775 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
2776 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2777
2778 /*
2779 * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
2780 * flag value.
2781 * @hide
2782 */
2783 private static final int[] LAYOUT_DIRECTION_FLAGS = {
2784 LAYOUT_DIRECTION_LTR,
2785 LAYOUT_DIRECTION_RTL,
2786 LAYOUT_DIRECTION_INHERIT,
2787 LAYOUT_DIRECTION_LOCALE
2788 };
2789
2790 /**
2791 * Default horizontal layout direction.
2792 */
2793 private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
2794
2795 /**
2796 * Default horizontal layout direction.
2797 * @hide
2798 */
2799 static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
2800
2801 /**
2802 * Text direction is inherited through {@link ViewGroup}
2803 */
2804 public static final int TEXT_DIRECTION_INHERIT = 0;
2805
2806 /**
2807 * Text direction is using "first strong algorithm". The first strong directional character
2808 * determines the paragraph direction. If there is no strong directional character, the
2809 * paragraph direction is the view's resolved layout direction.
2810 */
2811 public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
2812
2813 /**
2814 * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
2815 * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
2816 * If there are neither, the paragraph direction is the view's resolved layout direction.
2817 */
2818 public static final int TEXT_DIRECTION_ANY_RTL = 2;
2819
2820 /**
2821 * Text direction is forced to LTR.
2822 */
2823 public static final int TEXT_DIRECTION_LTR = 3;
2824
2825 /**
2826 * Text direction is forced to RTL.
2827 */
2828 public static final int TEXT_DIRECTION_RTL = 4;
2829
2830 /**
2831 * Text direction is coming from the system Locale.
2832 */
2833 public static final int TEXT_DIRECTION_LOCALE = 5;
2834
2835 /**
2836 * Text direction is using "first strong algorithm". The first strong directional character
2837 * determines the paragraph direction. If there is no strong directional character, the
2838 * paragraph direction is LTR.
2839 */
2840 public static final int TEXT_DIRECTION_FIRST_STRONG_LTR = 6;
2841
2842 /**
2843 * Text direction is using "first strong algorithm". The first strong directional character
2844 * determines the paragraph direction. If there is no strong directional character, the
2845 * paragraph direction is RTL.
2846 */
2847 public static final int TEXT_DIRECTION_FIRST_STRONG_RTL = 7;
2848
2849 /**
2850 * Default text direction is inherited
2851 */
2852 private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
2853
2854 /**
2855 * Default resolved text direction
2856 * @hide
2857 */
2858 static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
2859
2860 /**
2861 * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
2862 * @hide
2863 */
2864 static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
2865
2866 /**
2867 * Mask for use with private flags indicating bits used for text direction.
2868 * @hide
2869 */
2870 static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
2871 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2872
2873 /**
2874 * Array of text direction flags for mapping attribute "textDirection" to correct
2875 * flag value.
2876 * @hide
2877 */
2878 private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
2879 TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2880 TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2881 TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2882 TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2883 TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2884 TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2885 TEXT_DIRECTION_FIRST_STRONG_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2886 TEXT_DIRECTION_FIRST_STRONG_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
2887 };
2888
2889 /**
2890 * Indicates whether the view text direction has been resolved.
2891 * @hide
2892 */
2893 static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
2894 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2895
2896 /**
2897 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2898 * @hide
2899 */
2900 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
2901
2902 /**
2903 * Mask for use with private flags indicating bits used for resolved text direction.
2904 * @hide
2905 */
2906 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
2907 << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2908
2909 /**
2910 * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
2911 * @hide
2912 */
2913 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
2914 TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2915
2916 /** @hide */
2917 @IntDef(prefix = { "TEXT_ALIGNMENT_" }, value = {
2918 TEXT_ALIGNMENT_INHERIT,
2919 TEXT_ALIGNMENT_GRAVITY,
2920 TEXT_ALIGNMENT_CENTER,
2921 TEXT_ALIGNMENT_TEXT_START,
2922 TEXT_ALIGNMENT_TEXT_END,
2923 TEXT_ALIGNMENT_VIEW_START,
2924 TEXT_ALIGNMENT_VIEW_END
2925 })
2926 @Retention(RetentionPolicy.SOURCE)
2927 public @interface TextAlignment {}
2928
2929 /**
2930 * Default text alignment. The text alignment of this View is inherited from its parent.
2931 * Use with {@link #setTextAlignment(int)}
2932 */
2933 public static final int TEXT_ALIGNMENT_INHERIT = 0;
2934
2935 /**
2936 * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
2937 * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph's text direction.
2938 *
2939 * Use with {@link #setTextAlignment(int)}
2940 */
2941 public static final int TEXT_ALIGNMENT_GRAVITY = 1;
2942
2943 /**
2944 * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2945 *
2946 * Use with {@link #setTextAlignment(int)}
2947 */
2948 public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2949
2950 /**
2951 * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2952 *
2953 * Use with {@link #setTextAlignment(int)}
2954 */
2955 public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2956
2957 /**
2958 * Center the paragraph, e.g. ALIGN_CENTER.
2959 *
2960 * Use with {@link #setTextAlignment(int)}
2961 */
2962 public static final int TEXT_ALIGNMENT_CENTER = 4;
2963
2964 /**
2965 * Align to the start of the view, which is ALIGN_LEFT if the view's resolved
2966 * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2967 *
2968 * Use with {@link #setTextAlignment(int)}
2969 */
2970 public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2971
2972 /**
2973 * Align to the end of the view, which is ALIGN_RIGHT if the view's resolved
2974 * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2975 *
2976 * Use with {@link #setTextAlignment(int)}
2977 */
2978 public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2979
2980 /**
2981 * Default text alignment is inherited
2982 */
2983 private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2984
2985 /**
2986 * Default resolved text alignment
2987 * @hide
2988 */
2989 static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2990
2991 /**
2992 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2993 * @hide
2994 */
2995 static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2996
2997 /**
2998 * Mask for use with private flags indicating bits used for text alignment.
2999 * @hide
3000 */
3001 static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
3002
3003 /**
3004 * Array of text direction flags for mapping attribute "textAlignment" to correct
3005 * flag value.
3006 * @hide
3007 */
3008 private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
3009 TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
3010 TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
3011 TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
3012 TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
3013 TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
3014 TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
3015 TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
3016 };
3017
3018 /**
3019 * Indicates whether the view text alignment has been resolved.
3020 * @hide
3021 */
3022 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
3023
3024 /**
3025 * Bit shift to get the resolved text alignment.
3026 * @hide
3027 */
3028 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
3029
3030 /**
3031 * Mask for use with private flags indicating bits used for text alignment.
3032 * @hide
3033 */
3034 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
3035 << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
3036
3037 /**
3038 * Indicates whether if the view text alignment has been resolved to gravity
3039 */
3040 private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
3041 TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
3042
3043 // Accessiblity constants for mPrivateFlags2
3044
3045 /**
3046 * Shift for the bits in {@link #mPrivateFlags2} related to the
3047 * "importantForAccessibility" attribute.
3048 */
3049 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
3050
3051 /**
3052 * Automatically determine whether a view is important for accessibility.
3053 */
3054 public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
3055
3056 /**
3057 * The view is important for accessibility.
3058 */
3059 public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
3060
3061 /**
3062 * The view is not important for accessibility.
3063 */
3064 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
3065
3066 /**
3067 * The view is not important for accessibility, nor are any of its
3068 * descendant views.
3069 */
3070 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004;
3071
3072 /**
3073 * The default whether the view is important for accessibility.
3074 */
3075 static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
3076
3077 /**
3078 * Mask for obtaining the bits which specify how to determine
3079 * whether a view is important for accessibility.
3080 */
3081 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
3082 | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO
3083 | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS)
3084 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
3085
3086 /**
3087 * Shift for the bits in {@link #mPrivateFlags2} related to the
3088 * "accessibilityLiveRegion" attribute.
3089 */
3090 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23;
3091
3092 /**
3093 * Live region mode specifying that accessibility services should not
3094 * automatically announce changes to this view. This is the default live
3095 * region mode for most views.
3096 * <p>
3097 * Use with {@link #setAccessibilityLiveRegion(int)}.
3098 */
3099 public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000;
3100
3101 /**
3102 * Live region mode specifying that accessibility services should announce
3103 * changes to this view.
3104 * <p>
3105 * Use with {@link #setAccessibilityLiveRegion(int)}.
3106 */
3107 public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001;
3108
3109 /**
3110 * Live region mode specifying that accessibility services should interrupt
3111 * ongoing speech to immediately announce changes to this view.
3112 * <p>
3113 * Use with {@link #setAccessibilityLiveRegion(int)}.
3114 */
3115 public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002;
3116
3117 /**
3118 * The default whether the view is important for accessibility.
3119 */
3120 static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE;
3121
3122 /**
3123 * Mask for obtaining the bits which specify a view's accessibility live
3124 * region mode.
3125 */
3126 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE
3127 | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE)
3128 << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
3129
3130 /**
3131 * Flag indicating whether a view has accessibility focus.
3132 */
3133 static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000;
3134
3135 /**
3136 * Flag whether the accessibility state of the subtree rooted at this view changed.
3137 */
3138 static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000;
3139
3140 /**
3141 * Flag indicating whether a view failed the quickReject() check in draw(). This condition
3142 * is used to check whether later changes to the view's transform should invalidate the
3143 * view to force the quickReject test to run again.
3144 */
3145 static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
3146
3147 /**
3148 * Flag indicating that start/end padding has been resolved into left/right padding
3149 * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
3150 * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
3151 * during measurement. In some special cases this is required such as when an adapter-based
3152 * view measures prospective children without attaching them to a window.
3153 */
3154 static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
3155
3156 /**
3157 * Flag indicating that the start/end drawables has been resolved into left/right ones.
3158 */
3159 static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
3160
3161 /**
3162 * Indicates that the view is tracking some sort of transient state
3163 * that the app should not need to be aware of, but that the framework
3164 * should take special care to preserve.
3165 */
3166 static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000;
3167
3168 /**
3169 * Group of bits indicating that RTL properties resolution is done.
3170 */
3171 static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
3172 PFLAG2_TEXT_DIRECTION_RESOLVED |
3173 PFLAG2_TEXT_ALIGNMENT_RESOLVED |
3174 PFLAG2_PADDING_RESOLVED |
3175 PFLAG2_DRAWABLE_RESOLVED;
3176
3177 // There are a couple of flags left in mPrivateFlags2
3178
3179 /* End of masks for mPrivateFlags2 */
3180
3181 /*
3182 * Masks for mPrivateFlags3, as generated by dumpFlags():
3183 *
3184 * |-------|-------|-------|-------|
3185 * 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM
3186 * 1 PFLAG3_VIEW_IS_ANIMATING_ALPHA
3187 * 1 PFLAG3_IS_LAID_OUT
3188 * 1 PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT
3189 * 1 PFLAG3_CALLED_SUPER
3190 * 1 PFLAG3_APPLYING_INSETS
3191 * 1 PFLAG3_FITTING_SYSTEM_WINDOWS
3192 * 1 PFLAG3_NESTED_SCROLLING_ENABLED
3193 * 1 PFLAG3_SCROLL_INDICATOR_TOP
3194 * 1 PFLAG3_SCROLL_INDICATOR_BOTTOM
3195 * 1 PFLAG3_SCROLL_INDICATOR_LEFT
3196 * 1 PFLAG3_SCROLL_INDICATOR_RIGHT
3197 * 1 PFLAG3_SCROLL_INDICATOR_START
3198 * 1 PFLAG3_SCROLL_INDICATOR_END
3199 * 1 PFLAG3_ASSIST_BLOCKED
3200 * 1 PFLAG3_CLUSTER
3201 * 1 PFLAG3_IS_AUTOFILLED
3202 * 1 PFLAG3_FINGER_DOWN
3203 * 1 PFLAG3_FOCUSED_BY_DEFAULT
3204 * 1111 PFLAG3_IMPORTANT_FOR_AUTOFILL
3205 * 1 PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE
3206 * 1 PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED
3207 * 1 PFLAG3_TEMPORARY_DETACH
3208 * 1 PFLAG3_NO_REVEAL_ON_FOCUS
3209 * 1 PFLAG3_NOTIFY_AUTOFILL_ENTER_ON_LAYOUT
3210 * 1 PFLAG3_SCREEN_READER_FOCUSABLE
3211 * 1 PFLAG3_AGGREGATED_VISIBLE
3212 * 1 PFLAG3_AUTOFILLID_EXPLICITLY_SET
3213 * 1 PFLAG3_ACCESSIBILITY_HEADING
3214 * |-------|-------|-------|-------|
3215 */
3216
3217 /**
3218 * Flag indicating that view has a transform animation set on it. This is used to track whether
3219 * an animation is cleared between successive frames, in order to tell the associated
3220 * DisplayList to clear its animation matrix.
3221 */
3222 static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
3223
3224 /**
3225 * Flag indicating that view has an alpha animation set on it. This is used to track whether an
3226 * animation is cleared between successive frames, in order to tell the associated
3227 * DisplayList to restore its alpha value.
3228 */
3229 static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
3230
3231 /**
3232 * Flag indicating that the view has been through at least one layout since it
3233 * was last attached to a window.
3234 */
3235 static final int PFLAG3_IS_LAID_OUT = 0x4;
3236
3237 /**
3238 * Flag indicating that a call to measure() was skipped and should be done
3239 * instead when layout() is invoked.
3240 */
3241 static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8;
3242
3243 /**
3244 * Flag indicating that an overridden method correctly called down to
3245 * the superclass implementation as required by the API spec.
3246 */
3247 static final int PFLAG3_CALLED_SUPER = 0x10;
3248
3249 /**
3250 * Flag indicating that we're in the process of applying window insets.
3251 */
3252 static final int PFLAG3_APPLYING_INSETS = 0x20;
3253
3254 /**
3255 * Flag indicating that we're in the process of fitting system windows using the old method.
3256 */
3257 static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40;
3258
3259 /**
3260 * Flag indicating that nested scrolling is enabled for this view.
3261 * The view will optionally cooperate with views up its parent chain to allow for
3262 * integrated nested scrolling along the same axis.
3263 */
3264 static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80;
3265
3266 /**
3267 * Flag indicating that the bottom scroll indicator should be displayed
3268 * when this view can scroll up.
3269 */
3270 static final int PFLAG3_SCROLL_INDICATOR_TOP = 0x0100;
3271
3272 /**
3273 * Flag indicating that the bottom scroll indicator should be displayed
3274 * when this view can scroll down.
3275 */
3276 static final int PFLAG3_SCROLL_INDICATOR_BOTTOM = 0x0200;
3277
3278 /**
3279 * Flag indicating that the left scroll indicator should be displayed
3280 * when this view can scroll left.
3281 */
3282 static final int PFLAG3_SCROLL_INDICATOR_LEFT = 0x0400;
3283
3284 /**
3285 * Flag indicating that the right scroll indicator should be displayed
3286 * when this view can scroll right.
3287 */
3288 static final int PFLAG3_SCROLL_INDICATOR_RIGHT = 0x0800;
3289
3290 /**
3291 * Flag indicating that the start scroll indicator should be displayed
3292 * when this view can scroll in the start direction.
3293 */
3294 static final int PFLAG3_SCROLL_INDICATOR_START = 0x1000;
3295
3296 /**
3297 * Flag indicating that the end scroll indicator should be displayed
3298 * when this view can scroll in the end direction.
3299 */
3300 static final int PFLAG3_SCROLL_INDICATOR_END = 0x2000;
3301
3302 static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
3303
3304 static final int SCROLL_INDICATORS_NONE = 0x0000;
3305
3306 /**
3307 * Mask for use with setFlags indicating bits used for indicating which
3308 * scroll indicators are enabled.
3309 */
3310 static final int SCROLL_INDICATORS_PFLAG3_MASK = PFLAG3_SCROLL_INDICATOR_TOP
3311 | PFLAG3_SCROLL_INDICATOR_BOTTOM | PFLAG3_SCROLL_INDICATOR_LEFT
3312 | PFLAG3_SCROLL_INDICATOR_RIGHT | PFLAG3_SCROLL_INDICATOR_START
3313 | PFLAG3_SCROLL_INDICATOR_END;
3314
3315 /**
3316 * Left-shift required to translate between public scroll indicator flags
3317 * and internal PFLAGS3 flags. When used as a right-shift, translates
3318 * PFLAGS3 flags to public flags.
3319 */
3320 static final int SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT = 8;
3321
3322 /** @hide */
3323 @Retention(RetentionPolicy.SOURCE)
3324 @IntDef(flag = true, prefix = { "SCROLL_INDICATOR_" }, value = {
3325 SCROLL_INDICATOR_TOP,
3326 SCROLL_INDICATOR_BOTTOM,
3327 SCROLL_INDICATOR_LEFT,
3328 SCROLL_INDICATOR_RIGHT,
3329 SCROLL_INDICATOR_START,
3330 SCROLL_INDICATOR_END,
3331 })
3332 public @interface ScrollIndicators {}
3333
3334 /**
3335 * Scroll indicator direction for the top edge of the view.
3336 *
3337 * @see #setScrollIndicators(int)
3338 * @see #setScrollIndicators(int, int)
3339 * @see #getScrollIndicators()
3340 */
3341 public static final int SCROLL_INDICATOR_TOP =
3342 PFLAG3_SCROLL_INDICATOR_TOP >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
3343
3344 /**
3345 * Scroll indicator direction for the bottom edge of the view.
3346 *
3347 * @see #setScrollIndicators(int)
3348 * @see #setScrollIndicators(int, int)
3349 * @see #getScrollIndicators()
3350 */
3351 public static final int SCROLL_INDICATOR_BOTTOM =
3352 PFLAG3_SCROLL_INDICATOR_BOTTOM >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
3353
3354 /**
3355 * Scroll indicator direction for the left edge of the view.
3356 *
3357 * @see #setScrollIndicators(int)
3358 * @see #setScrollIndicators(int, int)
3359 * @see #getScrollIndicators()
3360 */
3361 public static final int SCROLL_INDICATOR_LEFT =
3362 PFLAG3_SCROLL_INDICATOR_LEFT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
3363
3364 /**
3365 * Scroll indicator direction for the right edge of the view.
3366 *
3367 * @see #setScrollIndicators(int)
3368 * @see #setScrollIndicators(int, int)
3369 * @see #getScrollIndicators()
3370 */
3371 public static final int SCROLL_INDICATOR_RIGHT =
3372 PFLAG3_SCROLL_INDICATOR_RIGHT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
3373
3374 /**
3375 * Scroll indicator direction for the starting edge of the view.
3376 * <p>
3377 * Resolved according to the view's layout direction, see
3378 * {@link #getLayoutDirection()} for more information.
3379 *
3380 * @see #setScrollIndicators(int)
3381 * @see #setScrollIndicators(int, int)
3382 * @see #getScrollIndicators()
3383 */
3384 public static final int SCROLL_INDICATOR_START =
3385 PFLAG3_SCROLL_INDICATOR_START >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
3386
3387 /**
3388 * Scroll indicator direction for the ending edge of the view.
3389 * <p>
3390 * Resolved according to the view's layout direction, see
3391 * {@link #getLayoutDirection()} for more information.
3392 *
3393 * @see #setScrollIndicators(int)
3394 * @see #setScrollIndicators(int, int)
3395 * @see #getScrollIndicators()
3396 */
3397 public static final int SCROLL_INDICATOR_END =
3398 PFLAG3_SCROLL_INDICATOR_END >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
3399
3400 /**
3401 * <p>Indicates that we are allowing {@link ViewStructure} to traverse
3402 * into this view.<p>
3403 */
3404 static final int PFLAG3_ASSIST_BLOCKED = 0x4000;
3405
3406 /**
3407 * Flag indicating that the view is a root of a keyboard navigation cluster.
3408 *
3409 * @see #isKeyboardNavigationCluster()
3410 * @see #setKeyboardNavigationCluster(boolean)
3411 */
3412 private static final int PFLAG3_CLUSTER = 0x8000;
3413
3414 /**
3415 * Flag indicating that the view is autofilled
3416 *
3417 * @see #isAutofilled()
3418 * @see #setAutofilled(boolean, boolean)
3419 */
3420 private static final int PFLAG3_IS_AUTOFILLED = 0x10000;
3421
3422 /**
3423 * Indicates that the user is currently touching the screen.
3424 * Currently used for the tooltip positioning only.
3425 */
3426 private static final int PFLAG3_FINGER_DOWN = 0x20000;
3427
3428 /**
3429 * Flag indicating that this view is the default-focus view.
3430 *
3431 * @see #isFocusedByDefault()
3432 * @see #setFocusedByDefault(boolean)
3433 */
3434 private static final int PFLAG3_FOCUSED_BY_DEFAULT = 0x40000;
3435
3436 /**
3437 * Shift for the bits in {@link #mPrivateFlags3} related to the
3438 * "importantForAutofill" attribute.
3439 */
3440 static final int PFLAG3_IMPORTANT_FOR_AUTOFILL_SHIFT = 19;
3441
3442 /**
3443 * Mask for obtaining the bits which specify how to determine
3444 * whether a view is important for autofill.
3445 */
3446 static final int PFLAG3_IMPORTANT_FOR_AUTOFILL_MASK = (IMPORTANT_FOR_AUTOFILL_AUTO
3447 | IMPORTANT_FOR_AUTOFILL_YES | IMPORTANT_FOR_AUTOFILL_NO
3448 | IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS
3449 | IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS)
3450 << PFLAG3_IMPORTANT_FOR_AUTOFILL_SHIFT;
3451
3452 /**
3453 * Whether this view has rendered elements that overlap (see {@link
3454 * #hasOverlappingRendering()}, {@link #forceHasOverlappingRendering(boolean)}, and
3455 * {@link #getHasOverlappingRendering()} ). The value in this bit is only valid when
3456 * PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED has been set. Otherwise, the value is
3457 * determined by whatever {@link #hasOverlappingRendering()} returns.
3458 */
3459 private static final int PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE = 0x800000;
3460
3461 /**
3462 * Whether {@link #forceHasOverlappingRendering(boolean)} has been called. When true, value
3463 * in PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE is valid.
3464 */
3465 private static final int PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED = 0x1000000;
3466
3467 /**
3468 * Flag indicating that the view is temporarily detached from the parent view.
3469 *
3470 * @see #onStartTemporaryDetach()
3471 * @see #onFinishTemporaryDetach()
3472 */
3473 static final int PFLAG3_TEMPORARY_DETACH = 0x2000000;
3474
3475 /**
3476 * Flag indicating that the view does not wish to be revealed within its parent
3477 * hierarchy when it gains focus. Expressed in the negative since the historical
3478 * default behavior is to reveal on focus; this flag suppresses that behavior.
3479 *
3480 * @see #setRevealOnFocusHint(boolean)
3481 * @see #getRevealOnFocusHint()
3482 */
3483 private static final int PFLAG3_NO_REVEAL_ON_FOCUS = 0x4000000;
3484
3485 /**
3486 * Flag indicating that when layout is completed we should notify
3487 * that the view was entered for autofill purposes. To minimize
3488 * showing autofill for views not visible to the user we evaluate
3489 * user visibility which cannot be done until the view is laid out.
3490 */
3491 static final int PFLAG3_NOTIFY_AUTOFILL_ENTER_ON_LAYOUT = 0x8000000;
3492
3493 /**
3494 * Works like focusable for screen readers, but without the side effects on input focus.
3495 * @see #setScreenReaderFocusable(boolean)
3496 */
3497 private static final int PFLAG3_SCREEN_READER_FOCUSABLE = 0x10000000;
3498
3499 /**
3500 * The last aggregated visibility. Used to detect when it truly changes.
3501 */
3502 private static final int PFLAG3_AGGREGATED_VISIBLE = 0x20000000;
3503
3504 /**
3505 * Used to indicate that {@link #mAutofillId} was explicitly set through
3506 * {@link #setAutofillId(AutofillId)}.
3507 */
3508 private static final int PFLAG3_AUTOFILLID_EXPLICITLY_SET = 0x40000000;
3509
3510 /**
3511 * Indicates if the View is a heading for accessibility purposes
3512 */
3513 private static final int PFLAG3_ACCESSIBILITY_HEADING = 0x80000000;
3514
3515 /* End of masks for mPrivateFlags3 */
3516
3517 /*
3518 * Masks for mPrivateFlags4, as generated by dumpFlags():
3519 *
3520 * |-------|-------|-------|-------|
3521 * 1111 PFLAG4_IMPORTANT_FOR_CONTENT_CAPTURE_MASK
3522 * 1 PFLAG4_NOTIFIED_CONTENT_CAPTURE_APPEARED
3523 * 1 PFLAG4_NOTIFIED_CONTENT_CAPTURE_DISAPPEARED
3524 * 1 PFLAG4_CONTENT_CAPTURE_IMPORTANCE_IS_CACHED
3525 * 1 PFLAG4_CONTENT_CAPTURE_IMPORTANCE_CACHED_VALUE
3526 * 11 PFLAG4_CONTENT_CAPTURE_IMPORTANCE_MASK
3527 * 1 PFLAG4_FRAMEWORK_OPTIONAL_FITS_SYSTEM_WINDOWS
3528 * 1 PFLAG4_AUTOFILL_HIDE_HIGHLIGHT
3529 * 11 PFLAG4_SCROLL_CAPTURE_HINT_MASK
3530 * 1 PFLAG4_ALLOW_CLICK_WHEN_DISABLED
3531 * 1 PFLAG4_DETACHED
3532 * 1 PFLAG4_HAS_TRANSLATION_TRANSIENT_STATE
3533 * 1 PFLAG4_DRAG_A11Y_STARTED
3534 * 1 PFLAG4_AUTO_HANDWRITING_INITIATION_ENABLED
3535 * |-------|-------|-------|-------|
3536 */
3537
3538 /**
3539 * Mask for obtaining the bits which specify how to determine
3540 * whether a view is important for autofill.
3541 *
3542 * <p>NOTE: the important for content capture values were the first flags added and are set in
3543 * the rightmost position, so we don't need to shift them
3544 */
3545 private static final int PFLAG4_IMPORTANT_FOR_CONTENT_CAPTURE_MASK =
3546 IMPORTANT_FOR_CONTENT_CAPTURE_AUTO | IMPORTANT_FOR_CONTENT_CAPTURE_YES
3547 | IMPORTANT_FOR_CONTENT_CAPTURE_NO
3548 | IMPORTANT_FOR_CONTENT_CAPTURE_YES_EXCLUDE_DESCENDANTS
3549 | IMPORTANT_FOR_CONTENT_CAPTURE_NO_EXCLUDE_DESCENDANTS;
3550
3551 /*
3552 * Variables used to control when the IntelligenceManager.notifyNodeAdded()/removed() methods
3553 * should be called.
3554 *
3555 * The idea is to call notifyAppeared() after the view is layout and visible, then call
3556 * notifyDisappeared() when it's gone (without known when it was removed from the parent).
3557 */
3558 private static final int PFLAG4_NOTIFIED_CONTENT_CAPTURE_APPEARED = 0x10;
3559 private static final int PFLAG4_NOTIFIED_CONTENT_CAPTURE_DISAPPEARED = 0x20;
3560
3561 /*
3562 * Flags used to cache the value returned by isImportantForContentCapture while the view
3563 * hierarchy is being traversed.
3564 */
3565 private static final int PFLAG4_CONTENT_CAPTURE_IMPORTANCE_IS_CACHED = 0x40;
3566 private static final int PFLAG4_CONTENT_CAPTURE_IMPORTANCE_CACHED_VALUE = 0x80;
3567
3568 private static final int PFLAG4_CONTENT_CAPTURE_IMPORTANCE_MASK =
3569 PFLAG4_CONTENT_CAPTURE_IMPORTANCE_IS_CACHED
3570 | PFLAG4_CONTENT_CAPTURE_IMPORTANCE_CACHED_VALUE;
3571
3572 /**
3573 * @see #OPTIONAL_FITS_SYSTEM_WINDOWS
3574 */
3575 static final int PFLAG4_FRAMEWORK_OPTIONAL_FITS_SYSTEM_WINDOWS = 0x000000100;
3576
3577 /**
3578 * Flag indicating the field should not have yellow highlight when autofilled.
3579 */
3580 private static final int PFLAG4_AUTOFILL_HIDE_HIGHLIGHT = 0x200;
3581
3582 /**
3583 * Shift for the bits in {@link #mPrivateFlags4} related to scroll capture.
3584 */
3585 static final int PFLAG4_SCROLL_CAPTURE_HINT_SHIFT = 10;
3586
3587 static final int PFLAG4_SCROLL_CAPTURE_HINT_MASK = (SCROLL_CAPTURE_HINT_INCLUDE
3588 | SCROLL_CAPTURE_HINT_EXCLUDE | SCROLL_CAPTURE_HINT_EXCLUDE_DESCENDANTS)
3589 << PFLAG4_SCROLL_CAPTURE_HINT_SHIFT;
3590
3591 /**
3592 * Indicates if the view can receive click events when disabled.
3593 */
3594 private static final int PFLAG4_ALLOW_CLICK_WHEN_DISABLED = 0x000001000;
3595
3596 /**
3597 * Indicates if the view is just detached.
3598 */
3599 private static final int PFLAG4_DETACHED = 0x000002000;
3600
3601 /**
3602 * Indicates that the view has transient state because the system is translating it.
3603 */
3604 private static final int PFLAG4_HAS_TRANSLATION_TRANSIENT_STATE = 0x000004000;
3605
3606 /**
3607 * Indicates that the view has started a drag with {@link AccessibilityAction#ACTION_DRAG_START}
3608 */
3609 private static final int PFLAG4_DRAG_A11Y_STARTED = 0x000008000;
3610
3611 /**
3612 * Indicates that the view enables auto handwriting initiation.
3613 */
3614 private static final int PFLAG4_AUTO_HANDWRITING_ENABLED = 0x000010000;
3615 /* End of masks for mPrivateFlags4 */
3616
3617 /** @hide */
3618 protected static final int VIEW_STRUCTURE_FOR_ASSIST = 0;
3619 /** @hide */
3620 protected static final int VIEW_STRUCTURE_FOR_AUTOFILL = 1;
3621 /** @hide */
3622 protected static final int VIEW_STRUCTURE_FOR_CONTENT_CAPTURE = 2;
3623
3624 /** @hide */
3625 @IntDef(flag = true, prefix = { "VIEW_STRUCTURE_FOR" }, value = {
3626 VIEW_STRUCTURE_FOR_ASSIST,
3627 VIEW_STRUCTURE_FOR_AUTOFILL,
3628 VIEW_STRUCTURE_FOR_CONTENT_CAPTURE
3629 })
3630 @Retention(RetentionPolicy.SOURCE)
3631 public @interface ViewStructureType {}
3632
3633 /**
3634 * Always allow a user to over-scroll this view, provided it is a
3635 * view that can scroll.
3636 *
3637 * @see #getOverScrollMode()
3638 * @see #setOverScrollMode(int)
3639 */
3640 public static final int OVER_SCROLL_ALWAYS = 0;
3641
3642 /**
3643 * Allow a user to over-scroll this view only if the content is large
3644 * enough to meaningfully scroll, provided it is a view that can scroll.
3645 *
3646 * @see #getOverScrollMode()
3647 * @see #setOverScrollMode(int)
3648 */
3649 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
3650
3651 /**
3652 * Never allow a user to over-scroll this view.
3653 *
3654 * @see #getOverScrollMode()
3655 * @see #setOverScrollMode(int)
3656 */
3657 public static final int OVER_SCROLL_NEVER = 2;
3658
3659 /**
3660 * Special constant for {@link #setSystemUiVisibility(int)}: View has
3661 * requested the system UI (status bar) to be visible (the default).
3662 *
3663 * @see #setSystemUiVisibility(int)
3664 * @deprecated SystemUiVisibility flags are deprecated. Use {@link WindowInsetsController}
3665 * instead.
3666 */
3667 @Deprecated
3668 public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
3669
3670 /**
3671 * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
3672 * system UI to enter an unobtrusive "low profile" mode.
3673 *
3674 * <p>This is for use in games, book readers, video players, or any other
3675 * "immersive" application where the usual system chrome is deemed too distracting.
3676 *
3677 * <p>In low profile mode, the status bar and/or navigation icons may dim.
3678 *
3679 * @see #setSystemUiVisibility(int)
3680 * @deprecated Low profile mode is deprecated. Hide the system bars instead if the application
3681 * needs to be in a unobtrusive mode. Use {@link WindowInsetsController#hide(int)} with
3682 * {@link Type#systemBars()}.
3683 */
3684 @Deprecated
3685 public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
3686
3687 /**
3688 * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
3689 * system navigation be temporarily hidden.
3690 *
3691 * <p>This is an even less obtrusive state than that called for by
3692 * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
3693 * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
3694 * those to disappear. This is useful (in conjunction with the
3695 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
3696 * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
3697 * window flags) for displaying content using every last pixel on the display.
3698 *
3699 * <p>There is a limitation: because navigation controls are so important, the least user
3700 * interaction will cause them to reappear immediately. When this happens, both
3701 * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
3702 * so that both elements reappear at the same time.
3703 *
3704 * @see #setSystemUiVisibility(int)
3705 * @deprecated Use {@link WindowInsetsController#hide(int)} with {@link Type#navigationBars()}
3706 * instead.
3707 */
3708 @Deprecated
3709 public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
3710
3711 /**
3712 * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
3713 * into the normal fullscreen mode so that its content can take over the screen
3714 * while still allowing the user to interact with the application.
3715 *
3716 * <p>This has the same visual effect as
3717 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
3718 * WindowManager.LayoutParams.FLAG_FULLSCREEN},
3719 * meaning that non-critical screen decorations (such as the status bar) will be
3720 * hidden while the user is in the View's window, focusing the experience on
3721 * that content. Unlike the window flag, if you are using ActionBar in
3722 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
3723 * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
3724 * hide the action bar.
3725 *
3726 * <p>This approach to going fullscreen is best used over the window flag when
3727 * it is a transient state -- that is, the application does this at certain
3728 * points in its user interaction where it wants to allow the user to focus
3729 * on content, but not as a continuous state. For situations where the application
3730 * would like to simply stay full screen the entire time (such as a game that
3731 * wants to take over the screen), the
3732 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
3733 * is usually a better approach. The state set here will be removed by the system
3734 * in various situations (such as the user moving to another application) like
3735 * the other system UI states.
3736 *
3737 * <p>When using this flag, the application should provide some easy facility
3738 * for the user to go out of it. A common example would be in an e-book
3739 * reader, where tapping on the screen brings back whatever screen and UI
3740 * decorations that had been hidden while the user was immersed in reading
3741 * the book.
3742 *
3743 * @see #setSystemUiVisibility(int)
3744 * @deprecated Use {@link WindowInsetsController#hide(int)} with {@link Type#statusBars()}
3745 * instead.
3746 */
3747 @Deprecated
3748 public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
3749
3750 /**
3751 * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
3752 * flags, we would like a stable view of the content insets given to
3753 * {@link #fitSystemWindows(Rect)}. This means that the insets seen there
3754 * will always represent the worst case that the application can expect
3755 * as a continuous state. In the stock Android UI this is the space for
3756 * the system bar, nav bar, and status bar, but not more transient elements
3757 * such as an input method.
3758 *
3759 * The stable layout your UI sees is based on the system UI modes you can
3760 * switch to. That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
3761 * then you will get a stable layout for changes of the
3762 * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
3763 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
3764 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
3765 * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
3766 * with a stable layout. (Note that you should avoid using
3767 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
3768 *
3769 * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
3770 * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
3771 * then a hidden status bar will be considered a "stable" state for purposes
3772 * here. This allows your UI to continually hide the status bar, while still
3773 * using the system UI flags to hide the action bar while still retaining
3774 * a stable layout. Note that changing the window fullscreen flag will never
3775 * provide a stable layout for a clean transition.
3776 *
3777 * <p>If you are using ActionBar in
3778 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
3779 * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
3780 * insets it adds to those given to the application.
3781 *
3782 * @deprecated Use {@link WindowInsets#getInsetsIgnoringVisibility(int)} instead to retrieve
3783 * insets that don't change when system bars change visibility state.
3784 */
3785 @Deprecated
3786 public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
3787
3788 /**
3789 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
3790 * to be laid out as if it has requested
3791 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't. This
3792 * allows it to avoid artifacts when switching in and out of that mode, at
3793 * the expense that some of its user interface may be covered by screen
3794 * decorations when they are shown. You can perform layout of your inner
3795 * UI elements to account for the navigation system UI through the
3796 * {@link #fitSystemWindows(Rect)} method.
3797 *
3798 * @deprecated For floating windows, use {@link LayoutParams#setFitInsetsTypes(int)} with
3799 * {@link Type#navigationBars()}. For non-floating windows that fill the screen, call
3800 * {@link Window#setDecorFitsSystemWindows(boolean)} with {@code false}.
3801 */
3802 public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
3803
3804 /**
3805 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
3806 * to be laid out as if it has requested
3807 * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't. This
3808 * allows it to avoid artifacts when switching in and out of that mode, at
3809 * the expense that some of its user interface may be covered by screen
3810 * decorations when they are shown. You can perform layout of your inner
3811 * UI elements to account for non-fullscreen system UI through the
3812 * {@link #fitSystemWindows(Rect)} method.
3813 *
3814 * <p>Note: on displays that have a {@link DisplayCutout}, the window may still be placed
3815 * differently than if {@link #SYSTEM_UI_FLAG_FULLSCREEN} was set, if the
3816 * window's {@link WindowManager.LayoutParams#layoutInDisplayCutoutMode
3817 * layoutInDisplayCutoutMode} is
3818 * {@link WindowManager.LayoutParams#LAYOUT_IN_DISPLAY_CUTOUT_MODE_DEFAULT
3819 * LAYOUT_IN_DISPLAY_CUTOUT_MODE_DEFAULT}. To avoid this, use either of the other modes.
3820 *
3821 * @see WindowManager.LayoutParams#layoutInDisplayCutoutMode
3822 * @see WindowManager.LayoutParams#LAYOUT_IN_DISPLAY_CUTOUT_MODE_DEFAULT
3823 * @see WindowManager.LayoutParams#LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
3824 * @see WindowManager.LayoutParams#LAYOUT_IN_DISPLAY_CUTOUT_MODE_NEVER
3825 *
3826 * @deprecated For floating windows, use {@link LayoutParams#setFitInsetsTypes(int)} with
3827 * {@link Type#statusBars()} ()}. For non-floating windows that fill the screen, call
3828 * {@link Window#setDecorFitsSystemWindows(boolean)} with {@code false}.
3829 */
3830 @Deprecated
3831 public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
3832
3833 /**
3834 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
3835 * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. If this flag is
3836 * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any
3837 * user interaction.
3838 * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only
3839 * has an effect when used in combination with that flag.</p>
3840 *
3841 * @deprecated Use {@link WindowInsetsController#BEHAVIOR_DEFAULT} instead.
3842 */
3843 @Deprecated
3844 public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800;
3845
3846 /**
3847 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
3848 * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation
3849 * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. Use this flag to create an immersive
3850 * experience while also hiding the system bars. If this flag is not set,
3851 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user
3852 * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system
3853 * if the user swipes from the top of the screen.
3854 * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with
3855 * system gestures, such as swiping from the top of the screen. These transient system bars
3856 * will overlay app's content, may have some degree of transparency, and will automatically
3857 * hide after a short timeout.
3858 * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and
3859 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination
3860 * with one or both of those flags.</p>
3861 *
3862 * @deprecated Use {@link WindowInsetsController#BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE} instead.
3863 */
3864 @Deprecated
3865 public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000;
3866
3867 /**
3868 * Flag for {@link #setSystemUiVisibility(int)}: Requests the status bar to draw in a mode that
3869 * is compatible with light status bar backgrounds.
3870 *
3871 * <p>For this to take effect, the window must request
3872 * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS
3873 * FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not
3874 * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_STATUS
3875 * FLAG_TRANSLUCENT_STATUS}.
3876 *
3877 * @see android.R.attr#windowLightStatusBar
3878 * @deprecated Use {@link WindowInsetsController#APPEARANCE_LIGHT_STATUS_BARS} instead.
3879 */
3880 @Deprecated
3881 public static final int SYSTEM_UI_FLAG_LIGHT_STATUS_BAR = 0x00002000;
3882
3883 /**
3884 * This flag was previously used for a private API. DO NOT reuse it for a public API as it might
3885 * trigger undefined behavior on older platforms with apps compiled against a new SDK.
3886 */
3887 private static final int SYSTEM_UI_RESERVED_LEGACY1 = 0x00004000;
3888
3889 /**
3890 * This flag was previously used for a private API. DO NOT reuse it for a public API as it might
3891 * trigger undefined behavior on older platforms with apps compiled against a new SDK.
3892 */
3893 private static final int SYSTEM_UI_RESERVED_LEGACY2 = 0x00010000;
3894
3895 /**
3896 * Flag for {@link #setSystemUiVisibility(int)}: Requests the navigation bar to draw in a mode
3897 * that is compatible with light navigation bar backgrounds.
3898 *
3899 * <p>For this to take effect, the window must request
3900 * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS
3901 * FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not
3902 * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_NAVIGATION
3903 * FLAG_TRANSLUCENT_NAVIGATION}.
3904 *
3905 * @see android.R.attr#windowLightNavigationBar
3906 * @deprecated Use {@link WindowInsetsController#APPEARANCE_LIGHT_NAVIGATION_BARS} instead.
3907 */
3908 @Deprecated
3909 public static final int SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR = 0x00000010;
3910
3911 /**
3912 * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
3913 */
3914 @Deprecated
3915 public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
3916
3917 /**
3918 * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
3919 */
3920 @Deprecated
3921 public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
3922
3923 /**
3924 * @hide
3925 *
3926 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3927 * out of the public fields to keep the undefined bits out of the developer's way.
3928 *
3929 * Flag to make the status bar not expandable. Unless you also
3930 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
3931 */
3932 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
3933 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
3934
3935 /**
3936 * @hide
3937 *
3938 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3939 * out of the public fields to keep the undefined bits out of the developer's way.
3940 *
3941 * Flag to hide notification icons and scrolling ticker text.
3942 */
3943 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
3944
3945 /**
3946 * @hide
3947 *
3948 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3949 * out of the public fields to keep the undefined bits out of the developer's way.
3950 *
3951 * Flag to disable incoming notification alerts. This will not block
3952 * icons, but it will block sound, vibrating and other visual or aural notifications.
3953 */
3954 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
3955
3956 /**
3957 * @hide
3958 *
3959 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3960 * out of the public fields to keep the undefined bits out of the developer's way.
3961 *
3962 * Flag to hide only the scrolling ticker. Note that
3963 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
3964 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
3965 */
3966 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
3967
3968 /**
3969 * @hide
3970 *
3971 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3972 * out of the public fields to keep the undefined bits out of the developer's way.
3973 *
3974 * Flag to hide the center system info area.
3975 */
3976 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
3977
3978 /**
3979 * @hide
3980 *
3981 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3982 * out of the public fields to keep the undefined bits out of the developer's way.
3983 *
3984 * Flag to hide only the home button. Don't use this
3985 * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3986 */
3987 @UnsupportedAppUsage
3988 public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
3989
3990 /**
3991 * @hide
3992 *
3993 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3994 * out of the public fields to keep the undefined bits out of the developer's way.
3995 *
3996 * Flag to hide only the back button. Don't use this
3997 * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3998 */
3999 @UnsupportedAppUsage
4000 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
4001
4002 /**
4003 * @hide
4004 *
4005 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
4006 * out of the public fields to keep the undefined bits out of the developer's way.
4007 *
4008 * Flag to hide only the clock. You might use this if your activity has
4009 * its own clock making the status bar's clock redundant.
4010 */
4011 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
4012
4013 /**
4014 * @hide
4015 *
4016 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
4017 * out of the public fields to keep the undefined bits out of the developer's way.
4018 *
4019 * Flag to hide only the recent apps button. Don't use this
4020 * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
4021 */
4022 @UnsupportedAppUsage
4023 public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
4024
4025 /**
4026 * @hide
4027 *
4028 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
4029 * out of the public fields to keep the undefined bits out of the developer's way.
4030 *
4031 * Flag to disable the global search gesture. Don't use this
4032 * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
4033 */
4034 public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
4035
4036 /**
4037 * @hide
4038 *
4039 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
4040 * out of the public fields to keep the undefined bits out of the developer's way.
4041 *
4042 * Flag to disable the ongoing call chip.
4043 */
4044 public static final int STATUS_BAR_DISABLE_ONGOING_CALL_CHIP = 0x04000000;
4045
4046 /**
4047 * @hide
4048 */
4049 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FF7;
4050
4051 /**
4052 * These are the system UI flags that can be cleared by events outside
4053 * of an application. Currently this is just the ability to tap on the
4054 * screen while hiding the navigation bar to have it return.
4055 * @hide
4056 */
4057 public static final int SYSTEM_UI_CLEARABLE_FLAGS =
4058 SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
4059 | SYSTEM_UI_FLAG_FULLSCREEN;
4060
4061 /**
4062 * Flags that can impact the layout in relation to system UI.
4063 *
4064 * @deprecated System UI layout flags are deprecated.
4065 */
4066 @Deprecated
4067 public static final int SYSTEM_UI_LAYOUT_FLAGS =
4068 SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
4069 | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
4070
4071 /** @hide */
4072 @IntDef(flag = true, prefix = { "FIND_VIEWS_" }, value = {
4073 FIND_VIEWS_WITH_TEXT,
4074 FIND_VIEWS_WITH_CONTENT_DESCRIPTION
4075 })
4076 @Retention(RetentionPolicy.SOURCE)
4077 public @interface FindViewFlags {}
4078
4079 /**
4080 * Find views that render the specified text.
4081 *
4082 * @see #findViewsWithText(ArrayList, CharSequence, int)
4083 */
4084 public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
4085
4086 /**
4087 * Find find views that contain the specified content description.
4088 *
4089 * @see #findViewsWithText(ArrayList, CharSequence, int)
4090 */
4091 public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
4092
4093 /**
4094 * Find views that contain {@link AccessibilityNodeProvider}. Such
4095 * a View is a root of virtual view hierarchy and may contain the searched
4096 * text. If this flag is set Views with providers are automatically
4097 * added and it is a responsibility of the client to call the APIs of
4098 * the provider to determine whether the virtual tree rooted at this View
4099 * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
4100 * representing the virtual views with this text.
4101 *
4102 * @see #findViewsWithText(ArrayList, CharSequence, int)
4103 *
4104 * @hide
4105 */
4106 public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
4107
4108 /**
4109 * The undefined cursor position.
4110 *
4111 * @hide
4112 */
4113 public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
4114
4115 /**
4116 * Indicates that the screen has changed state and is now off.
4117 *
4118 * @see #onScreenStateChanged(int)
4119 */
4120 public static final int SCREEN_STATE_OFF = 0x0;
4121
4122 /**
4123 * Indicates that the screen has changed state and is now on.
4124 *
4125 * @see #onScreenStateChanged(int)
4126 */
4127 public static final int SCREEN_STATE_ON = 0x1;
4128
4129 /**
4130 * Indicates no axis of view scrolling.
4131 */
4132 public static final int SCROLL_AXIS_NONE = 0;
4133
4134 /**
4135 * Indicates scrolling along the horizontal axis.
4136 */
4137 public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0;
4138
4139 /**
4140 * Indicates scrolling along the vertical axis.
4141 */
4142 public static final int SCROLL_AXIS_VERTICAL = 1 << 1;
4143
4144 /**
4145 * Controls the over-scroll mode for this view.
4146 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
4147 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
4148 * and {@link #OVER_SCROLL_NEVER}.
4149 */
4150 private int mOverScrollMode;
4151
4152 /**
4153 * The parent this view is attached to.
4154 * {@hide}
4155 *
4156 * @see #getParent()
4157 */
4158 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
4159 protected ViewParent mParent;
4160
4161 /**
4162 * {@hide}
4163 *
4164 * Not available for general use. If you need help, hang up and then dial one of the following
4165 * public APIs:
4166 *
4167 * @see #isAttachedToWindow() for current attach state
4168 * @see #onAttachedToWindow() for subclasses performing work when becoming attached
4169 * @see #onDetachedFromWindow() for subclasses performing work when becoming detached
4170 * @see OnAttachStateChangeListener for other code performing work on attach/detach
4171 * @see #getHandler() for posting messages to this view's UI thread/looper
4172 * @see #getParent() for interacting with the parent chain
4173 * @see #getWindowToken() for the current window token
4174 * @see #getRootView() for the view at the root of the attached hierarchy
4175 * @see #getDisplay() for the Display this view is presented on
4176 * @see #getRootWindowInsets() for the current insets applied to the whole attached window
4177 * @see #hasWindowFocus() for whether the attached window is currently focused
4178 * @see #getWindowVisibility() for checking the visibility of the attached window
4179 */
4180 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
4181 AttachInfo mAttachInfo;
4182
4183 /**
4184 * {@hide}
4185 */
4186 @ViewDebug.ExportedProperty(flagMapping = {
4187 @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
4188 name = "FORCE_LAYOUT"),
4189 @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
4190 name = "LAYOUT_REQUIRED"),
4191 @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
4192 name = "DRAWING_CACHE_INVALID", outputIf = false),
4193 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
4194 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
4195 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
4196 }, formatToHexString = true)
4197
4198 /* @hide */
4199 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 123769414)
4200 public int mPrivateFlags;
4201 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 123768943)
4202 int mPrivateFlags2;
4203 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 129147060)
4204 int mPrivateFlags3;
4205
4206 private int mPrivateFlags4;
4207
4208 /**
4209 * This view's request for the visibility of the status bar.
4210 * @hide
4211 */
4212 @ViewDebug.ExportedProperty(flagMapping = {
4213 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
4214 equals = SYSTEM_UI_FLAG_LOW_PROFILE,
4215 name = "LOW_PROFILE"),
4216 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
4217 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
4218 name = "HIDE_NAVIGATION"),
4219 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_FULLSCREEN,
4220 equals = SYSTEM_UI_FLAG_FULLSCREEN,
4221 name = "FULLSCREEN"),
4222 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LAYOUT_STABLE,
4223 equals = SYSTEM_UI_FLAG_LAYOUT_STABLE,
4224 name = "LAYOUT_STABLE"),
4225 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION,
4226 equals = SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION,
4227 name = "LAYOUT_HIDE_NAVIGATION"),
4228 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN,
4229 equals = SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN,
4230 name = "LAYOUT_FULLSCREEN"),
4231 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_IMMERSIVE,
4232 equals = SYSTEM_UI_FLAG_IMMERSIVE,
4233 name = "IMMERSIVE"),
4234 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_IMMERSIVE_STICKY,
4235 equals = SYSTEM_UI_FLAG_IMMERSIVE_STICKY,
4236 name = "IMMERSIVE_STICKY"),
4237 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LIGHT_STATUS_BAR,
4238 equals = SYSTEM_UI_FLAG_LIGHT_STATUS_BAR,
4239 name = "LIGHT_STATUS_BAR"),
4240 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR,
4241 equals = SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR,
4242 name = "LIGHT_NAVIGATION_BAR"),
4243 @ViewDebug.FlagToString(mask = STATUS_BAR_DISABLE_EXPAND,
4244 equals = STATUS_BAR_DISABLE_EXPAND,
4245 name = "STATUS_BAR_DISABLE_EXPAND"),
4246 @ViewDebug.FlagToString(mask = STATUS_BAR_DISABLE_NOTIFICATION_ICONS,
4247 equals = STATUS_BAR_DISABLE_NOTIFICATION_ICONS,
4248 name = "STATUS_BAR_DISABLE_NOTIFICATION_ICONS"),
4249 @ViewDebug.FlagToString(mask = STATUS_BAR_DISABLE_NOTIFICATION_ALERTS,
4250 equals = STATUS_BAR_DISABLE_NOTIFICATION_ALERTS,
4251 name = "STATUS_BAR_DISABLE_NOTIFICATION_ALERTS"),
4252 @ViewDebug.FlagToString(mask = STATUS_BAR_DISABLE_NOTIFICATION_TICKER,
4253 equals = STATUS_BAR_DISABLE_NOTIFICATION_TICKER,
4254 name = "STATUS_BAR_DISABLE_NOTIFICATION_TICKER"),
4255 @ViewDebug.FlagToString(mask = STATUS_BAR_DISABLE_SYSTEM_INFO,
4256 equals = STATUS_BAR_DISABLE_SYSTEM_INFO,
4257 name = "STATUS_BAR_DISABLE_SYSTEM_INFO"),
4258 @ViewDebug.FlagToString(mask = STATUS_BAR_DISABLE_HOME,
4259 equals = STATUS_BAR_DISABLE_HOME,
4260 name = "STATUS_BAR_DISABLE_HOME"),
4261 @ViewDebug.FlagToString(mask = STATUS_BAR_DISABLE_BACK,
4262 equals = STATUS_BAR_DISABLE_BACK,
4263 name = "STATUS_BAR_DISABLE_BACK"),
4264 @ViewDebug.FlagToString(mask = STATUS_BAR_DISABLE_CLOCK,
4265 equals = STATUS_BAR_DISABLE_CLOCK,
4266 name = "STATUS_BAR_DISABLE_CLOCK"),
4267 @ViewDebug.FlagToString(mask = STATUS_BAR_DISABLE_RECENT,
4268 equals = STATUS_BAR_DISABLE_RECENT,
4269 name = "STATUS_BAR_DISABLE_RECENT"),
4270 @ViewDebug.FlagToString(mask = STATUS_BAR_DISABLE_SEARCH,
4271 equals = STATUS_BAR_DISABLE_SEARCH,
4272 name = "STATUS_BAR_DISABLE_SEARCH"),
4273 @ViewDebug.FlagToString(mask = STATUS_BAR_DISABLE_ONGOING_CALL_CHIP,
4274 equals = STATUS_BAR_DISABLE_ONGOING_CALL_CHIP,
4275 name = "STATUS_BAR_DISABLE_ONGOING_CALL_CHIP")
4276 }, formatToHexString = true)
4277 @SystemUiVisibility
4278 int mSystemUiVisibility;
4279
4280 /**
4281 * @hide
4282 */
4283 @IntDef(flag = true, prefix = "", value = {
4284 SYSTEM_UI_FLAG_LOW_PROFILE,
4285 SYSTEM_UI_FLAG_HIDE_NAVIGATION,
4286 SYSTEM_UI_FLAG_FULLSCREEN,
4287 SYSTEM_UI_FLAG_LAYOUT_STABLE,
4288 SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION,
4289 SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN,
4290 SYSTEM_UI_FLAG_IMMERSIVE,
4291 SYSTEM_UI_FLAG_IMMERSIVE_STICKY,
4292 SYSTEM_UI_FLAG_LIGHT_STATUS_BAR,
4293 SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR,
4294 STATUS_BAR_DISABLE_EXPAND,
4295 STATUS_BAR_DISABLE_NOTIFICATION_ICONS,
4296 STATUS_BAR_DISABLE_NOTIFICATION_ALERTS,
4297 STATUS_BAR_DISABLE_NOTIFICATION_TICKER,
4298 STATUS_BAR_DISABLE_SYSTEM_INFO,
4299 STATUS_BAR_DISABLE_HOME,
4300 STATUS_BAR_DISABLE_BACK,
4301 STATUS_BAR_DISABLE_CLOCK,
4302 STATUS_BAR_DISABLE_RECENT,
4303 STATUS_BAR_DISABLE_SEARCH,
4304 STATUS_BAR_DISABLE_ONGOING_CALL_CHIP,
4305 })
4306 @Retention(RetentionPolicy.SOURCE)
4307 public @interface SystemUiVisibility {}
4308
4309 /**
4310 * Reference count for transient state.
4311 * @see #setHasTransientState(boolean)
4312 */
4313 int mTransientStateCount = 0;
4314
4315 /**
4316 * Count of how many windows this view has been attached to.
4317 */
4318 int mWindowAttachCount;
4319
4320 /**
4321 * The layout parameters associated with this view and used by the parent
4322 * {@link android.view.ViewGroup} to determine how this view should be
4323 * laid out.
4324 *
4325 * The field should not be used directly. Instead {@link #getLayoutParams()} and {@link
4326 * #setLayoutParams(ViewGroup.LayoutParams)} should be used. The setter guarantees internal
4327 * state correctness of the class.
4328 * {@hide}
4329 */
4330 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
4331 protected ViewGroup.LayoutParams mLayoutParams;
4332
4333 /**
4334 * The view flags hold various views states.
4335 *
4336 * Use {@link #setTransitionVisibility(int)} to change the visibility of this view without
4337 * triggering updates.
4338 * {@hide}
4339 */
4340 @ViewDebug.ExportedProperty(formatToHexString = true)
4341 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
4342 int mViewFlags;
4343
4344 static class TransformationInfo {
4345 /**
4346 * The transform matrix for the View. This transform is calculated internally
4347 * based on the translation, rotation, and scale properties.
4348 *
4349 * Do *not* use this variable directly; instead call getMatrix(), which will
4350 * load the value from the View's RenderNode.
4351 */
4352 private final Matrix mMatrix = new Matrix();
4353
4354 /**
4355 * The inverse transform matrix for the View. This transform is calculated
4356 * internally based on the translation, rotation, and scale properties.
4357 *
4358 * Do *not* use this variable directly; instead call getInverseMatrix(),
4359 * which will load the value from the View's RenderNode.
4360 */
4361 private Matrix mInverseMatrix;
4362
4363 /**
4364 * The opacity of the View. This is a value from 0 to 1, where 0 means
4365 * completely transparent and 1 means completely opaque.
4366 */
4367 @ViewDebug.ExportedProperty
4368 private float mAlpha = 1f;
4369
4370 /**
4371 * The opacity of the view as manipulated by the Fade transition. This is a
4372 * property only used by transitions, which is composited with the other alpha
4373 * values to calculate the final visual alpha value.
4374 */
4375 float mTransitionAlpha = 1f;
4376 }
4377
4378 /** @hide */
4379 @UnsupportedAppUsage
4380 public TransformationInfo mTransformationInfo;
4381
4382 /**
4383 * Current clip bounds. to which all drawing of this view are constrained.
4384 */
4385 @ViewDebug.ExportedProperty(category = "drawing")
4386 Rect mClipBounds = null;
4387
4388 private boolean mLastIsOpaque;
4389
4390 /**
4391 * The distance in pixels from the left edge of this view's parent
4392 * to the left edge of this view.
4393 * {@hide}
4394 */
4395 @ViewDebug.ExportedProperty(category = "layout")
4396 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
4397 protected int mLeft;
4398 /**
4399 * The distance in pixels from the left edge of this view's parent
4400 * to the right edge of this view.
4401 * {@hide}
4402 */
4403 @ViewDebug.ExportedProperty(category = "layout")
4404 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
4405 protected int mRight;
4406 /**
4407 * The distance in pixels from the top edge of this view's parent
4408 * to the top edge of this view.
4409 * {@hide}
4410 */
4411 @ViewDebug.ExportedProperty(category = "layout")
4412 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
4413 protected int mTop;
4414 /**
4415 * The distance in pixels from the top edge of this view's parent
4416 * to the bottom edge of this view.
4417 * {@hide}
4418 */
4419 @ViewDebug.ExportedProperty(category = "layout")
4420 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
4421 protected int mBottom;
4422
4423 /**
4424 * The offset, in pixels, by which the content of this view is scrolled
4425 * horizontally.
4426 * Please use {@link View#getScrollX()} and {@link View#setScrollX(int)} instead of
4427 * accessing these directly.
4428 * {@hide}
4429 */
4430 @ViewDebug.ExportedProperty(category = "scrolling")
4431 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
4432 protected int mScrollX;
4433 /**
4434 * The offset, in pixels, by which the content of this view is scrolled
4435 * vertically.
4436 * Please use {@link View#getScrollY()} and {@link View#setScrollY(int)} instead of
4437 * accessing these directly.
4438 * {@hide}
4439 */
4440 @ViewDebug.ExportedProperty(category = "scrolling")
4441 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
4442 protected int mScrollY;
4443
4444 /**
4445 * The final computed left padding in pixels that is used for drawing. This is the distance in
4446 * pixels between the left edge of this view and the left edge of its content.
4447 * {@hide}
4448 */
4449 @ViewDebug.ExportedProperty(category = "padding")
4450 @UnsupportedAppUsage
4451 protected int mPaddingLeft = 0;
4452 /**
4453 * The final computed right padding in pixels that is used for drawing. This is the distance in
4454 * pixels between the right edge of this view and the right edge of its content.
4455 * {@hide}
4456 */
4457 @ViewDebug.ExportedProperty(category = "padding")
4458 @UnsupportedAppUsage
4459 protected int mPaddingRight = 0;
4460 /**
4461 * The final computed top padding in pixels that is used for drawing. This is the distance in
4462 * pixels between the top edge of this view and the top edge of its content.
4463 * {@hide}
4464 */
4465 @ViewDebug.ExportedProperty(category = "padding")
4466 @UnsupportedAppUsage
4467 protected int mPaddingTop;
4468 /**
4469 * The final computed bottom padding in pixels that is used for drawing. This is the distance in
4470 * pixels between the bottom edge of this view and the bottom edge of its content.
4471 * {@hide}
4472 */
4473 @ViewDebug.ExportedProperty(category = "padding")
4474 @UnsupportedAppUsage
4475 protected int mPaddingBottom;
4476
4477 /**
4478 * The layout insets in pixels, that is the distance in pixels between the
4479 * visible edges of this view its bounds.
4480 */
4481 private Insets mLayoutInsets;
4482
4483 /**
4484 * Briefly describes the state of the view and is primarily used for accessibility support.
4485 */
4486 private CharSequence mStateDescription;
4487
4488 /**
4489 * Briefly describes the view and is primarily used for accessibility support.
4490 */
4491 private CharSequence mContentDescription;
4492
4493 /**
4494 * If this view represents a distinct part of the window, it can have a title that labels the
4495 * area.
4496 */
4497 private CharSequence mAccessibilityPaneTitle;
4498
4499 /**
4500 * Specifies the id of a view for which this view serves as a label for
4501 * accessibility purposes.
4502 */
4503 private int mLabelForId = View.NO_ID;
4504
4505 /**
4506 * Predicate for matching labeled view id with its label for
4507 * accessibility purposes.
4508 */
4509 private MatchLabelForPredicate mMatchLabelForPredicate;
4510
4511 /**
4512 * Specifies a view before which this one is visited in accessibility traversal.
4513 */
4514 private int mAccessibilityTraversalBeforeId = NO_ID;
4515
4516 /**
4517 * Specifies a view after which this one is visited in accessibility traversal.
4518 */
4519 private int mAccessibilityTraversalAfterId = NO_ID;
4520
4521 /**
4522 * Predicate for matching a view by its id.
4523 */
4524 private MatchIdPredicate mMatchIdPredicate;
4525
4526 /**
4527 * The right padding after RTL resolution, but before taking account of scroll bars.
4528 *
4529 * @hide
4530 */
4531 @ViewDebug.ExportedProperty(category = "padding")
4532 protected int mUserPaddingRight;
4533
4534 /**
4535 * The resolved bottom padding before taking account of scroll bars.
4536 *
4537 * @hide
4538 */
4539 @ViewDebug.ExportedProperty(category = "padding")
4540 protected int mUserPaddingBottom;
4541
4542 /**
4543 * The left padding after RTL resolution, but before taking account of scroll bars.
4544 *
4545 * @hide
4546 */
4547 @ViewDebug.ExportedProperty(category = "padding")
4548 protected int mUserPaddingLeft;
4549
4550 /**
4551 * Cache the paddingStart set by the user to append to the scrollbar's size.
4552 *
4553 */
4554 @ViewDebug.ExportedProperty(category = "padding")
4555 int mUserPaddingStart;
4556
4557 /**
4558 * Cache the paddingEnd set by the user to append to the scrollbar's size.
4559 *
4560 */
4561 @ViewDebug.ExportedProperty(category = "padding")
4562 int mUserPaddingEnd;
4563
4564 /**
4565 * The left padding as set by a setter method, a background's padding, or via XML property
4566 * resolution. This value is the padding before LTR resolution or taking account of scrollbars.
4567 *
4568 * @hide
4569 */
4570 int mUserPaddingLeftInitial;
4571
4572 /**
4573 * The right padding as set by a setter method, a background's padding, or via XML property
4574 * resolution. This value is the padding before LTR resolution or taking account of scrollbars.
4575 *
4576 * @hide
4577 */
4578 int mUserPaddingRightInitial;
4579
4580 /**
4581 * Default undefined padding
4582 */
4583 private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
4584
4585 /**
4586 * Cache if a left padding has been defined explicitly via padding, horizontal padding,
4587 * or leftPadding in XML, or by setPadding(...) or setRelativePadding(...)
4588 */
4589 private boolean mLeftPaddingDefined = false;
4590
4591 /**
4592 * Cache if a right padding has been defined explicitly via padding, horizontal padding,
4593 * or rightPadding in XML, or by setPadding(...) or setRelativePadding(...)
4594 */
4595 private boolean mRightPaddingDefined = false;
4596
4597 /**
4598 * @hide
4599 */
4600 int mOldWidthMeasureSpec = Integer.MIN_VALUE;
4601 /**
4602 * @hide
4603 */
4604 int mOldHeightMeasureSpec = Integer.MIN_VALUE;
4605
4606 private LongSparseLongArray mMeasureCache;
4607
4608 @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
4609 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
4610 private Drawable mBackground;
4611 private TintInfo mBackgroundTint;
4612
4613 @ViewDebug.ExportedProperty(deepExport = true, prefix = "fg_")
4614 private ForegroundInfo mForegroundInfo;
4615
4616 private Drawable mScrollIndicatorDrawable;
4617
4618 /**
4619 * RenderNode used for backgrounds.
4620 * <p>
4621 * When non-null and valid, this is expected to contain an up-to-date copy
4622 * of the background drawable. It is cleared on temporary detach, and reset
4623 * on cleanup.
4624 * @hide
4625 */
4626 RenderNode mBackgroundRenderNode;
4627
4628 @UnsupportedAppUsage
4629 private int mBackgroundResource;
4630 private boolean mBackgroundSizeChanged;
4631
4632 /** The default focus highlight.
4633 * @see #mDefaultFocusHighlightEnabled
4634 * @see Drawable#hasFocusStateSpecified()
4635 */
4636 private Drawable mDefaultFocusHighlight;
4637 private Drawable mDefaultFocusHighlightCache;
4638 private boolean mDefaultFocusHighlightSizeChanged;
4639 /**
4640 * True if the default focus highlight is needed on the target device.
4641 */
4642 private static boolean sUseDefaultFocusHighlight;
4643
4644 /**
4645 * True if zero-sized views can be focused.
4646 */
4647 private static boolean sCanFocusZeroSized;
4648
4649 /**
4650 * Always assign focus if a focusable View is available.
4651 */
4652 private static boolean sAlwaysAssignFocus;
4653
4654 private String mTransitionName;
4655
4656 static class TintInfo {
4657 ColorStateList mTintList;
4658 BlendMode mBlendMode;
4659 boolean mHasTintMode;
4660 boolean mHasTintList;
4661 }
4662
4663 private static class ForegroundInfo {
4664 private Drawable mDrawable;
4665 private TintInfo mTintInfo;
4666 private int mGravity = Gravity.FILL;
4667 private boolean mInsidePadding = true;
4668 private boolean mBoundsChanged = true;
4669 private final Rect mSelfBounds = new Rect();
4670 private final Rect mOverlayBounds = new Rect();
4671 }
4672
4673 static class ListenerInfo {
4674
4675 @UnsupportedAppUsage
4676 ListenerInfo() {
4677 }
4678
4679 /**
4680 * Listener used to dispatch focus change events.
4681 * This field should be made private, so it is hidden from the SDK.
4682 * {@hide}
4683 */
4684 @UnsupportedAppUsage
4685 protected OnFocusChangeListener mOnFocusChangeListener;
4686
4687 /**
4688 * Listeners for layout change events.
4689 */
4690 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
4691
4692 protected OnScrollChangeListener mOnScrollChangeListener;
4693
4694 /**
4695 * Listeners for attach events.
4696 */
4697 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
4698
4699 /**
4700 * Listener used to dispatch click events.
4701 * This field should be made private, so it is hidden from the SDK.
4702 * {@hide}
4703 */
4704 @UnsupportedAppUsage
4705 public OnClickListener mOnClickListener;
4706
4707 /**
4708 * Listener used to dispatch long click events.
4709 * This field should be made private, so it is hidden from the SDK.
4710 * {@hide}
4711 */
4712 @UnsupportedAppUsage
4713 protected OnLongClickListener mOnLongClickListener;
4714
4715 /**
4716 * Listener used to dispatch context click events. This field should be made private, so it
4717 * is hidden from the SDK.
4718 * {@hide}
4719 */
4720 protected OnContextClickListener mOnContextClickListener;
4721
4722 /**
4723 * Listener used to build the context menu.
4724 * This field should be made private, so it is hidden from the SDK.
4725 * {@hide}
4726 */
4727 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
4728 protected OnCreateContextMenuListener mOnCreateContextMenuListener;
4729
4730 @UnsupportedAppUsage
4731 private OnKeyListener mOnKeyListener;
4732
4733 @UnsupportedAppUsage
4734 private OnTouchListener mOnTouchListener;
4735
4736 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
4737 private OnHoverListener mOnHoverListener;
4738
4739 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
4740 private OnGenericMotionListener mOnGenericMotionListener;
4741
4742 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
4743 private OnDragListener mOnDragListener;
4744
4745 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
4746
4747 OnApplyWindowInsetsListener mOnApplyWindowInsetsListener;
4748
4749 OnCapturedPointerListener mOnCapturedPointerListener;
4750
4751 private ArrayList<OnUnhandledKeyEventListener> mUnhandledKeyListeners;
4752
4753 WindowInsetsAnimation.Callback mWindowInsetsAnimationCallback;
4754
4755 /**
4756 * This lives here since it's only valid for interactive views. This list is null
4757 * until its first use.
4758 */
4759 private List<Rect> mSystemGestureExclusionRects = null;
4760 private List<Rect> mKeepClearRects = null;
4761 private List<Rect> mUnrestrictedKeepClearRects = null;
4762 private boolean mPreferKeepClear = false;
4763 private Rect mHandwritingArea = null;
4764
4765 /**
4766 * Used to track {@link #mSystemGestureExclusionRects}, {@link #mKeepClearRects} and
4767 * {@link #mHandwritingArea}.
4768 */
4769 public RenderNode.PositionUpdateListener mPositionUpdateListener;
4770 private Runnable mPositionChangedUpdate;
4771
4772 /**
4773 * Allows the application to implement custom scroll capture support.
4774 */
4775 ScrollCaptureCallback mScrollCaptureCallback;
4776
4777 @Nullable
4778 private OnReceiveContentListener mOnReceiveContentListener;
4779 }
4780
4781 @UnsupportedAppUsage
4782 ListenerInfo mListenerInfo;
4783
4784 private static class TooltipInfo {
4785 /**
4786 * Text to be displayed in a tooltip popup.
4787 */
4788 @Nullable
4789 CharSequence mTooltipText;
4790
4791 /**
4792 * View-relative position of the tooltip anchor point.
4793 */
4794 int mAnchorX;
4795 int mAnchorY;
4796
4797 /**
4798 * The tooltip popup.
4799 */
4800 @Nullable
4801 TooltipPopup mTooltipPopup;
4802
4803 /**
4804 * Set to true if the tooltip was shown as a result of a long click.
4805 */
4806 boolean mTooltipFromLongClick;
4807
4808 /**
4809 * Keep these Runnables so that they can be used to reschedule.
4810 */
4811 Runnable mShowTooltipRunnable;
4812 Runnable mHideTooltipRunnable;
4813
4814 /**
4815 * Hover move is ignored if it is within this distance in pixels from the previous one.
4816 */
4817 int mHoverSlop;
4818
4819 /**
4820 * Update the anchor position if it significantly (that is by at least mHoverSlop)
4821 * different from the previously stored position. Ignoring insignificant changes
4822 * filters out the jitter which is typical for such input sources as stylus.
4823 *
4824 * @return True if the position has been updated.
4825 */
4826 private boolean updateAnchorPos(MotionEvent event) {
4827 final int newAnchorX = (int) event.getX();
4828 final int newAnchorY = (int) event.getY();
4829 if (Math.abs(newAnchorX - mAnchorX) <= mHoverSlop
4830 && Math.abs(newAnchorY - mAnchorY) <= mHoverSlop) {
4831 return false;
4832 }
4833 mAnchorX = newAnchorX;
4834 mAnchorY = newAnchorY;
4835 return true;
4836 }
4837
4838 /**
4839 * Clear the anchor position to ensure that the next change is considered significant.
4840 */
4841 private void clearAnchorPos() {
4842 mAnchorX = Integer.MAX_VALUE;
4843 mAnchorY = Integer.MAX_VALUE;
4844 }
4845 }
4846
4847 TooltipInfo mTooltipInfo;
4848
4849 // Temporary values used to hold (x,y) coordinates when delegating from the
4850 // two-arg performLongClick() method to the legacy no-arg version.
4851 private float mLongClickX = Float.NaN;
4852 private float mLongClickY = Float.NaN;
4853
4854 /**
4855 * The application environment this view lives in.
4856 * This field should be made private, so it is hidden from the SDK.
4857 * {@hide}
4858 */
4859 @ViewDebug.ExportedProperty(deepExport = true)
4860 @UnsupportedAppUsage
4861 @UiContext
4862 protected Context mContext;
4863
4864 @UnsupportedAppUsage
4865 private final Resources mResources;
4866
4867 @UnsupportedAppUsage
4868 private ScrollabilityCache mScrollCache;
4869
4870 private int[] mDrawableState = null;
4871
4872 ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND;
4873
4874 /**
4875 * Animator that automatically runs based on state changes.
4876 */
4877 private StateListAnimator mStateListAnimator;
4878
4879 /**
4880 * When this view has focus and the next focus is {@link #FOCUS_LEFT},
4881 * the user may specify which view to go to next.
4882 */
4883 private int mNextFocusLeftId = View.NO_ID;
4884
4885 /**
4886 * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
4887 * the user may specify which view to go to next.
4888 */
4889 private int mNextFocusRightId = View.NO_ID;
4890
4891 /**
4892 * When this view has focus and the next focus is {@link #FOCUS_UP},
4893 * the user may specify which view to go to next.
4894 */
4895 private int mNextFocusUpId = View.NO_ID;
4896
4897 /**
4898 * When this view has focus and the next focus is {@link #FOCUS_DOWN},
4899 * the user may specify which view to go to next.
4900 */
4901 private int mNextFocusDownId = View.NO_ID;
4902
4903 /**
4904 * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
4905 * the user may specify which view to go to next.
4906 */
4907 int mNextFocusForwardId = View.NO_ID;
4908
4909 /**
4910 * User-specified next keyboard navigation cluster in the {@link #FOCUS_FORWARD} direction.
4911 *
4912 * @see #findUserSetNextKeyboardNavigationCluster(View, int)
4913 */
4914 int mNextClusterForwardId = View.NO_ID;
4915
4916 /**
4917 * Whether this View should use a default focus highlight when it gets focused but doesn't
4918 * have {@link android.R.attr#state_focused} defined in its background.
4919 */
4920 boolean mDefaultFocusHighlightEnabled = true;
4921
4922 private CheckForLongPress mPendingCheckForLongPress;
4923 @UnsupportedAppUsage
4924 private CheckForTap mPendingCheckForTap = null;
4925 private PerformClick mPerformClick;
4926 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
4927 private SendAccessibilityEventThrottle mSendStateChangedAccessibilityEvent;
4928 private UnsetPressedState mUnsetPressedState;
4929
4930 /**
4931 * Whether the long press's action has been invoked. The tap's action is invoked on the
4932 * up event while a long press is invoked as soon as the long press duration is reached, so
4933 * a long press could be performed before the tap is checked, in which case the tap's action
4934 * should not be invoked.
4935 */
4936 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
4937 private boolean mHasPerformedLongPress;
4938
4939 /**
4940 * Whether a context click button is currently pressed down. This is true when the stylus is
4941 * touching the screen and the primary button has been pressed, or if a mouse's right button is
4942 * pressed. This is false once the button is released or if the stylus has been lifted.
4943 */
4944 private boolean mInContextButtonPress;
4945
4946 /**
4947 * Whether the next up event should be ignored for the purposes of gesture recognition. This is
4948 * true after a stylus button press has occured, when the next up event should not be recognized
4949 * as a tap.
4950 */
4951 private boolean mIgnoreNextUpEvent;
4952
4953 /**
4954 * The minimum height of the view. We'll try our best to have the height
4955 * of this view to at least this amount.
4956 */
4957 @ViewDebug.ExportedProperty(category = "measurement")
4958 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
4959 private int mMinHeight;
4960
4961 /**
4962 * The minimum width of the view. We'll try our best to have the width
4963 * of this view to at least this amount.
4964 */
4965 @ViewDebug.ExportedProperty(category = "measurement")
4966 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
4967 private int mMinWidth;
4968
4969 /**
4970 * The delegate to handle touch events that are physically in this view
4971 * but should be handled by another view.
4972 */
4973 private TouchDelegate mTouchDelegate = null;
4974
4975 /**
4976 * While touch exploration is in use, set to true when hovering across boundaries and
4977 * inside the touch area of the delegate at receiving {@link MotionEvent#ACTION_HOVER_ENTER}
4978 * or {@link MotionEvent#ACTION_HOVER_MOVE}. False when leaving boundaries or receiving a
4979 * {@link MotionEvent#ACTION_HOVER_EXIT}.
4980 * Note that children of view group are excluded in the touch area.
4981 * @see #dispatchTouchExplorationHoverEvent
4982 */
4983 private boolean mHoveringTouchDelegate = false;
4984
4985 /**
4986 * Solid color to use as a background when creating the drawing cache. Enables
4987 * the cache to use 16 bit bitmaps instead of 32 bit.
4988 */
4989 private int mDrawingCacheBackgroundColor = 0;
4990
4991 /**
4992 * Special tree observer used when mAttachInfo is null.
4993 */
4994 private ViewTreeObserver mFloatingTreeObserver;
4995
4996 /**
4997 * Cache the touch slop from the context that created the view.
4998 */
4999 private int mTouchSlop;
5000
5001 /**
5002 * Cache the ambiguous gesture multiplier from the context that created the view.
5003 */
5004 private float mAmbiguousGestureMultiplier;
5005
5006 /**
5007 * Object that handles automatic animation of view properties.
5008 */
5009 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
5010 private ViewPropertyAnimator mAnimator = null;
5011
5012 /**
5013 * List of registered FrameMetricsObservers.
5014 */
5015 private ArrayList<FrameMetricsObserver> mFrameMetricsObservers;
5016
5017 /**
5018 * Flag indicating that a drag can cross window boundaries. When
5019 * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called
5020 * with this flag set, all visible applications with targetSdkVersion >=
5021 * {@link android.os.Build.VERSION_CODES#N API 24} will be able to participate
5022 * in the drag operation and receive the dragged content.
5023 *
5024 * <p>If this is the only flag set, then the drag recipient will only have access to text data
5025 * and intents contained in the {@link ClipData} object. Access to URIs contained in the
5026 * {@link ClipData} is determined by other DRAG_FLAG_GLOBAL_* flags</p>
5027 */
5028 public static final int DRAG_FLAG_GLOBAL = 1 << 8; // 256
5029
5030 /**
5031 * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to
5032 * request read access to the content URI(s) contained in the {@link ClipData} object.
5033 * @see android.content.Intent#FLAG_GRANT_READ_URI_PERMISSION
5034 */
5035 public static final int DRAG_FLAG_GLOBAL_URI_READ = Intent.FLAG_GRANT_READ_URI_PERMISSION;
5036
5037 /**
5038 * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to
5039 * request write access to the content URI(s) contained in the {@link ClipData} object.
5040 * @see android.content.Intent#FLAG_GRANT_WRITE_URI_PERMISSION
5041 */
5042 public static final int DRAG_FLAG_GLOBAL_URI_WRITE = Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
5043
5044 /**
5045 * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link
5046 * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant can be persisted across device
5047 * reboots until explicitly revoked with
5048 * {@link android.content.Context#revokeUriPermission(Uri, int)} Context.revokeUriPermission}.
5049 * @see android.content.Intent#FLAG_GRANT_PERSISTABLE_URI_PERMISSION
5050 */
5051 public static final int DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION =
5052 Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION;
5053
5054 /**
5055 * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link
5056 * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant applies to any URI that is a prefix
5057 * match against the original granted URI.
5058 * @see android.content.Intent#FLAG_GRANT_PREFIX_URI_PERMISSION
5059 */
5060 public static final int DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION =
5061 Intent.FLAG_GRANT_PREFIX_URI_PERMISSION;
5062
5063 /**
5064 * Flag indicating that the drag shadow will be opaque. When
5065 * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called
5066 * with this flag set, the drag shadow will be opaque, otherwise, it will be semitransparent.
5067 */
5068 public static final int DRAG_FLAG_OPAQUE = 1 << 9;
5069
5070 /**
5071 * Flag indicating that the drag was initiated with
5072 * {@link AccessibilityNodeInfo.AccessibilityAction#ACTION_DRAG_START}. When
5073 * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called, this
5074 * is used by the system to perform a drag without animations.
5075 */
5076 public static final int DRAG_FLAG_ACCESSIBILITY_ACTION = 1 << 10;
5077
5078 /**
5079 * Flag indicating that the caller desires to take ownership of the drag surface for handling
5080 * the animation associated with an unhandled drag. It is mainly useful if the view starting
5081 * a global drag changes visibility during the gesture and the default animation of animating
5082 * the surface back to the origin is not sufficient.
5083 *
5084 * The calling app must hold the {@link android.Manifest.permission#START_TASKS_FROM_RECENTS}
5085 * permission and will receive the drag surface as a part of
5086 * {@link action.view.DragEvent#ACTION_DRAG_ENDED} only if the drag event's
5087 * {@link action.view.DragEvent#getDragResult()} is {@code false}. The caller is responsible
5088 * for removing the surface after its animation.
5089 *
5090 * This flag has no effect if the system decides that a cancel-drag animation does not need to
5091 * occur.
5092 * @hide
5093 */
5094 public static final int DRAG_FLAG_REQUEST_SURFACE_FOR_RETURN_ANIMATION = 1 << 11;
5095
5096 /**
5097 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
5098 */
5099 private float mVerticalScrollFactor;
5100
5101 /**
5102 * Position of the vertical scroll bar.
5103 */
5104 @UnsupportedAppUsage
5105 private int mVerticalScrollbarPosition;
5106
5107 /**
5108 * Position the scroll bar at the default position as determined by the system.
5109 */
5110 public static final int SCROLLBAR_POSITION_DEFAULT = 0;
5111
5112 /**
5113 * Position the scroll bar along the left edge.
5114 */
5115 public static final int SCROLLBAR_POSITION_LEFT = 1;
5116
5117 /**
5118 * Position the scroll bar along the right edge.
5119 */
5120 public static final int SCROLLBAR_POSITION_RIGHT = 2;
5121
5122 /**
5123 * Indicates that the view does not have a layer.
5124 *
5125 * @see #getLayerType()
5126 * @see #setLayerType(int, android.graphics.Paint)
5127 * @see #LAYER_TYPE_SOFTWARE
5128 * @see #LAYER_TYPE_HARDWARE
5129 */
5130 public static final int LAYER_TYPE_NONE = 0;
5131
5132 /**
5133 * <p>Indicates that the view has a software layer. A software layer is backed
5134 * by a bitmap and causes the view to be rendered using Android's software
5135 * rendering pipeline, even if hardware acceleration is enabled.</p>
5136 *
5137 * <p>Software layers have various usages:</p>
5138 * <p>When the application is not using hardware acceleration, a software layer
5139 * is useful to apply a specific color filter and/or blending mode and/or
5140 * translucency to a view and all its children.</p>
5141 * <p>When the application is using hardware acceleration, a software layer
5142 * is useful to render drawing primitives not supported by the hardware
5143 * accelerated pipeline. It can also be used to cache a complex view tree
5144 * into a texture and reduce the complexity of drawing operations. For instance,
5145 * when animating a complex view tree with a translation, a software layer can
5146 * be used to render the view tree only once.</p>
5147 * <p>Software layers should be avoided when the affected view tree updates
5148 * often. Every update will require to re-render the software layer, which can
5149 * potentially be slow (particularly when hardware acceleration is turned on
5150 * since the layer will have to be uploaded into a hardware texture after every
5151 * update.)</p>
5152 *
5153 * @see #getLayerType()
5154 * @see #setLayerType(int, android.graphics.Paint)
5155 * @see #LAYER_TYPE_NONE
5156 * @see #LAYER_TYPE_HARDWARE
5157 */
5158 public static final int LAYER_TYPE_SOFTWARE = 1;
5159
5160 /**
5161 * <p>Indicates that the view has a hardware layer. A hardware layer is backed
5162 * by a hardware specific texture (generally Frame Buffer Objects or FBO on
5163 * OpenGL hardware) and causes the view to be rendered using Android's hardware
5164 * rendering pipeline, but only if hardware acceleration is turned on for the
5165 * view hierarchy. When hardware acceleration is turned off, hardware layers
5166 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
5167 *
5168 * <p>A hardware layer is useful to apply a specific color filter and/or
5169 * blending mode and/or translucency to a view and all its children.</p>
5170 * <p>A hardware layer can be used to cache a complex view tree into a
5171 * texture and reduce the complexity of drawing operations. For instance,
5172 * when animating a complex view tree with a translation, a hardware layer can
5173 * be used to render the view tree only once.</p>
5174 * <p>A hardware layer can also be used to increase the rendering quality when
5175 * rotation transformations are applied on a view. It can also be used to
5176 * prevent potential clipping issues when applying 3D transforms on a view.</p>
5177 *
5178 * @see #getLayerType()
5179 * @see #setLayerType(int, android.graphics.Paint)
5180 * @see #LAYER_TYPE_NONE
5181 * @see #LAYER_TYPE_SOFTWARE
5182 */
5183 public static final int LAYER_TYPE_HARDWARE = 2;
5184
5185 /** @hide */
5186 @IntDef(prefix = { "LAYER_TYPE_" }, value = {
5187 LAYER_TYPE_NONE,
5188 LAYER_TYPE_SOFTWARE,
5189 LAYER_TYPE_HARDWARE
5190 })
5191 @Retention(RetentionPolicy.SOURCE)
5192 public @interface LayerType {}
5193
5194 @ViewDebug.ExportedProperty(category = "drawing", mapping = {
5195 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
5196 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
5197 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
5198 })
5199 int mLayerType = LAYER_TYPE_NONE;
5200 Paint mLayerPaint;
5201
5202 /**
5203 * Set to true when drawing cache is enabled and cannot be created.
5204 *
5205 * @hide
5206 */
5207 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
5208 public boolean mCachingFailed;
5209 @UnsupportedAppUsage
5210 private Bitmap mDrawingCache;
5211 @UnsupportedAppUsage
5212 private Bitmap mUnscaledDrawingCache;
5213
5214 /**
5215 * RenderNode holding View properties, potentially holding a DisplayList of View content.
5216 * <p>
5217 * When non-null and valid, this is expected to contain an up-to-date copy
5218 * of the View content. Its DisplayList content is cleared on temporary detach and reset on
5219 * cleanup.
5220 */
5221 @UnsupportedAppUsage
5222 final RenderNode mRenderNode;
5223
5224 /**
5225 * Set to true when the view is sending hover accessibility events because it
5226 * is the innermost hovered view.
5227 */
5228 private boolean mSendingHoverAccessibilityEvents;
5229
5230 /**
5231 * Delegate for injecting accessibility functionality.
5232 */
5233 @UnsupportedAppUsage
5234 AccessibilityDelegate mAccessibilityDelegate;
5235
5236 /**
5237 * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
5238 * and add/remove objects to/from the overlay directly through the Overlay methods.
5239 */
5240 ViewOverlay mOverlay;
5241
5242 /**
5243 * The currently active parent view for receiving delegated nested scrolling events.
5244 * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared
5245 * by {@link #stopNestedScroll()} at the same point where we clear
5246 * requestDisallowInterceptTouchEvent.
5247 */
5248 private ViewParent mNestedScrollingParent;
5249
5250 /**
5251 * Consistency verifier for debugging purposes.
5252 * @hide
5253 */
5254 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
5255 InputEventConsistencyVerifier.isInstrumentationEnabled() ?
5256 new InputEventConsistencyVerifier(this, 0) : null;
5257
5258 private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
5259
5260 private int[] mTempNestedScrollConsumed;
5261
5262 /**
5263 * An overlay is going to draw this View instead of being drawn as part of this
5264 * View's parent. mGhostView is the View in the Overlay that must be invalidated
5265 * when this view is invalidated.
5266 */
5267 GhostView mGhostView;
5268
5269 /**
5270 * Holds pairs of adjacent attribute data: attribute name followed by its value.
5271 * @hide
5272 */
5273 @ViewDebug.ExportedProperty(category = "attributes", hasAdjacentMapping = true)
5274 public String[] mAttributes;
5275
5276 /**
5277 * Maps a Resource id to its name.
5278 */
5279 private static SparseArray<String> mAttributeMap;
5280
5281 /**
5282 * Queue of pending runnables. Used to postpone calls to post() until this
5283 * view is attached and has a handler.
5284 */
5285 private HandlerActionQueue mRunQueue;
5286
5287 /**
5288 * The pointer icon when the mouse hovers on this view. The default is null.
5289 */
5290 private PointerIcon mPointerIcon;
5291
5292 /**
5293 * @hide
5294 */
5295 @UnsupportedAppUsage
5296 String mStartActivityRequestWho;
5297
5298 @Nullable
5299 private RoundScrollbarRenderer mRoundScrollbarRenderer;
5300
5301 /** Used to delay visibility updates sent to the autofill manager */
5302 private Handler mVisibilityChangeForAutofillHandler;
5303
5304 /**
5305 * Used when app developers explicitly set the {@link ContentCaptureSession} associated with the
5306 * view (through {@link #setContentCaptureSession(ContentCaptureSession)}.
5307 */
5308 @Nullable
5309 private ContentCaptureSession mContentCaptureSession;
5310
5311 /**
5312 * Whether {@link ContentCaptureSession} is cached, resets on {@link #invalidate()}.
5313 */
5314 private boolean mContentCaptureSessionCached;
5315
5316 @LayoutRes
5317 private int mSourceLayoutId = ID_NULL;
5318
5319 @Nullable
5320 private SparseIntArray mAttributeSourceResId;
5321
5322 @Nullable
5323 private SparseArray<int[]> mAttributeResolutionStacks;
5324
5325 @StyleRes
5326 private int mExplicitStyle;
5327
5328 /**
5329 * Specifies which input source classes should provide unbuffered input events to this view
5330 *
5331 * @see View#requestUnbufferedDispatch(int)
5332 */
5333 @InputSourceClass
5334 int mUnbufferedInputSource = InputDevice.SOURCE_CLASS_NONE;
5335
5336 @Nullable
5337 private String[] mReceiveContentMimeTypes;
5338
5339 @Nullable
5340 private ViewTranslationCallback mViewTranslationCallback;
5341
5342 @Nullable
5343
5344 private ViewTranslationResponse mViewTranslationResponse;
5345
5346 /**
5347 * Simple constructor to use when creating a view from code.
5348 *
5349 * @param context The Context the view is running in, through which it can
5350 * access the current theme, resources, etc.
5351 */
5352 public View(Context context) {
5353 mContext = context;
5354 mResources = context != null ? context.getResources() : null;
5355 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED | FOCUSABLE_AUTO;
5356 // Set some flags defaults
5357 mPrivateFlags2 =
5358 (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
5359 (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
5360 (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
5361 (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
5362 (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
5363 (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
5364 mPrivateFlags4 = PFLAG4_AUTO_HANDWRITING_ENABLED;
5365
5366 final ViewConfiguration configuration = ViewConfiguration.get(context);
5367 mTouchSlop = configuration.getScaledTouchSlop();
5368 mAmbiguousGestureMultiplier = configuration.getScaledAmbiguousGestureMultiplier();
5369
5370 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
5371 mUserPaddingStart = UNDEFINED_PADDING;
5372 mUserPaddingEnd = UNDEFINED_PADDING;
5373 mRenderNode = RenderNode.create(getClass().getName(), new ViewAnimationHostBridge(this));
5374
5375 if (!sCompatibilityDone && context != null) {
5376 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
5377
5378 // Older apps may need this compatibility hack for measurement.
5379 sUseBrokenMakeMeasureSpec = targetSdkVersion <= Build.VERSION_CODES.JELLY_BEAN_MR1;
5380
5381 // Older apps expect onMeasure() to always be called on a layout pass, regardless
5382 // of whether a layout was requested on that View.
5383 sIgnoreMeasureCache = targetSdkVersion < Build.VERSION_CODES.KITKAT;
5384
5385 // In M and newer, our widgets can pass a "hint" value in the size
5386 // for UNSPECIFIED MeasureSpecs. This lets child views of scrolling containers
5387 // know what the expected parent size is going to be, so e.g. list items can size
5388 // themselves at 1/3 the size of their container. It breaks older apps though,
5389 // specifically apps that use some popular open source libraries.
5390 sUseZeroUnspecifiedMeasureSpec = targetSdkVersion < Build.VERSION_CODES.M;
5391
5392 // Old versions of the platform would give different results from
5393 // LinearLayout measurement passes using EXACTLY and non-EXACTLY
5394 // modes, so we always need to run an additional EXACTLY pass.
5395 sAlwaysRemeasureExactly = targetSdkVersion <= Build.VERSION_CODES.M;
5396
5397 // Prior to N, TextureView would silently ignore calls to setBackground/setForeground.
5398 // On N+, we throw, but that breaks compatibility with apps that use these methods.
5399 sTextureViewIgnoresDrawableSetters = targetSdkVersion <= Build.VERSION_CODES.M;
5400
5401 // Prior to N, we would drop margins in LayoutParam conversions. The fix triggers bugs
5402 // in apps so we target check it to avoid breaking existing apps.
5403 sPreserveMarginParamsInLayoutParamConversion =
5404 targetSdkVersion >= Build.VERSION_CODES.N;
5405
5406 sCascadedDragDrop = targetSdkVersion < Build.VERSION_CODES.N;
5407
5408 sHasFocusableExcludeAutoFocusable = targetSdkVersion < Build.VERSION_CODES.O;
5409
5410 sAutoFocusableOffUIThreadWontNotifyParents = targetSdkVersion < Build.VERSION_CODES.O;
5411
5412 sUseDefaultFocusHighlight = context.getResources().getBoolean(
5413 com.android.internal.R.bool.config_useDefaultFocusHighlight);
5414
5415 sThrowOnInvalidFloatProperties = targetSdkVersion >= Build.VERSION_CODES.P;
5416
5417 sCanFocusZeroSized = targetSdkVersion < Build.VERSION_CODES.P;
5418
5419 sAlwaysAssignFocus = targetSdkVersion < Build.VERSION_CODES.P;
5420
5421 sAcceptZeroSizeDragShadow = targetSdkVersion < Build.VERSION_CODES.P;
5422
5423 sBrokenInsetsDispatch = targetSdkVersion < Build.VERSION_CODES.R;
5424
5425 sBrokenWindowBackground = targetSdkVersion < Build.VERSION_CODES.Q;
5426
5427 GradientDrawable.sWrapNegativeAngleMeasurements =
5428 targetSdkVersion >= Build.VERSION_CODES.Q;
5429
5430 sForceLayoutWhenInsetsChanged = targetSdkVersion < Build.VERSION_CODES.R;
5431
5432 sCompatibilityDone = true;
5433 }
5434 }
5435
5436 /**
5437 * Constructor that is called when inflating a view from XML. This is called
5438 * when a view is being constructed from an XML file, supplying attributes
5439 * that were specified in the XML file. This version uses a default style of
5440 * 0, so the only attribute values applied are those in the Context's Theme
5441 * and the given AttributeSet.
5442 *
5443 * <p>
5444 * The method onFinishInflate() will be called after all children have been
5445 * added.
5446 *
5447 * @param context The Context the view is running in, through which it can
5448 * access the current theme, resources, etc.
5449 * @param attrs The attributes of the XML tag that is inflating the view.
5450 * @see #View(Context, AttributeSet, int)
5451 */
5452 public View(Context context, @Nullable AttributeSet attrs) {
5453 this(context, attrs, 0);
5454 }
5455
5456 /**
5457 * Perform inflation from XML and apply a class-specific base style from a
5458 * theme attribute. This constructor of View allows subclasses to use their
5459 * own base style when they are inflating. For example, a Button class's
5460 * constructor would call this version of the super class constructor and
5461 * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this
5462 * allows the theme's button style to modify all of the base view attributes
5463 * (in particular its background) as well as the Button class's attributes.
5464 *
5465 * @param context The Context the view is running in, through which it can
5466 * access the current theme, resources, etc.
5467 * @param attrs The attributes of the XML tag that is inflating the view.
5468 * @param defStyleAttr An attribute in the current theme that contains a
5469 * reference to a style resource that supplies default values for
5470 * the view. Can be 0 to not look for defaults.
5471 * @see #View(Context, AttributeSet)
5472 */
5473 public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
5474 this(context, attrs, defStyleAttr, 0);
5475 }
5476
5477 /**
5478 * Perform inflation from XML and apply a class-specific base style from a
5479 * theme attribute or style resource. This constructor of View allows
5480 * subclasses to use their own base style when they are inflating.
5481 * <p>
5482 * When determining the final value of a particular attribute, there are
5483 * four inputs that come into play:
5484 * <ol>
5485 * <li>Any attribute values in the given AttributeSet.
5486 * <li>The style resource specified in the AttributeSet (named "style").
5487 * <li>The default style specified by <var>defStyleAttr</var>.
5488 * <li>The default style specified by <var>defStyleRes</var>.
5489 * <li>The base values in this theme.
5490 * </ol>
5491 * <p>
5492 * Each of these inputs is considered in-order, with the first listed taking
5493 * precedence over the following ones. In other words, if in the
5494 * AttributeSet you have supplied <code>&lt;Button * textColor="#ff000000"&gt;</code>
5495 * , then the button's text will <em>always</em> be black, regardless of
5496 * what is specified in any of the styles.
5497 *
5498 * @param context The Context the view is running in, through which it can
5499 * access the current theme, resources, etc.
5500 * @param attrs The attributes of the XML tag that is inflating the view.
5501 * @param defStyleAttr An attribute in the current theme that contains a
5502 * reference to a style resource that supplies default values for
5503 * the view. Can be 0 to not look for defaults.
5504 * @param defStyleRes A resource identifier of a style resource that
5505 * supplies default values for the view, used only if
5506 * defStyleAttr is 0 or can not be found in the theme. Can be 0
5507 * to not look for defaults.
5508 * @see #View(Context, AttributeSet, int)
5509 */
5510 public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
5511 this(context);
5512
5513 mSourceLayoutId = Resources.getAttributeSetSourceResId(attrs);
5514
5515 final TypedArray a = context.obtainStyledAttributes(
5516 attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes);
5517
5518 retrieveExplicitStyle(context.getTheme(), attrs);
5519 saveAttributeDataForStyleable(context, com.android.internal.R.styleable.View, attrs, a,
5520 defStyleAttr, defStyleRes);
5521
5522 if (sDebugViewAttributes) {
5523 saveAttributeData(attrs, a);
5524 }
5525
5526 Drawable background = null;
5527
5528 int leftPadding = -1;
5529 int topPadding = -1;
5530 int rightPadding = -1;
5531 int bottomPadding = -1;
5532 int startPadding = UNDEFINED_PADDING;
5533 int endPadding = UNDEFINED_PADDING;
5534
5535 int padding = -1;
5536 int paddingHorizontal = -1;
5537 int paddingVertical = -1;
5538
5539 int viewFlagValues = 0;
5540 int viewFlagMasks = 0;
5541
5542 boolean setScrollContainer = false;
5543
5544 int x = 0;
5545 int y = 0;
5546
5547 float tx = 0;
5548 float ty = 0;
5549 float tz = 0;
5550 float elevation = 0;
5551 float rotation = 0;
5552 float rotationX = 0;
5553 float rotationY = 0;
5554 float sx = 1f;
5555 float sy = 1f;
5556 boolean transformSet = false;
5557
5558 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
5559 int overScrollMode = mOverScrollMode;
5560 boolean initializeScrollbars = false;
5561 boolean initializeScrollIndicators = false;
5562
5563 boolean startPaddingDefined = false;
5564 boolean endPaddingDefined = false;
5565 boolean leftPaddingDefined = false;
5566 boolean rightPaddingDefined = false;
5567
5568 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
5569
5570 // Set default values.
5571 viewFlagValues |= FOCUSABLE_AUTO;
5572 viewFlagMasks |= FOCUSABLE_AUTO;
5573
5574 final int N = a.getIndexCount();
5575 for (int i = 0; i < N; i++) {
5576 int attr = a.getIndex(i);
5577 switch (attr) {
5578 case com.android.internal.R.styleable.View_background:
5579 background = a.getDrawable(attr);
5580 break;
5581 case com.android.internal.R.styleable.View_padding:
5582 padding = a.getDimensionPixelSize(attr, -1);
5583 mUserPaddingLeftInitial = padding;
5584 mUserPaddingRightInitial = padding;
5585 leftPaddingDefined = true;
5586 rightPaddingDefined = true;
5587 break;
5588 case com.android.internal.R.styleable.View_paddingHorizontal:
5589 paddingHorizontal = a.getDimensionPixelSize(attr, -1);
5590 mUserPaddingLeftInitial = paddingHorizontal;
5591 mUserPaddingRightInitial = paddingHorizontal;
5592 leftPaddingDefined = true;
5593 rightPaddingDefined = true;
5594 break;
5595 case com.android.internal.R.styleable.View_paddingVertical:
5596 paddingVertical = a.getDimensionPixelSize(attr, -1);
5597 break;
5598 case com.android.internal.R.styleable.View_paddingLeft:
5599 leftPadding = a.getDimensionPixelSize(attr, -1);
5600 mUserPaddingLeftInitial = leftPadding;
5601 leftPaddingDefined = true;
5602 break;
5603 case com.android.internal.R.styleable.View_paddingTop:
5604 topPadding = a.getDimensionPixelSize(attr, -1);
5605 break;
5606 case com.android.internal.R.styleable.View_paddingRight:
5607 rightPadding = a.getDimensionPixelSize(attr, -1);
5608 mUserPaddingRightInitial = rightPadding;
5609 rightPaddingDefined = true;
5610 break;
5611 case com.android.internal.R.styleable.View_paddingBottom:
5612 bottomPadding = a.getDimensionPixelSize(attr, -1);
5613 break;
5614 case com.android.internal.R.styleable.View_paddingStart:
5615 startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
5616 startPaddingDefined = (startPadding != UNDEFINED_PADDING);
5617 break;
5618 case com.android.internal.R.styleable.View_paddingEnd:
5619 endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
5620 endPaddingDefined = (endPadding != UNDEFINED_PADDING);
5621 break;
5622 case com.android.internal.R.styleable.View_scrollX:
5623 x = a.getDimensionPixelOffset(attr, 0);
5624 break;
5625 case com.android.internal.R.styleable.View_scrollY:
5626 y = a.getDimensionPixelOffset(attr, 0);
5627 break;
5628 case com.android.internal.R.styleable.View_alpha:
5629 setAlpha(a.getFloat(attr, 1f));
5630 break;
5631 case com.android.internal.R.styleable.View_transformPivotX:
5632 setPivotX(a.getDimension(attr, 0));
5633 break;
5634 case com.android.internal.R.styleable.View_transformPivotY:
5635 setPivotY(a.getDimension(attr, 0));
5636 break;
5637 case com.android.internal.R.styleable.View_translationX:
5638 tx = a.getDimension(attr, 0);
5639 transformSet = true;
5640 break;
5641 case com.android.internal.R.styleable.View_translationY:
5642 ty = a.getDimension(attr, 0);
5643 transformSet = true;
5644 break;
5645 case com.android.internal.R.styleable.View_translationZ:
5646 tz = a.getDimension(attr, 0);
5647 transformSet = true;
5648 break;
5649 case com.android.internal.R.styleable.View_elevation:
5650 elevation = a.getDimension(attr, 0);
5651 transformSet = true;
5652 break;
5653 case com.android.internal.R.styleable.View_rotation:
5654 rotation = a.getFloat(attr, 0);
5655 transformSet = true;
5656 break;
5657 case com.android.internal.R.styleable.View_rotationX:
5658 rotationX = a.getFloat(attr, 0);
5659 transformSet = true;
5660 break;
5661 case com.android.internal.R.styleable.View_rotationY:
5662 rotationY = a.getFloat(attr, 0);
5663 transformSet = true;
5664 break;
5665 case com.android.internal.R.styleable.View_scaleX:
5666 sx = a.getFloat(attr, 1f);
5667 transformSet = true;
5668 break;
5669 case com.android.internal.R.styleable.View_scaleY:
5670 sy = a.getFloat(attr, 1f);
5671 transformSet = true;
5672 break;
5673 case com.android.internal.R.styleable.View_id:
5674 mID = a.getResourceId(attr, NO_ID);
5675 break;
5676 case com.android.internal.R.styleable.View_tag:
5677 mTag = a.getText(attr);
5678 break;
5679 case com.android.internal.R.styleable.View_fitsSystemWindows:
5680 if (a.getBoolean(attr, false)) {
5681 viewFlagValues |= FITS_SYSTEM_WINDOWS;
5682 viewFlagMasks |= FITS_SYSTEM_WINDOWS;
5683 }
5684 break;
5685 case com.android.internal.R.styleable.View_focusable:
5686 viewFlagValues = (viewFlagValues & ~FOCUSABLE_MASK) | getFocusableAttribute(a);
5687 if ((viewFlagValues & FOCUSABLE_AUTO) == 0) {
5688 viewFlagMasks |= FOCUSABLE_MASK;
5689 }
5690 break;
5691 case com.android.internal.R.styleable.View_focusableInTouchMode:
5692 if (a.getBoolean(attr, false)) {
5693 // unset auto focus since focusableInTouchMode implies explicit focusable
5694 viewFlagValues &= ~FOCUSABLE_AUTO;
5695 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
5696 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
5697 }
5698 break;
5699 case com.android.internal.R.styleable.View_clickable:
5700 if (a.getBoolean(attr, false)) {
5701 viewFlagValues |= CLICKABLE;
5702 viewFlagMasks |= CLICKABLE;
5703 }
5704 break;
5705 case com.android.internal.R.styleable.View_allowClickWhenDisabled:
5706 setAllowClickWhenDisabled(a.getBoolean(attr, false));
5707 break;
5708 case com.android.internal.R.styleable.View_longClickable:
5709 if (a.getBoolean(attr, false)) {
5710 viewFlagValues |= LONG_CLICKABLE;
5711 viewFlagMasks |= LONG_CLICKABLE;
5712 }
5713 break;
5714 case com.android.internal.R.styleable.View_contextClickable:
5715 if (a.getBoolean(attr, false)) {
5716 viewFlagValues |= CONTEXT_CLICKABLE;
5717 viewFlagMasks |= CONTEXT_CLICKABLE;
5718 }
5719 break;
5720 case com.android.internal.R.styleable.View_saveEnabled:
5721 if (!a.getBoolean(attr, true)) {
5722 viewFlagValues |= SAVE_DISABLED;
5723 viewFlagMasks |= SAVE_DISABLED_MASK;
5724 }
5725 break;
5726 case com.android.internal.R.styleable.View_duplicateParentState:
5727 if (a.getBoolean(attr, false)) {
5728 viewFlagValues |= DUPLICATE_PARENT_STATE;
5729 viewFlagMasks |= DUPLICATE_PARENT_STATE;
5730 }
5731 break;
5732 case com.android.internal.R.styleable.View_visibility:
5733 final int visibility = a.getInt(attr, 0);
5734 if (visibility != 0) {
5735 viewFlagValues |= VISIBILITY_FLAGS[visibility];
5736 viewFlagMasks |= VISIBILITY_MASK;
5737 }
5738 break;
5739 case com.android.internal.R.styleable.View_layoutDirection:
5740 // Clear any layout direction flags (included resolved bits) already set
5741 mPrivateFlags2 &=
5742 ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
5743 // Set the layout direction flags depending on the value of the attribute
5744 final int layoutDirection = a.getInt(attr, -1);
5745 final int value = (layoutDirection != -1) ?
5746 LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
5747 mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
5748 break;
5749 case com.android.internal.R.styleable.View_drawingCacheQuality:
5750 final int cacheQuality = a.getInt(attr, 0);
5751 if (cacheQuality != 0) {
5752 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
5753 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
5754 }
5755 break;
5756 case com.android.internal.R.styleable.View_contentDescription:
5757 setContentDescription(a.getString(attr));
5758 break;
5759 case com.android.internal.R.styleable.View_accessibilityTraversalBefore:
5760 setAccessibilityTraversalBefore(a.getResourceId(attr, NO_ID));
5761 break;
5762 case com.android.internal.R.styleable.View_accessibilityTraversalAfter:
5763 setAccessibilityTraversalAfter(a.getResourceId(attr, NO_ID));
5764 break;
5765 case com.android.internal.R.styleable.View_labelFor:
5766 setLabelFor(a.getResourceId(attr, NO_ID));
5767 break;
5768 case com.android.internal.R.styleable.View_soundEffectsEnabled:
5769 if (!a.getBoolean(attr, true)) {
5770 viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
5771 viewFlagMasks |= SOUND_EFFECTS_ENABLED;
5772 }
5773 break;
5774 case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
5775 if (!a.getBoolean(attr, true)) {
5776 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
5777 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
5778 }
5779 break;
5780 case R.styleable.View_scrollbars:
5781 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
5782 if (scrollbars != SCROLLBARS_NONE) {
5783 viewFlagValues |= scrollbars;
5784 viewFlagMasks |= SCROLLBARS_MASK;
5785 initializeScrollbars = true;
5786 }
5787 break;
5788 //noinspection deprecation
5789 case R.styleable.View_fadingEdge:
5790 if (targetSdkVersion >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
5791 // Ignore the attribute starting with ICS
5792 break;
5793 }
5794 // With builds < ICS, fall through and apply fading edges
5795 case R.styleable.View_requiresFadingEdge:
5796 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
5797 if (fadingEdge != FADING_EDGE_NONE) {
5798 viewFlagValues |= fadingEdge;
5799 viewFlagMasks |= FADING_EDGE_MASK;
5800 initializeFadingEdgeInternal(a);
5801 }
5802 break;
5803 case R.styleable.View_scrollbarStyle:
5804 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
5805 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
5806 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
5807 viewFlagMasks |= SCROLLBARS_STYLE_MASK;
5808 }
5809 break;
5810 case R.styleable.View_isScrollContainer:
5811 setScrollContainer = true;
5812 if (a.getBoolean(attr, false)) {
5813 setScrollContainer(true);
5814 }
5815 break;
5816 case com.android.internal.R.styleable.View_keepScreenOn:
5817 if (a.getBoolean(attr, false)) {
5818 viewFlagValues |= KEEP_SCREEN_ON;
5819 viewFlagMasks |= KEEP_SCREEN_ON;
5820 }
5821 break;
5822 case R.styleable.View_filterTouchesWhenObscured:
5823 if (a.getBoolean(attr, false)) {
5824 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
5825 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
5826 }
5827 break;
5828 case R.styleable.View_nextFocusLeft:
5829 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
5830 break;
5831 case R.styleable.View_nextFocusRight:
5832 mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
5833 break;
5834 case R.styleable.View_nextFocusUp:
5835 mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
5836 break;
5837 case R.styleable.View_nextFocusDown:
5838 mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
5839 break;
5840 case R.styleable.View_nextFocusForward:
5841 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
5842 break;
5843 case R.styleable.View_nextClusterForward:
5844 mNextClusterForwardId = a.getResourceId(attr, View.NO_ID);
5845 break;
5846 case R.styleable.View_minWidth:
5847 mMinWidth = a.getDimensionPixelSize(attr, 0);
5848 break;
5849 case R.styleable.View_minHeight:
5850 mMinHeight = a.getDimensionPixelSize(attr, 0);
5851 break;
5852 case R.styleable.View_onClick:
5853 if (context.isRestricted()) {
5854 throw new IllegalStateException("The android:onClick attribute cannot "
5855 + "be used within a restricted context");
5856 }
5857
5858 final String handlerName = a.getString(attr);
5859 if (handlerName != null) {
5860 setOnClickListener(new DeclaredOnClickListener(this, handlerName));
5861 }
5862 break;
5863 case R.styleable.View_overScrollMode:
5864 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
5865 break;
5866 case R.styleable.View_verticalScrollbarPosition:
5867 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
5868 break;
5869 case R.styleable.View_layerType:
5870 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
5871 break;
5872 case R.styleable.View_textDirection:
5873 // Clear any text direction flag already set
5874 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
5875 // Set the text direction flags depending on the value of the attribute
5876 final int textDirection = a.getInt(attr, -1);
5877 if (textDirection != -1) {
5878 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
5879 }
5880 break;
5881 case R.styleable.View_textAlignment:
5882 // Clear any text alignment flag already set
5883 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
5884 // Set the text alignment flag depending on the value of the attribute
5885 final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
5886 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
5887 break;
5888 case R.styleable.View_importantForAccessibility:
5889 setImportantForAccessibility(a.getInt(attr,
5890 IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
5891 break;
5892 case R.styleable.View_accessibilityLiveRegion:
5893 setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT));
5894 break;
5895 case R.styleable.View_transitionName:
5896 setTransitionName(a.getString(attr));
5897 break;
5898 case R.styleable.View_nestedScrollingEnabled:
5899 setNestedScrollingEnabled(a.getBoolean(attr, false));
5900 break;
5901 case R.styleable.View_stateListAnimator:
5902 setStateListAnimator(AnimatorInflater.loadStateListAnimator(context,
5903 a.getResourceId(attr, 0)));
5904 break;
5905 case R.styleable.View_backgroundTint:
5906 // This will get applied later during setBackground().
5907 if (mBackgroundTint == null) {
5908 mBackgroundTint = new TintInfo();
5909 }
5910 mBackgroundTint.mTintList = a.getColorStateList(
5911 R.styleable.View_backgroundTint);
5912 mBackgroundTint.mHasTintList = true;
5913 break;
5914 case R.styleable.View_backgroundTintMode:
5915 // This will get applied later during setBackground().
5916 if (mBackgroundTint == null) {
5917 mBackgroundTint = new TintInfo();
5918 }
5919 mBackgroundTint.mBlendMode = Drawable.parseBlendMode(a.getInt(
5920 R.styleable.View_backgroundTintMode, -1), null);
5921 mBackgroundTint.mHasTintMode = true;
5922 break;
5923 case R.styleable.View_outlineProvider:
5924 setOutlineProviderFromAttribute(a.getInt(R.styleable.View_outlineProvider,
5925 PROVIDER_BACKGROUND));
5926 break;
5927 case R.styleable.View_foreground:
5928 if (targetSdkVersion >= Build.VERSION_CODES.M || this instanceof FrameLayout) {
5929 setForeground(a.getDrawable(attr));
5930 }
5931 break;
5932 case R.styleable.View_foregroundGravity:
5933 if (targetSdkVersion >= Build.VERSION_CODES.M || this instanceof FrameLayout) {
5934 setForegroundGravity(a.getInt(attr, Gravity.NO_GRAVITY));
5935 }
5936 break;
5937 case R.styleable.View_foregroundTintMode:
5938 if (targetSdkVersion >= Build.VERSION_CODES.M || this instanceof FrameLayout) {
5939 setForegroundTintBlendMode(
5940 Drawable.parseBlendMode(a.getInt(attr, -1),
5941 null));
5942 }
5943 break;
5944 case R.styleable.View_foregroundTint:
5945 if (targetSdkVersion >= Build.VERSION_CODES.M || this instanceof FrameLayout) {
5946 setForegroundTintList(a.getColorStateList(attr));
5947 }
5948 break;
5949 case R.styleable.View_foregroundInsidePadding:
5950 if (targetSdkVersion >= Build.VERSION_CODES.M || this instanceof FrameLayout) {
5951 if (mForegroundInfo == null) {
5952 mForegroundInfo = new ForegroundInfo();
5953 }
5954 mForegroundInfo.mInsidePadding = a.getBoolean(attr,
5955 mForegroundInfo.mInsidePadding);
5956 }
5957 break;
5958 case R.styleable.View_scrollIndicators:
5959 final int scrollIndicators =
5960 (a.getInt(attr, 0) << SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT)
5961 & SCROLL_INDICATORS_PFLAG3_MASK;
5962 if (scrollIndicators != 0) {
5963 mPrivateFlags3 |= scrollIndicators;
5964 initializeScrollIndicators = true;
5965 }
5966 break;
5967 case R.styleable.View_pointerIcon:
5968 final int resourceId = a.getResourceId(attr, 0);
5969 if (resourceId != 0) {
5970 setPointerIcon(PointerIcon.load(
5971 context.getResources(), resourceId));
5972 } else {
5973 final int pointerType = a.getInt(attr, PointerIcon.TYPE_NOT_SPECIFIED);
5974 if (pointerType != PointerIcon.TYPE_NOT_SPECIFIED) {
5975 setPointerIcon(PointerIcon.getSystemIcon(context, pointerType));
5976 }
5977 }
5978 break;
5979 case R.styleable.View_forceHasOverlappingRendering:
5980 if (a.peekValue(attr) != null) {
5981 forceHasOverlappingRendering(a.getBoolean(attr, true));
5982 }
5983 break;
5984 case R.styleable.View_tooltipText:
5985 setTooltipText(a.getText(attr));
5986 break;
5987 case R.styleable.View_keyboardNavigationCluster:
5988 if (a.peekValue(attr) != null) {
5989 setKeyboardNavigationCluster(a.getBoolean(attr, true));
5990 }
5991 break;
5992 case R.styleable.View_focusedByDefault:
5993 if (a.peekValue(attr) != null) {
5994 setFocusedByDefault(a.getBoolean(attr, true));
5995 }
5996 break;
5997 case R.styleable.View_autofillHints:
5998 if (a.peekValue(attr) != null) {
5999 CharSequence[] rawHints = null;
6000 String rawString = null;
6001
6002 if (a.getType(attr) == TypedValue.TYPE_REFERENCE) {
6003 int resId = a.getResourceId(attr, 0);
6004
6005 try {
6006 rawHints = a.getTextArray(attr);
6007 } catch (Resources.NotFoundException e) {
6008 rawString = getResources().getString(resId);
6009 }
6010 } else {
6011 rawString = a.getString(attr);
6012 }
6013
6014 if (rawHints == null) {
6015 if (rawString == null) {
6016 throw new IllegalArgumentException(
6017 "Could not resolve autofillHints");
6018 } else {
6019 rawHints = rawString.split(",");
6020 }
6021 }
6022
6023 String[] hints = new String[rawHints.length];
6024
6025 int numHints = rawHints.length;
6026 for (int rawHintNum = 0; rawHintNum < numHints; rawHintNum++) {
6027 hints[rawHintNum] = rawHints[rawHintNum].toString().trim();
6028 }
6029 setAutofillHints(hints);
6030 }
6031 break;
6032 case R.styleable.View_importantForAutofill:
6033 if (a.peekValue(attr) != null) {
6034 setImportantForAutofill(a.getInt(attr, IMPORTANT_FOR_AUTOFILL_AUTO));
6035 }
6036 break;
6037 case R.styleable.View_importantForContentCapture:
6038 if (a.peekValue(attr) != null) {
6039 setImportantForContentCapture(a.getInt(attr,
6040 IMPORTANT_FOR_CONTENT_CAPTURE_AUTO));
6041 }
6042 case R.styleable.View_defaultFocusHighlightEnabled:
6043 if (a.peekValue(attr) != null) {
6044 setDefaultFocusHighlightEnabled(a.getBoolean(attr, true));
6045 }
6046 break;
6047 case R.styleable.View_screenReaderFocusable:
6048 if (a.peekValue(attr) != null) {
6049 setScreenReaderFocusable(a.getBoolean(attr, false));
6050 }
6051 break;
6052 case R.styleable.View_accessibilityPaneTitle:
6053 if (a.peekValue(attr) != null) {
6054 setAccessibilityPaneTitle(a.getString(attr));
6055 }
6056 break;
6057 case R.styleable.View_outlineSpotShadowColor:
6058 setOutlineSpotShadowColor(a.getColor(attr, Color.BLACK));
6059 break;
6060 case R.styleable.View_outlineAmbientShadowColor:
6061 setOutlineAmbientShadowColor(a.getColor(attr, Color.BLACK));
6062 break;
6063 case com.android.internal.R.styleable.View_accessibilityHeading:
6064 setAccessibilityHeading(a.getBoolean(attr, false));
6065 break;
6066 case R.styleable.View_forceDarkAllowed:
6067 mRenderNode.setForceDarkAllowed(a.getBoolean(attr, true));
6068 break;
6069 case R.styleable.View_scrollCaptureHint:
6070 setScrollCaptureHint((a.getInt(attr, SCROLL_CAPTURE_HINT_AUTO)));
6071 break;
6072 case R.styleable.View_clipToOutline:
6073 setClipToOutline(a.getBoolean(attr, false));
6074 break;
6075 case R.styleable.View_preferKeepClear:
6076 setPreferKeepClear(a.getBoolean(attr, false));
6077 break;
6078 case R.styleable.View_autoHandwritingEnabled:
6079 setAutoHandwritingEnabled(a.getBoolean(attr, true));
6080 break;
6081 }
6082 }
6083
6084 setOverScrollMode(overScrollMode);
6085
6086 // Cache start/end user padding as we cannot fully resolve padding here (we don't have yet
6087 // the resolved layout direction). Those cached values will be used later during padding
6088 // resolution.
6089 mUserPaddingStart = startPadding;
6090 mUserPaddingEnd = endPadding;
6091
6092 if (background != null) {
6093 setBackground(background);
6094 }
6095
6096 // setBackground above will record that padding is currently provided by the background.
6097 // If we have padding specified via xml, record that here instead and use it.
6098 mLeftPaddingDefined = leftPaddingDefined;
6099 mRightPaddingDefined = rightPaddingDefined;
6100
6101 // Valid paddingHorizontal/paddingVertical beats leftPadding, rightPadding, topPadding,
6102 // bottomPadding, and padding set by background. Valid padding beats everything.
6103 if (padding >= 0) {
6104 leftPadding = padding;
6105 topPadding = padding;
6106 rightPadding = padding;
6107 bottomPadding = padding;
6108 mUserPaddingLeftInitial = padding;
6109 mUserPaddingRightInitial = padding;
6110 } else {
6111 if (paddingHorizontal >= 0) {
6112 leftPadding = paddingHorizontal;
6113 rightPadding = paddingHorizontal;
6114 mUserPaddingLeftInitial = paddingHorizontal;
6115 mUserPaddingRightInitial = paddingHorizontal;
6116 }
6117 if (paddingVertical >= 0) {
6118 topPadding = paddingVertical;
6119 bottomPadding = paddingVertical;
6120 }
6121 }
6122
6123 if (isRtlCompatibilityMode()) {
6124 // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
6125 // left / right padding are used if defined (meaning here nothing to do). If they are not
6126 // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
6127 // start / end and resolve them as left / right (layout direction is not taken into account).
6128 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
6129 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
6130 // defined.
6131 if (!mLeftPaddingDefined && startPaddingDefined) {
6132 leftPadding = startPadding;
6133 }
6134 mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
6135 if (!mRightPaddingDefined && endPaddingDefined) {
6136 rightPadding = endPadding;
6137 }
6138 mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
6139 } else {
6140 // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
6141 // values defined. Otherwise, left /right values are used.
6142 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
6143 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
6144 // defined.
6145 final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
6146
6147 if (mLeftPaddingDefined && !hasRelativePadding) {
6148 mUserPaddingLeftInitial = leftPadding;
6149 }
6150 if (mRightPaddingDefined && !hasRelativePadding) {
6151 mUserPaddingRightInitial = rightPadding;
6152 }
6153 }
6154
6155 // mPaddingTop and mPaddingBottom may have been set by setBackground(Drawable) so must pass
6156 // them on if topPadding or bottomPadding are not valid.
6157 internalSetPadding(
6158 mUserPaddingLeftInitial,
6159 topPadding >= 0 ? topPadding : mPaddingTop,
6160 mUserPaddingRightInitial,
6161 bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
6162
6163 if (viewFlagMasks != 0) {
6164 setFlags(viewFlagValues, viewFlagMasks);
6165 }
6166
6167 if (initializeScrollbars) {
6168 initializeScrollbarsInternal(a);
6169 }
6170
6171 if (initializeScrollIndicators) {
6172 initializeScrollIndicatorsInternal();
6173 }
6174
6175 a.recycle();
6176
6177 // Needs to be called after mViewFlags is set
6178 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
6179 recomputePadding();
6180 }
6181
6182 if (x != 0 || y != 0) {
6183 scrollTo(x, y);
6184 }
6185
6186 if (transformSet) {
6187 setTranslationX(tx);
6188 setTranslationY(ty);
6189 setTranslationZ(tz);
6190 setElevation(elevation);
6191 setRotation(rotation);
6192 setRotationX(rotationX);
6193 setRotationY(rotationY);
6194 setScaleX(sx);
6195 setScaleY(sy);
6196 }
6197
6198 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
6199 setScrollContainer(true);
6200 }
6201
6202 computeOpaqueFlags();
6203 }
6204
6205 /**
6206 * Returns the ordered list of resource ID that are considered when resolving attribute values
6207 * for this {@link View}. The list will include layout resource ID if the View is inflated from
6208 * XML. It will also include a set of explicit styles if specified in XML using
6209 * {@code style="..."}. Finally, it will include the default styles resolved from the theme.
6210 *
6211 * <p>
6212 * <b>Note:</b> this method will only return actual values if the view attribute debugging
6213 * is enabled in Android developer options.
6214 *
6215 * @param attribute Attribute resource ID for which the resolution stack should be returned.
6216 * @return ordered list of resource ID that are considered when resolving attribute values for
6217 * this {@link View}.
6218 */
6219 @NonNull
6220 public int[] getAttributeResolutionStack(@AttrRes int attribute) {
6221 if (!sDebugViewAttributes
6222 || mAttributeResolutionStacks == null
6223 || mAttributeResolutionStacks.get(attribute) == null) {
6224 return new int[0];
6225 }
6226 int[] attributeResolutionStack = mAttributeResolutionStacks.get(attribute);
6227 int stackSize = attributeResolutionStack.length;
6228 if (mSourceLayoutId != ID_NULL) {
6229 stackSize++;
6230 }
6231
6232 int currentIndex = 0;
6233 int[] stack = new int[stackSize];
6234
6235 if (mSourceLayoutId != ID_NULL) {
6236 stack[currentIndex] = mSourceLayoutId;
6237 currentIndex++;
6238 }
6239 for (int i = 0; i < attributeResolutionStack.length; i++) {
6240 stack[currentIndex] = attributeResolutionStack[i];
6241 currentIndex++;
6242 }
6243 return stack;
6244 }
6245
6246 /**
6247 * Returns the mapping of attribute resource ID to source resource ID where the attribute value
6248 * was set. Source resource ID can either be a layout resource ID, if the value was set in XML
6249 * within the View tag, or a style resource ID, if the attribute was set in a style. The source
6250 * resource value will be one of the resource IDs from {@link #getAttributeSourceResourceMap()}.
6251 *
6252 * <p>
6253 * <b>Note:</b> this method will only return actual values if the view attribute debugging
6254 * is enabled in Android developer options.
6255 *
6256 * @return mapping of attribute resource ID to source resource ID where the attribute value
6257 * was set.
6258 */
6259 @NonNull
6260 @SuppressWarnings("AndroidFrameworkEfficientCollections")
6261 public Map<Integer, Integer> getAttributeSourceResourceMap() {
6262 HashMap<Integer, Integer> map = new HashMap<>();
6263 if (!sDebugViewAttributes || mAttributeSourceResId == null) {
6264 return map;
6265 }
6266 for (int i = 0; i < mAttributeSourceResId.size(); i++) {
6267 map.put(mAttributeSourceResId.keyAt(i), mAttributeSourceResId.valueAt(i));
6268 }
6269 return map;
6270 }
6271
6272 /**
6273 * Returns the resource ID for the style specified using {@code style="..."} in the
6274 * {@link AttributeSet}'s backing XML element or {@link Resources#ID_NULL} otherwise if not
6275 * specified or otherwise not applicable.
6276 * <p>
6277 * Each {@link View} can have an explicit style specified in the layout file.
6278 * This style is used first during the {@link View} attribute resolution, then if an attribute
6279 * is not defined there the resource system looks at default style and theme as fallbacks.
6280 *
6281 * <p>
6282 * <b>Note:</b> this method will only return actual values if the view attribute debugging
6283 * is enabled in Android developer options.
6284 *
6285 * @return The resource ID for the style specified using {@code style="..."} in the
6286 * {@link AttributeSet}'s backing XML element or {@link Resources#ID_NULL} otherwise
6287 * if not specified or otherwise not applicable.
6288 */
6289 @StyleRes
6290 public int getExplicitStyle() {
6291 if (!sDebugViewAttributes) {
6292 return ID_NULL;
6293 }
6294 return mExplicitStyle;
6295 }
6296
6297 /**
6298 * An implementation of OnClickListener that attempts to lazily load a
6299 * named click handling method from a parent or ancestor context.
6300 */
6301 private static class DeclaredOnClickListener implements OnClickListener {
6302 private final View mHostView;
6303 private final String mMethodName;
6304
6305 private Method mResolvedMethod;
6306 private Context mResolvedContext;
6307
6308 public DeclaredOnClickListener(@NonNull View hostView, @NonNull String methodName) {
6309 mHostView = hostView;
6310 mMethodName = methodName;
6311 }
6312
6313 @Override
6314 public void onClick(@NonNull View v) {
6315 if (mResolvedMethod == null) {
6316 resolveMethod(mHostView.getContext(), mMethodName);
6317 }
6318
6319 try {
6320 mResolvedMethod.invoke(mResolvedContext, v);
6321 } catch (IllegalAccessException e) {
6322 throw new IllegalStateException(
6323 "Could not execute non-public method for android:onClick", e);
6324 } catch (InvocationTargetException e) {
6325 throw new IllegalStateException(
6326 "Could not execute method for android:onClick", e);
6327 }
6328 }
6329
6330 @NonNull
6331 private void resolveMethod(@Nullable Context context, @NonNull String name) {
6332 while (context != null) {
6333 try {
6334 if (!context.isRestricted()) {
6335 final Method method = context.getClass().getMethod(mMethodName, View.class);
6336 if (method != null) {
6337 mResolvedMethod = method;
6338 mResolvedContext = context;
6339 return;
6340 }
6341 }
6342 } catch (NoSuchMethodException e) {
6343 // Failed to find method, keep searching up the hierarchy.
6344 }
6345
6346 if (context instanceof ContextWrapper) {
6347 context = ((ContextWrapper) context).getBaseContext();
6348 } else {
6349 // Can't search up the hierarchy, null out and fail.
6350 context = null;
6351 }
6352 }
6353
6354 final int id = mHostView.getId();
6355 final String idText = id == NO_ID ? "" : " with id '"
6356 + mHostView.getContext().getResources().getResourceEntryName(id) + "'";
6357 throw new IllegalStateException("Could not find method " + mMethodName
6358 + "(View) in a parent or ancestor Context for android:onClick "
6359 + "attribute defined on view " + mHostView.getClass() + idText);
6360 }
6361 }
6362
6363 /**
6364 * Non-public constructor for use in testing
6365 */
6366 @UnsupportedAppUsage
6367 View() {
6368 mResources = null;
6369 mRenderNode = RenderNode.create(getClass().getName(), new ViewAnimationHostBridge(this));
6370 }
6371
6372 /**
6373 * Returns {@code true} when the View is attached and the system developer setting to show
6374 * the layout bounds is enabled or {@code false} otherwise.
6375 */
6376 public final boolean isShowingLayoutBounds() {
6377 return DEBUG_DRAW || mAttachInfo != null && mAttachInfo.mDebugLayout;
6378 }
6379
6380 /**
6381 * Used to test isShowingLayoutBounds(). This sets the local value used
6382 * by that function. This method does nothing if the layout isn't attached.
6383 *
6384 * @hide
6385 */
6386 @TestApi
6387 public final void setShowingLayoutBounds(boolean debugLayout) {
6388 if (mAttachInfo != null) {
6389 mAttachInfo.mDebugLayout = debugLayout;
6390 }
6391 }
6392
6393 private static SparseArray<String> getAttributeMap() {
6394 if (mAttributeMap == null) {
6395 mAttributeMap = new SparseArray<>();
6396 }
6397 return mAttributeMap;
6398 }
6399
6400 private void retrieveExplicitStyle(@NonNull Resources.Theme theme,
6401 @Nullable AttributeSet attrs) {
6402 if (!sDebugViewAttributes) {
6403 return;
6404 }
6405 mExplicitStyle = theme.getExplicitStyle(attrs);
6406 }
6407
6408 /**
6409 * Stores debugging information about attributes. This should be called in a constructor by
6410 * every custom {@link View} that uses a custom styleable. If the custom view does not call it,
6411 * then the custom attributes used by this view will not be visible in layout inspection tools.
6412 *
6413 * @param context Context under which this view is created.
6414 * @param styleable A reference to styleable array R.styleable.Foo
6415 * @param attrs AttributeSet used to construct this view.
6416 * @param t Resolved {@link TypedArray} returned by a call to
6417 * {@link Resources#obtainAttributes(AttributeSet, int[])}.
6418 * @param defStyleAttr Default style attribute passed into the view constructor.
6419 * @param defStyleRes Default style resource passed into the view constructor.
6420 */
6421 public final void saveAttributeDataForStyleable(@NonNull Context context,
6422 @NonNull int[] styleable, @Nullable AttributeSet attrs, @NonNull TypedArray t,
6423 int defStyleAttr, int defStyleRes) {
6424 if (!sDebugViewAttributes) {
6425 return;
6426 }
6427
6428 int[] attributeResolutionStack = context.getTheme().getAttributeResolutionStack(
6429 defStyleAttr, defStyleRes, mExplicitStyle);
6430
6431 if (mAttributeResolutionStacks == null) {
6432 mAttributeResolutionStacks = new SparseArray<>();
6433 }
6434
6435 if (mAttributeSourceResId == null) {
6436 mAttributeSourceResId = new SparseIntArray();
6437 }
6438
6439 final int indexCount = t.getIndexCount();
6440 for (int j = 0; j < indexCount; ++j) {
6441 final int index = t.getIndex(j);
6442 mAttributeSourceResId.append(styleable[index], t.getSourceResourceId(index, 0));
6443 mAttributeResolutionStacks.append(styleable[index], attributeResolutionStack);
6444 }
6445 }
6446
6447 private void saveAttributeData(@Nullable AttributeSet attrs, @NonNull TypedArray t) {
6448 final int attrsCount = attrs == null ? 0 : attrs.getAttributeCount();
6449 final int indexCount = t.getIndexCount();
6450 final String[] attributes = new String[(attrsCount + indexCount) * 2];
6451
6452 int i = 0;
6453
6454 // Store raw XML attributes.
6455 for (int j = 0; j < attrsCount; ++j) {
6456 attributes[i] = attrs.getAttributeName(j);
6457 attributes[i + 1] = attrs.getAttributeValue(j);
6458 i += 2;
6459 }
6460
6461 // Store resolved styleable attributes.
6462 final Resources res = t.getResources();
6463 final SparseArray<String> attributeMap = getAttributeMap();
6464 for (int j = 0; j < indexCount; ++j) {
6465 final int index = t.getIndex(j);
6466 if (!t.hasValueOrEmpty(index)) {
6467 // Value is undefined. Skip it.
6468 continue;
6469 }
6470
6471 final int resourceId = t.getResourceId(index, 0);
6472 if (resourceId == 0) {
6473 // Value is not a reference. Skip it.
6474 continue;
6475 }
6476
6477 String resourceName = attributeMap.get(resourceId);
6478 if (resourceName == null) {
6479 try {
6480 resourceName = res.getResourceName(resourceId);
6481 } catch (Resources.NotFoundException e) {
6482 resourceName = "0x" + Integer.toHexString(resourceId);
6483 }
6484 attributeMap.put(resourceId, resourceName);
6485 }
6486
6487 attributes[i] = resourceName;
6488 attributes[i + 1] = t.getString(index);
6489 i += 2;
6490 }
6491
6492 // Trim to fit contents.
6493 final String[] trimmed = new String[i];
6494 System.arraycopy(attributes, 0, trimmed, 0, i);
6495 mAttributes = trimmed;
6496 }
6497
6498 @Override
6499 public String toString() {
6500 StringBuilder out = new StringBuilder(256);
6501 out.append(getClass().getName());
6502 out.append('{');
6503 out.append(Integer.toHexString(System.identityHashCode(this)));
6504 out.append(' ');
6505 switch (mViewFlags&VISIBILITY_MASK) {
6506 case VISIBLE: out.append('V'); break;
6507 case INVISIBLE: out.append('I'); break;
6508 case GONE: out.append('G'); break;
6509 default: out.append('.'); break;
6510 }
6511 out.append((mViewFlags & FOCUSABLE) == FOCUSABLE ? 'F' : '.');
6512 out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
6513 out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
6514 out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
6515 out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
6516 out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
6517 out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
6518 out.append((mViewFlags&CONTEXT_CLICKABLE) != 0 ? 'X' : '.');
6519 out.append(' ');
6520 out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
6521 out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
6522 out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
6523 if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
6524 out.append('p');
6525 } else {
6526 out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
6527 }
6528 out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
6529 out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
6530 out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
6531 out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
6532 out.append(' ');
6533 out.append(mLeft);
6534 out.append(',');
6535 out.append(mTop);
6536 out.append('-');
6537 out.append(mRight);
6538 out.append(',');
6539 out.append(mBottom);
6540 final int id = getId();
6541 if (id != NO_ID) {
6542 out.append(" #");
6543 out.append(Integer.toHexString(id));
6544 final Resources r = mResources;
6545 if (id > 0 && Resources.resourceHasPackage(id) && r != null) {
6546 try {
6547 String pkgname;
6548 switch (id&0xff000000) {
6549 case 0x7f000000:
6550 pkgname="app";
6551 break;
6552 case 0x01000000:
6553 pkgname="android";
6554 break;
6555 default:
6556 pkgname = r.getResourcePackageName(id);
6557 break;
6558 }
6559 String typename = r.getResourceTypeName(id);
6560 String entryname = r.getResourceEntryName(id);
6561 out.append(" ");
6562 out.append(pkgname);
6563 out.append(":");
6564 out.append(typename);
6565 out.append("/");
6566 out.append(entryname);
6567 } catch (Resources.NotFoundException e) {
6568 }
6569 }
6570 }
6571 if (mAutofillId != null) {
6572 out.append(" aid="); out.append(mAutofillId);
6573 }
6574 out.append("}");
6575 return out.toString();
6576 }
6577
6578 /**
6579 * <p>
6580 * Initializes the fading edges from a given set of styled attributes. This
6581 * method should be called by subclasses that need fading edges and when an
6582 * instance of these subclasses is created programmatically rather than
6583 * being inflated from XML. This method is automatically called when the XML
6584 * is inflated.
6585 * </p>
6586 *
6587 * @param a the styled attributes set to initialize the fading edges from
6588 *
6589 * @removed
6590 */
6591 protected void initializeFadingEdge(TypedArray a) {
6592 // This method probably shouldn't have been included in the SDK to begin with.
6593 // It relies on 'a' having been initialized using an attribute filter array that is
6594 // not publicly available to the SDK. The old method has been renamed
6595 // to initializeFadingEdgeInternal and hidden for framework use only;
6596 // this one initializes using defaults to make it safe to call for apps.
6597
6598 TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
6599
6600 initializeFadingEdgeInternal(arr);
6601
6602 arr.recycle();
6603 }
6604
6605 /**
6606 * <p>
6607 * Initializes the fading edges from a given set of styled attributes. This
6608 * method should be called by subclasses that need fading edges and when an
6609 * instance of these subclasses is created programmatically rather than
6610 * being inflated from XML. This method is automatically called when the XML
6611 * is inflated.
6612 * </p>
6613 *
6614 * @param a the styled attributes set to initialize the fading edges from
6615 * @hide This is the real method; the public one is shimmed to be safe to call from apps.
6616 */
6617 protected void initializeFadingEdgeInternal(TypedArray a) {
6618 initScrollCache();
6619
6620 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
6621 R.styleable.View_fadingEdgeLength,
6622 ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
6623 }
6624
6625 /**
6626 * Returns the size of the vertical faded edges used to indicate that more
6627 * content in this view is visible.
6628 *
6629 * @return The size in pixels of the vertical faded edge or 0 if vertical
6630 * faded edges are not enabled for this view.
6631 * @attr ref android.R.styleable#View_fadingEdgeLength
6632 */
6633 public int getVerticalFadingEdgeLength() {
6634 if (isVerticalFadingEdgeEnabled()) {
6635 ScrollabilityCache cache = mScrollCache;
6636 if (cache != null) {
6637 return cache.fadingEdgeLength;
6638 }
6639 }
6640 return 0;
6641 }
6642
6643 /**
6644 * Set the size of the faded edge used to indicate that more content in this
6645 * view is available. Will not change whether the fading edge is enabled; use
6646 * {@link #setVerticalFadingEdgeEnabled(boolean)} or
6647 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
6648 * for the vertical or horizontal fading edges.
6649 *
6650 * @param length The size in pixels of the faded edge used to indicate that more
6651 * content in this view is visible.
6652 */
6653 public void setFadingEdgeLength(int length) {
6654 initScrollCache();
6655 mScrollCache.fadingEdgeLength = length;
6656 }
6657
6658 /**
6659 * Returns the size of the horizontal faded edges used to indicate that more
6660 * content in this view is visible.
6661 *
6662 * @return The size in pixels of the horizontal faded edge or 0 if horizontal
6663 * faded edges are not enabled for this view.
6664 * @attr ref android.R.styleable#View_fadingEdgeLength
6665 */
6666 public int getHorizontalFadingEdgeLength() {
6667 if (isHorizontalFadingEdgeEnabled()) {
6668 ScrollabilityCache cache = mScrollCache;
6669 if (cache != null) {
6670 return cache.fadingEdgeLength;
6671 }
6672 }
6673 return 0;
6674 }
6675
6676 /**
6677 * Returns the width of the vertical scrollbar.
6678 *
6679 * @return The width in pixels of the vertical scrollbar or 0 if there
6680 * is no vertical scrollbar.
6681 */
6682 public int getVerticalScrollbarWidth() {
6683 ScrollabilityCache cache = mScrollCache;
6684 if (cache != null) {
6685 ScrollBarDrawable scrollBar = cache.scrollBar;
6686 if (scrollBar != null) {
6687 int size = scrollBar.getSize(true);
6688 if (size <= 0) {
6689 size = cache.scrollBarSize;
6690 }
6691 return size;
6692 }
6693 return 0;
6694 }
6695 return 0;
6696 }
6697
6698 /**
6699 * Returns the height of the horizontal scrollbar.
6700 *
6701 * @return The height in pixels of the horizontal scrollbar or 0 if
6702 * there is no horizontal scrollbar.
6703 */
6704 protected int getHorizontalScrollbarHeight() {
6705 ScrollabilityCache cache = mScrollCache;
6706 if (cache != null) {
6707 ScrollBarDrawable scrollBar = cache.scrollBar;
6708 if (scrollBar != null) {
6709 int size = scrollBar.getSize(false);
6710 if (size <= 0) {
6711 size = cache.scrollBarSize;
6712 }
6713 return size;
6714 }
6715 return 0;
6716 }
6717 return 0;
6718 }
6719
6720 /**
6721 * <p>
6722 * Initializes the scrollbars from a given set of styled attributes. This
6723 * method should be called by subclasses that need scrollbars and when an
6724 * instance of these subclasses is created programmatically rather than
6725 * being inflated from XML. This method is automatically called when the XML
6726 * is inflated.
6727 * </p>
6728 *
6729 * @param a the styled attributes set to initialize the scrollbars from
6730 *
6731 * @removed
6732 */
6733 protected void initializeScrollbars(TypedArray a) {
6734 // It's not safe to use this method from apps. The parameter 'a' must have been obtained
6735 // using the View filter array which is not available to the SDK. As such, internal
6736 // framework usage now uses initializeScrollbarsInternal and we grab a default
6737 // TypedArray with the right filter instead here.
6738 TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
6739
6740 initializeScrollbarsInternal(arr);
6741
6742 // We ignored the method parameter. Recycle the one we actually did use.
6743 arr.recycle();
6744 }
6745
6746 private void initializeScrollBarDrawable() {
6747 initScrollCache();
6748
6749 if (mScrollCache.scrollBar == null) {
6750 mScrollCache.scrollBar = new ScrollBarDrawable();
6751 mScrollCache.scrollBar.setState(getDrawableState());
6752 mScrollCache.scrollBar.setCallback(this);
6753 }
6754 }
6755
6756 /**
6757 * <p>
6758 * Initializes the scrollbars from a given set of styled attributes. This
6759 * method should be called by subclasses that need scrollbars and when an
6760 * instance of these subclasses is created programmatically rather than
6761 * being inflated from XML. This method is automatically called when the XML
6762 * is inflated.
6763 * </p>
6764 *
6765 * @param a the styled attributes set to initialize the scrollbars from
6766 * @hide
6767 */
6768 @UnsupportedAppUsage
6769 protected void initializeScrollbarsInternal(TypedArray a) {
6770 initScrollCache();
6771
6772 final ScrollabilityCache scrollabilityCache = mScrollCache;
6773
6774 if (scrollabilityCache.scrollBar == null) {
6775 scrollabilityCache.scrollBar = new ScrollBarDrawable();
6776 scrollabilityCache.scrollBar.setState(getDrawableState());
6777 scrollabilityCache.scrollBar.setCallback(this);
6778 }
6779
6780 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
6781
6782 if (!fadeScrollbars) {
6783 scrollabilityCache.state = ScrollabilityCache.ON;
6784 }
6785 scrollabilityCache.fadeScrollBars = fadeScrollbars;
6786
6787
6788 scrollabilityCache.scrollBarFadeDuration = a.getInt(
6789 R.styleable.View_scrollbarFadeDuration, ViewConfiguration
6790 .getScrollBarFadeDuration());
6791 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
6792 R.styleable.View_scrollbarDefaultDelayBeforeFade,
6793 ViewConfiguration.getScrollDefaultDelay());
6794
6795
6796 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
6797 com.android.internal.R.styleable.View_scrollbarSize,
6798 ViewConfiguration.get(mContext).getScaledScrollBarSize());
6799
6800 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
6801 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
6802
6803 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
6804 if (thumb != null) {
6805 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
6806 }
6807
6808 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
6809 false);
6810 if (alwaysDraw) {
6811 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
6812 }
6813
6814 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
6815 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
6816
6817 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
6818 if (thumb != null) {
6819 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
6820 }
6821
6822 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
6823 false);
6824 if (alwaysDraw) {
6825 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
6826 }
6827
6828 // Apply layout direction to the new Drawables if needed
6829 final int layoutDirection = getLayoutDirection();
6830 if (track != null) {
6831 track.setLayoutDirection(layoutDirection);
6832 }
6833 if (thumb != null) {
6834 thumb.setLayoutDirection(layoutDirection);
6835 }
6836
6837 // Re-apply user/background padding so that scrollbar(s) get added
6838 resolvePadding();
6839 }
6840
6841 /**
6842 * Defines the vertical scrollbar thumb drawable
6843 * @attr ref android.R.styleable#View_scrollbarThumbVertical
6844 *
6845 * @see #awakenScrollBars(int)
6846 * @see #isVerticalScrollBarEnabled()
6847 * @see #setVerticalScrollBarEnabled(boolean)
6848 */
6849 public void setVerticalScrollbarThumbDrawable(@Nullable Drawable drawable) {
6850 initializeScrollBarDrawable();
6851 mScrollCache.scrollBar.setVerticalThumbDrawable(drawable);
6852 }
6853
6854 /**
6855 * Defines the vertical scrollbar track drawable
6856 * @attr ref android.R.styleable#View_scrollbarTrackVertical
6857 *
6858 * @see #awakenScrollBars(int)
6859 * @see #isVerticalScrollBarEnabled()
6860 * @see #setVerticalScrollBarEnabled(boolean)
6861 */
6862 public void setVerticalScrollbarTrackDrawable(@Nullable Drawable drawable) {
6863 initializeScrollBarDrawable();
6864 mScrollCache.scrollBar.setVerticalTrackDrawable(drawable);
6865 }
6866
6867 /**
6868 * Defines the horizontal thumb drawable
6869 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
6870 *
6871 * @see #awakenScrollBars(int)
6872 * @see #isHorizontalScrollBarEnabled()
6873 * @see #setHorizontalScrollBarEnabled(boolean)
6874 */
6875 public void setHorizontalScrollbarThumbDrawable(@Nullable Drawable drawable) {
6876 initializeScrollBarDrawable();
6877 mScrollCache.scrollBar.setHorizontalThumbDrawable(drawable);
6878 }
6879
6880 /**
6881 * Defines the horizontal track drawable
6882 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
6883 *
6884 * @see #awakenScrollBars(int)
6885 * @see #isHorizontalScrollBarEnabled()
6886 * @see #setHorizontalScrollBarEnabled(boolean)
6887 */
6888 public void setHorizontalScrollbarTrackDrawable(@Nullable Drawable drawable) {
6889 initializeScrollBarDrawable();
6890 mScrollCache.scrollBar.setHorizontalTrackDrawable(drawable);
6891 }
6892
6893 /**
6894 * Returns the currently configured Drawable for the thumb of the vertical scroll bar if it
6895 * exists, null otherwise.
6896 *
6897 * @see #awakenScrollBars(int)
6898 * @see #isVerticalScrollBarEnabled()
6899 * @see #setVerticalScrollBarEnabled(boolean)
6900 */
6901 public @Nullable Drawable getVerticalScrollbarThumbDrawable() {
6902 return mScrollCache != null ? mScrollCache.scrollBar.getVerticalThumbDrawable() : null;
6903 }
6904
6905 /**
6906 * Returns the currently configured Drawable for the track of the vertical scroll bar if it
6907 * exists, null otherwise.
6908 *
6909 * @see #awakenScrollBars(int)
6910 * @see #isVerticalScrollBarEnabled()
6911 * @see #setVerticalScrollBarEnabled(boolean)
6912 */
6913 public @Nullable Drawable getVerticalScrollbarTrackDrawable() {
6914 return mScrollCache != null ? mScrollCache.scrollBar.getVerticalTrackDrawable() : null;
6915 }
6916
6917 /**
6918 * Returns the currently configured Drawable for the thumb of the horizontal scroll bar if it
6919 * exists, null otherwise.
6920 *
6921 * @see #awakenScrollBars(int)
6922 * @see #isHorizontalScrollBarEnabled()
6923 * @see #setHorizontalScrollBarEnabled(boolean)
6924 */
6925 public @Nullable Drawable getHorizontalScrollbarThumbDrawable() {
6926 return mScrollCache != null ? mScrollCache.scrollBar.getHorizontalThumbDrawable() : null;
6927 }
6928
6929 /**
6930 * Returns the currently configured Drawable for the track of the horizontal scroll bar if it
6931 * exists, null otherwise.
6932 *
6933 * @see #awakenScrollBars(int)
6934 * @see #isHorizontalScrollBarEnabled()
6935 * @see #setHorizontalScrollBarEnabled(boolean)
6936 */
6937 public @Nullable Drawable getHorizontalScrollbarTrackDrawable() {
6938 return mScrollCache != null ? mScrollCache.scrollBar.getHorizontalTrackDrawable() : null;
6939 }
6940
6941 private void initializeScrollIndicatorsInternal() {
6942 // Some day maybe we'll break this into top/left/start/etc. and let the
6943 // client control it. Until then, you can have any scroll indicator you
6944 // want as long as it's a 1dp foreground-colored rectangle.
6945 if (mScrollIndicatorDrawable == null) {
6946 mScrollIndicatorDrawable = mContext.getDrawable(R.drawable.scroll_indicator_material);
6947 }
6948 }
6949
6950 /**
6951 * <p>
6952 * Initalizes the scrollability cache if necessary.
6953 * </p>
6954 */
6955 private void initScrollCache() {
6956 if (mScrollCache == null) {
6957 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
6958 }
6959 }
6960
6961 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
6962 private ScrollabilityCache getScrollCache() {
6963 initScrollCache();
6964 return mScrollCache;
6965 }
6966
6967 /**
6968 * Set the position of the vertical scroll bar. Should be one of
6969 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
6970 * {@link #SCROLLBAR_POSITION_RIGHT}.
6971 *
6972 * @param position Where the vertical scroll bar should be positioned.
6973 */
6974 public void setVerticalScrollbarPosition(int position) {
6975 if (mVerticalScrollbarPosition != position) {
6976 mVerticalScrollbarPosition = position;
6977 computeOpaqueFlags();
6978 resolvePadding();
6979 }
6980 }
6981
6982 /**
6983 * @return The position where the vertical scroll bar will show, if applicable.
6984 * @see #setVerticalScrollbarPosition(int)
6985 */
6986 public int getVerticalScrollbarPosition() {
6987 return mVerticalScrollbarPosition;
6988 }
6989
6990 boolean isOnScrollbar(float x, float y) {
6991 if (mScrollCache == null) {
6992 return false;
6993 }
6994 x += getScrollX();
6995 y += getScrollY();
6996 final boolean canScrollVertically =
6997 computeVerticalScrollRange() > computeVerticalScrollExtent();
6998 if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden() && canScrollVertically) {
6999 final Rect touchBounds = mScrollCache.mScrollBarTouchBounds;
7000 getVerticalScrollBarBounds(null, touchBounds);
7001 if (touchBounds.contains((int) x, (int) y)) {
7002 return true;
7003 }
7004 }
7005 final boolean canScrollHorizontally =
7006 computeHorizontalScrollRange() > computeHorizontalScrollExtent();
7007 if (isHorizontalScrollBarEnabled() && canScrollHorizontally) {
7008 final Rect touchBounds = mScrollCache.mScrollBarTouchBounds;
7009 getHorizontalScrollBarBounds(null, touchBounds);
7010 if (touchBounds.contains((int) x, (int) y)) {
7011 return true;
7012 }
7013 }
7014 return false;
7015 }
7016
7017 @UnsupportedAppUsage
7018 boolean isOnScrollbarThumb(float x, float y) {
7019 return isOnVerticalScrollbarThumb(x, y) || isOnHorizontalScrollbarThumb(x, y);
7020 }
7021
7022 private boolean isOnVerticalScrollbarThumb(float x, float y) {
7023 if (mScrollCache == null || !isVerticalScrollBarEnabled() || isVerticalScrollBarHidden()) {
7024 return false;
7025 }
7026 final int range = computeVerticalScrollRange();
7027 final int extent = computeVerticalScrollExtent();
7028 if (range > extent) {
7029 x += getScrollX();
7030 y += getScrollY();
7031 final Rect bounds = mScrollCache.mScrollBarBounds;
7032 final Rect touchBounds = mScrollCache.mScrollBarTouchBounds;
7033 getVerticalScrollBarBounds(bounds, touchBounds);
7034 final int offset = computeVerticalScrollOffset();
7035 final int thumbLength = ScrollBarUtils.getThumbLength(bounds.height(), bounds.width(),
7036 extent, range);
7037 final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.height(), thumbLength,
7038 extent, range, offset);
7039 final int thumbTop = bounds.top + thumbOffset;
7040 final int adjust = Math.max(mScrollCache.scrollBarMinTouchTarget - thumbLength, 0) / 2;
7041 if (x >= touchBounds.left && x <= touchBounds.right
7042 && y >= thumbTop - adjust && y <= thumbTop + thumbLength + adjust) {
7043 return true;
7044 }
7045 }
7046 return false;
7047 }
7048
7049 private boolean isOnHorizontalScrollbarThumb(float x, float y) {
7050 if (mScrollCache == null || !isHorizontalScrollBarEnabled()) {
7051 return false;
7052 }
7053 final int range = computeHorizontalScrollRange();
7054 final int extent = computeHorizontalScrollExtent();
7055 if (range > extent) {
7056 x += getScrollX();
7057 y += getScrollY();
7058 final Rect bounds = mScrollCache.mScrollBarBounds;
7059 final Rect touchBounds = mScrollCache.mScrollBarTouchBounds;
7060 getHorizontalScrollBarBounds(bounds, touchBounds);
7061 final int offset = computeHorizontalScrollOffset();
7062
7063 final int thumbLength = ScrollBarUtils.getThumbLength(bounds.width(), bounds.height(),
7064 extent, range);
7065 final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.width(), thumbLength,
7066 extent, range, offset);
7067 final int thumbLeft = bounds.left + thumbOffset;
7068 final int adjust = Math.max(mScrollCache.scrollBarMinTouchTarget - thumbLength, 0) / 2;
7069 if (x >= thumbLeft - adjust && x <= thumbLeft + thumbLength + adjust
7070 && y >= touchBounds.top && y <= touchBounds.bottom) {
7071 return true;
7072 }
7073 }
7074 return false;
7075 }
7076
7077 @UnsupportedAppUsage
7078 boolean isDraggingScrollBar() {
7079 return mScrollCache != null
7080 && mScrollCache.mScrollBarDraggingState != ScrollabilityCache.NOT_DRAGGING;
7081 }
7082
7083 /**
7084 * Sets the state of all scroll indicators.
7085 * <p>
7086 * See {@link #setScrollIndicators(int, int)} for usage information.
7087 *
7088 * @param indicators a bitmask of indicators that should be enabled, or
7089 * {@code 0} to disable all indicators
7090 * @see #setScrollIndicators(int, int)
7091 * @see #getScrollIndicators()
7092 * @attr ref android.R.styleable#View_scrollIndicators
7093 */
7094 @RemotableViewMethod
7095 public void setScrollIndicators(@ScrollIndicators int indicators) {
7096 setScrollIndicators(indicators,
7097 SCROLL_INDICATORS_PFLAG3_MASK >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT);
7098 }
7099
7100 /**
7101 * Sets the state of the scroll indicators specified by the mask. To change
7102 * all scroll indicators at once, see {@link #setScrollIndicators(int)}.
7103 * <p>
7104 * When a scroll indicator is enabled, it will be displayed if the view
7105 * can scroll in the direction of the indicator.
7106 * <p>
7107 * Multiple indicator types may be enabled or disabled by passing the
7108 * logical OR of the desired types. If multiple types are specified, they
7109 * will all be set to the same enabled state.
7110 * <p>
7111 * For example, to enable the top scroll indicatorExample: {@code setScrollIndicators
7112 *
7113 * @param indicators the indicator direction, or the logical OR of multiple
7114 * indicator directions. One or more of:
7115 * <ul>
7116 * <li>{@link #SCROLL_INDICATOR_TOP}</li>
7117 * <li>{@link #SCROLL_INDICATOR_BOTTOM}</li>
7118 * <li>{@link #SCROLL_INDICATOR_LEFT}</li>
7119 * <li>{@link #SCROLL_INDICATOR_RIGHT}</li>
7120 * <li>{@link #SCROLL_INDICATOR_START}</li>
7121 * <li>{@link #SCROLL_INDICATOR_END}</li>
7122 * </ul>
7123 * @see #setScrollIndicators(int)
7124 * @see #getScrollIndicators()
7125 * @attr ref android.R.styleable#View_scrollIndicators
7126 */
7127 public void setScrollIndicators(@ScrollIndicators int indicators, @ScrollIndicators int mask) {
7128 // Shift and sanitize mask.
7129 mask <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
7130 mask &= SCROLL_INDICATORS_PFLAG3_MASK;
7131
7132 // Shift and mask indicators.
7133 indicators <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
7134 indicators &= mask;
7135
7136 // Merge with non-masked flags.
7137 final int updatedFlags = indicators | (mPrivateFlags3 & ~mask);
7138
7139 if (mPrivateFlags3 != updatedFlags) {
7140 mPrivateFlags3 = updatedFlags;
7141
7142 if (indicators != 0) {
7143 initializeScrollIndicatorsInternal();
7144 }
7145 invalidate();
7146 }
7147 }
7148
7149 /**
7150 * Returns a bitmask representing the enabled scroll indicators.
7151 * <p>
7152 * For example, if the top and left scroll indicators are enabled and all
7153 * other indicators are disabled, the return value will be
7154 * {@code View.SCROLL_INDICATOR_TOP | View.SCROLL_INDICATOR_LEFT}.
7155 * <p>
7156 * To check whether the bottom scroll indicator is enabled, use the value
7157 * of {@code (getScrollIndicators() & View.SCROLL_INDICATOR_BOTTOM) != 0}.
7158 *
7159 * @return a bitmask representing the enabled scroll indicators
7160 */
7161 @InspectableProperty(flagMapping = {
7162 @FlagEntry(target = SCROLL_INDICATORS_NONE, mask = 0xffff_ffff, name = "none"),
7163 @FlagEntry(target = SCROLL_INDICATOR_TOP, name = "top"),
7164 @FlagEntry(target = SCROLL_INDICATOR_BOTTOM, name = "bottom"),
7165 @FlagEntry(target = SCROLL_INDICATOR_LEFT, name = "left"),
7166 @FlagEntry(target = SCROLL_INDICATOR_RIGHT, name = "right"),
7167 @FlagEntry(target = SCROLL_INDICATOR_START, name = "start"),
7168 @FlagEntry(target = SCROLL_INDICATOR_END, name = "end")
7169 })
7170 @ScrollIndicators
7171 public int getScrollIndicators() {
7172 return (mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK)
7173 >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
7174 }
7175
7176 @UnsupportedAppUsage
7177 ListenerInfo getListenerInfo() {
7178 if (mListenerInfo != null) {
7179 return mListenerInfo;
7180 }
7181 mListenerInfo = new ListenerInfo();
7182 return mListenerInfo;
7183 }
7184
7185 /**
7186 * Register a callback to be invoked when the scroll X or Y positions of
7187 * this view change.
7188 * <p>
7189 * <b>Note:</b> Some views handle scrolling independently from View and may
7190 * have their own separate listeners for scroll-type events. For example,
7191 * {@link android.widget.ListView ListView} allows clients to register an
7192 * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
7193 * to listen for changes in list scroll position.
7194 *
7195 * @param l The listener to notify when the scroll X or Y position changes.
7196 * @see android.view.View#getScrollX()
7197 * @see android.view.View#getScrollY()
7198 */
7199 public void setOnScrollChangeListener(OnScrollChangeListener l) {
7200 getListenerInfo().mOnScrollChangeListener = l;
7201 }
7202
7203 /**
7204 * Register a callback to be invoked when focus of this view changed.
7205 *
7206 * @param l The callback that will run.
7207 */
7208 public void setOnFocusChangeListener(OnFocusChangeListener l) {
7209 getListenerInfo().mOnFocusChangeListener = l;
7210 }
7211
7212 /**
7213 * Add a listener that will be called when the bounds of the view change due to
7214 * layout processing.
7215 *
7216 * @param listener The listener that will be called when layout bounds change.
7217 */
7218 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
7219 ListenerInfo li = getListenerInfo();
7220 if (li.mOnLayoutChangeListeners == null) {
7221 li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
7222 }
7223 if (!li.mOnLayoutChangeListeners.contains(listener)) {
7224 li.mOnLayoutChangeListeners.add(listener);
7225 }
7226 }
7227
7228 /**
7229 * Remove a listener for layout changes.
7230 *
7231 * @param listener The listener for layout bounds change.
7232 */
7233 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
7234 ListenerInfo li = mListenerInfo;
7235 if (li == null || li.mOnLayoutChangeListeners == null) {
7236 return;
7237 }
7238 li.mOnLayoutChangeListeners.remove(listener);
7239 }
7240
7241 /**
7242 * Add a listener for attach state changes.
7243 *
7244 * This listener will be called whenever this view is attached or detached
7245 * from a window. Remove the listener using
7246 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
7247 *
7248 * @param listener Listener to attach
7249 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
7250 */
7251 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
7252 ListenerInfo li = getListenerInfo();
7253 if (li.mOnAttachStateChangeListeners == null) {
7254 li.mOnAttachStateChangeListeners
7255 = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
7256 }
7257 li.mOnAttachStateChangeListeners.add(listener);
7258 }
7259
7260 /**
7261 * Remove a listener for attach state changes. The listener will receive no further
7262 * notification of window attach/detach events.
7263 *
7264 * @param listener Listener to remove
7265 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
7266 */
7267 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
7268 ListenerInfo li = mListenerInfo;
7269 if (li == null || li.mOnAttachStateChangeListeners == null) {
7270 return;
7271 }
7272 li.mOnAttachStateChangeListeners.remove(listener);
7273 }
7274
7275 /**
7276 * Returns the focus-change callback registered for this view.
7277 *
7278 * @return The callback, or null if one is not registered.
7279 */
7280 public OnFocusChangeListener getOnFocusChangeListener() {
7281 ListenerInfo li = mListenerInfo;
7282 return li != null ? li.mOnFocusChangeListener : null;
7283 }
7284
7285 /**
7286 * Register a callback to be invoked when this view is clicked. If this view is not
7287 * clickable, it becomes clickable.
7288 *
7289 * @param l The callback that will run
7290 *
7291 * @see #setClickable(boolean)
7292 */
7293 public void setOnClickListener(@Nullable OnClickListener l) {
7294 if (!isClickable()) {
7295 setClickable(true);
7296 }
7297 getListenerInfo().mOnClickListener = l;
7298 }
7299
7300 /**
7301 * Return whether this view has an attached OnClickListener. Returns
7302 * true if there is a listener, false if there is none.
7303 */
7304 public boolean hasOnClickListeners() {
7305 ListenerInfo li = mListenerInfo;
7306 return (li != null && li.mOnClickListener != null);
7307 }
7308
7309 /**
7310 * Register a callback to be invoked when this view is clicked and held. If this view is not
7311 * long clickable, it becomes long clickable.
7312 *
7313 * @param l The callback that will run
7314 *
7315 * @see #setLongClickable(boolean)
7316 */
7317 public void setOnLongClickListener(@Nullable OnLongClickListener l) {
7318 if (!isLongClickable()) {
7319 setLongClickable(true);
7320 }
7321 getListenerInfo().mOnLongClickListener = l;
7322 }
7323
7324 /**
7325 * Return whether this view has an attached OnLongClickListener. Returns
7326 * true if there is a listener, false if there is none.
7327 */
7328 public boolean hasOnLongClickListeners() {
7329 ListenerInfo li = mListenerInfo;
7330 return (li != null && li.mOnLongClickListener != null);
7331 }
7332
7333 /**
7334 * @return the registered {@link OnLongClickListener} if there is one, {@code null} otherwise.
7335 * @hide
7336 */
7337 @Nullable
7338 public OnLongClickListener getOnLongClickListener() {
7339 ListenerInfo li = mListenerInfo;
7340 return (li != null) ? li.mOnLongClickListener : null;
7341 }
7342
7343 /**
7344 * Register a callback to be invoked when this view is context clicked. If the view is not
7345 * context clickable, it becomes context clickable.
7346 *
7347 * @param l The callback that will run
7348 * @see #setContextClickable(boolean)
7349 */
7350 public void setOnContextClickListener(@Nullable OnContextClickListener l) {
7351 if (!isContextClickable()) {
7352 setContextClickable(true);
7353 }
7354 getListenerInfo().mOnContextClickListener = l;
7355 }
7356
7357 /**
7358 * Register a callback to be invoked when the context menu for this view is
7359 * being built. If this view is not long clickable, it becomes long clickable.
7360 *
7361 * @param l The callback that will run
7362 *
7363 */
7364 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
7365 if (!isLongClickable()) {
7366 setLongClickable(true);
7367 }
7368 getListenerInfo().mOnCreateContextMenuListener = l;
7369 }
7370
7371 /**
7372 * Set an observer to collect stats for each frame rendered for this view.
7373 *
7374 * @hide
7375 */
7376 public void addFrameMetricsListener(Window window,
7377 Window.OnFrameMetricsAvailableListener listener,
7378 Handler handler) {
7379 if (mAttachInfo != null) {
7380 if (mAttachInfo.mThreadedRenderer != null) {
7381 if (mFrameMetricsObservers == null) {
7382 mFrameMetricsObservers = new ArrayList<>();
7383 }
7384
7385 FrameMetricsObserver fmo = new FrameMetricsObserver(window, handler, listener);
7386 mFrameMetricsObservers.add(fmo);
7387 mAttachInfo.mThreadedRenderer.addObserver(fmo.getRendererObserver());
7388 } else {
7389 Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats");
7390 }
7391 } else {
7392 if (mFrameMetricsObservers == null) {
7393 mFrameMetricsObservers = new ArrayList<>();
7394 }
7395
7396 FrameMetricsObserver fmo = new FrameMetricsObserver(window, handler, listener);
7397 mFrameMetricsObservers.add(fmo);
7398 }
7399 }
7400
7401 /**
7402 * Remove observer configured to collect frame stats for this view.
7403 *
7404 * @hide
7405 */
7406 public void removeFrameMetricsListener(
7407 Window.OnFrameMetricsAvailableListener listener) {
7408 ThreadedRenderer renderer = getThreadedRenderer();
7409 FrameMetricsObserver fmo = findFrameMetricsObserver(listener);
7410 if (fmo == null) {
7411 throw new IllegalArgumentException(
7412 "attempt to remove OnFrameMetricsAvailableListener that was never added");
7413 }
7414
7415 if (mFrameMetricsObservers != null) {
7416 mFrameMetricsObservers.remove(fmo);
7417 if (renderer != null) {
7418 renderer.removeObserver(fmo.getRendererObserver());
7419 }
7420 }
7421 }
7422
7423 private void registerPendingFrameMetricsObservers() {
7424 if (mFrameMetricsObservers != null) {
7425 ThreadedRenderer renderer = getThreadedRenderer();
7426 if (renderer != null) {
7427 for (FrameMetricsObserver fmo : mFrameMetricsObservers) {
7428 renderer.addObserver(fmo.getRendererObserver());
7429 }
7430 } else {
7431 Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats");
7432 }
7433 }
7434 }
7435
7436 private FrameMetricsObserver findFrameMetricsObserver(
7437 Window.OnFrameMetricsAvailableListener listener) {
7438 if (mFrameMetricsObservers != null) {
7439 for (int i = 0; i < mFrameMetricsObservers.size(); i++) {
7440 FrameMetricsObserver observer = mFrameMetricsObservers.get(i);
7441 if (observer.mListener == listener) {
7442 return observer;
7443 }
7444 }
7445 }
7446
7447 return null;
7448 }
7449
7450 /** @hide */
7451 public void setNotifyAutofillManagerOnClick(boolean notify) {
7452 if (notify) {
7453 mPrivateFlags |= PFLAG_NOTIFY_AUTOFILL_MANAGER_ON_CLICK;
7454 } else {
7455 mPrivateFlags &= ~PFLAG_NOTIFY_AUTOFILL_MANAGER_ON_CLICK;
7456 }
7457 }
7458
7459 private void notifyAutofillManagerOnClick() {
7460 if ((mPrivateFlags & PFLAG_NOTIFY_AUTOFILL_MANAGER_ON_CLICK) != 0) {
7461 try {
7462 getAutofillManager().notifyViewClicked(this);
7463 } finally {
7464 // Set it to already called so it's not called twice when called by
7465 // performClickInternal()
7466 mPrivateFlags &= ~PFLAG_NOTIFY_AUTOFILL_MANAGER_ON_CLICK;
7467 }
7468 }
7469 }
7470
7471 /**
7472 * Entry point for {@link #performClick()} - other methods on View should call it instead of
7473 * {@code performClick()} directly to make sure the autofill manager is notified when
7474 * necessary (as subclasses could extend {@code performClick()} without calling the parent's
7475 * method).
7476 */
7477 private boolean performClickInternal() {
7478 // Must notify autofill manager before performing the click actions to avoid scenarios where
7479 // the app has a click listener that changes the state of views the autofill service might
7480 // be interested on.
7481 notifyAutofillManagerOnClick();
7482
7483 return performClick();
7484 }
7485
7486 /**
7487 * Call this view's OnClickListener, if it is defined. Performs all normal
7488 * actions associated with clicking: reporting accessibility event, playing
7489 * a sound, etc.
7490 *
7491 * @return True there was an assigned OnClickListener that was called, false
7492 * otherwise is returned.
7493 */
7494 // NOTE: other methods on View should not call this method directly, but performClickInternal()
7495 // instead, to guarantee that the autofill manager is notified when necessary (as subclasses
7496 // could extend this method without calling super.performClick()).
7497 public boolean performClick() {
7498 // We still need to call this method to handle the cases where performClick() was called
7499 // externally, instead of through performClickInternal()
7500 notifyAutofillManagerOnClick();
7501
7502 final boolean result;
7503 final ListenerInfo li = mListenerInfo;
7504 if (li != null && li.mOnClickListener != null) {
7505 playSoundEffect(SoundEffectConstants.CLICK);
7506 li.mOnClickListener.onClick(this);
7507 result = true;
7508 } else {
7509 result = false;
7510 }
7511
7512 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
7513
7514 notifyEnterOrExitForAutoFillIfNeeded(true);
7515
7516 return result;
7517 }
7518
7519 /**
7520 * Directly call any attached OnClickListener. Unlike {@link #performClick()},
7521 * this only calls the listener, and does not do any associated clicking
7522 * actions like reporting an accessibility event.
7523 *
7524 * @return True there was an assigned OnClickListener that was called, false
7525 * otherwise is returned.
7526 */
7527 public boolean callOnClick() {
7528 ListenerInfo li = mListenerInfo;
7529 if (li != null && li.mOnClickListener != null) {
7530 li.mOnClickListener.onClick(this);
7531 return true;
7532 }
7533 return false;
7534 }
7535
7536 /**
7537 * Calls this view's OnLongClickListener, if it is defined. Invokes the
7538 * context menu if the OnLongClickListener did not consume the event.
7539 *
7540 * @return {@code true} if one of the above receivers consumed the event,
7541 * {@code false} otherwise
7542 */
7543 public boolean performLongClick() {
7544 return performLongClickInternal(mLongClickX, mLongClickY);
7545 }
7546
7547 /**
7548 * Calls this view's OnLongClickListener, if it is defined. Invokes the
7549 * context menu if the OnLongClickListener did not consume the event,
7550 * anchoring it to an (x,y) coordinate.
7551 *
7552 * @param x x coordinate of the anchoring touch event, or {@link Float#NaN}
7553 * to disable anchoring
7554 * @param y y coordinate of the anchoring touch event, or {@link Float#NaN}
7555 * to disable anchoring
7556 * @return {@code true} if one of the above receivers consumed the event,
7557 * {@code false} otherwise
7558 */
7559 public boolean performLongClick(float x, float y) {
7560 mLongClickX = x;
7561 mLongClickY = y;
7562 final boolean handled = performLongClick();
7563 mLongClickX = Float.NaN;
7564 mLongClickY = Float.NaN;
7565 return handled;
7566 }
7567
7568 /**
7569 * Calls this view's OnLongClickListener, if it is defined. Invokes the
7570 * context menu if the OnLongClickListener did not consume the event,
7571 * optionally anchoring it to an (x,y) coordinate.
7572 *
7573 * @param x x coordinate of the anchoring touch event, or {@link Float#NaN}
7574 * to disable anchoring
7575 * @param y y coordinate of the anchoring touch event, or {@link Float#NaN}
7576 * to disable anchoring
7577 * @return {@code true} if one of the above receivers consumed the event,
7578 * {@code false} otherwise
7579 */
7580 private boolean performLongClickInternal(float x, float y) {
7581 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
7582
7583 boolean handled = false;
7584 final ListenerInfo li = mListenerInfo;
7585 if (li != null && li.mOnLongClickListener != null) {
7586 handled = li.mOnLongClickListener.onLongClick(View.this);
7587 }
7588 if (!handled) {
7589 final boolean isAnchored = !Float.isNaN(x) && !Float.isNaN(y);
7590 handled = isAnchored ? showContextMenu(x, y) : showContextMenu();
7591 }
7592 if ((mViewFlags & TOOLTIP) == TOOLTIP) {
7593 if (!handled) {
7594 handled = showLongClickTooltip((int) x, (int) y);
7595 }
7596 }
7597 if (handled) {
7598 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
7599 }
7600 return handled;
7601 }
7602
7603 /**
7604 * Call this view's OnContextClickListener, if it is defined.
7605 *
7606 * @param x the x coordinate of the context click
7607 * @param y the y coordinate of the context click
7608 * @return True if there was an assigned OnContextClickListener that consumed the event, false
7609 * otherwise.
7610 */
7611 public boolean performContextClick(float x, float y) {
7612 return performContextClick();
7613 }
7614
7615 /**
7616 * Call this view's OnContextClickListener, if it is defined.
7617 *
7618 * @return True if there was an assigned OnContextClickListener that consumed the event, false
7619 * otherwise.
7620 */
7621 public boolean performContextClick() {
7622 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CONTEXT_CLICKED);
7623
7624 boolean handled = false;
7625 ListenerInfo li = mListenerInfo;
7626 if (li != null && li.mOnContextClickListener != null) {
7627 handled = li.mOnContextClickListener.onContextClick(View.this);
7628 }
7629 if (handled) {
7630 performHapticFeedback(HapticFeedbackConstants.CONTEXT_CLICK);
7631 }
7632 return handled;
7633 }
7634
7635 /**
7636 * Performs button-related actions during a touch down event.
7637 *
7638 * @param event The event.
7639 * @return True if the down was consumed.
7640 *
7641 * @hide
7642 */
7643 protected boolean performButtonActionOnTouchDown(MotionEvent event) {
7644 if (event.isFromSource(InputDevice.SOURCE_MOUSE) &&
7645 (event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
7646 showContextMenu(event.getX(), event.getY());
7647 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
7648 return true;
7649 }
7650 return false;
7651 }
7652
7653 /**
7654 * Shows the context menu for this view.
7655 *
7656 * @return {@code true} if the context menu was shown, {@code false}
7657 * otherwise
7658 * @see #showContextMenu(float, float)
7659 */
7660 public boolean showContextMenu() {
7661 return getParent().showContextMenuForChild(this);
7662 }
7663
7664 /**
7665 * Shows the context menu for this view anchored to the specified
7666 * view-relative coordinate.
7667 *
7668 * @param x the X coordinate in pixels relative to the view to which the
7669 * menu should be anchored, or {@link Float#NaN} to disable anchoring
7670 * @param y the Y coordinate in pixels relative to the view to which the
7671 * menu should be anchored, or {@link Float#NaN} to disable anchoring
7672 * @return {@code true} if the context menu was shown, {@code false}
7673 * otherwise
7674 */
7675 public boolean showContextMenu(float x, float y) {
7676 return getParent().showContextMenuForChild(this, x, y);
7677 }
7678
7679 /**
7680 * Start an action mode with the default type {@link ActionMode#TYPE_PRIMARY}.
7681 *
7682 * @param callback Callback that will control the lifecycle of the action mode
7683 * @return The new action mode if it is started, null otherwise
7684 *
7685 * @see ActionMode
7686 * @see #startActionMode(android.view.ActionMode.Callback, int)
7687 */
7688 public ActionMode startActionMode(ActionMode.Callback callback) {
7689 return startActionMode(callback, ActionMode.TYPE_PRIMARY);
7690 }
7691
7692 /**
7693 * Start an action mode with the given type.
7694 *
7695 * @param callback Callback that will control the lifecycle of the action mode
7696 * @param type One of {@link ActionMode#TYPE_PRIMARY} or {@link ActionMode#TYPE_FLOATING}.
7697 * @return The new action mode if it is started, null otherwise
7698 *
7699 * @see ActionMode
7700 */
7701 public ActionMode startActionMode(ActionMode.Callback callback, int type) {
7702 ViewParent parent = getParent();
7703 if (parent == null) return null;
7704 try {
7705 return parent.startActionModeForChild(this, callback, type);
7706 } catch (AbstractMethodError ame) {
7707 // Older implementations of custom views might not implement this.
7708 return parent.startActionModeForChild(this, callback);
7709 }
7710 }
7711
7712 /**
7713 * Call {@link Context#startActivityForResult(String, Intent, int, Bundle)} for the View's
7714 * Context, creating a unique View identifier to retrieve the result.
7715 *
7716 * @param intent The Intent to be started.
7717 * @param requestCode The request code to use.
7718 * @hide
7719 */
7720 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
7721 public void startActivityForResult(Intent intent, int requestCode) {
7722 mStartActivityRequestWho = "@android:view:" + System.identityHashCode(this);
7723 getContext().startActivityForResult(mStartActivityRequestWho, intent, requestCode, null);
7724 }
7725
7726 /**
7727 * If this View corresponds to the calling who, dispatches the activity result.
7728 * @param who The identifier for the targeted View to receive the result.
7729 * @param requestCode The integer request code originally supplied to
7730 * startActivityForResult(), allowing you to identify who this
7731 * result came from.
7732 * @param resultCode The integer result code returned by the child activity
7733 * through its setResult().
7734 * @param data An Intent, which can return result data to the caller
7735 * (various data can be attached to Intent "extras").
7736 * @return {@code true} if the activity result was dispatched.
7737 * @hide
7738 */
7739 public boolean dispatchActivityResult(
7740 String who, int requestCode, int resultCode, Intent data) {
7741 if (mStartActivityRequestWho != null && mStartActivityRequestWho.equals(who)) {
7742 onActivityResult(requestCode, resultCode, data);
7743 mStartActivityRequestWho = null;
7744 return true;
7745 }
7746 return false;
7747 }
7748
7749 /**
7750 * Receive the result from a previous call to {@link #startActivityForResult(Intent, int)}.
7751 *
7752 * @param requestCode The integer request code originally supplied to
7753 * startActivityForResult(), allowing you to identify who this
7754 * result came from.
7755 * @param resultCode The integer result code returned by the child activity
7756 * through its setResult().
7757 * @param data An Intent, which can return result data to the caller
7758 * (various data can be attached to Intent "extras").
7759 * @hide
7760 */
7761 public void onActivityResult(int requestCode, int resultCode, Intent data) {
7762 // Do nothing.
7763 }
7764
7765 /**
7766 * Register a callback to be invoked when a hardware key is pressed in this view.
7767 * Key presses in software input methods will generally not trigger the methods of
7768 * this listener.
7769 * @param l the key listener to attach to this view
7770 */
7771 public void setOnKeyListener(OnKeyListener l) {
7772 getListenerInfo().mOnKeyListener = l;
7773 }
7774
7775 /**
7776 * Register a callback to be invoked when a touch event is sent to this view.
7777 * @param l the touch listener to attach to this view
7778 */
7779 public void setOnTouchListener(OnTouchListener l) {
7780 getListenerInfo().mOnTouchListener = l;
7781 }
7782
7783 /**
7784 * Register a callback to be invoked when a generic motion event is sent to this view.
7785 * @param l the generic motion listener to attach to this view
7786 */
7787 public void setOnGenericMotionListener(OnGenericMotionListener l) {
7788 getListenerInfo().mOnGenericMotionListener = l;
7789 }
7790
7791 /**
7792 * Register a callback to be invoked when a hover event is sent to this view.
7793 * @param l the hover listener to attach to this view
7794 */
7795 public void setOnHoverListener(OnHoverListener l) {
7796 getListenerInfo().mOnHoverListener = l;
7797 }
7798
7799 /**
7800 * Register a drag event listener callback object for this View. The parameter is
7801 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
7802 * View, the system calls the
7803 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
7804 * @param l An implementation of {@link android.view.View.OnDragListener}.
7805 */
7806 public void setOnDragListener(OnDragListener l) {
7807 getListenerInfo().mOnDragListener = l;
7808 }
7809
7810 /**
7811 * Give this view focus. This will cause
7812 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
7813 *
7814 * Note: this does not check whether this {@link View} should get focus, it just
7815 * gives it focus no matter what. It should only be called internally by framework
7816 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
7817 *
7818 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
7819 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
7820 * focus moved when requestFocus() is called. It may not always
7821 * apply, in which case use the default View.FOCUS_DOWN.
7822 * @param previouslyFocusedRect The rectangle of the view that had focus
7823 * prior in this View's coordinate system.
7824 */
7825 void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) {
7826 if (DBG) {
7827 System.out.println(this + " requestFocus()");
7828 }
7829
7830 if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
7831 mPrivateFlags |= PFLAG_FOCUSED;
7832
7833 View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
7834
7835 if (mParent != null) {
7836 mParent.requestChildFocus(this, this);
7837 updateFocusedInCluster(oldFocus, direction);
7838 }
7839
7840 if (mAttachInfo != null) {
7841 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
7842 }
7843
7844 onFocusChanged(true, direction, previouslyFocusedRect);
7845 refreshDrawableState();
7846 }
7847 }
7848
7849 /**
7850 * Sets this view's preference for reveal behavior when it gains focus.
7851 *
7852 * <p>When set to true, this is a signal to ancestor views in the hierarchy that
7853 * this view would prefer to be brought fully into view when it gains focus.
7854 * For example, a text field that a user is meant to type into. Other views such
7855 * as scrolling containers may prefer to opt-out of this behavior.</p>
7856 *
7857 * <p>The default value for views is true, though subclasses may change this
7858 * based on their preferred behavior.</p>
7859 *
7860 * @param revealOnFocus true to request reveal on focus in ancestors, false otherwise
7861 *
7862 * @see #getRevealOnFocusHint()
7863 */
7864 public final void setRevealOnFocusHint(boolean revealOnFocus) {
7865 if (revealOnFocus) {
7866 mPrivateFlags3 &= ~PFLAG3_NO_REVEAL_ON_FOCUS;
7867 } else {
7868 mPrivateFlags3 |= PFLAG3_NO_REVEAL_ON_FOCUS;
7869 }
7870 }
7871
7872 /**
7873 * Returns this view's preference for reveal behavior when it gains focus.
7874 *
7875 * <p>When this method returns true for a child view requesting focus, ancestor
7876 * views responding to a focus change in {@link ViewParent#requestChildFocus(View, View)}
7877 * should make a best effort to make the newly focused child fully visible to the user.
7878 * When it returns false, ancestor views should preferably not disrupt scroll positioning or
7879 * other properties affecting visibility to the user as part of the focus change.</p>
7880 *
7881 * @return true if this view would prefer to become fully visible when it gains focus,
7882 * false if it would prefer not to disrupt scroll positioning
7883 *
7884 * @see #setRevealOnFocusHint(boolean)
7885 */
7886 public final boolean getRevealOnFocusHint() {
7887 return (mPrivateFlags3 & PFLAG3_NO_REVEAL_ON_FOCUS) == 0;
7888 }
7889
7890 /**
7891 * Populates <code>outRect</code> with the hotspot bounds. By default,
7892 * the hotspot bounds are identical to the screen bounds.
7893 *
7894 * @param outRect rect to populate with hotspot bounds
7895 * @hide Only for internal use by views and widgets.
7896 */
7897 public void getHotspotBounds(Rect outRect) {
7898 final Drawable background = getBackground();
7899 if (background != null) {
7900 background.getHotspotBounds(outRect);
7901 } else {
7902 getBoundsOnScreen(outRect);
7903 }
7904 }
7905
7906 /**
7907 * Request that a rectangle of this view be visible on the screen,
7908 * scrolling if necessary just enough.
7909 *
7910 * <p>A View should call this if it maintains some notion of which part
7911 * of its content is interesting. For example, a text editing view
7912 * should call this when its cursor moves.
7913 * <p>The Rectangle passed into this method should be in the View's content coordinate space.
7914 * It should not be affected by which part of the View is currently visible or its scroll
7915 * position.
7916 *
7917 * @param rectangle The rectangle in the View's content coordinate space
7918 * @return Whether any parent scrolled.
7919 */
7920 public boolean requestRectangleOnScreen(Rect rectangle) {
7921 return requestRectangleOnScreen(rectangle, false);
7922 }
7923
7924 /**
7925 * Request that a rectangle of this view be visible on the screen,
7926 * scrolling if necessary just enough.
7927 *
7928 * <p>A View should call this if it maintains some notion of which part
7929 * of its content is interesting. For example, a text editing view
7930 * should call this when its cursor moves.
7931 * <p>The Rectangle passed into this method should be in the View's content coordinate space.
7932 * It should not be affected by which part of the View is currently visible or its scroll
7933 * position.
7934 * <p>When <code>immediate</code> is set to true, scrolling will not be
7935 * animated.
7936 *
7937 * @param rectangle The rectangle in the View's content coordinate space
7938 * @param immediate True to forbid animated scrolling, false otherwise
7939 * @return Whether any parent scrolled.
7940 */
7941 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
7942 if (mParent == null) {
7943 return false;
7944 }
7945
7946 View child = this;
7947
7948 RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
7949 position.set(rectangle);
7950
7951 ViewParent parent = mParent;
7952 boolean scrolled = false;
7953 while (parent != null) {
7954 rectangle.set((int) position.left, (int) position.top,
7955 (int) position.right, (int) position.bottom);
7956
7957 scrolled |= parent.requestChildRectangleOnScreen(child, rectangle, immediate);
7958
7959 if (!(parent instanceof View)) {
7960 break;
7961 }
7962
7963 // move it from child's content coordinate space to parent's content coordinate space
7964 position.offset(child.mLeft - child.getScrollX(), child.mTop -child.getScrollY());
7965
7966 child = (View) parent;
7967 parent = child.getParent();
7968 }
7969
7970 return scrolled;
7971 }
7972
7973 /**
7974 * Called when this view wants to give up focus. If focus is cleared
7975 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
7976 * <p>
7977 * <strong>Note:</strong> When not in touch-mode, the framework will try to give focus
7978 * to the first focusable View from the top after focus is cleared. Hence, if this
7979 * View is the first from the top that can take focus, then all callbacks
7980 * related to clearing focus will be invoked after which the framework will
7981 * give focus to this view.
7982 * </p>
7983 */
7984 public void clearFocus() {
7985 if (DBG) {
7986 System.out.println(this + " clearFocus()");
7987 }
7988
7989 final boolean refocus = sAlwaysAssignFocus || !isInTouchMode();
7990 clearFocusInternal(null, true, refocus);
7991 }
7992
7993 /**
7994 * Clears focus from the view, optionally propagating the change up through
7995 * the parent hierarchy and requesting that the root view place new focus.
7996 *
7997 * @param propagate whether to propagate the change up through the parent
7998 * hierarchy
7999 * @param refocus when propagate is true, specifies whether to request the
8000 * root view place new focus
8001 */
8002 void clearFocusInternal(View focused, boolean propagate, boolean refocus) {
8003 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
8004 mPrivateFlags &= ~PFLAG_FOCUSED;
8005 clearParentsWantFocus();
8006
8007 if (propagate && mParent != null) {
8008 mParent.clearChildFocus(this);
8009 }
8010
8011 onFocusChanged(false, 0, null);
8012 refreshDrawableState();
8013
8014 if (propagate && (!refocus || !rootViewRequestFocus())) {
8015 notifyGlobalFocusCleared(this);
8016 }
8017 }
8018 }
8019
8020 void notifyGlobalFocusCleared(View oldFocus) {
8021 if (oldFocus != null && mAttachInfo != null) {
8022 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
8023 }
8024 }
8025
8026 boolean rootViewRequestFocus() {
8027 final View root = getRootView();
8028 return root != null && root.requestFocus();
8029 }
8030
8031 /**
8032 * Called internally by the view system when a new view is getting focus.
8033 * This is what clears the old focus.
8034 * <p>
8035 * <b>NOTE:</b> The parent view's focused child must be updated manually
8036 * after calling this method. Otherwise, the view hierarchy may be left in
8037 * an inconstent state.
8038 */
8039 void unFocus(View focused) {
8040 if (DBG) {
8041 System.out.println(this + " unFocus()");
8042 }
8043
8044 clearFocusInternal(focused, false, false);
8045 }
8046
8047 /**
8048 * Returns true if this view has focus itself, or is the ancestor of the
8049 * view that has focus.
8050 *
8051 * @return True if this view has or contains focus, false otherwise.
8052 */
8053 @ViewDebug.ExportedProperty(category = "focus")
8054 public boolean hasFocus() {
8055 return (mPrivateFlags & PFLAG_FOCUSED) != 0;
8056 }
8057
8058 /**
8059 * Returns true if this view is focusable or if it contains a reachable View
8060 * for which {@link #hasFocusable()} returns {@code true}. A "reachable hasFocusable()"
8061 * is a view whose parents do not block descendants focus.
8062 * Only {@link #VISIBLE} views are considered focusable.
8063 *
8064 * <p>As of {@link Build.VERSION_CODES#O} views that are determined to be focusable
8065 * through {@link #FOCUSABLE_AUTO} will also cause this method to return {@code true}.
8066 * Apps that declare a {@link android.content.pm.ApplicationInfo#targetSdkVersion} of
8067 * earlier than {@link Build.VERSION_CODES#O} will continue to see this method return
8068 * {@code false} for views not explicitly marked as focusable.
8069 * Use {@link #hasExplicitFocusable()} if you require the pre-{@link Build.VERSION_CODES#O}
8070 * behavior.</p>
8071 *
8072 * @return {@code true} if the view is focusable or if the view contains a focusable
8073 * view, {@code false} otherwise
8074 *
8075 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
8076 * @see ViewGroup#getTouchscreenBlocksFocus()
8077 * @see #hasExplicitFocusable()
8078 */
8079 public boolean hasFocusable() {
8080 return hasFocusable(!sHasFocusableExcludeAutoFocusable, false);
8081 }
8082
8083 /**
8084 * Returns true if this view is focusable or if it contains a reachable View
8085 * for which {@link #hasExplicitFocusable()} returns {@code true}.
8086 * A "reachable hasExplicitFocusable()" is a view whose parents do not block descendants focus.
8087 * Only {@link #VISIBLE} views for which {@link #getFocusable()} would return
8088 * {@link #FOCUSABLE} are considered focusable.
8089 *
8090 * <p>This method preserves the pre-{@link Build.VERSION_CODES#O} behavior of
8091 * {@link #hasFocusable()} in that only views explicitly set focusable will cause
8092 * this method to return true. A view set to {@link #FOCUSABLE_AUTO} that resolves
8093 * to focusable will not.</p>
8094 *
8095 * @return {@code true} if the view is focusable or if the view contains a focusable
8096 * view, {@code false} otherwise
8097 *
8098 * @see #hasFocusable()
8099 */
8100 public boolean hasExplicitFocusable() {
8101 return hasFocusable(false, true);
8102 }
8103
8104 boolean hasFocusable(boolean allowAutoFocus, boolean dispatchExplicit) {
8105 if (!isFocusableInTouchMode()) {
8106 for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) {
8107 final ViewGroup g = (ViewGroup) p;
8108 if (g.shouldBlockFocusForTouchscreen()) {
8109 return false;
8110 }
8111 }
8112 }
8113
8114 // Invisible, gone, or disabled views are never focusable.
8115 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE
8116 || (mViewFlags & ENABLED_MASK) != ENABLED) {
8117 return false;
8118 }
8119
8120 // Only use effective focusable value when allowed.
8121 if ((allowAutoFocus || getFocusable() != FOCUSABLE_AUTO) && isFocusable()) {
8122 return true;
8123 }
8124
8125 return false;
8126 }
8127
8128 /**
8129 * Called by the view system when the focus state of this view changes.
8130 * When the focus change event is caused by directional navigation, direction
8131 * and previouslyFocusedRect provide insight into where the focus is coming from.
8132 * When overriding, be sure to call up through to the super class so that
8133 * the standard focus handling will occur.
8134 *
8135 * @param gainFocus True if the View has focus; false otherwise.
8136 * @param direction The direction focus has moved when requestFocus()
8137 * is called to give this view focus. Values are
8138 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
8139 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
8140 * It may not always apply, in which case use the default.
8141 * @param previouslyFocusedRect The rectangle, in this view's coordinate
8142 * system, of the previously focused view. If applicable, this will be
8143 * passed in as finer grained information about where the focus is coming
8144 * from (in addition to direction). Will be <code>null</code> otherwise.
8145 */
8146 @CallSuper
8147 protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction,
8148 @Nullable Rect previouslyFocusedRect) {
8149 if (gainFocus) {
8150 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
8151 } else {
8152 notifyViewAccessibilityStateChangedIfNeeded(
8153 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
8154 }
8155
8156 // Here we check whether we still need the default focus highlight, and switch it on/off.
8157 switchDefaultFocusHighlight();
8158
8159 if (!gainFocus) {
8160 if (isPressed()) {
8161 setPressed(false);
8162 }
8163 if (hasWindowFocus()) {
8164 notifyFocusChangeToImeFocusController(false /* hasFocus */);
8165 }
8166 onFocusLost();
8167 } else if (hasWindowFocus()) {
8168 notifyFocusChangeToImeFocusController(true /* hasFocus */);
8169 }
8170
8171 invalidate(true);
8172 ListenerInfo li = mListenerInfo;
8173 if (li != null && li.mOnFocusChangeListener != null) {
8174 li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
8175 }
8176
8177 if (mAttachInfo != null) {
8178 mAttachInfo.mKeyDispatchState.reset(this);
8179 }
8180
8181 if (mParent != null) {
8182 mParent.onDescendantUnbufferedRequested();
8183 }
8184
8185 notifyEnterOrExitForAutoFillIfNeeded(gainFocus);
8186 updatePreferKeepClearForFocus();
8187 }
8188
8189 /**
8190 * Notify {@link ImeFocusController} about the focus change of the {@link View}.
8191 *
8192 * @param hasFocus {@code true} when the {@link View} is being focused.
8193 */
8194 private void notifyFocusChangeToImeFocusController(boolean hasFocus) {
8195 if (mAttachInfo == null) {
8196 return;
8197 }
8198 mAttachInfo.mViewRootImpl.getImeFocusController().onViewFocusChanged(this, hasFocus);
8199 }
8200
8201 /** @hide */
8202 public void notifyEnterOrExitForAutoFillIfNeeded(boolean enter) {
8203 if (canNotifyAutofillEnterExitEvent()) {
8204 AutofillManager afm = getAutofillManager();
8205 if (afm != null) {
8206 if (enter) {
8207 // We have not been laid out yet, hence cannot evaluate
8208 // whether this view is visible to the user, we will do
8209 // the evaluation once layout is complete.
8210 // Sometimes, views are already laid out, but it's still
8211 // not visible to the user, we also do the evaluation once
8212 // the view is visible. ex: There is a fade-in animation
8213 // for the activity, the view will be laid out when the
8214 // animation beginning. On the time, the view is not visible
8215 // to the user. And then as the animation progresses, the view
8216 // becomes visible to the user.
8217 if (!isLaidOut() || !isVisibleToUser()) {
8218 mPrivateFlags3 |= PFLAG3_NOTIFY_AUTOFILL_ENTER_ON_LAYOUT;
8219 } else if (isVisibleToUser()) {
8220 if (isFocused()) {
8221 // TODO This is a potential problem that View gets focus before it's
8222 // visible to User. Ideally View should handle the event when
8223 // isVisibleToUser() becomes true where it should issue
8224 // notifyViewEntered().
8225 afm.notifyViewEntered(this);
8226 } else {
8227 afm.notifyViewEnteredForFillDialog(this);
8228 }
8229 }
8230 } else if (!isFocused()) {
8231 afm.notifyViewExited(this);
8232 }
8233 }
8234 }
8235 }
8236
8237 /**
8238 * Visually distinct portion of a window with window-like semantics are considered panes for
8239 * accessibility purposes. One example is the content view of a fragment that is replaced.
8240 * In order for accessibility services to understand a pane's window-like behavior, panes
8241 * should have descriptive titles. Views with pane titles produce {@link AccessibilityEvent}s
8242 * when they appear, disappear, or change title.
8243 *
8244 * @param accessibilityPaneTitle The pane's title. Setting to {@code null} indicates that this
8245 * View is not a pane.
8246 *
8247 * {@see AccessibilityNodeInfo#setPaneTitle(CharSequence)}
8248 *
8249 * @attr ref android.R.styleable#View_accessibilityPaneTitle
8250 */
8251 public void setAccessibilityPaneTitle(@Nullable CharSequence accessibilityPaneTitle) {
8252 if (!TextUtils.equals(accessibilityPaneTitle, mAccessibilityPaneTitle)) {
8253 boolean currentPaneTitleEmpty = mAccessibilityPaneTitle == null;
8254 boolean newPaneTitleEmpty = accessibilityPaneTitle == null;
8255 mAccessibilityPaneTitle = accessibilityPaneTitle;
8256 // Make explicitly important as nulled titles need to be important for DISAPPEARED
8257 // events.
8258 if (mAccessibilityPaneTitle != null
8259 && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
8260 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
8261 }
8262 if (currentPaneTitleEmpty) {
8263 notifyViewAccessibilityStateChangedIfNeeded(
8264 AccessibilityEvent.CONTENT_CHANGE_TYPE_PANE_APPEARED);
8265 } else if (newPaneTitleEmpty) {
8266 notifyViewAccessibilityStateChangedIfNeeded(
8267 AccessibilityEvent.CONTENT_CHANGE_TYPE_PANE_DISAPPEARED);
8268 } else {
8269 notifyViewAccessibilityStateChangedIfNeeded(
8270 AccessibilityEvent.CONTENT_CHANGE_TYPE_PANE_TITLE);
8271 }
8272 }
8273 }
8274
8275 /**
8276 * Get the title of the pane for purposes of accessibility.
8277 *
8278 * @return The current pane title.
8279 *
8280 * {@see #setAccessibilityPaneTitle}.
8281 *
8282 * @attr ref android.R.styleable#View_accessibilityPaneTitle
8283 */
8284 @InspectableProperty
8285 @Nullable
8286 public CharSequence getAccessibilityPaneTitle() {
8287 return mAccessibilityPaneTitle;
8288 }
8289
8290 private boolean isAccessibilityPane() {
8291 return mAccessibilityPaneTitle != null;
8292 }
8293
8294 /**
8295 * Sends an accessibility event of the given type. If accessibility is
8296 * not enabled this method has no effect. The default implementation calls
8297 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
8298 * to populate information about the event source (this View), then calls
8299 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
8300 * populate the text content of the event source including its descendants,
8301 * then for events type {@link AccessibilityEvent#TYPE_VIEW_SCROLLED}
8302 * and {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} with
8303 * subtype {@link AccessibilityEvent#CONTENT_CHANGE_TYPE_STATE_DESCRIPTION},
8304 * throttle the events, and last calls
8305 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
8306 * on its parent to request sending of the event to interested parties.
8307 * <p>
8308 * If an {@link AccessibilityDelegate} has been specified via calling
8309 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
8310 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
8311 * responsible for handling this call.
8312 * </p>
8313 * <p>
8314 * If this view uses {@link AccessibilityNodeProvider} to provide virtual view hierarchy rooted
8315 * at this view, this method should not be called to send events from virtual children because
8316 * it will populate the events with wrong information and the events should be throttled per
8317 * child instead at the virtual root level. To send events from virtual children, call
8318 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} on the view's
8319 * parent to request sending of the event to interested parties.
8320 * </p>
8321 *
8322 * @param eventType The type of the event to send, as defined by several types from
8323 * {@link AccessibilityEvent}, such as
8324 * {@link AccessibilityEvent#TYPE_VIEW_CLICKED} or
8325 * {@link AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
8326 *
8327 * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
8328 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
8329 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
8330 * @see AccessibilityDelegate
8331 */
8332 public void sendAccessibilityEvent(int eventType) {
8333 if (mAccessibilityDelegate != null) {
8334 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
8335 } else {
8336 sendAccessibilityEventInternal(eventType);
8337 }
8338 }
8339
8340 /**
8341 * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
8342 * {@link AccessibilityEvent} to suggest that an accessibility service announce the
8343 * specified text to its users.
8344 * <p>
8345 * Note: The event generated with this API carries no semantic meaning, and is appropriate only
8346 * in exceptional situations. Apps can generally achieve correct behavior for accessibility by
8347 * accurately supplying the semantics of their UI.
8348 * They should not need to specify what exactly is announced to users.
8349 *
8350 * @param text The announcement text.
8351 */
8352 public void announceForAccessibility(CharSequence text) {
8353 if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
8354 AccessibilityEvent event = AccessibilityEvent.obtain(
8355 AccessibilityEvent.TYPE_ANNOUNCEMENT);
8356 onInitializeAccessibilityEvent(event);
8357 event.getText().add(text);
8358 event.setContentDescription(null);
8359 mParent.requestSendAccessibilityEvent(this, event);
8360 }
8361 }
8362
8363 /**
8364 * @see #sendAccessibilityEvent(int)
8365 *
8366 * Note: Called from the default {@link AccessibilityDelegate}.
8367 *
8368 * @hide
8369 */
8370 public void sendAccessibilityEventInternal(int eventType) {
8371 if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8372 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
8373 }
8374 }
8375
8376 /**
8377 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
8378 * takes as an argument an empty {@link AccessibilityEvent} and does not
8379 * perform a check whether accessibility is enabled.
8380 * <p>
8381 * If an {@link AccessibilityDelegate} has been specified via calling
8382 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
8383 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
8384 * is responsible for handling this call.
8385 * </p>
8386 *
8387 * @param event The event to send.
8388 *
8389 * @see #sendAccessibilityEvent(int)
8390 */
8391 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
8392 if (mAccessibilityDelegate != null) {
8393 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
8394 } else {
8395 sendAccessibilityEventUncheckedInternal(event);
8396 }
8397 }
8398
8399 /**
8400 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
8401 *
8402 * Note: Called from the default {@link AccessibilityDelegate}.
8403 *
8404 * @hide
8405 */
8406 public void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
8407 // Panes disappearing are relevant even if though the view is no longer visible.
8408 boolean isWindowStateChanged =
8409 (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
8410 boolean isWindowDisappearedEvent = isWindowStateChanged && ((event.getContentChangeTypes()
8411 & AccessibilityEvent.CONTENT_CHANGE_TYPE_PANE_DISAPPEARED) != 0);
8412 boolean detached = detached();
8413 if (!isShown() && !isWindowDisappearedEvent && !detached) {
8414 return;
8415 }
8416 onInitializeAccessibilityEvent(event);
8417 // Only a subset of accessibility events populates text content.
8418 if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
8419 dispatchPopulateAccessibilityEvent(event);
8420 }
8421 SendAccessibilityEventThrottle throttle = getThrottleForAccessibilityEvent(event);
8422 if (throttle != null) {
8423 throttle.post(event);
8424 } else if (!isWindowDisappearedEvent && detached) {
8425 // Views could be attached soon later. Accessibility events during this temporarily
8426 // detached period should be sent too.
8427 postDelayed(() -> {
8428 if (AccessibilityManager.getInstance(mContext).isEnabled() && isShown()) {
8429 requestParentSendAccessibilityEvent(event);
8430 }
8431 }, ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
8432 } else {
8433 requestParentSendAccessibilityEvent(event);
8434 }
8435 }
8436
8437 private void requestParentSendAccessibilityEvent(AccessibilityEvent event) {
8438 ViewParent parent = getParent();
8439 if (parent != null) {
8440 getParent().requestSendAccessibilityEvent(this, event);
8441 }
8442 }
8443
8444 private SendAccessibilityEventThrottle getThrottleForAccessibilityEvent(
8445 AccessibilityEvent event) {
8446 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_SCROLLED) {
8447 if (mSendViewScrolledAccessibilityEvent == null) {
8448 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
8449 }
8450 return mSendViewScrolledAccessibilityEvent;
8451 }
8452 boolean isStateContentChanged = (event.getContentChangeTypes()
8453 & AccessibilityEvent.CONTENT_CHANGE_TYPE_STATE_DESCRIPTION) != 0;
8454 if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED
8455 && isStateContentChanged) {
8456 if (mSendStateChangedAccessibilityEvent == null) {
8457 mSendStateChangedAccessibilityEvent = new SendAccessibilityEventThrottle();
8458 }
8459 return mSendStateChangedAccessibilityEvent;
8460 }
8461 return null;
8462 }
8463
8464 private void clearAccessibilityThrottles() {
8465 cancel(mSendViewScrolledAccessibilityEvent);
8466 cancel(mSendStateChangedAccessibilityEvent);
8467 }
8468
8469 /**
8470 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
8471 * to its children for adding their text content to the event. Note that the
8472 * event text is populated in a separate dispatch path since we add to the
8473 * event not only the text of the source but also the text of all its descendants.
8474 * A typical implementation will call
8475 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
8476 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
8477 * on each child. Override this method if custom population of the event text
8478 * content is required.
8479 * <p>
8480 * If an {@link AccessibilityDelegate} has been specified via calling
8481 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
8482 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
8483 * is responsible for handling this call.
8484 * </p>
8485 * <p>
8486 * <em>Note:</em> Accessibility events of certain types are not dispatched for
8487 * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
8488 * </p>
8489 *
8490 * @param event The event.
8491 *
8492 * @return True if the event population was completed.
8493 */
8494 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
8495 if (mAccessibilityDelegate != null) {
8496 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
8497 } else {
8498 return dispatchPopulateAccessibilityEventInternal(event);
8499 }
8500 }
8501
8502 /**
8503 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
8504 *
8505 * Note: Called from the default {@link AccessibilityDelegate}.
8506 *
8507 * @hide
8508 */
8509 public boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
8510 onPopulateAccessibilityEvent(event);
8511 return false;
8512 }
8513
8514 /**
8515 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
8516 * giving a chance to this View to populate the accessibility event with its
8517 * text content. While this method is free to modify event
8518 * attributes other than text content, doing so should normally be performed in
8519 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
8520 * <p>
8521 * Example: Adding formatted date string to an accessibility event in addition
8522 * to the text added by the super implementation:
8523 * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
8524 * super.onPopulateAccessibilityEvent(event);
8525 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
8526 * String selectedDateUtterance = DateUtils.formatDateTime(mContext,
8527 * mCurrentDate.getTimeInMillis(), flags);
8528 * event.getText().add(selectedDateUtterance);
8529 * }</pre>
8530 * <p>
8531 * If an {@link AccessibilityDelegate} has been specified via calling
8532 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
8533 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
8534 * is responsible for handling this call.
8535 * </p>
8536 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
8537 * information to the event, in case the default implementation has basic information to add.
8538 * </p>
8539 *
8540 * @param event The accessibility event which to populate.
8541 *
8542 * @see #sendAccessibilityEvent(int)
8543 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
8544 */
8545 @CallSuper
8546 public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
8547 if (mAccessibilityDelegate != null) {
8548 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
8549 } else {
8550 onPopulateAccessibilityEventInternal(event);
8551 }
8552 }
8553
8554 /**
8555 * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
8556 *
8557 * Note: Called from the default {@link AccessibilityDelegate}.
8558 *
8559 * @hide
8560 */
8561 public void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
8562 if ((event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED)
8563 && isAccessibilityPane()) {
8564 event.getText().add(getAccessibilityPaneTitle());
8565 }
8566 }
8567
8568 /**
8569 * Initializes an {@link AccessibilityEvent} with information about
8570 * this View which is the event source. In other words, the source of
8571 * an accessibility event is the view whose state change triggered firing
8572 * the event.
8573 * <p>
8574 * Example: Setting the password property of an event in addition
8575 * to properties set by the super implementation:
8576 * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
8577 * super.onInitializeAccessibilityEvent(event);
8578 * event.setPassword(true);
8579 * }</pre>
8580 * <p>
8581 * If an {@link AccessibilityDelegate} has been specified via calling
8582 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
8583 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
8584 * is responsible for handling this call.
8585 * </p>
8586 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
8587 * information to the event, in case the default implementation has basic information to add.
8588 * </p>
8589 * @param event The event to initialize.
8590 *
8591 * @see #sendAccessibilityEvent(int)
8592 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
8593 */
8594 @CallSuper
8595 public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
8596 if (mAccessibilityDelegate != null) {
8597 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
8598 } else {
8599 onInitializeAccessibilityEventInternal(event);
8600 }
8601 }
8602
8603 /**
8604 * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
8605 *
8606 * Note: Called from the default {@link AccessibilityDelegate}.
8607 *
8608 * @hide
8609 */
8610 @UnsupportedAppUsage
8611 public void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
8612 event.setSource(this);
8613 event.setClassName(getAccessibilityClassName());
8614 event.setPackageName(getContext().getPackageName());
8615 event.setEnabled(isEnabled());
8616 event.setContentDescription(mContentDescription);
8617 event.setScrollX(getScrollX());
8618 event.setScrollY(getScrollY());
8619
8620 switch (event.getEventType()) {
8621 case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
8622 ArrayList<View> focusablesTempList = (mAttachInfo != null)
8623 ? mAttachInfo.mTempArrayList : new ArrayList<View>();
8624 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
8625 event.setItemCount(focusablesTempList.size());
8626 event.setCurrentItemIndex(focusablesTempList.indexOf(this));
8627 if (mAttachInfo != null) {
8628 focusablesTempList.clear();
8629 }
8630 } break;
8631 case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
8632 CharSequence text = getIterableTextForAccessibility();
8633 if (text != null && text.length() > 0) {
8634 event.setFromIndex(getAccessibilitySelectionStart());
8635 event.setToIndex(getAccessibilitySelectionEnd());
8636 event.setItemCount(text.length());
8637 }
8638 } break;
8639 }
8640 }
8641
8642 /**
8643 * Returns an {@link AccessibilityNodeInfo} representing this view from the
8644 * point of view of an {@link android.accessibilityservice.AccessibilityService}.
8645 * This method is responsible for obtaining an accessibility node info from a
8646 * pool of reusable instances and calling
8647 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
8648 * initialize the former.
8649 * <p>
8650 * Note: The client is responsible for recycling the obtained instance by calling
8651 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
8652 * </p>
8653 *
8654 * @return A populated {@link AccessibilityNodeInfo}.
8655 *
8656 * @see AccessibilityNodeInfo
8657 */
8658 public AccessibilityNodeInfo createAccessibilityNodeInfo() {
8659 if (mAccessibilityDelegate != null) {
8660 return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
8661 } else {
8662 return createAccessibilityNodeInfoInternal();
8663 }
8664 }
8665
8666 /**
8667 * @see #createAccessibilityNodeInfo()
8668 *
8669 * @hide
8670 */
8671 public @Nullable AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
8672 AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
8673 if (provider != null) {
8674 return provider.createAccessibilityNodeInfo(AccessibilityNodeProvider.HOST_VIEW_ID);
8675 } else {
8676 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
8677 onInitializeAccessibilityNodeInfo(info);
8678 return info;
8679 }
8680 }
8681
8682 /**
8683 * Initializes an {@link AccessibilityNodeInfo} with information about this view.
8684 * The base implementation sets:
8685 * <ul>
8686 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
8687 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
8688 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
8689 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
8690 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
8691 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
8692 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
8693 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
8694 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
8695 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
8696 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
8697 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
8698 * <li>{@link AccessibilityNodeInfo#setContextClickable(boolean)}</li>
8699 * </ul>
8700 * <p>
8701 * Subclasses should override this method, call the super implementation,
8702 * and set additional attributes.
8703 * </p>
8704 * <p>
8705 * If an {@link AccessibilityDelegate} has been specified via calling
8706 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
8707 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
8708 * is responsible for handling this call.
8709 * </p>
8710 *
8711 * @param info The instance to initialize.
8712 */
8713 @CallSuper
8714 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
8715 if (mAccessibilityDelegate != null) {
8716 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
8717 } else {
8718 onInitializeAccessibilityNodeInfoInternal(info);
8719 }
8720 }
8721
8722 /**
8723 * Gets the location of this view in screen coordinates.
8724 *
8725 * @param outRect The output location
8726 * @hide
8727 */
8728 @UnsupportedAppUsage
8729 public void getBoundsOnScreen(Rect outRect) {
8730 getBoundsOnScreen(outRect, false);
8731 }
8732
8733 /**
8734 * Gets the location of this view in screen coordinates.
8735 *
8736 * @param outRect The output location
8737 * @param clipToParent Whether to clip child bounds to the parent ones.
8738 * @hide
8739 */
8740 @UnsupportedAppUsage
8741 public void getBoundsOnScreen(Rect outRect, boolean clipToParent) {
8742 if (mAttachInfo == null) {
8743 return;
8744 }
8745 RectF position = mAttachInfo.mTmpTransformRect;
8746 getBoundsToScreenInternal(position, clipToParent);
8747 outRect.set(Math.round(position.left), Math.round(position.top),
8748 Math.round(position.right), Math.round(position.bottom));
8749 }
8750
8751 /**
8752 * Gets the location of this view in screen coordinates.
8753 *
8754 * @param outRect The output location
8755 * @param clipToParent Whether to clip child bounds to the parent ones.
8756 * @hide
8757 */
8758 public void getBoundsOnScreen(RectF outRect, boolean clipToParent) {
8759 if (mAttachInfo == null) {
8760 return;
8761 }
8762 RectF position = mAttachInfo.mTmpTransformRect;
8763 getBoundsToScreenInternal(position, clipToParent);
8764 outRect.set(position.left, position.top, position.right, position.bottom);
8765 }
8766
8767 private void getBoundsToScreenInternal(RectF position, boolean clipToParent) {
8768 position.set(0, 0, mRight - mLeft, mBottom - mTop);
8769 mapRectFromViewToScreenCoords(position, clipToParent);
8770 }
8771
8772 /**
8773 * Map a rectangle from view-relative coordinates to screen-relative coordinates
8774 *
8775 * @param rect The rectangle to be mapped
8776 * @param clipToParent Whether to clip child bounds to the parent ones.
8777 * @hide
8778 */
8779 public void mapRectFromViewToScreenCoords(RectF rect, boolean clipToParent) {
8780 if (!hasIdentityMatrix()) {
8781 getMatrix().mapRect(rect);
8782 }
8783
8784 rect.offset(mLeft, mTop);
8785
8786 ViewParent parent = mParent;
8787 while (parent instanceof View) {
8788 View parentView = (View) parent;
8789
8790 rect.offset(-parentView.mScrollX, -parentView.mScrollY);
8791
8792 if (clipToParent) {
8793 rect.left = Math.max(rect.left, 0);
8794 rect.top = Math.max(rect.top, 0);
8795 rect.right = Math.min(rect.right, parentView.getWidth());
8796 rect.bottom = Math.min(rect.bottom, parentView.getHeight());
8797 }
8798
8799 if (!parentView.hasIdentityMatrix()) {
8800 parentView.getMatrix().mapRect(rect);
8801 }
8802
8803 rect.offset(parentView.mLeft, parentView.mTop);
8804
8805 parent = parentView.mParent;
8806 }
8807
8808 if (parent instanceof ViewRootImpl) {
8809 ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
8810 rect.offset(0, -viewRootImpl.mCurScrollY);
8811 }
8812
8813 rect.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
8814 }
8815
8816 /**
8817 * Return the class name of this object to be used for accessibility purposes.
8818 * Subclasses should only override this if they are implementing something that
8819 * should be seen as a completely new class of view when used by accessibility,
8820 * unrelated to the class it is deriving from. This is used to fill in
8821 * {@link AccessibilityNodeInfo#setClassName AccessibilityNodeInfo.setClassName}.
8822 */
8823 public CharSequence getAccessibilityClassName() {
8824 return View.class.getName();
8825 }
8826
8827 /**
8828 * Called when assist structure is being retrieved from a view as part of
8829 * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData}.
8830 * @param structure Fill in with structured view data. The default implementation
8831 * fills in all data that can be inferred from the view itself.
8832 */
8833 public void onProvideStructure(ViewStructure structure) {
8834 onProvideStructure(structure, VIEW_STRUCTURE_FOR_ASSIST, /* flags= */ 0);
8835 }
8836
8837 /**
8838 * Populates a {@link ViewStructure} to fullfil an autofill request.
8839 *
8840 * <p>The structure should contain at least the following properties:
8841 * <ul>
8842 * <li>Autofill id ({@link ViewStructure#setAutofillId(AutofillId, int)}).
8843 * <li>Autofill type ({@link ViewStructure#setAutofillType(int)}).
8844 * <li>Autofill value ({@link ViewStructure#setAutofillValue(AutofillValue)}).
8845 * <li>Whether the data is sensitive ({@link ViewStructure#setDataIsSensitive(boolean)}).
8846 * </ul>
8847 *
8848 * <p>It's also recommended to set the following properties - the more properties the structure
8849 * has, the higher the chances of an {@link android.service.autofill.AutofillService} properly
8850 * using the structure:
8851 *
8852 * <ul>
8853 * <li>Autofill hints ({@link ViewStructure#setAutofillHints(String[])}).
8854 * <li>Autofill options ({@link ViewStructure#setAutofillOptions(CharSequence[])}) when the
8855 * view can only be filled with predefined values (typically used when the autofill type
8856 * is {@link #AUTOFILL_TYPE_LIST}).
8857 * <li>Resource id ({@link ViewStructure#setId(int, String, String, String)}).
8858 * <li>Class name ({@link ViewStructure#setClassName(String)}).
8859 * <li>Content description ({@link ViewStructure#setContentDescription(CharSequence)}).
8860 * <li>Visual properties such as visibility ({@link ViewStructure#setVisibility(int)}),
8861 * dimensions ({@link ViewStructure#setDimens(int, int, int, int, int, int)}), and
8862 * opacity ({@link ViewStructure#setOpaque(boolean)}).
8863 * <li>For views representing text fields, text properties such as the text itself
8864 * ({@link ViewStructure#setText(CharSequence)}), text hints
8865 * ({@link ViewStructure#setHint(CharSequence)}, input type
8866 * ({@link ViewStructure#setInputType(int)}),
8867 * <li>For views representing HTML nodes, its web domain
8868 * ({@link ViewStructure#setWebDomain(String)}) and HTML properties
8869 * (({@link ViewStructure#setHtmlInfo(android.view.ViewStructure.HtmlInfo)}).
8870 * </ul>
8871 *
8872 * <p>The default implementation of this method already sets most of these properties based on
8873 * related {@link View} methods (for example, the autofill id is set using
8874 * {@link #getAutofillId()}, the autofill type set using {@link #getAutofillType()}, etc.),
8875 * and views in the standard Android widgets library also override it to set their
8876 * relevant properties (for example, {@link android.widget.TextView} already sets the text
8877 * properties), so it's recommended to only override this method
8878 * (and call {@code super.onProvideAutofillStructure()}) when:
8879 *
8880 * <ul>
8881 * <li>The view contents does not include PII (Personally Identifiable Information), so it
8882 * can call {@link ViewStructure#setDataIsSensitive(boolean)} passing {@code false}.
8883 * <li>The view can only be autofilled with predefined options, so it can call
8884 * {@link ViewStructure#setAutofillOptions(CharSequence[])}.
8885 * </ul>
8886 *
8887 * <p><b>Note:</b> The {@code left} and {@code top} values set in
8888 * {@link ViewStructure#setDimens(int, int, int, int, int, int)} must be relative to the next
8889 * {@link ViewGroup#isImportantForAutofill()} predecessor view included in the structure.
8890 *
8891 * <p>Views support the Autofill Framework mainly by:
8892 * <ul>
8893 * <li>Providing the metadata defining what the view means and how it can be autofilled.
8894 * <li>Notifying the Android System when the view value changed by calling
8895 * {@link AutofillManager#notifyValueChanged(View)}.
8896 * <li>Implementing the methods that autofill the view.
8897 * </ul>
8898 * <p>This method is responsible for the former; {@link #autofill(AutofillValue)} is responsible
8899 * for the latter.
8900 *
8901 * @param structure fill in with structured view data for autofill purposes.
8902 * @param flags optional flags.
8903 *
8904 * @see #AUTOFILL_FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
8905 */
8906 public void onProvideAutofillStructure(ViewStructure structure, @AutofillFlags int flags) {
8907 onProvideStructure(structure, VIEW_STRUCTURE_FOR_AUTOFILL, flags);
8908 }
8909
8910 /**
8911 * Populates a {@link ViewStructure} for content capture.
8912 *
8913 * <p>This method is called after a view that is eligible for content capture
8914 * (for example, if it {@link #isImportantForContentCapture()}, an intelligence service is
8915 * enabled for the user, and the activity rendering the view is enabled for content capture)
8916 * is laid out and is visible. The populated structure is then passed to the service through
8917 * {@link ContentCaptureSession#notifyViewAppeared(ViewStructure)}.
8918 *
8919 * <p>The default implementation of this method sets the most relevant properties based on
8920 * related {@link View} methods, and views in the standard Android widgets library also
8921 * override it to set their relevant properties. Therefore, if overriding this method, it
8922 * is recommended to call {@code super.onProvideContentCaptureStructure()}.
8923 *
8924 * <p><b>Note: </b>views that manage a virtual structure under this view must populate just
8925 * the node representing this view and return right away, then asynchronously report (not
8926 * necessarily in the UI thread) when the children nodes appear, disappear or have their text
8927 * changed by calling
8928 * {@link ContentCaptureSession#notifyViewAppeared(ViewStructure)},
8929 * {@link ContentCaptureSession#notifyViewDisappeared(AutofillId)}, and
8930 * {@link ContentCaptureSession#notifyViewTextChanged(AutofillId, CharSequence)}
8931 * respectively. The structure for a child must be created using
8932 * {@link ContentCaptureSession#newVirtualViewStructure(AutofillId, long)}, and the
8933 * {@code autofillId} for a child can be obtained either through
8934 * {@code childStructure.getAutofillId()} or
8935 * {@link ContentCaptureSession#newAutofillId(AutofillId, long)}.
8936 *
8937 * <p>When the virtual view hierarchy represents a web page, you should also:
8938 *
8939 * <ul>
8940 * <li>Call {@link ContentCaptureManager#getContentCaptureConditions()} to infer content
8941 * capture events should be generate for that URL.
8942 * <li>Create a new {@link ContentCaptureSession} child for every HTML element that
8943 * renders a new URL (like an {@code IFRAME}) and use that session to notify events from
8944 * that subtree.
8945 * </ul>
8946 *
8947 * <p><b>Note: </b>the following methods of the {@code structure} will be ignored:
8948 * <ul>
8949 * <li>{@link ViewStructure#setChildCount(int)}
8950 * <li>{@link ViewStructure#addChildCount(int)}
8951 * <li>{@link ViewStructure#getChildCount()}
8952 * <li>{@link ViewStructure#newChild(int)}
8953 * <li>{@link ViewStructure#asyncNewChild(int)}
8954 * <li>{@link ViewStructure#asyncCommit()}
8955 * <li>{@link ViewStructure#setWebDomain(String)}
8956 * <li>{@link ViewStructure#newHtmlInfoBuilder(String)}
8957 * <li>{@link ViewStructure#setHtmlInfo(android.view.ViewStructure.HtmlInfo)}
8958 * <li>{@link ViewStructure#setDataIsSensitive(boolean)}
8959 * <li>{@link ViewStructure#setAlpha(float)}
8960 * <li>{@link ViewStructure#setElevation(float)}
8961 * <li>{@link ViewStructure#setTransformation(Matrix)}
8962 *
8963 * </ul>
8964 */
8965 public void onProvideContentCaptureStructure(@NonNull ViewStructure structure, int flags) {
8966 onProvideStructure(structure, VIEW_STRUCTURE_FOR_CONTENT_CAPTURE, flags);
8967 }
8968
8969 /** @hide */
8970 protected void onProvideStructure(@NonNull ViewStructure structure,
8971 @ViewStructureType int viewFor, int flags) {
8972 final int id = mID;
8973 if (id != NO_ID && !isViewIdGenerated(id)) {
8974 String pkg, type, entry;
8975 try {
8976 final Resources res = getResources();
8977 entry = res.getResourceEntryName(id);
8978 type = res.getResourceTypeName(id);
8979 pkg = res.getResourcePackageName(id);
8980 } catch (Resources.NotFoundException e) {
8981 entry = type = pkg = null;
8982 }
8983 structure.setId(id, pkg, type, entry);
8984 } else {
8985 structure.setId(id, null, null, null);
8986 }
8987
8988 if (viewFor == VIEW_STRUCTURE_FOR_AUTOFILL
8989 || viewFor == VIEW_STRUCTURE_FOR_CONTENT_CAPTURE) {
8990 final @AutofillType int autofillType = getAutofillType();
8991 // Don't need to fill autofill info if view does not support it.
8992 // For example, only TextViews that are editable support autofill
8993 if (autofillType != AUTOFILL_TYPE_NONE) {
8994 structure.setAutofillType(autofillType);
8995 structure.setAutofillHints(getAutofillHints());
8996 structure.setAutofillValue(getAutofillValue());
8997 }
8998 structure.setImportantForAutofill(getImportantForAutofill());
8999 structure.setReceiveContentMimeTypes(getReceiveContentMimeTypes());
9000 }
9001
9002 int ignoredParentLeft = 0;
9003 int ignoredParentTop = 0;
9004 if (viewFor == VIEW_STRUCTURE_FOR_AUTOFILL
9005 && (flags & AUTOFILL_FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) == 0) {
9006 View parentGroup = null;
9007
9008 ViewParent viewParent = getParent();
9009 if (viewParent instanceof View) {
9010 parentGroup = (View) viewParent;
9011 }
9012
9013 while (parentGroup != null && !parentGroup.isImportantForAutofill()) {
9014 ignoredParentLeft += parentGroup.mLeft;
9015 ignoredParentTop += parentGroup.mTop;
9016
9017 viewParent = parentGroup.getParent();
9018 if (viewParent instanceof View) {
9019 parentGroup = (View) viewParent;
9020 } else {
9021 break;
9022 }
9023 }
9024 }
9025
9026 structure.setDimens(ignoredParentLeft + mLeft, ignoredParentTop + mTop, mScrollX, mScrollY,
9027 mRight - mLeft, mBottom - mTop);
9028 if (viewFor == VIEW_STRUCTURE_FOR_ASSIST) {
9029 if (!hasIdentityMatrix()) {
9030 structure.setTransformation(getMatrix());
9031 }
9032 structure.setElevation(getZ());
9033 }
9034 structure.setVisibility(getVisibility());
9035 structure.setEnabled(isEnabled());
9036 if (isClickable()) {
9037 structure.setClickable(true);
9038 }
9039 if (isFocusable()) {
9040 structure.setFocusable(true);
9041 }
9042 if (isFocused()) {
9043 structure.setFocused(true);
9044 }
9045 if (isAccessibilityFocused()) {
9046 structure.setAccessibilityFocused(true);
9047 }
9048 if (isSelected()) {
9049 structure.setSelected(true);
9050 }
9051 if (isActivated()) {
9052 structure.setActivated(true);
9053 }
9054 if (isLongClickable()) {
9055 structure.setLongClickable(true);
9056 }
9057 if (this instanceof Checkable) {
9058 structure.setCheckable(true);
9059 if (((Checkable)this).isChecked()) {
9060 structure.setChecked(true);
9061 }
9062 }
9063 if (isOpaque()) {
9064 structure.setOpaque(true);
9065 }
9066 if (isContextClickable()) {
9067 structure.setContextClickable(true);
9068 }
9069 structure.setClassName(getAccessibilityClassName().toString());
9070 structure.setContentDescription(getContentDescription());
9071 }
9072
9073 /**
9074 * Called when assist structure is being retrieved from a view as part of
9075 * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData} to
9076 * generate additional virtual structure under this view. The default implementation
9077 * uses {@link #getAccessibilityNodeProvider()} to try to generate this from the
9078 * view's virtual accessibility nodes, if any. You can override this for a more
9079 * optimal implementation providing this data.
9080 */
9081 public void onProvideVirtualStructure(ViewStructure structure) {
9082 onProvideVirtualStructureCompat(structure, false);
9083 }
9084
9085 /**
9086 * Fallback implementation to populate a ViewStructure from accessibility state.
9087 *
9088 * @param structure The structure to populate.
9089 * @param forAutofill Whether the structure is needed for autofill.
9090 */
9091 private void onProvideVirtualStructureCompat(ViewStructure structure, boolean forAutofill) {
9092 final AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
9093 if (provider != null) {
9094 if (forAutofill && Log.isLoggable(AUTOFILL_LOG_TAG, Log.VERBOSE)) {
9095 Log.v(AUTOFILL_LOG_TAG, "onProvideVirtualStructureCompat() for " + this);
9096 }
9097 final AccessibilityNodeInfo info = createAccessibilityNodeInfo();
9098 structure.setChildCount(1);
9099 final ViewStructure root = structure.newChild(0);
9100 populateVirtualStructure(root, provider, info, forAutofill);
9101 info.recycle();
9102 }
9103 }
9104
9105 /**
9106 * Populates a {@link ViewStructure} containing virtual children to fullfil an autofill
9107 * request.
9108 *
9109 * <p>This method should be used when the view manages a virtual structure under this view. For
9110 * example, a view that draws input fields using {@link #draw(Canvas)}.
9111 *
9112 * <p>When implementing this method, subclasses must follow the rules below:
9113 *
9114 * <ul>
9115 * <li>Add virtual children by calling the {@link ViewStructure#newChild(int)} or
9116 * {@link ViewStructure#asyncNewChild(int)} methods, where the {@code id} is an unique id
9117 * identifying the children in the virtual structure.
9118 * <li>The children hierarchy can have multiple levels if necessary, but ideally it should
9119 * exclude intermediate levels that are irrelevant for autofill; that would improve the
9120 * autofill performance.
9121 * <li>Also implement {@link #autofill(SparseArray)} to autofill the virtual
9122 * children.
9123 * <li>Set the autofill properties of the child structure as defined by
9124 * {@link #onProvideAutofillStructure(ViewStructure, int)}, using
9125 * {@link ViewStructure#setAutofillId(AutofillId, int)} to set its autofill id.
9126 * <li>Call {@link android.view.autofill.AutofillManager#notifyViewEntered(View, int, Rect)}
9127 * and/or {@link android.view.autofill.AutofillManager#notifyViewExited(View, int)}
9128 * when the focused virtual child changed.
9129 * <li>Override {@link #isVisibleToUserForAutofill(int)} to allow the platform to query
9130 * whether a given virtual view is visible to the user in order to support triggering
9131 * save when all views of interest go away.
9132 * <li>Call
9133 * {@link android.view.autofill.AutofillManager#notifyValueChanged(View, int, AutofillValue)}
9134 * when the value of a virtual child changed.
9135 * <li>Call {@link
9136 * android.view.autofill.AutofillManager#notifyViewVisibilityChanged(View, int, boolean)}
9137 * when the visibility of a virtual child changed.
9138 * <li>Call
9139 * {@link android.view.autofill.AutofillManager#notifyViewClicked(View, int)} when a virtual
9140 * child is clicked.
9141 * <li>Call {@link AutofillManager#commit()} when the autofill context of the view structure
9142 * changed and the current context should be committed (for example, when the user tapped
9143 * a {@code SUBMIT} button in an HTML page).
9144 * <li>Call {@link AutofillManager#cancel()} when the autofill context of the view structure
9145 * changed and the current context should be canceled (for example, when the user tapped
9146 * a {@code CANCEL} button in an HTML page).
9147 * <li>Provide ways for users to manually request autofill by calling
9148 * {@link AutofillManager#requestAutofill(View, int, Rect)}.
9149 * <li>The {@code left} and {@code top} values set in
9150 * {@link ViewStructure#setDimens(int, int, int, int, int, int)} must be relative to the
9151 * next {@link ViewGroup#isImportantForAutofill()} predecessor view included in the
9152 * structure.
9153 * </ul>
9154 *
9155 * <p>Views with virtual children support the Autofill Framework mainly by:
9156 * <ul>
9157 * <li>Providing the metadata defining what the virtual children mean and how they can be
9158 * autofilled.
9159 * <li>Implementing the methods that autofill the virtual children.
9160 * </ul>
9161 * <p>This method is responsible for the former; {@link #autofill(SparseArray)} is responsible
9162 * for the latter.
9163 *
9164 * @param structure fill in with virtual children data for autofill purposes.
9165 * @param flags optional flags.
9166 *
9167 * @see #AUTOFILL_FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
9168 */
9169 public void onProvideAutofillVirtualStructure(ViewStructure structure, int flags) {
9170 if (mContext.isAutofillCompatibilityEnabled()) {
9171 onProvideVirtualStructureCompat(structure, true);
9172 }
9173 }
9174
9175 /**
9176 * Sets the listener to be {@link #performReceiveContent used} to handle insertion of
9177 * content into this view.
9178 *
9179 * <p>Depending on the type of view, this listener may be invoked for different scenarios. For
9180 * example, for an editable {@link android.widget.TextView}, this listener will be invoked for
9181 * the following scenarios:
9182 * <ol>
9183 * <li>Paste from the clipboard (e.g. "Paste" or "Paste as plain text" action in the
9184 * insertion/selection menu)
9185 * <li>Content insertion from the keyboard (from {@link InputConnection#commitContent})
9186 * <li>Drag and drop (drop events from {@link #onDragEvent})
9187 * <li>Autofill
9188 * <li>Selection replacement via {@link Intent#ACTION_PROCESS_TEXT}
9189 * </ol>
9190 *
9191 * <p>When setting a listener, clients must also declare the accepted MIME types.
9192 * The listener will still be invoked even if the MIME type of the content is not one of the
9193 * declared MIME types (e.g. if the user pastes content whose type is not one of the declared
9194 * MIME types).
9195 * In that case, the listener may reject the content (defer to the default platform behavior)
9196 * or execute some other fallback logic (e.g. show an appropriate message to the user).
9197 * The declared MIME types serve as a hint to allow different features to optionally alter
9198 * their behavior. For example, a soft keyboard may optionally choose to hide its UI for
9199 * inserting GIFs for a particular input field if the MIME types set here for that field
9200 * don't include "image/gif" or "image/*".
9201 *
9202 * <p>Note: MIME type matching in the Android framework is case-sensitive, unlike formal RFC
9203 * MIME types. As a result, you should always write your MIME types with lowercase letters,
9204 * or use {@link android.content.Intent#normalizeMimeType} to ensure that it is converted to
9205 * lowercase.
9206 *
9207 * @param mimeTypes The MIME types accepted by the given listener. These may use patterns
9208 * such as "image/*", but may not start with a wildcard. This argument must
9209 * not be null or empty if a non-null listener is passed in.
9210 * @param listener The listener to use. This can be null to reset to the default behavior.
9211 */
9212 public void setOnReceiveContentListener(
9213 @SuppressLint("NullableCollection") @Nullable String[] mimeTypes,
9214 @Nullable OnReceiveContentListener listener) {
9215 if (listener != null) {
9216 Preconditions.checkArgument(mimeTypes != null && mimeTypes.length > 0,
9217 "When the listener is set, MIME types must also be set");
9218 }
9219 if (mimeTypes != null) {
9220 Preconditions.checkArgument(Arrays.stream(mimeTypes).noneMatch(t -> t.startsWith("*")),
9221 "A MIME type set here must not start with *: " + Arrays.toString(mimeTypes));
9222 }
9223 mReceiveContentMimeTypes = ArrayUtils.isEmpty(mimeTypes) ? null : mimeTypes;
9224 getListenerInfo().mOnReceiveContentListener = listener;
9225 }
9226
9227 /**
9228 * Receives the given content. If no listener is set, invokes {@link #onReceiveContent}. If a
9229 * listener is {@link #setOnReceiveContentListener set}, invokes the listener instead; if the
9230 * listener returns a non-null result, invokes {@link #onReceiveContent} to handle it.
9231 *
9232 * @param payload The content to insert and related metadata.
9233 *
9234 * @return The portion of the passed-in content that was not accepted (may be all, some, or none
9235 * of the passed-in content).
9236 */
9237 @Nullable
9238 public ContentInfo performReceiveContent(@NonNull ContentInfo payload) {
9239 final OnReceiveContentListener listener = (mListenerInfo == null) ? null
9240 : getListenerInfo().mOnReceiveContentListener;
9241 if (listener != null) {
9242 final ContentInfo remaining = listener.onReceiveContent(this, payload);
9243 return (remaining == null) ? null : onReceiveContent(remaining);
9244 }
9245 return onReceiveContent(payload);
9246 }
9247
9248 /**
9249 * Implements the default behavior for receiving content for this type of view. The default
9250 * view implementation is a no-op (returns the passed-in content without acting on it).
9251 *
9252 * <p>Widgets should override this method to define their default behavior for receiving
9253 * content. Apps should {@link #setOnReceiveContentListener set a listener} to provide
9254 * app-specific handling for receiving content.
9255 *
9256 * <p>See {@link #setOnReceiveContentListener} and {@link #performReceiveContent} for more info.
9257 *
9258 * @param payload The content to insert and related metadata.
9259 *
9260 * @return The portion of the passed-in content that was not handled (may be all, some, or none
9261 * of the passed-in content).
9262 */
9263 @Nullable
9264 public ContentInfo onReceiveContent(@NonNull ContentInfo payload) {
9265 return payload;
9266 }
9267
9268 /**
9269 * Returns the MIME types accepted by {@link #performReceiveContent} for this view, as
9270 * configured via {@link #setOnReceiveContentListener}. By default returns null.
9271 *
9272 * <p>Different features (e.g. pasting from the clipboard, inserting stickers from the soft
9273 * keyboard, etc) may optionally use this metadata to conditionally alter their behavior. For
9274 * example, a soft keyboard may choose to hide its UI for inserting GIFs for a particular
9275 * input field if the MIME types returned here for that field don't include "image/gif" or
9276 * "image/*".
9277 *
9278 * <p>Note: Comparisons of MIME types should be performed using utilities such as
9279 * {@link ClipDescription#compareMimeTypes} rather than simple string equality, in order to
9280 * correctly handle patterns such as "text/*", "image/*", etc. Note that MIME type matching
9281 * in the Android framework is case-sensitive, unlike formal RFC MIME types. As a result,
9282 * you should always write your MIME types with lowercase letters, or use
9283 * {@link android.content.Intent#normalizeMimeType} to ensure that it is converted to
9284 * lowercase.
9285 *
9286 * @return The MIME types accepted by {@link #performReceiveContent} for this view (may
9287 * include patterns such as "image/*").
9288 */
9289 @SuppressLint("NullableCollection")
9290 @Nullable
9291 public String[] getReceiveContentMimeTypes() {
9292 return mReceiveContentMimeTypes;
9293 }
9294
9295 /**
9296 * Automatically fills the content of this view with the {@code value}.
9297 *
9298 * <p>Views support the Autofill Framework mainly by:
9299 * <ul>
9300 * <li>Providing the metadata defining what the view means and how it can be autofilled.
9301 * <li>Implementing the methods that autofill the view.
9302 * </ul>
9303 * <p>{@link #onProvideAutofillStructure(ViewStructure, int)} is responsible for the former,
9304 * this method is responsible for latter.
9305 *
9306 * <p>This method does nothing by default, but when overridden it typically:
9307 * <ol>
9308 * <li>Checks if the provided value matches the expected type (which is defined by
9309 * {@link #getAutofillType()}).
9310 * <li>Checks if the view is editable - if it isn't, it should return right away.
9311 * <li>Call the proper getter method on {@link AutofillValue} to fetch the actual value.
9312 * <li>Pass the actual value to the equivalent setter in the view.
9313 * </ol>
9314 *
9315 * <p>For example, a text-field view could implement the method this way:
9316 *
9317 * <pre class="prettyprint">
9318 * &#64;Override
9319 * public void autofill(AutofillValue value) {
9320 * if (!value.isText() || !this.isEditable()) {
9321 * return;
9322 * }
9323 * CharSequence text = value.getTextValue();
9324 * if (text != null) {
9325 * this.setText(text);
9326 * }
9327 * }
9328 * </pre>
9329 *
9330 * <p>If the value is updated asynchronously, the next call to
9331 * {@link AutofillManager#notifyValueChanged(View)} must happen <b>after</b> the value was
9332 * changed to the autofilled value. If not, the view will not be considered autofilled.
9333 *
9334 * <p><b>Note:</b> After this method is called, the value returned by
9335 * {@link #getAutofillValue()} must be equal to the {@code value} passed to it, otherwise the
9336 * view will not be highlighted as autofilled.
9337 *
9338 * @param value value to be autofilled.
9339 */
9340 public void autofill(@SuppressWarnings("unused") AutofillValue value) {
9341 }
9342
9343 /**
9344 * Automatically fills the content of the virtual children within this view.
9345 *
9346 * <p>Views with virtual children support the Autofill Framework mainly by:
9347 * <ul>
9348 * <li>Providing the metadata defining what the virtual children mean and how they can be
9349 * autofilled.
9350 * <li>Implementing the methods that autofill the virtual children.
9351 * </ul>
9352 * <p>{@link #onProvideAutofillVirtualStructure(ViewStructure, int)} is responsible for the
9353 * former, this method is responsible for the latter - see {@link #autofill(AutofillValue)} and
9354 * {@link #onProvideAutofillVirtualStructure(ViewStructure, int)} for more info about autofill.
9355 *
9356 * <p>If a child value is updated asynchronously, the next call to
9357 * {@link AutofillManager#notifyValueChanged(View, int, AutofillValue)} must happen
9358 * <b>after</b> the value was changed to the autofilled value. If not, the child will not be
9359 * considered autofilled.
9360 *
9361 * <p><b>Note:</b> To indicate that a virtual view was autofilled,
9362 * <code>?android:attr/autofilledHighlight</code> should be drawn over it until the data
9363 * changes.
9364 *
9365 * @param values map of values to be autofilled, keyed by virtual child id.
9366 *
9367 * @attr ref android.R.styleable#Theme_autofilledHighlight
9368 */
9369 public void autofill(@NonNull @SuppressWarnings("unused") SparseArray<AutofillValue> values) {
9370 if (!mContext.isAutofillCompatibilityEnabled()) {
9371 return;
9372 }
9373 final AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
9374 if (provider == null) {
9375 return;
9376 }
9377 final int valueCount = values.size();
9378 for (int i = 0; i < valueCount; i++) {
9379 final AutofillValue value = values.valueAt(i);
9380 if (value.isText()) {
9381 final int virtualId = values.keyAt(i);
9382 final CharSequence text = value.getTextValue();
9383 final Bundle arguments = new Bundle();
9384 arguments.putCharSequence(
9385 AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, text);
9386 provider.performAction(virtualId, AccessibilityNodeInfo.ACTION_SET_TEXT, arguments);
9387 }
9388 }
9389 }
9390
9391 /**
9392 * Gets the unique, logical identifier of this view in the activity, for autofill purposes.
9393 *
9394 * <p>The autofill id is created on demand, unless it is explicitly set by
9395 * {@link #setAutofillId(AutofillId)}.
9396 *
9397 * <p>See {@link #setAutofillId(AutofillId)} for more info.
9398 *
9399 * @return The View's autofill id.
9400 */
9401 public final AutofillId getAutofillId() {
9402 if (mAutofillId == null) {
9403 // The autofill id needs to be unique, but its value doesn't matter,
9404 // so it's better to reuse the accessibility id to save space.
9405 mAutofillId = new AutofillId(getAutofillViewId());
9406 }
9407 return mAutofillId;
9408 }
9409
9410 /**
9411 * Sets the unique, logical identifier of this view in the activity, for autofill purposes.
9412 *
9413 * <p>The autofill id is created on demand, and this method should only be called when a view is
9414 * reused after {@link #dispatchProvideAutofillStructure(ViewStructure, int)} is called, as
9415 * that method creates a snapshot of the view that is passed along to the autofill service.
9416 *
9417 * <p>This method is typically used when view subtrees are recycled to represent different
9418 * content* &mdash;in this case, the autofill id can be saved before the view content is swapped
9419 * out, and restored later when it's swapped back in. For example:
9420 *
9421 * <pre>
9422 * EditText reusableView = ...;
9423 * ViewGroup parentView = ...;
9424 * AutofillManager afm = ...;
9425 *
9426 * // Swap out the view and change its contents
9427 * AutofillId oldId = reusableView.getAutofillId();
9428 * CharSequence oldText = reusableView.getText();
9429 * parentView.removeView(reusableView);
9430 * AutofillId newId = afm.getNextAutofillId();
9431 * reusableView.setText("New I am");
9432 * reusableView.setAutofillId(newId);
9433 * parentView.addView(reusableView);
9434 *
9435 * // Later, swap the old content back in
9436 * parentView.removeView(reusableView);
9437 * reusableView.setAutofillId(oldId);
9438 * reusableView.setText(oldText);
9439 * parentView.addView(reusableView);
9440 * </pre>
9441 *
9442 * <p>NOTE: If this view is a descendant of an {@link android.widget.AdapterView}, the system
9443 * may reset its autofill id when this view is recycled. If the autofill ids need to be stable,
9444 * they should be set again in
9445 * {@link android.widget.Adapter#getView(int, android.view.View, android.view.ViewGroup)}.
9446 *
9447 * @param id an autofill ID that is unique in the {@link android.app.Activity} hosting the view,
9448 * or {@code null} to reset it. Usually it's an id previously allocated to another view (and
9449 * obtained through {@link #getAutofillId()}), or a new value obtained through
9450 * {@link AutofillManager#getNextAutofillId()}.
9451 *
9452 * @throws IllegalStateException if the view is already {@link #isAttachedToWindow() attached to
9453 * a window}.
9454 *
9455 * @throws IllegalArgumentException if the id is an autofill id associated with a virtual view.
9456 */
9457 public void setAutofillId(@Nullable AutofillId id) {
9458 // TODO(b/37566627): add unit / CTS test for all possible combinations below
9459 if (Log.isLoggable(AUTOFILL_LOG_TAG, Log.VERBOSE)) {
9460 Log.v(AUTOFILL_LOG_TAG, "setAutofill(): from " + mAutofillId + " to " + id);
9461 }
9462 if (isAttachedToWindow()) {
9463 throw new IllegalStateException("Cannot set autofill id when view is attached");
9464 }
9465 if (id != null && !id.isNonVirtual()) {
9466 throw new IllegalStateException("Cannot set autofill id assigned to virtual views");
9467 }
9468 if (id == null && (mPrivateFlags3 & PFLAG3_AUTOFILLID_EXPLICITLY_SET) == 0) {
9469 // Ignore reset because it was never explicitly set before.
9470 return;
9471 }
9472 mAutofillId = id;
9473 if (id != null) {
9474 mAutofillViewId = id.getViewId();
9475 mPrivateFlags3 |= PFLAG3_AUTOFILLID_EXPLICITLY_SET;
9476 } else {
9477 mAutofillViewId = NO_ID;
9478 mPrivateFlags3 &= ~PFLAG3_AUTOFILLID_EXPLICITLY_SET;
9479 }
9480 }
9481
9482 /**
9483 * Forces a reset of the autofill ids of the subtree rooted at this view. Like calling
9484 * {@link #setAutofillId(AutofillId) setAutofillId(null)} for each view, but works even if the
9485 * views are attached to a window.
9486 *
9487 * <p>This is useful if the views are being recycled, since an autofill id should uniquely
9488 * identify a particular piece of content.
9489 *
9490 * @hide
9491 */
9492 public void resetSubtreeAutofillIds() {
9493 if (mAutofillViewId == NO_ID) {
9494 return;
9495 }
9496 if (Log.isLoggable(CONTENT_CAPTURE_LOG_TAG, Log.VERBOSE)) {
9497 Log.v(CONTENT_CAPTURE_LOG_TAG, "resetAutofillId() for " + mAutofillViewId);
9498 } else if (Log.isLoggable(AUTOFILL_LOG_TAG, Log.VERBOSE)) {
9499 Log.v(AUTOFILL_LOG_TAG, "resetAutofillId() for " + mAutofillViewId);
9500 }
9501 mAutofillId = null;
9502 mAutofillViewId = NO_ID;
9503 mPrivateFlags3 &= ~PFLAG3_AUTOFILLID_EXPLICITLY_SET;
9504 }
9505
9506 /**
9507 * Describes the autofill type of this view, so an
9508 * {@link android.service.autofill.AutofillService} can create the proper {@link AutofillValue}
9509 * when autofilling the view.
9510 *
9511 * <p>By default returns {@link #AUTOFILL_TYPE_NONE}, but views should override it to properly
9512 * support the Autofill Framework.
9513 *
9514 * @return either {@link #AUTOFILL_TYPE_NONE}, {@link #AUTOFILL_TYPE_TEXT},
9515 * {@link #AUTOFILL_TYPE_LIST}, {@link #AUTOFILL_TYPE_DATE}, or {@link #AUTOFILL_TYPE_TOGGLE}.
9516 *
9517 * @see #onProvideAutofillStructure(ViewStructure, int)
9518 * @see #autofill(AutofillValue)
9519 */
9520 public @AutofillType int getAutofillType() {
9521 return AUTOFILL_TYPE_NONE;
9522 }
9523
9524 /**
9525 * Gets the hints that help an {@link android.service.autofill.AutofillService} determine how
9526 * to autofill the view with the user's data.
9527 *
9528 * <p>See {@link #setAutofillHints(String...)} for more info about these hints.
9529 *
9530 * @return The hints set via the attribute or {@link #setAutofillHints(String...)}, or
9531 * {@code null} if no hints were set.
9532 *
9533 * @attr ref android.R.styleable#View_autofillHints
9534 */
9535 @ViewDebug.ExportedProperty()
9536 @InspectableProperty
9537 @Nullable public String[] getAutofillHints() {
9538 return mAutofillHints;
9539 }
9540
9541 /**
9542 * @hide
9543 */
9544 @TestApi
9545 public boolean isAutofilled() {
9546 return (mPrivateFlags3 & PFLAG3_IS_AUTOFILLED) != 0;
9547 }
9548
9549 /**
9550 * @hide
9551 */
9552 public boolean hideAutofillHighlight() {
9553 return (mPrivateFlags4 & PFLAG4_AUTOFILL_HIDE_HIGHLIGHT) != 0;
9554 }
9555
9556 /**
9557 * Gets the {@link View}'s current autofill value.
9558 *
9559 * <p>By default returns {@code null}, but subclasses should override it and return an
9560 * appropriate value to properly support the Autofill Framework.
9561 *
9562 * @see #onProvideAutofillStructure(ViewStructure, int)
9563 * @see #autofill(AutofillValue)
9564 */
9565 @Nullable
9566 public AutofillValue getAutofillValue() {
9567 return null;
9568 }
9569
9570 /**
9571 * Gets the mode for determining whether this view is important for autofill.
9572 *
9573 * <p>See {@link #setImportantForAutofill(int)} and {@link #isImportantForAutofill()} for more
9574 * info about this mode.
9575 *
9576 * @return {@link #IMPORTANT_FOR_AUTOFILL_AUTO} by default, or value passed to
9577 * {@link #setImportantForAutofill(int)}.
9578 *
9579 * @attr ref android.R.styleable#View_importantForAutofill
9580 */
9581 @ViewDebug.ExportedProperty(mapping = {
9582 @ViewDebug.IntToString(from = IMPORTANT_FOR_AUTOFILL_AUTO, to = "auto"),
9583 @ViewDebug.IntToString(from = IMPORTANT_FOR_AUTOFILL_YES, to = "yes"),
9584 @ViewDebug.IntToString(from = IMPORTANT_FOR_AUTOFILL_NO, to = "no"),
9585 @ViewDebug.IntToString(from = IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS,
9586 to = "yesExcludeDescendants"),
9587 @ViewDebug.IntToString(from = IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS,
9588 to = "noExcludeDescendants")})
9589 @InspectableProperty(enumMapping = {
9590 @EnumEntry(value = IMPORTANT_FOR_AUTOFILL_AUTO, name = "auto"),
9591 @EnumEntry(value = IMPORTANT_FOR_AUTOFILL_YES, name = "yes"),
9592 @EnumEntry(value = IMPORTANT_FOR_AUTOFILL_NO, name = "no"),
9593 @EnumEntry(value = IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS,
9594 name = "yesExcludeDescendants"),
9595 @EnumEntry(value = IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS,
9596 name = "noExcludeDescendants"),
9597 })
9598 public @AutofillImportance int getImportantForAutofill() {
9599 return (mPrivateFlags3
9600 & PFLAG3_IMPORTANT_FOR_AUTOFILL_MASK) >> PFLAG3_IMPORTANT_FOR_AUTOFILL_SHIFT;
9601 }
9602
9603 /**
9604 * Sets the mode for determining whether this view is considered important for autofill.
9605 *
9606 * <p>The platform determines the importance for autofill automatically but you
9607 * can use this method to customize the behavior. For example:
9608 *
9609 * <ol>
9610 * <li>When the view contents is irrelevant for autofill (for example, a text field used in a
9611 * "Captcha" challenge), it should be {@link #IMPORTANT_FOR_AUTOFILL_NO}.
9612 * <li>When both the view and its children are irrelevant for autofill (for example, the root
9613 * view of an activity containing a spreadhseet editor), it should be
9614 * {@link #IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS}.
9615 * <li>When the view content is relevant for autofill but its children aren't (for example,
9616 * a credit card expiration date represented by a custom view that overrides the proper
9617 * autofill methods and has 2 children representing the month and year), it should
9618 * be {@link #IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS}.
9619 * </ol>
9620 *
9621 * <p><b>Note:</b> Setting the mode as {@link #IMPORTANT_FOR_AUTOFILL_NO} or
9622 * {@link #IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS} does not guarantee the view (and its
9623 * children) will be always be considered not important; for example, when the user explicitly
9624 * makes an autofill request, all views are considered important. See
9625 * {@link #isImportantForAutofill()} for more details about how the View's importance for
9626 * autofill is used.
9627 *
9628 * @param mode {@link #IMPORTANT_FOR_AUTOFILL_AUTO}, {@link #IMPORTANT_FOR_AUTOFILL_YES},
9629 * {@link #IMPORTANT_FOR_AUTOFILL_NO}, {@link #IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS},
9630 * or {@link #IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS}.
9631 *
9632 * @attr ref android.R.styleable#View_importantForAutofill
9633 */
9634 public void setImportantForAutofill(@AutofillImportance int mode) {
9635 mPrivateFlags3 &= ~PFLAG3_IMPORTANT_FOR_AUTOFILL_MASK;
9636 mPrivateFlags3 |= (mode << PFLAG3_IMPORTANT_FOR_AUTOFILL_SHIFT)
9637 & PFLAG3_IMPORTANT_FOR_AUTOFILL_MASK;
9638 }
9639
9640 /**
9641 * Hints the Android System whether the {@link android.app.assist.AssistStructure.ViewNode}
9642 * associated with this view is considered important for autofill purposes.
9643 *
9644 * <p>Generally speaking, a view is important for autofill if:
9645 * <ol>
9646 * <li>The view can be autofilled by an {@link android.service.autofill.AutofillService}.
9647 * <li>The view contents can help an {@link android.service.autofill.AutofillService}
9648 * determine how other views can be autofilled.
9649 * <ol>
9650 *
9651 * <p>For example, view containers should typically return {@code false} for performance reasons
9652 * (since the important info is provided by their children), but if its properties have relevant
9653 * information (for example, a resource id called {@code credentials}, it should return
9654 * {@code true}. On the other hand, views representing labels or editable fields should
9655 * typically return {@code true}, but in some cases they could return {@code false}
9656 * (for example, if they're part of a "Captcha" mechanism).
9657 *
9658 * <p>The value returned by this method depends on the value returned by
9659 * {@link #getImportantForAutofill()}:
9660 *
9661 * <ol>
9662 * <li>if it returns {@link #IMPORTANT_FOR_AUTOFILL_YES} or
9663 * {@link #IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS}, then it returns {@code true}
9664 * <li>if it returns {@link #IMPORTANT_FOR_AUTOFILL_NO} or
9665 * {@link #IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS}, then it returns {@code false}
9666 * <li>if it returns {@link #IMPORTANT_FOR_AUTOFILL_AUTO}, then it uses some simple heuristics
9667 * that can return {@code true} in some cases (like a container with a resource id),
9668 * but {@code false} in most.
9669 * <li>otherwise, it returns {@code false}.
9670 * </ol>
9671 *
9672 * <p>When a view is considered important for autofill:
9673 * <ul>
9674 * <li>The view might automatically trigger an autofill request when focused on.
9675 * <li>The contents of the view are included in the {@link ViewStructure} used in an autofill
9676 * request.
9677 * </ul>
9678 *
9679 * <p>On the other hand, when a view is considered not important for autofill:
9680 * <ul>
9681 * <li>The view never automatically triggers autofill requests, but it can trigger a manual
9682 * request through {@link AutofillManager#requestAutofill(View)}.
9683 * <li>The contents of the view are not included in the {@link ViewStructure} used in an
9684 * autofill request, unless the request has the
9685 * {@link #AUTOFILL_FLAG_INCLUDE_NOT_IMPORTANT_VIEWS} flag.
9686 * </ul>
9687 *
9688 * @return whether the view is considered important for autofill.
9689 *
9690 * @see #setImportantForAutofill(int)
9691 * @see #IMPORTANT_FOR_AUTOFILL_AUTO
9692 * @see #IMPORTANT_FOR_AUTOFILL_YES
9693 * @see #IMPORTANT_FOR_AUTOFILL_NO
9694 * @see #IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS
9695 * @see #IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS
9696 * @see AutofillManager#requestAutofill(View)
9697 */
9698 public final boolean isImportantForAutofill() {
9699 // Check parent mode to ensure we're not hidden.
9700 ViewParent parent = mParent;
9701 while (parent instanceof View) {
9702 final int parentImportance = ((View) parent).getImportantForAutofill();
9703 if (parentImportance == IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS
9704 || parentImportance == IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS) {
9705 if (Log.isLoggable(AUTOFILL_LOG_TAG, Log.VERBOSE)) {
9706 Log.v(AUTOFILL_LOG_TAG, "View (" + this + ") is not important for autofill "
9707 + "because parent " + parent + "'s importance is " + parentImportance);
9708 }
9709 return false;
9710 }
9711 parent = parent.getParent();
9712 }
9713
9714 final int importance = getImportantForAutofill();
9715
9716 // First, check the explicit states.
9717 if (importance == IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS
9718 || importance == IMPORTANT_FOR_AUTOFILL_YES) {
9719 return true;
9720 }
9721 if (importance == IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS
9722 || importance == IMPORTANT_FOR_AUTOFILL_NO) {
9723 if (Log.isLoggable(AUTOFILL_LOG_TAG, Log.VERBOSE)) {
9724 Log.v(AUTOFILL_LOG_TAG, "View (" + this + ") is not important for autofill "
9725 + "because its importance is " + importance);
9726 }
9727 return false;
9728 }
9729
9730 // Then use some heuristics to handle AUTO.
9731 if (importance != IMPORTANT_FOR_AUTOFILL_AUTO) {
9732 Log.w(AUTOFILL_LOG_TAG, "invalid autofill importance (" + importance + " on view "
9733 + this);
9734 return false;
9735 }
9736
9737 // Always include views that have an explicit resource id.
9738 final int id = mID;
9739 if (id != NO_ID && !isViewIdGenerated(id)) {
9740 final Resources res = getResources();
9741 String entry = null;
9742 String pkg = null;
9743 try {
9744 entry = res.getResourceEntryName(id);
9745 pkg = res.getResourcePackageName(id);
9746 } catch (Resources.NotFoundException e) {
9747 // ignore
9748 }
9749 if (entry != null && pkg != null && pkg.equals(mContext.getPackageName())) {
9750 return true;
9751 }
9752 }
9753
9754 // If the app developer explicitly set hints for it, it's important.
9755 if (getAutofillHints() != null) {
9756 return true;
9757 }
9758
9759 // Otherwise, assume it's not important...
9760 return false;
9761 }
9762
9763 /**
9764 * Gets the mode for determining whether this view is important for content capture.
9765 *
9766 * <p>See {@link #setImportantForContentCapture(int)} and
9767 * {@link #isImportantForContentCapture()} for more info about this mode.
9768 *
9769 * @return {@link #IMPORTANT_FOR_CONTENT_CAPTURE_AUTO} by default, or value passed to
9770 * {@link #setImportantForContentCapture(int)}.
9771 *
9772 * @attr ref android.R.styleable#View_importantForContentCapture
9773 */
9774 @ViewDebug.ExportedProperty(mapping = {
9775 @ViewDebug.IntToString(from = IMPORTANT_FOR_CONTENT_CAPTURE_AUTO, to = "auto"),
9776 @ViewDebug.IntToString(from = IMPORTANT_FOR_CONTENT_CAPTURE_YES, to = "yes"),
9777 @ViewDebug.IntToString(from = IMPORTANT_FOR_CONTENT_CAPTURE_NO, to = "no"),
9778 @ViewDebug.IntToString(from = IMPORTANT_FOR_CONTENT_CAPTURE_YES_EXCLUDE_DESCENDANTS,
9779 to = "yesExcludeDescendants"),
9780 @ViewDebug.IntToString(from = IMPORTANT_FOR_CONTENT_CAPTURE_NO_EXCLUDE_DESCENDANTS,
9781 to = "noExcludeDescendants")})
9782 @InspectableProperty(enumMapping = {
9783 @EnumEntry(value = IMPORTANT_FOR_CONTENT_CAPTURE_AUTO, name = "auto"),
9784 @EnumEntry(value = IMPORTANT_FOR_CONTENT_CAPTURE_YES, name = "yes"),
9785 @EnumEntry(value = IMPORTANT_FOR_CONTENT_CAPTURE_NO, name = "no"),
9786 @EnumEntry(value = IMPORTANT_FOR_CONTENT_CAPTURE_YES_EXCLUDE_DESCENDANTS,
9787 name = "yesExcludeDescendants"),
9788 @EnumEntry(value = IMPORTANT_FOR_CONTENT_CAPTURE_NO_EXCLUDE_DESCENDANTS,
9789 name = "noExcludeDescendants"),
9790 })
9791 public @ContentCaptureImportance int getImportantForContentCapture() {
9792 // NOTE: the important for content capture values were the first flags added and are set in
9793 // the rightmost position, so we don't need to shift them
9794 return mPrivateFlags4 & PFLAG4_IMPORTANT_FOR_CONTENT_CAPTURE_MASK;
9795 }
9796
9797 /**
9798 * Sets the mode for determining whether this view is considered important for content capture.
9799 *
9800 * <p>The platform determines the importance for autofill automatically but you
9801 * can use this method to customize the behavior. Typically, a view that provides text should
9802 * be marked as {@link #IMPORTANT_FOR_CONTENT_CAPTURE_YES}.
9803 *
9804 * @param mode {@link #IMPORTANT_FOR_CONTENT_CAPTURE_AUTO},
9805 * {@link #IMPORTANT_FOR_CONTENT_CAPTURE_YES}, {@link #IMPORTANT_FOR_CONTENT_CAPTURE_NO},
9806 * {@link #IMPORTANT_FOR_CONTENT_CAPTURE_YES_EXCLUDE_DESCENDANTS},
9807 * or {@link #IMPORTANT_FOR_CONTENT_CAPTURE_NO_EXCLUDE_DESCENDANTS}.
9808 *
9809 * @attr ref android.R.styleable#View_importantForContentCapture
9810 */
9811 public void setImportantForContentCapture(@ContentCaptureImportance int mode) {
9812 // Reset first
9813 mPrivateFlags4 &= ~PFLAG4_IMPORTANT_FOR_CONTENT_CAPTURE_MASK;
9814 // Then set again
9815 // NOTE: the important for content capture values were the first flags added and are set in
9816 // the rightmost position, so we don't need to shift them
9817 mPrivateFlags4 |= (mode & PFLAG4_IMPORTANT_FOR_CONTENT_CAPTURE_MASK);
9818 }
9819
9820 /**
9821 * Hints the Android System whether this view is considered important for content capture, based
9822 * on the value explicitly set by {@link #setImportantForContentCapture(int)} and heuristics
9823 * when it's {@link #IMPORTANT_FOR_CONTENT_CAPTURE_AUTO}.
9824 *
9825 * <p>See {@link ContentCaptureManager} for more info about content capture.
9826 *
9827 * @return whether the view is considered important for content capture.
9828 *
9829 * @see #setImportantForContentCapture(int)
9830 * @see #IMPORTANT_FOR_CONTENT_CAPTURE_AUTO
9831 * @see #IMPORTANT_FOR_CONTENT_CAPTURE_YES
9832 * @see #IMPORTANT_FOR_CONTENT_CAPTURE_NO
9833 * @see #IMPORTANT_FOR_CONTENT_CAPTURE_YES_EXCLUDE_DESCENDANTS
9834 * @see #IMPORTANT_FOR_CONTENT_CAPTURE_NO_EXCLUDE_DESCENDANTS
9835 */
9836 public final boolean isImportantForContentCapture() {
9837 boolean isImportant;
9838 if ((mPrivateFlags4 & PFLAG4_CONTENT_CAPTURE_IMPORTANCE_IS_CACHED) != 0) {
9839 isImportant = (mPrivateFlags4 & PFLAG4_CONTENT_CAPTURE_IMPORTANCE_CACHED_VALUE) != 0;
9840 return isImportant;
9841 }
9842
9843 isImportant = calculateIsImportantForContentCapture();
9844
9845 mPrivateFlags4 &= ~PFLAG4_CONTENT_CAPTURE_IMPORTANCE_CACHED_VALUE;
9846 if (isImportant) {
9847 mPrivateFlags4 |= PFLAG4_CONTENT_CAPTURE_IMPORTANCE_CACHED_VALUE;
9848 }
9849 mPrivateFlags4 |= PFLAG4_CONTENT_CAPTURE_IMPORTANCE_IS_CACHED;
9850 return isImportant;
9851 }
9852
9853 /**
9854 * Calculates whether the flag is important for content capture so it can be used by
9855 * {@link #isImportantForContentCapture()} while the tree is traversed.
9856 */
9857 private boolean calculateIsImportantForContentCapture() {
9858 // Check parent mode to ensure we're important
9859 ViewParent parent = mParent;
9860 while (parent instanceof View) {
9861 final int parentImportance = ((View) parent).getImportantForContentCapture();
9862 if (parentImportance == IMPORTANT_FOR_CONTENT_CAPTURE_NO_EXCLUDE_DESCENDANTS
9863 || parentImportance == IMPORTANT_FOR_CONTENT_CAPTURE_YES_EXCLUDE_DESCENDANTS) {
9864 if (Log.isLoggable(CONTENT_CAPTURE_LOG_TAG, Log.VERBOSE)) {
9865 Log.v(CONTENT_CAPTURE_LOG_TAG, "View (" + this + ") is not important for "
9866 + "content capture because parent " + parent + "'s importance is "
9867 + parentImportance);
9868 }
9869 return false;
9870 }
9871 parent = parent.getParent();
9872 }
9873
9874 final int importance = getImportantForContentCapture();
9875
9876 // First, check the explicit states.
9877 if (importance == IMPORTANT_FOR_CONTENT_CAPTURE_YES_EXCLUDE_DESCENDANTS
9878 || importance == IMPORTANT_FOR_CONTENT_CAPTURE_YES) {
9879 return true;
9880 }
9881 if (importance == IMPORTANT_FOR_CONTENT_CAPTURE_NO_EXCLUDE_DESCENDANTS
9882 || importance == IMPORTANT_FOR_CONTENT_CAPTURE_NO) {
9883 if (Log.isLoggable(CONTENT_CAPTURE_LOG_TAG, Log.VERBOSE)) {
9884 Log.v(CONTENT_CAPTURE_LOG_TAG, "View (" + this + ") is not important for content "
9885 + "capture because its importance is " + importance);
9886 }
9887 return false;
9888 }
9889
9890 // Then use some heuristics to handle AUTO.
9891 if (importance != IMPORTANT_FOR_CONTENT_CAPTURE_AUTO) {
9892 Log.w(CONTENT_CAPTURE_LOG_TAG, "invalid content capture importance (" + importance
9893 + " on view " + this);
9894 return false;
9895 }
9896
9897 // View group is important if at least one children also is
9898 if (this instanceof ViewGroup) {
9899 final ViewGroup group = (ViewGroup) this;
9900 for (int i = 0; i < group.getChildCount(); i++) {
9901 final View child = group.getChildAt(i);
9902 if (child.isImportantForContentCapture()) {
9903 return true;
9904 }
9905 }
9906 }
9907
9908 // If the app developer explicitly set hints or autofill hintsfor it, it's important.
9909 if (getAutofillHints() != null) {
9910 return true;
9911 }
9912
9913 // Otherwise, assume it's not important...
9914 return false;
9915 }
9916
9917 /**
9918 * Helper used to notify the {@link ContentCaptureManager} when the view is removed or
9919 * added, based on whether it's laid out and visible, and without knowing if the parent removed
9920 * it from the view hierarchy.
9921 *
9922 * <p>This method is called from many places (visibility changed, view laid out, view attached
9923 * or detached to/from window, etc...) and hence must contain the logic to call the manager, as
9924 * described below:
9925 *
9926 * <ol>
9927 * <li>It should only be called when content capture is enabled for the view.
9928 * <li>It must call viewAppeared() before viewDisappeared()
9929 * <li>viewAppeared() can only be called when the view is visible and laid out
9930 * <li>It should not call the same event twice.
9931 * </ol>
9932 */
9933 private void notifyAppearedOrDisappearedForContentCaptureIfNeeded(boolean appeared) {
9934 AttachInfo ai = mAttachInfo;
9935 // Skip it while the view is being laid out for the first time
9936 if (ai != null && !ai.mReadyForContentCaptureUpdates) return;
9937
9938 // First check if context has client, so it saves a service lookup when it doesn't
9939 if (mContext.getContentCaptureOptions() == null) return;
9940
9941 if (appeared) {
9942 // The appeared event stops sending to AiAi.
9943 // 1. The view is hidden.
9944 // 2. The same event was sent.
9945 // 3. The view is not laid out, and it will be laid out in the future.
9946 // Some recycled views cached its layout and a relayout is unnecessary. In this case,
9947 // system still needs to notify content capture the view appeared. When a view is
9948 // recycled, it will set the flag PFLAG4_NOTIFIED_CONTENT_CAPTURE_DISAPPEARED.
9949 final boolean isRecycledWithoutRelayout = getNotifiedContentCaptureDisappeared()
9950 && getVisibility() == VISIBLE
9951 && !isLayoutRequested();
9952 if (getVisibility() != VISIBLE || getNotifiedContentCaptureAppeared()
9953 || !(isLaidOut() || isRecycledWithoutRelayout)) {
9954 if (DEBUG_CONTENT_CAPTURE) {
9955 Log.v(CONTENT_CAPTURE_LOG_TAG, "Ignoring 'appeared' on " + this + ": laid="
9956 + isLaidOut() + ", visibleToUser=" + isVisibleToUser()
9957 + ", visible=" + (getVisibility() == VISIBLE)
9958 + ": alreadyNotifiedAppeared=" + getNotifiedContentCaptureAppeared()
9959 + ", alreadyNotifiedDisappeared="
9960 + getNotifiedContentCaptureDisappeared());
9961 }
9962 return;
9963 }
9964 } else {
9965 if (!getNotifiedContentCaptureAppeared() || getNotifiedContentCaptureDisappeared()) {
9966 if (DEBUG_CONTENT_CAPTURE) {
9967 Log.v(CONTENT_CAPTURE_LOG_TAG, "Ignoring 'disappeared' on " + this + ": laid="
9968 + isLaidOut() + ", visibleToUser=" + isVisibleToUser()
9969 + ", visible=" + (getVisibility() == VISIBLE)
9970 + ": alreadyNotifiedAppeared=" + getNotifiedContentCaptureAppeared()
9971 + ", alreadyNotifiedDisappeared="
9972 + getNotifiedContentCaptureDisappeared());
9973 }
9974 return;
9975 }
9976 }
9977
9978 ContentCaptureSession session = getContentCaptureSession();
9979 if (session == null) return;
9980
9981 // ... and finally at the view level
9982 // NOTE: isImportantForContentCapture() is more expensive than cm.isContentCaptureEnabled()
9983 if (!isImportantForContentCapture()) return;
9984
9985 if (appeared) {
9986 setNotifiedContentCaptureAppeared();
9987
9988 if (ai != null) {
9989 ai.delayNotifyContentCaptureEvent(session, this, appeared);
9990 } else {
9991 if (DEBUG_CONTENT_CAPTURE) {
9992 Log.w(CONTENT_CAPTURE_LOG_TAG, "no AttachInfo on appeared for " + this);
9993 }
9994 }
9995 } else {
9996 mPrivateFlags4 |= PFLAG4_NOTIFIED_CONTENT_CAPTURE_DISAPPEARED;
9997 mPrivateFlags4 &= ~PFLAG4_NOTIFIED_CONTENT_CAPTURE_APPEARED;
9998
9999 if (ai != null) {
10000 ai.delayNotifyContentCaptureEvent(session, this, appeared);
10001 } else {
10002 if (DEBUG_CONTENT_CAPTURE) {
10003 Log.v(CONTENT_CAPTURE_LOG_TAG, "no AttachInfo on disappeared for " + this);
10004 }
10005 }
10006
10007 // We reset any translation state as views may be re-used (e.g., as in ListView and
10008 // RecyclerView). We only need to do this for views important for content capture since
10009 // views unimportant for content capture won't be translated anyway.
10010 if (!isTemporarilyDetached()) {
10011 clearTranslationState();
10012 }
10013 }
10014 }
10015
10016 private void setNotifiedContentCaptureAppeared() {
10017 mPrivateFlags4 |= PFLAG4_NOTIFIED_CONTENT_CAPTURE_APPEARED;
10018 mPrivateFlags4 &= ~PFLAG4_NOTIFIED_CONTENT_CAPTURE_DISAPPEARED;
10019 }
10020
10021 /** @hide */
10022 protected boolean getNotifiedContentCaptureAppeared() {
10023 return (mPrivateFlags4 & PFLAG4_NOTIFIED_CONTENT_CAPTURE_APPEARED) != 0;
10024 }
10025
10026
10027 private boolean getNotifiedContentCaptureDisappeared() {
10028 return (mPrivateFlags4 & PFLAG4_NOTIFIED_CONTENT_CAPTURE_DISAPPEARED) != 0;
10029 }
10030
10031 /**
10032 * Sets the (optional) {@link ContentCaptureSession} associated with this view.
10033 *
10034 * <p>This method should be called when you need to associate a {@link ContentCaptureContext} to
10035 * the content capture events associated with this view or its view hierarchy (if it's a
10036 * {@link ViewGroup}).
10037 *
10038 * <p>For example, if your activity is associated with a web domain, first you would need to
10039 * set the context for the main DOM:
10040 *
10041 * <pre>
10042 * ContentCaptureSession mainSession = rootView.getContentCaptureSession();
10043 * mainSession.setContentCaptureContext(ContentCaptureContext.forLocusId(Uri.parse(myUrl));
10044 * </pre>
10045 *
10046 * <p>Then if the page had an {@code IFRAME}, you would create a new session for it:
10047 *
10048 * <pre>
10049 * ContentCaptureSession iframeSession = mainSession.createContentCaptureSession(
10050 * ContentCaptureContext.forLocusId(Uri.parse(iframeUrl)));
10051 * iframeView.setContentCaptureSession(iframeSession);
10052 * </pre>
10053 *
10054 * @param contentCaptureSession a session created by
10055 * {@link ContentCaptureSession#createContentCaptureSession(
10056 * android.view.contentcapture.ContentCaptureContext)}.
10057 */
10058 public void setContentCaptureSession(@Nullable ContentCaptureSession contentCaptureSession) {
10059 mContentCaptureSession = contentCaptureSession;
10060 }
10061
10062 /**
10063 * Gets the session used to notify content capture events.
10064 *
10065 * @return session explicitly set by {@link #setContentCaptureSession(ContentCaptureSession)},
10066 * inherited by ancestors, default session or {@code null} if content capture is disabled for
10067 * this view.
10068 */
10069 @Nullable
10070 public final ContentCaptureSession getContentCaptureSession() {
10071 if (mContentCaptureSessionCached) {
10072 return mContentCaptureSession;
10073 }
10074
10075 mContentCaptureSession = getAndCacheContentCaptureSession();
10076 mContentCaptureSessionCached = true;
10077 return mContentCaptureSession;
10078 }
10079
10080 @Nullable
10081 private ContentCaptureSession getAndCacheContentCaptureSession() {
10082 // First try the session explicitly set by setContentCaptureSession()
10083 if (mContentCaptureSession != null) {
10084 return mContentCaptureSession;
10085 }
10086
10087 // Then the session explicitly set in an ancestor
10088 ContentCaptureSession session = null;
10089 if (mParent instanceof View) {
10090 session = ((View) mParent).getContentCaptureSession();
10091 }
10092
10093 // Finally, if no session was explicitly set, use the context's default session.
10094 if (session == null) {
10095 final ContentCaptureManager ccm = mContext
10096 .getSystemService(ContentCaptureManager.class);
10097 return ccm == null ? null : ccm.getMainContentCaptureSession();
10098 }
10099 return session;
10100 }
10101
10102 @Nullable
10103 private AutofillManager getAutofillManager() {
10104 return mContext.getSystemService(AutofillManager.class);
10105 }
10106
10107 private boolean isAutofillable() {
10108 if (getAutofillType() == AUTOFILL_TYPE_NONE) return false;
10109
10110 if (!isImportantForAutofill()) {
10111 // View is not important for "regular" autofill, so we must check if Augmented Autofill
10112 // is enabled for the activity
10113 final AutofillOptions options = mContext.getAutofillOptions();
10114 if (options == null || !options.isAugmentedAutofillEnabled(mContext)) {
10115 return false;
10116 }
10117 final AutofillManager afm = getAutofillManager();
10118 if (afm == null) return false;
10119 afm.notifyViewEnteredForAugmentedAutofill(this);
10120 }
10121
10122 return getAutofillViewId() > LAST_APP_AUTOFILL_ID;
10123 }
10124
10125 /** @hide */
10126 public boolean canNotifyAutofillEnterExitEvent() {
10127 return isAutofillable() && isAttachedToWindow();
10128 }
10129
10130 private void populateVirtualStructure(ViewStructure structure,
10131 AccessibilityNodeProvider provider, AccessibilityNodeInfo info,
10132 boolean forAutofill) {
10133 structure.setId(AccessibilityNodeInfo.getVirtualDescendantId(info.getSourceNodeId()),
10134 null, null, info.getViewIdResourceName());
10135 Rect rect = structure.getTempRect();
10136 info.getBoundsInParent(rect);
10137 structure.setDimens(rect.left, rect.top, 0, 0, rect.width(), rect.height());
10138 structure.setVisibility(VISIBLE);
10139 structure.setEnabled(info.isEnabled());
10140 if (info.isClickable()) {
10141 structure.setClickable(true);
10142 }
10143 if (info.isFocusable()) {
10144 structure.setFocusable(true);
10145 }
10146 if (info.isFocused()) {
10147 structure.setFocused(true);
10148 }
10149 if (info.isAccessibilityFocused()) {
10150 structure.setAccessibilityFocused(true);
10151 }
10152 if (info.isSelected()) {
10153 structure.setSelected(true);
10154 }
10155 if (info.isLongClickable()) {
10156 structure.setLongClickable(true);
10157 }
10158 if (info.isCheckable()) {
10159 structure.setCheckable(true);
10160 if (info.isChecked()) {
10161 structure.setChecked(true);
10162 }
10163 }
10164 if (info.isContextClickable()) {
10165 structure.setContextClickable(true);
10166 }
10167 if (forAutofill) {
10168 structure.setAutofillId(new AutofillId(getAutofillId(),
10169 AccessibilityNodeInfo.getVirtualDescendantId(info.getSourceNodeId())));
10170 }
10171 CharSequence cname = info.getClassName();
10172 structure.setClassName(cname != null ? cname.toString() : null);
10173 structure.setContentDescription(info.getContentDescription());
10174 if (forAutofill) {
10175 final int maxTextLength = info.getMaxTextLength();
10176 if (maxTextLength != -1) {
10177 structure.setMaxTextLength(maxTextLength);
10178 }
10179 structure.setHint(info.getHintText());
10180 }
10181 CharSequence text = info.getText();
10182 boolean hasText = text != null || info.getError() != null;
10183 if (hasText) {
10184 structure.setText(text, info.getTextSelectionStart(), info.getTextSelectionEnd());
10185 }
10186 if (forAutofill) {
10187 if (info.isEditable()) {
10188 structure.setDataIsSensitive(true);
10189 if (hasText) {
10190 structure.setAutofillType(AUTOFILL_TYPE_TEXT);
10191 structure.setAutofillValue(AutofillValue.forText(text));
10192 }
10193 int inputType = info.getInputType();
10194 if (inputType == 0 && info.isPassword()) {
10195 inputType = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD;
10196 }
10197 structure.setInputType(inputType);
10198 } else {
10199 structure.setDataIsSensitive(false);
10200 }
10201 }
10202 final int NCHILDREN = info.getChildCount();
10203 if (NCHILDREN > 0) {
10204 structure.setChildCount(NCHILDREN);
10205 for (int i=0; i<NCHILDREN; i++) {
10206 if (AccessibilityNodeInfo.getVirtualDescendantId(info.getChildNodeIds().get(i))
10207 == AccessibilityNodeProvider.HOST_VIEW_ID) {
10208 Log.e(VIEW_LOG_TAG, "Virtual view pointing to its host. Ignoring");
10209 continue;
10210 }
10211 AccessibilityNodeInfo cinfo = provider.createAccessibilityNodeInfo(
10212 AccessibilityNodeInfo.getVirtualDescendantId(info.getChildId(i)));
10213 if (cinfo != null) {
10214 ViewStructure child = structure.newChild(i);
10215 populateVirtualStructure(child, provider, cinfo, forAutofill);
10216 cinfo.recycle();
10217 }
10218 }
10219 }
10220 }
10221
10222 /**
10223 * Dispatch creation of {@link ViewStructure} down the hierarchy. The default
10224 * implementation calls {@link #onProvideStructure} and
10225 * {@link #onProvideVirtualStructure}.
10226 */
10227 public void dispatchProvideStructure(ViewStructure structure) {
10228 dispatchProvideStructure(structure, VIEW_STRUCTURE_FOR_ASSIST, /* flags= */ 0);
10229 }
10230
10231 /**
10232 * Dispatches creation of a {@link ViewStructure}s for autofill purposes down the hierarchy,
10233 * when an Assist structure is being created as part of an autofill request.
10234 *
10235 * <p>The default implementation does the following:
10236 * <ul>
10237 * <li>Sets the {@link AutofillId} in the structure.
10238 * <li>Calls {@link #onProvideAutofillStructure(ViewStructure, int)}.
10239 * <li>Calls {@link #onProvideAutofillVirtualStructure(ViewStructure, int)}.
10240 * </ul>
10241 *
10242 * <p>Typically, this method should only be overridden by subclasses that provide a view
10243 * hierarchy (such as {@link ViewGroup}) - other classes should override
10244 * {@link #onProvideAutofillStructure(ViewStructure, int)} or
10245 * {@link #onProvideAutofillVirtualStructure(ViewStructure, int)} instead.
10246 *
10247 * <p>When overridden, it must:
10248 *
10249 * <ul>
10250 * <li>Either call
10251 * {@code super.dispatchProvideAutofillStructure(structure, flags)} or explicitly
10252 * set the {@link AutofillId} in the structure (for example, by calling
10253 * {@code structure.setAutofillId(getAutofillId())}).
10254 * <li>Decide how to handle the {@link #AUTOFILL_FLAG_INCLUDE_NOT_IMPORTANT_VIEWS} flag - when
10255 * set, all views in the structure should be considered important for autofill,
10256 * regardless of what {@link #isImportantForAutofill()} returns. We encourage you to
10257 * respect this flag to provide a better user experience - this flag is typically used
10258 * when an user explicitly requested autofill. If the flag is not set,
10259 * then only views marked as important for autofill should be included in the
10260 * structure - skipping non-important views optimizes the overall autofill performance.
10261 * </ul>
10262 *
10263 * @param structure fill in with structured view data for autofill purposes.
10264 * @param flags optional flags.
10265 *
10266 * @see #AUTOFILL_FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
10267 */
10268 public void dispatchProvideAutofillStructure(@NonNull ViewStructure structure,
10269 @AutofillFlags int flags) {
10270 dispatchProvideStructure(structure, VIEW_STRUCTURE_FOR_AUTOFILL, flags);
10271 }
10272
10273 private void dispatchProvideStructure(@NonNull ViewStructure structure,
10274 @ViewStructureType int viewFor, @AutofillFlags int flags) {
10275 if (viewFor == VIEW_STRUCTURE_FOR_AUTOFILL) {
10276 structure.setAutofillId(getAutofillId());
10277 onProvideAutofillStructure(structure, flags);
10278 onProvideAutofillVirtualStructure(structure, flags);
10279 } else if (!isAssistBlocked()) {
10280 onProvideStructure(structure);
10281 onProvideVirtualStructure(structure);
10282 } else {
10283 structure.setClassName(getAccessibilityClassName().toString());
10284 structure.setAssistBlocked(true);
10285 }
10286 }
10287
10288 /**
10289 * Dispatches the initial content capture events for a view structure.
10290 *
10291 * @hide
10292 */
10293 public void dispatchInitialProvideContentCaptureStructure() {
10294 AttachInfo ai = mAttachInfo;
10295 if (ai == null) {
10296 Log.w(CONTENT_CAPTURE_LOG_TAG,
10297 "dispatchProvideContentCaptureStructure(): no AttachInfo for " + this);
10298 return;
10299 }
10300 ContentCaptureManager ccm = ai.mContentCaptureManager;
10301 if (ccm == null) {
10302 Log.w(CONTENT_CAPTURE_LOG_TAG, "dispatchProvideContentCaptureStructure(): "
10303 + "no ContentCaptureManager for " + this);
10304 return;
10305 }
10306
10307 // We must set it before checkign if the view itself is important, because it might
10308 // initially not be (for example, if it's empty), although that might change later (for
10309 // example, if important views are added)
10310 ai.mReadyForContentCaptureUpdates = true;
10311
10312 if (!isImportantForContentCapture()) {
10313 if (Log.isLoggable(CONTENT_CAPTURE_LOG_TAG, Log.DEBUG)) {
10314 Log.d(CONTENT_CAPTURE_LOG_TAG,
10315 "dispatchProvideContentCaptureStructure(): decorView is not important");
10316 }
10317 return;
10318 }
10319
10320 ai.mContentCaptureManager = ccm;
10321
10322 ContentCaptureSession session = getContentCaptureSession();
10323 if (session == null) {
10324 if (Log.isLoggable(CONTENT_CAPTURE_LOG_TAG, Log.DEBUG)) {
10325 Log.d(CONTENT_CAPTURE_LOG_TAG,
10326 "dispatchProvideContentCaptureStructure(): no session for " + this);
10327 }
10328 return;
10329 }
10330
10331 session.internalNotifyViewTreeEvent(/* started= */ true);
10332 try {
10333 dispatchProvideContentCaptureStructure();
10334 } finally {
10335 session.internalNotifyViewTreeEvent(/* started= */ false);
10336 }
10337 }
10338
10339 /** @hide */
10340 void dispatchProvideContentCaptureStructure() {
10341 ContentCaptureSession session = getContentCaptureSession();
10342 if (session != null) {
10343 ViewStructure structure = session.newViewStructure(this);
10344 onProvideContentCaptureStructure(structure, /* flags= */ 0);
10345 setNotifiedContentCaptureAppeared();
10346 session.notifyViewAppeared(structure);
10347 }
10348 }
10349
10350 /**
10351 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
10352 *
10353 * Note: Called from the default {@link AccessibilityDelegate}.
10354 *
10355 * @hide
10356 */
10357 public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
10358 if (mAttachInfo == null) {
10359 return;
10360 }
10361
10362 Rect bounds = mAttachInfo.mTmpInvalRect;
10363
10364 getDrawingRect(bounds);
10365 info.setBoundsInParent(bounds);
10366
10367 getBoundsOnScreen(bounds, true);
10368 info.setBoundsInScreen(bounds);
10369
10370 ViewParent parent = getParentForAccessibility();
10371 if (parent instanceof View) {
10372 info.setParent((View) parent);
10373 }
10374
10375 if (mID != View.NO_ID) {
10376 View rootView = getRootView();
10377 if (rootView == null) {
10378 rootView = this;
10379 }
10380
10381 View label = rootView.findLabelForView(this, mID);
10382 if (label != null) {
10383 info.setLabeledBy(label);
10384 }
10385
10386 if ((mAttachInfo.mAccessibilityFetchFlags
10387 & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
10388 && Resources.resourceHasPackage(mID)) {
10389 try {
10390 String viewId = getResources().getResourceName(mID);
10391 info.setViewIdResourceName(viewId);
10392 } catch (Resources.NotFoundException nfe) {
10393 /* ignore */
10394 }
10395 }
10396 }
10397
10398 if (mLabelForId != View.NO_ID) {
10399 View rootView = getRootView();
10400 if (rootView == null) {
10401 rootView = this;
10402 }
10403 View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
10404 if (labeled != null) {
10405 info.setLabelFor(labeled);
10406 }
10407 }
10408
10409 if (mAccessibilityTraversalBeforeId != View.NO_ID) {
10410 View rootView = getRootView();
10411 if (rootView == null) {
10412 rootView = this;
10413 }
10414 View next = rootView.findViewInsideOutShouldExist(this,
10415 mAccessibilityTraversalBeforeId);
10416 if (next != null && next.includeForAccessibility()) {
10417 info.setTraversalBefore(next);
10418 }
10419 }
10420
10421 if (mAccessibilityTraversalAfterId != View.NO_ID) {
10422 View rootView = getRootView();
10423 if (rootView == null) {
10424 rootView = this;
10425 }
10426 View next = rootView.findViewInsideOutShouldExist(this,
10427 mAccessibilityTraversalAfterId);
10428 if (next != null && next.includeForAccessibility()) {
10429 info.setTraversalAfter(next);
10430 }
10431 }
10432
10433 info.setVisibleToUser(isVisibleToUser());
10434
10435 info.setImportantForAccessibility(isImportantForAccessibility());
10436 info.setPackageName(mContext.getPackageName());
10437 info.setClassName(getAccessibilityClassName());
10438 info.setStateDescription(getStateDescription());
10439 info.setContentDescription(getContentDescription());
10440
10441 info.setEnabled(isEnabled());
10442 info.setClickable(isClickable());
10443 info.setFocusable(isFocusable());
10444 info.setScreenReaderFocusable(isScreenReaderFocusable());
10445 info.setFocused(isFocused());
10446 info.setAccessibilityFocused(isAccessibilityFocused());
10447 info.setSelected(isSelected());
10448 info.setLongClickable(isLongClickable());
10449 info.setContextClickable(isContextClickable());
10450 info.setLiveRegion(getAccessibilityLiveRegion());
10451 if ((mTooltipInfo != null) && (mTooltipInfo.mTooltipText != null)) {
10452 info.setTooltipText(mTooltipInfo.mTooltipText);
10453 info.addAction((mTooltipInfo.mTooltipPopup == null)
10454 ? AccessibilityNodeInfo.AccessibilityAction.ACTION_SHOW_TOOLTIP
10455 : AccessibilityNodeInfo.AccessibilityAction.ACTION_HIDE_TOOLTIP);
10456 }
10457
10458 // TODO: These make sense only if we are in an AdapterView but all
10459 // views can be selected. Maybe from accessibility perspective
10460 // we should report as selectable view in an AdapterView.
10461 info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
10462 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
10463
10464 if (isFocusable()) {
10465 if (isFocused()) {
10466 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
10467 } else {
10468 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
10469 }
10470 }
10471
10472 if (!isAccessibilityFocused()) {
10473 info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
10474 } else {
10475 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
10476 }
10477
10478 if (isClickable() && isEnabled()) {
10479 info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
10480 }
10481
10482 if (isLongClickable() && isEnabled()) {
10483 info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
10484 }
10485
10486 if (isContextClickable() && isEnabled()) {
10487 info.addAction(AccessibilityAction.ACTION_CONTEXT_CLICK);
10488 }
10489
10490 CharSequence text = getIterableTextForAccessibility();
10491 if (text != null && text.length() > 0) {
10492 info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
10493
10494 info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
10495 info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
10496 info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
10497 info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
10498 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
10499 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
10500 }
10501
10502 info.addAction(AccessibilityAction.ACTION_SHOW_ON_SCREEN);
10503 populateAccessibilityNodeInfoDrawingOrderInParent(info);
10504 info.setPaneTitle(mAccessibilityPaneTitle);
10505 info.setHeading(isAccessibilityHeading());
10506
10507 if (mTouchDelegate != null) {
10508 info.setTouchDelegateInfo(mTouchDelegate.getTouchDelegateInfo());
10509 }
10510
10511 if (startedSystemDragForAccessibility()) {
10512 info.addAction(AccessibilityAction.ACTION_DRAG_CANCEL);
10513 }
10514
10515 if (canAcceptAccessibilityDrop()) {
10516 info.addAction(AccessibilityAction.ACTION_DRAG_DROP);
10517 }
10518 }
10519
10520
10521 /**
10522 * Adds extra data to an {@link AccessibilityNodeInfo} based on an explicit request for the
10523 * additional data.
10524 * <p>
10525 * This method only needs overloading if the node is marked as having extra data available.
10526 * </p>
10527 *
10528 * @param info The info to which to add the extra data. Never {@code null}.
10529 * @param extraDataKey A key specifying the type of extra data to add to the info. The
10530 * extra data should be added to the {@link Bundle} returned by
10531 * the info's {@link AccessibilityNodeInfo#getExtras} method. Never
10532 * {@code null}.
10533 * @param arguments A {@link Bundle} holding any arguments relevant for this request. May be
10534 * {@code null} if the service provided no arguments.
10535 *
10536 * @see AccessibilityNodeInfo#setAvailableExtraData(List)
10537 */
10538 public void addExtraDataToAccessibilityNodeInfo(
10539 @NonNull AccessibilityNodeInfo info, @NonNull String extraDataKey,
10540 @Nullable Bundle arguments) {
10541 }
10542
10543 /**
10544 * Determine the order in which this view will be drawn relative to its siblings for a11y
10545 *
10546 * @param info The info whose drawing order should be populated
10547 */
10548 private void populateAccessibilityNodeInfoDrawingOrderInParent(AccessibilityNodeInfo info) {
10549 /*
10550 * If the view's bounds haven't been set yet, layout has not completed. In that situation,
10551 * drawing order may not be well-defined, and some Views with custom drawing order may
10552 * not be initialized sufficiently to respond properly getChildDrawingOrder.
10553 */
10554 if ((mPrivateFlags & PFLAG_HAS_BOUNDS) == 0) {
10555 info.setDrawingOrder(0);
10556 return;
10557 }
10558 int drawingOrderInParent = 1;
10559 // Iterate up the hierarchy if parents are not important for a11y
10560 View viewAtDrawingLevel = this;
10561 final ViewParent parent = getParentForAccessibility();
10562 while (viewAtDrawingLevel != parent) {
10563 final ViewParent currentParent = viewAtDrawingLevel.getParent();
10564 if (!(currentParent instanceof ViewGroup)) {
10565 // Should only happen for the Decor
10566 drawingOrderInParent = 0;
10567 break;
10568 } else {
10569 final ViewGroup parentGroup = (ViewGroup) currentParent;
10570 final int childCount = parentGroup.getChildCount();
10571 if (childCount > 1) {
10572 List<View> preorderedList = parentGroup.buildOrderedChildList();
10573 if (preorderedList != null) {
10574 final int childDrawIndex = preorderedList.indexOf(viewAtDrawingLevel);
10575 for (int i = 0; i < childDrawIndex; i++) {
10576 drawingOrderInParent += numViewsForAccessibility(preorderedList.get(i));
10577 }
10578 preorderedList.clear();
10579 } else {
10580 final int childIndex = parentGroup.indexOfChild(viewAtDrawingLevel);
10581 final boolean customOrder = parentGroup.isChildrenDrawingOrderEnabled();
10582 final int childDrawIndex = ((childIndex >= 0) && customOrder) ? parentGroup
10583 .getChildDrawingOrder(childCount, childIndex) : childIndex;
10584 final int numChildrenToIterate = customOrder ? childCount : childDrawIndex;
10585 if (childDrawIndex != 0) {
10586 for (int i = 0; i < numChildrenToIterate; i++) {
10587 final int otherDrawIndex = (customOrder ?
10588 parentGroup.getChildDrawingOrder(childCount, i) : i);
10589 if (otherDrawIndex < childDrawIndex) {
10590 drawingOrderInParent +=
10591 numViewsForAccessibility(parentGroup.getChildAt(i));
10592 }
10593 }
10594 }
10595 }
10596 }
10597 }
10598 viewAtDrawingLevel = (View) currentParent;
10599 }
10600 info.setDrawingOrder(drawingOrderInParent);
10601 }
10602
10603 private static int numViewsForAccessibility(View view) {
10604 if (view != null) {
10605 if (view.includeForAccessibility()) {
10606 return 1;
10607 } else if (view instanceof ViewGroup) {
10608 return ((ViewGroup) view).getNumChildrenForAccessibility();
10609 }
10610 }
10611 return 0;
10612 }
10613
10614 private View findLabelForView(View view, int labeledId) {
10615 if (mMatchLabelForPredicate == null) {
10616 mMatchLabelForPredicate = new MatchLabelForPredicate();
10617 }
10618 mMatchLabelForPredicate.mLabeledId = labeledId;
10619 return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
10620 }
10621
10622 /**
10623 * Computes whether this virtual autofill view is visible to the user.
10624 *
10625 * <p><b>Note: </b>By default it returns {@code true}, but views providing a virtual hierarchy
10626 * view must override it.
10627 *
10628 * @return Whether the view is visible on the screen.
10629 */
10630 public boolean isVisibleToUserForAutofill(int virtualId) {
10631 if (mContext.isAutofillCompatibilityEnabled()) {
10632 final AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
10633 if (provider != null) {
10634 final AccessibilityNodeInfo node = provider.createAccessibilityNodeInfo(virtualId);
10635 if (node != null) {
10636 return node.isVisibleToUser();
10637 }
10638 // if node is null, assume it's not visible anymore
10639 } else {
10640 Log.w(VIEW_LOG_TAG, "isVisibleToUserForAutofill(" + virtualId + "): no provider");
10641 }
10642 return false;
10643 }
10644 return true;
10645 }
10646
10647 /**
10648 * Computes whether this view is visible to the user. Such a view is
10649 * attached, visible, all its predecessors are visible, it is not clipped
10650 * entirely by its predecessors, and has an alpha greater than zero.
10651 *
10652 * @return Whether the view is visible on the screen.
10653 *
10654 * @hide
10655 */
10656 @UnsupportedAppUsage
10657 public boolean isVisibleToUser() {
10658 return isVisibleToUser(null);
10659 }
10660
10661 /**
10662 * Computes whether the given portion of this view is visible to the user.
10663 * Such a view is attached, visible, all its predecessors are visible,
10664 * has an alpha greater than zero, and the specified portion is not
10665 * clipped entirely by its predecessors.
10666 *
10667 * @param boundInView the portion of the view to test; coordinates should be relative; may be
10668 * <code>null</code>, and the entire view will be tested in this case.
10669 * When <code>true</code> is returned by the function, the actual visible
10670 * region will be stored in this parameter; that is, if boundInView is fully
10671 * contained within the view, no modification will be made, otherwise regions
10672 * outside of the visible area of the view will be clipped.
10673 *
10674 * @return Whether the specified portion of the view is visible on the screen.
10675 *
10676 * @hide
10677 */
10678 @UnsupportedAppUsage(trackingBug = 171933273)
10679 protected boolean isVisibleToUser(Rect boundInView) {
10680 if (mAttachInfo != null) {
10681 // Attached to invisible window means this view is not visible.
10682 if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
10683 return false;
10684 }
10685 // An invisible predecessor or one with alpha zero means
10686 // that this view is not visible to the user.
10687 Object current = this;
10688 while (current instanceof View) {
10689 View view = (View) current;
10690 // We have attach info so this view is attached and there is no
10691 // need to check whether we reach to ViewRootImpl on the way up.
10692 if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
10693 view.getVisibility() != VISIBLE) {
10694 return false;
10695 }
10696 current = view.mParent;
10697 }
10698 // Check if the view is entirely covered by its predecessors.
10699 Rect visibleRect = mAttachInfo.mTmpInvalRect;
10700 Point offset = mAttachInfo.mPoint;
10701 if (!getGlobalVisibleRect(visibleRect, offset)) {
10702 return false;
10703 }
10704 // Check if the visible portion intersects the rectangle of interest.
10705 if (boundInView != null) {
10706 visibleRect.offset(-offset.x, -offset.y);
10707 return boundInView.intersect(visibleRect);
10708 }
10709 return true;
10710 }
10711 return false;
10712 }
10713
10714 /**
10715 * Returns the delegate for implementing accessibility support via
10716 * composition. For more details see {@link AccessibilityDelegate}.
10717 *
10718 * @return The delegate, or null if none set.
10719 */
10720 public AccessibilityDelegate getAccessibilityDelegate() {
10721 return mAccessibilityDelegate;
10722 }
10723
10724 /**
10725 * Sets a delegate for implementing accessibility support via composition
10726 * (as opposed to inheritance). For more details, see
10727 * {@link AccessibilityDelegate}.
10728 * <p>
10729 * <strong>Note:</strong> On platform versions prior to
10730 * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on
10731 * views in the {@code android.widget.*} package are called <i>before</i>
10732 * host methods. This prevents certain properties such as class name from
10733 * being modified by overriding
10734 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)},
10735 * as any changes will be overwritten by the host class.
10736 * <p>
10737 * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate
10738 * methods are called <i>after</i> host methods, which all properties to be
10739 * modified without being overwritten by the host class.
10740 *
10741 * @param delegate the object to which accessibility method calls should be
10742 * delegated
10743 * @see AccessibilityDelegate
10744 */
10745 public void setAccessibilityDelegate(@Nullable AccessibilityDelegate delegate) {
10746 mAccessibilityDelegate = delegate;
10747 }
10748
10749 /**
10750 * Gets the provider for managing a virtual view hierarchy rooted at this View
10751 * and reported to {@link android.accessibilityservice.AccessibilityService}s
10752 * that explore the window content.
10753 * <p>
10754 * If this method returns an instance, this instance is responsible for managing
10755 * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
10756 * View including the one representing the View itself. Similarly the returned
10757 * instance is responsible for performing accessibility actions on any virtual
10758 * view or the root view itself.
10759 * </p>
10760 * <p>
10761 * If an {@link AccessibilityDelegate} has been specified via calling
10762 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
10763 * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
10764 * is responsible for handling this call.
10765 * </p>
10766 *
10767 * @return The provider.
10768 *
10769 * @see AccessibilityNodeProvider
10770 */
10771 public AccessibilityNodeProvider getAccessibilityNodeProvider() {
10772 if (mAccessibilityDelegate != null) {
10773 return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
10774 } else {
10775 return null;
10776 }
10777 }
10778
10779 /**
10780 * Gets the unique identifier of this view on the screen for accessibility purposes.
10781 *
10782 * @return The view accessibility id.
10783 *
10784 * @hide
10785 */
10786 @UnsupportedAppUsage
10787 public int getAccessibilityViewId() {
10788 if (mAccessibilityViewId == NO_ID) {
10789 mAccessibilityViewId = sNextAccessibilityViewId++;
10790 }
10791 return mAccessibilityViewId;
10792 }
10793
10794 /**
10795 * Gets the unique identifier of this view on the screen for autofill purposes.
10796 *
10797 * @return The view autofill id.
10798 *
10799 * @hide
10800 */
10801 public int getAutofillViewId() {
10802 if (mAutofillViewId == NO_ID) {
10803 mAutofillViewId = mContext.getNextAutofillId();
10804 }
10805 return mAutofillViewId;
10806 }
10807
10808 /**
10809 * Gets the unique identifier of the window in which this View resides.
10810 *
10811 * @return The window accessibility id.
10812 *
10813 * @hide
10814 */
10815 public int getAccessibilityWindowId() {
10816 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId
10817 : AccessibilityWindowInfo.UNDEFINED_WINDOW_ID;
10818 }
10819
10820 /**
10821 * Returns the {@link View}'s state description.
10822 * <p>
10823 * <strong>Note:</strong> Do not override this method, as it will have no
10824 * effect on the state description presented to accessibility services.
10825 * You must call {@link #setStateDescription(CharSequence)} to modify the
10826 * state description.
10827 *
10828 * @return the state description
10829 * @see #setStateDescription(CharSequence)
10830 */
10831 @ViewDebug.ExportedProperty(category = "accessibility")
10832 public final @Nullable CharSequence getStateDescription() {
10833 return mStateDescription;
10834 }
10835
10836 /**
10837 * Returns the {@link View}'s content description.
10838 * <p>
10839 * <strong>Note:</strong> Do not override this method, as it will have no
10840 * effect on the content description presented to accessibility services.
10841 * You must call {@link #setContentDescription(CharSequence)} to modify the
10842 * content description.
10843 *
10844 * @return the content description
10845 * @see #setContentDescription(CharSequence)
10846 * @attr ref android.R.styleable#View_contentDescription
10847 */
10848 @ViewDebug.ExportedProperty(category = "accessibility")
10849 @InspectableProperty
10850 public CharSequence getContentDescription() {
10851 return mContentDescription;
10852 }
10853
10854 /**
10855 * Sets the {@link View}'s state description.
10856 * <p>
10857 * A state description briefly describes the states of the view and is primarily used
10858 * for accessibility support to determine how the states of a view should be presented to
10859 * the user. It is a supplement to the boolean states (for example, checked/unchecked) and
10860 * it is used for customized state description (for example, "wifi, connected, three bars").
10861 * State description changes frequently while content description should change less often.
10862 * State description should be localized. For android widgets which have default state
10863 * descriptions, app developers can call this method to override the state descriptions.
10864 * Setting state description to null restores the default behavior.
10865 *
10866 * @param stateDescription The state description.
10867 * @see #getStateDescription()
10868 */
10869 @RemotableViewMethod
10870 public void setStateDescription(@Nullable CharSequence stateDescription) {
10871 if (mStateDescription == null) {
10872 if (stateDescription == null) {
10873 return;
10874 }
10875 } else if (mStateDescription.equals(stateDescription)) {
10876 return;
10877 }
10878 mStateDescription = stateDescription;
10879 if (!TextUtils.isEmpty(stateDescription)
10880 && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
10881 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
10882 }
10883 if (AccessibilityManager.getInstance(mContext).isEnabled()) {
10884 AccessibilityEvent event = AccessibilityEvent.obtain();
10885 event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
10886 event.setContentChangeTypes(AccessibilityEvent.CONTENT_CHANGE_TYPE_STATE_DESCRIPTION);
10887 sendAccessibilityEventUnchecked(event);
10888 }
10889 }
10890
10891 /**
10892 * Sets the {@link View}'s content description.
10893 * <p>
10894 * A content description briefly describes the view and is primarily used
10895 * for accessibility support to determine how a view should be presented to
10896 * the user. In the case of a view with no textual representation, such as
10897 * {@link android.widget.ImageButton}, a useful content description
10898 * explains what the view does. For example, an image button with a phone
10899 * icon that is used to place a call may use "Call" as its content
10900 * description. An image of a floppy disk that is used to save a file may
10901 * use "Save".
10902 *
10903 * @param contentDescription The content description.
10904 * @see #getContentDescription()
10905 * @attr ref android.R.styleable#View_contentDescription
10906 */
10907 @RemotableViewMethod
10908 public void setContentDescription(CharSequence contentDescription) {
10909 if (mContentDescription == null) {
10910 if (contentDescription == null) {
10911 return;
10912 }
10913 } else if (mContentDescription.equals(contentDescription)) {
10914 return;
10915 }
10916 mContentDescription = contentDescription;
10917 final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
10918 if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
10919 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
10920 notifySubtreeAccessibilityStateChangedIfNeeded();
10921 } else {
10922 notifyViewAccessibilityStateChangedIfNeeded(
10923 AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
10924 }
10925 }
10926
10927 /**
10928 * Sets the id of a view before which this one is visited in accessibility traversal.
10929 * A screen-reader must visit the content of this view before the content of the one
10930 * it precedes. For example, if view B is set to be before view A, then a screen-reader
10931 * will traverse the entire content of B before traversing the entire content of A,
10932 * regardles of what traversal strategy it is using.
10933 * <p>
10934 * Views that do not have specified before/after relationships are traversed in order
10935 * determined by the screen-reader.
10936 * </p>
10937 * <p>
10938 * Setting that this view is before a view that is not important for accessibility
10939 * or if this view is not important for accessibility will have no effect as the
10940 * screen-reader is not aware of unimportant views.
10941 * </p>
10942 *
10943 * @param beforeId The id of a view this one precedes in accessibility traversal.
10944 *
10945 * @attr ref android.R.styleable#View_accessibilityTraversalBefore
10946 *
10947 * @see #setImportantForAccessibility(int)
10948 */
10949 @RemotableViewMethod
10950 public void setAccessibilityTraversalBefore(@IdRes int beforeId) {
10951 if (mAccessibilityTraversalBeforeId == beforeId) {
10952 return;
10953 }
10954 mAccessibilityTraversalBeforeId = beforeId;
10955 notifyViewAccessibilityStateChangedIfNeeded(
10956 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10957 }
10958
10959 /**
10960 * Gets the id of a view before which this one is visited in accessibility traversal.
10961 *
10962 * @return The id of a view this one precedes in accessibility traversal if
10963 * specified, otherwise {@link #NO_ID}.
10964 *
10965 * @see #setAccessibilityTraversalBefore(int)
10966 */
10967 @IdRes
10968 @InspectableProperty
10969 public int getAccessibilityTraversalBefore() {
10970 return mAccessibilityTraversalBeforeId;
10971 }
10972
10973 /**
10974 * Sets the id of a view after which this one is visited in accessibility traversal.
10975 * A screen-reader must visit the content of the other view before the content of this
10976 * one. For example, if view B is set to be after view A, then a screen-reader
10977 * will traverse the entire content of A before traversing the entire content of B,
10978 * regardles of what traversal strategy it is using.
10979 * <p>
10980 * Views that do not have specified before/after relationships are traversed in order
10981 * determined by the screen-reader.
10982 * </p>
10983 * <p>
10984 * Setting that this view is after a view that is not important for accessibility
10985 * or if this view is not important for accessibility will have no effect as the
10986 * screen-reader is not aware of unimportant views.
10987 * </p>
10988 *
10989 * @param afterId The id of a view this one succedees in accessibility traversal.
10990 *
10991 * @attr ref android.R.styleable#View_accessibilityTraversalAfter
10992 *
10993 * @see #setImportantForAccessibility(int)
10994 */
10995 @RemotableViewMethod
10996 public void setAccessibilityTraversalAfter(@IdRes int afterId) {
10997 if (mAccessibilityTraversalAfterId == afterId) {
10998 return;
10999 }
11000 mAccessibilityTraversalAfterId = afterId;
11001 notifyViewAccessibilityStateChangedIfNeeded(
11002 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
11003 }
11004
11005 /**
11006 * Gets the id of a view after which this one is visited in accessibility traversal.
11007 *
11008 * @return The id of a view this one succeedes in accessibility traversal if
11009 * specified, otherwise {@link #NO_ID}.
11010 *
11011 * @see #setAccessibilityTraversalAfter(int)
11012 */
11013 @IdRes
11014 @InspectableProperty
11015 public int getAccessibilityTraversalAfter() {
11016 return mAccessibilityTraversalAfterId;
11017 }
11018
11019 /**
11020 * Gets the id of a view for which this view serves as a label for
11021 * accessibility purposes.
11022 *
11023 * @return The labeled view id.
11024 */
11025 @IdRes
11026 @ViewDebug.ExportedProperty(category = "accessibility")
11027 @InspectableProperty
11028 public int getLabelFor() {
11029 return mLabelForId;
11030 }
11031
11032 /**
11033 * Sets the id of a view for which this view serves as a label for
11034 * accessibility purposes.
11035 *
11036 * @param id The labeled view id.
11037 */
11038 @RemotableViewMethod
11039 public void setLabelFor(@IdRes int id) {
11040 if (mLabelForId == id) {
11041 return;
11042 }
11043 mLabelForId = id;
11044 if (mLabelForId != View.NO_ID
11045 && mID == View.NO_ID) {
11046 mID = generateViewId();
11047 }
11048 notifyViewAccessibilityStateChangedIfNeeded(
11049 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
11050 }
11051
11052 /**
11053 * Invoked whenever this view loses focus, either by losing window focus or by losing
11054 * focus within its window. This method can be used to clear any state tied to the
11055 * focus. For instance, if a button is held pressed with the trackball and the window
11056 * loses focus, this method can be used to cancel the press.
11057 *
11058 * Subclasses of View overriding this method should always call super.onFocusLost().
11059 *
11060 * @see #onFocusChanged(boolean, int, android.graphics.Rect)
11061 * @see #onWindowFocusChanged(boolean)
11062 *
11063 * @hide pending API council approval
11064 */
11065 @CallSuper
11066 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
11067 protected void onFocusLost() {
11068 resetPressedState();
11069 }
11070
11071 private void resetPressedState() {
11072 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
11073 return;
11074 }
11075
11076 if (isPressed()) {
11077 setPressed(false);
11078
11079 if (!mHasPerformedLongPress) {
11080 removeLongPressCallback();
11081 }
11082 }
11083 }
11084
11085 /**
11086 * Returns true if this view has focus
11087 *
11088 * @return True if this view has focus, false otherwise.
11089 */
11090 @ViewDebug.ExportedProperty(category = "focus")
11091 @InspectableProperty(hasAttributeId = false)
11092 public boolean isFocused() {
11093 return (mPrivateFlags & PFLAG_FOCUSED) != 0;
11094 }
11095
11096 /**
11097 * Find the view in the hierarchy rooted at this view that currently has
11098 * focus.
11099 *
11100 * @return The view that currently has focus, or null if no focused view can
11101 * be found.
11102 */
11103 public View findFocus() {
11104 return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
11105 }
11106
11107 /**
11108 * Indicates whether this view is one of the set of scrollable containers in
11109 * its window.
11110 *
11111 * @return whether this view is one of the set of scrollable containers in
11112 * its window
11113 *
11114 * @attr ref android.R.styleable#View_isScrollContainer
11115 */
11116 @InspectableProperty(name = "isScrollContainer")
11117 public boolean isScrollContainer() {
11118 return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
11119 }
11120
11121 /**
11122 * Change whether this view is one of the set of scrollable containers in
11123 * its window. This will be used to determine whether the window can
11124 * resize or must pan when a soft input area is open -- scrollable
11125 * containers allow the window to use resize mode since the container
11126 * will appropriately shrink.
11127 *
11128 * @attr ref android.R.styleable#View_isScrollContainer
11129 */
11130 public void setScrollContainer(boolean isScrollContainer) {
11131 if (isScrollContainer) {
11132 if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
11133 mAttachInfo.mScrollContainers.add(this);
11134 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
11135 }
11136 mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
11137 } else {
11138 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
11139 mAttachInfo.mScrollContainers.remove(this);
11140 }
11141 mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
11142 }
11143 }
11144
11145 /**
11146 * Returns the quality of the drawing cache.
11147 *
11148 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
11149 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
11150 *
11151 * @see #setDrawingCacheQuality(int)
11152 * @see #setDrawingCacheEnabled(boolean)
11153 * @see #isDrawingCacheEnabled()
11154 *
11155 * @attr ref android.R.styleable#View_drawingCacheQuality
11156 *
11157 * @deprecated The view drawing cache was largely made obsolete with the introduction of
11158 * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
11159 * layers are largely unnecessary and can easily result in a net loss in performance due to the
11160 * cost of creating and updating the layer. In the rare cases where caching layers are useful,
11161 * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
11162 * rendering. For software-rendered snapshots of a small part of the View hierarchy or
11163 * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
11164 * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
11165 * software-rendered usages are discouraged and have compatibility issues with hardware-only
11166 * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
11167 * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
11168 * reports or unit testing the {@link PixelCopy} API is recommended.
11169 */
11170 @Deprecated
11171 @DrawingCacheQuality
11172 @InspectableProperty(enumMapping = {
11173 @EnumEntry(value = DRAWING_CACHE_QUALITY_LOW, name = "low"),
11174 @EnumEntry(value = DRAWING_CACHE_QUALITY_HIGH, name = "high"),
11175 @EnumEntry(value = DRAWING_CACHE_QUALITY_AUTO, name = "auto")
11176 })
11177 public int getDrawingCacheQuality() {
11178 return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
11179 }
11180
11181 /**
11182 * Set the drawing cache quality of this view. This value is used only when the
11183 * drawing cache is enabled
11184 *
11185 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
11186 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
11187 *
11188 * @see #getDrawingCacheQuality()
11189 * @see #setDrawingCacheEnabled(boolean)
11190 * @see #isDrawingCacheEnabled()
11191 *
11192 * @attr ref android.R.styleable#View_drawingCacheQuality
11193 *
11194 * @deprecated The view drawing cache was largely made obsolete with the introduction of
11195 * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
11196 * layers are largely unnecessary and can easily result in a net loss in performance due to the
11197 * cost of creating and updating the layer. In the rare cases where caching layers are useful,
11198 * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
11199 * rendering. For software-rendered snapshots of a small part of the View hierarchy or
11200 * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
11201 * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
11202 * software-rendered usages are discouraged and have compatibility issues with hardware-only
11203 * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
11204 * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
11205 * reports or unit testing the {@link PixelCopy} API is recommended.
11206 */
11207 @Deprecated
11208 public void setDrawingCacheQuality(@DrawingCacheQuality int quality) {
11209 setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
11210 }
11211
11212 /**
11213 * Returns whether the screen should remain on, corresponding to the current
11214 * value of {@link #KEEP_SCREEN_ON}.
11215 *
11216 * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
11217 *
11218 * @see #setKeepScreenOn(boolean)
11219 *
11220 * @attr ref android.R.styleable#View_keepScreenOn
11221 */
11222 @InspectableProperty
11223 public boolean getKeepScreenOn() {
11224 return (mViewFlags & KEEP_SCREEN_ON) != 0;
11225 }
11226
11227 /**
11228 * Controls whether the screen should remain on, modifying the
11229 * value of {@link #KEEP_SCREEN_ON}.
11230 *
11231 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
11232 *
11233 * @see #getKeepScreenOn()
11234 *
11235 * @attr ref android.R.styleable#View_keepScreenOn
11236 */
11237 public void setKeepScreenOn(boolean keepScreenOn) {
11238 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
11239 }
11240
11241 /**
11242 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
11243 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
11244 *
11245 * @attr ref android.R.styleable#View_nextFocusLeft
11246 */
11247 @IdRes
11248 @InspectableProperty(name = "nextFocusLeft")
11249 public int getNextFocusLeftId() {
11250 return mNextFocusLeftId;
11251 }
11252
11253 /**
11254 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
11255 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
11256 * decide automatically.
11257 *
11258 * @attr ref android.R.styleable#View_nextFocusLeft
11259 */
11260 public void setNextFocusLeftId(@IdRes int nextFocusLeftId) {
11261 mNextFocusLeftId = nextFocusLeftId;
11262 }
11263
11264 /**
11265 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
11266 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
11267 *
11268 * @attr ref android.R.styleable#View_nextFocusRight
11269 */
11270 @IdRes
11271 @InspectableProperty(name = "nextFocusRight")
11272 public int getNextFocusRightId() {
11273 return mNextFocusRightId;
11274 }
11275
11276 /**
11277 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
11278 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
11279 * decide automatically.
11280 *
11281 * @attr ref android.R.styleable#View_nextFocusRight
11282 */
11283 public void setNextFocusRightId(@IdRes int nextFocusRightId) {
11284 mNextFocusRightId = nextFocusRightId;
11285 }
11286
11287 /**
11288 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
11289 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
11290 *
11291 * @attr ref android.R.styleable#View_nextFocusUp
11292 */
11293 @IdRes
11294 @InspectableProperty(name = "nextFocusUp")
11295 public int getNextFocusUpId() {
11296 return mNextFocusUpId;
11297 }
11298
11299 /**
11300 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
11301 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
11302 * decide automatically.
11303 *
11304 * @attr ref android.R.styleable#View_nextFocusUp
11305 */
11306 public void setNextFocusUpId(@IdRes int nextFocusUpId) {
11307 mNextFocusUpId = nextFocusUpId;
11308 }
11309
11310 /**
11311 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
11312 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
11313 *
11314 * @attr ref android.R.styleable#View_nextFocusDown
11315 */
11316 @IdRes
11317 @InspectableProperty(name = "nextFocusDown")
11318 public int getNextFocusDownId() {
11319 return mNextFocusDownId;
11320 }
11321
11322 /**
11323 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
11324 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
11325 * decide automatically.
11326 *
11327 * @attr ref android.R.styleable#View_nextFocusDown
11328 */
11329 public void setNextFocusDownId(@IdRes int nextFocusDownId) {
11330 mNextFocusDownId = nextFocusDownId;
11331 }
11332
11333 /**
11334 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
11335 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
11336 *
11337 * @attr ref android.R.styleable#View_nextFocusForward
11338 */
11339 @IdRes
11340 @InspectableProperty(name = "nextFocusForward")
11341 public int getNextFocusForwardId() {
11342 return mNextFocusForwardId;
11343 }
11344
11345 /**
11346 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
11347 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
11348 * decide automatically.
11349 *
11350 * @attr ref android.R.styleable#View_nextFocusForward
11351 */
11352 public void setNextFocusForwardId(@IdRes int nextFocusForwardId) {
11353 mNextFocusForwardId = nextFocusForwardId;
11354 }
11355
11356 /**
11357 * Gets the id of the root of the next keyboard navigation cluster.
11358 * @return The next keyboard navigation cluster ID, or {@link #NO_ID} if the framework should
11359 * decide automatically.
11360 *
11361 * @attr ref android.R.styleable#View_nextClusterForward
11362 */
11363 @IdRes
11364 @InspectableProperty(name = "nextClusterForward")
11365 public int getNextClusterForwardId() {
11366 return mNextClusterForwardId;
11367 }
11368
11369 /**
11370 * Sets the id of the view to use as the root of the next keyboard navigation cluster.
11371 * @param nextClusterForwardId The next cluster ID, or {@link #NO_ID} if the framework should
11372 * decide automatically.
11373 *
11374 * @attr ref android.R.styleable#View_nextClusterForward
11375 */
11376 public void setNextClusterForwardId(@IdRes int nextClusterForwardId) {
11377 mNextClusterForwardId = nextClusterForwardId;
11378 }
11379
11380 /**
11381 * Returns the visibility of this view and all of its ancestors
11382 *
11383 * @return True if this view and all of its ancestors are {@link #VISIBLE}
11384 */
11385 public boolean isShown() {
11386 View current = this;
11387 //noinspection ConstantConditions
11388 do {
11389 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
11390 return false;
11391 }
11392 ViewParent parent = current.mParent;
11393 if (parent == null) {
11394 return false; // We are not attached to the view root
11395 }
11396 if (!(parent instanceof View)) {
11397 return true;
11398 }
11399 current = (View) parent;
11400 } while (current != null);
11401
11402 return false;
11403 }
11404
11405 private boolean detached() {
11406 View current = this;
11407 //noinspection ConstantConditions
11408 do {
11409 if ((current.mPrivateFlags4 & PFLAG4_DETACHED) != 0) {
11410 return true;
11411 }
11412 ViewParent parent = current.mParent;
11413 if (parent == null) {
11414 return false;
11415 }
11416 if (!(parent instanceof View)) {
11417 return false;
11418 }
11419 current = (View) parent;
11420 } while (current != null);
11421
11422 return false;
11423 }
11424
11425 /**
11426 * Called by the view hierarchy when the content insets for a window have
11427 * changed, to allow it to adjust its content to fit within those windows.
11428 * The content insets tell you the space that the status bar, input method,
11429 * and other system windows infringe on the application's window.
11430 *
11431 * <p>You do not normally need to deal with this function, since the default
11432 * window decoration given to applications takes care of applying it to the
11433 * content of the window. If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
11434 * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
11435 * and your content can be placed under those system elements. You can then
11436 * use this method within your view hierarchy if you have parts of your UI
11437 * which you would like to ensure are not being covered.
11438 *
11439 * <p>The default implementation of this method simply applies the content
11440 * insets to the view's padding, consuming that content (modifying the
11441 * insets to be 0), and returning true. This behavior is off by default, but can
11442 * be enabled through {@link #setFitsSystemWindows(boolean)}.
11443 *
11444 * <p>This function's traversal down the hierarchy is depth-first. The same content
11445 * insets object is propagated down the hierarchy, so any changes made to it will
11446 * be seen by all following views (including potentially ones above in
11447 * the hierarchy since this is a depth-first traversal). The first view
11448 * that returns true will abort the entire traversal.
11449 *
11450 * <p>The default implementation works well for a situation where it is
11451 * used with a container that covers the entire window, allowing it to
11452 * apply the appropriate insets to its content on all edges. If you need
11453 * a more complicated layout (such as two different views fitting system
11454 * windows, one on the top of the window, and one on the bottom),
11455 * you can override the method and handle the insets however you would like.
11456 * Note that the insets provided by the framework are always relative to the
11457 * far edges of the window, not accounting for the location of the called view
11458 * within that window. (In fact when this method is called you do not yet know
11459 * where the layout will place the view, as it is done before layout happens.)
11460 *
11461 * <p>Note: unlike many View methods, there is no dispatch phase to this
11462 * call. If you are overriding it in a ViewGroup and want to allow the
11463 * call to continue to your children, you must be sure to call the super
11464 * implementation.
11465 *
11466 * <p>Here is a sample layout that makes use of fitting system windows
11467 * to have controls for a video view placed inside of the window decorations
11468 * that it hides and shows. This can be used with code like the second
11469 * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
11470 *
11471 * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
11472 *
11473 * @param insets Current content insets of the window. Prior to
11474 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
11475 * the insets or else you and Android will be unhappy.
11476 *
11477 * @return {@code true} if this view applied the insets and it should not
11478 * continue propagating further down the hierarchy, {@code false} otherwise.
11479 * @see #getFitsSystemWindows()
11480 * @see #setFitsSystemWindows(boolean)
11481 * @see #setSystemUiVisibility(int)
11482 *
11483 * @deprecated As of API 20 use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply
11484 * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use
11485 * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)}
11486 * to implement handling their own insets.
11487 */
11488 @Deprecated
11489 protected boolean fitSystemWindows(Rect insets) {
11490 if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) {
11491 if (insets == null) {
11492 // Null insets by definition have already been consumed.
11493 // This call cannot apply insets since there are none to apply,
11494 // so return false.
11495 return false;
11496 }
11497 // If we're not in the process of dispatching the newer apply insets call,
11498 // that means we're not in the compatibility path. Dispatch into the newer
11499 // apply insets path and take things from there.
11500 try {
11501 mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS;
11502 return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed();
11503 } finally {
11504 mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS;
11505 }
11506 } else {
11507 // We're being called from the newer apply insets path.
11508 // Perform the standard fallback behavior.
11509 return fitSystemWindowsInt(insets);
11510 }
11511 }
11512
11513 private boolean fitSystemWindowsInt(Rect insets) {
11514 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
11515 Rect localInsets = sThreadLocal.get();
11516 boolean res = computeFitSystemWindows(insets, localInsets);
11517 applyInsets(localInsets);
11518 return res;
11519 }
11520 return false;
11521 }
11522
11523 private void applyInsets(Rect insets) {
11524 mUserPaddingStart = UNDEFINED_PADDING;
11525 mUserPaddingEnd = UNDEFINED_PADDING;
11526 mUserPaddingLeftInitial = insets.left;
11527 mUserPaddingRightInitial = insets.right;
11528 internalSetPadding(insets.left, insets.top, insets.right, insets.bottom);
11529 }
11530
11531 /**
11532 * Called when the view should apply {@link WindowInsets} according to its internal policy.
11533 *
11534 * <p>This method should be overridden by views that wish to apply a policy different from or
11535 * in addition to the default behavior. Clients that wish to force a view subtree
11536 * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p>
11537 *
11538 * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set
11539 * it will be called during dispatch instead of this method. The listener may optionally
11540 * call this method from its own implementation if it wishes to apply the view's default
11541 * insets policy in addition to its own.</p>
11542 *
11543 * <p>Implementations of this method should either return the insets parameter unchanged
11544 * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed
11545 * that this view applied itself. This allows new inset types added in future platform
11546 * versions to pass through existing implementations unchanged without being erroneously
11547 * consumed.</p>
11548 *
11549 * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows}
11550 * property is set then the view will consume the system window insets and apply them
11551 * as padding for the view.</p>
11552 *
11553 * @param insets Insets to apply
11554 * @return The supplied insets with any applied insets consumed
11555 */
11556 public WindowInsets onApplyWindowInsets(WindowInsets insets) {
11557 if ((mPrivateFlags4 & PFLAG4_FRAMEWORK_OPTIONAL_FITS_SYSTEM_WINDOWS) != 0
11558 && (mViewFlags & FITS_SYSTEM_WINDOWS) != 0) {
11559 return onApplyFrameworkOptionalFitSystemWindows(insets);
11560 }
11561 if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) {
11562 // We weren't called from within a direct call to fitSystemWindows,
11563 // call into it as a fallback in case we're in a class that overrides it
11564 // and has logic to perform.
11565 if (fitSystemWindows(insets.getSystemWindowInsetsAsRect())) {
11566 return insets.consumeSystemWindowInsets();
11567 }
11568 } else {
11569 // We were called from within a direct call to fitSystemWindows.
11570 if (fitSystemWindowsInt(insets.getSystemWindowInsetsAsRect())) {
11571 return insets.consumeSystemWindowInsets();
11572 }
11573 }
11574 return insets;
11575 }
11576
11577 private WindowInsets onApplyFrameworkOptionalFitSystemWindows(WindowInsets insets) {
11578 Rect localInsets = sThreadLocal.get();
11579 WindowInsets result = computeSystemWindowInsets(insets, localInsets);
11580 applyInsets(localInsets);
11581 return result;
11582 }
11583
11584 /**
11585 * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying
11586 * window insets to this view. The listener's
11587 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
11588 * method will be called instead of the view's
11589 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
11590 *
11591 * @param listener Listener to set
11592 *
11593 * @see #onApplyWindowInsets(WindowInsets)
11594 */
11595 public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {
11596 getListenerInfo().mOnApplyWindowInsetsListener = listener;
11597 }
11598
11599 /**
11600 * Request to apply the given window insets to this view or another view in its subtree.
11601 *
11602 * <p>This method should be called by clients wishing to apply insets corresponding to areas
11603 * obscured by window decorations or overlays. This can include the status and navigation bars,
11604 * action bars, input methods and more. New inset categories may be added in the future.
11605 * The method returns the insets provided minus any that were applied by this view or its
11606 * children.</p>
11607 *
11608 * <p>Clients wishing to provide custom behavior should override the
11609 * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a
11610 * {@link OnApplyWindowInsetsListener} via the
11611 * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener}
11612 * method.</p>
11613 *
11614 * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method.
11615 * </p>
11616 *
11617 * @param insets Insets to apply
11618 * @return The provided insets minus the insets that were consumed
11619 */
11620 public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
11621 try {
11622 mPrivateFlags3 |= PFLAG3_APPLYING_INSETS;
11623 if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
11624 return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);
11625 } else {
11626 return onApplyWindowInsets(insets);
11627 }
11628 } finally {
11629 mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS;
11630 }
11631 }
11632
11633 /**
11634 * Sets a {@link WindowInsetsAnimation.Callback} to be notified about animations of windows that
11635 * cause insets.
11636 * <p>
11637 * The callback's {@link WindowInsetsAnimation.Callback#getDispatchMode()
11638 * dispatch mode} will affect whether animation callbacks are dispatched to the children of
11639 * this view.
11640 * </p>
11641 * @param callback The callback to set.
11642 */
11643 public void setWindowInsetsAnimationCallback(
11644 @Nullable WindowInsetsAnimation.Callback callback) {
11645 getListenerInfo().mWindowInsetsAnimationCallback = callback;
11646 }
11647
11648 /**
11649 * @return {@code true} if any {@link WindowInsetsAnimation.Callback} is registered on the view
11650 * or view tree of the sub-hierarchy {@code false} otherwise.
11651 * @hide
11652 */
11653 public boolean hasWindowInsetsAnimationCallback() {
11654 return getListenerInfo().mWindowInsetsAnimationCallback != null;
11655 }
11656
11657 /**
11658 * Dispatches {@link WindowInsetsAnimation.Callback#onPrepare(WindowInsetsAnimation)}
11659 * when Window Insets animation is being prepared.
11660 * @param animation current animation
11661 *
11662 * @see WindowInsetsAnimation.Callback#onPrepare(WindowInsetsAnimation)
11663 */
11664 public void dispatchWindowInsetsAnimationPrepare(
11665 @NonNull WindowInsetsAnimation animation) {
11666 if (mListenerInfo != null && mListenerInfo.mWindowInsetsAnimationCallback != null) {
11667 mListenerInfo.mWindowInsetsAnimationCallback.onPrepare(animation);
11668 }
11669 }
11670
11671 /**
11672 * Dispatches {@link WindowInsetsAnimation.Callback#onStart(WindowInsetsAnimation, Bounds)}
11673 * when Window Insets animation is started.
11674 * @param animation current animation
11675 * @param bounds the upper and lower {@link Bounds} that provides range of
11676 * {@link WindowInsetsAnimation}.
11677 * @return the upper and lower {@link Bounds}.
11678 */
11679 @NonNull
11680 public Bounds dispatchWindowInsetsAnimationStart(
11681 @NonNull WindowInsetsAnimation animation, @NonNull Bounds bounds) {
11682 if (mListenerInfo != null && mListenerInfo.mWindowInsetsAnimationCallback != null) {
11683 return mListenerInfo.mWindowInsetsAnimationCallback.onStart(animation, bounds);
11684 }
11685 return bounds;
11686 }
11687
11688 /**
11689 * Dispatches {@link WindowInsetsAnimation.Callback#onProgress(WindowInsets, List)}
11690 * when Window Insets animation makes progress.
11691 * @param insets The current {@link WindowInsets}.
11692 * @param runningAnimations The currently running {@link WindowInsetsAnimation}s.
11693 * @return current {@link WindowInsets}.
11694 */
11695 @NonNull
11696 public WindowInsets dispatchWindowInsetsAnimationProgress(@NonNull WindowInsets insets,
11697 @NonNull List<WindowInsetsAnimation> runningAnimations) {
11698 if (mListenerInfo != null && mListenerInfo.mWindowInsetsAnimationCallback != null) {
11699 return mListenerInfo.mWindowInsetsAnimationCallback.onProgress(insets,
11700 runningAnimations);
11701 } else {
11702 return insets;
11703 }
11704 }
11705
11706 /**
11707 * Dispatches {@link WindowInsetsAnimation.Callback#onEnd(WindowInsetsAnimation)}
11708 * when Window Insets animation ends.
11709 * @param animation The current ongoing {@link WindowInsetsAnimation}.
11710 */
11711 public void dispatchWindowInsetsAnimationEnd(@NonNull WindowInsetsAnimation animation) {
11712 if (mListenerInfo != null && mListenerInfo.mWindowInsetsAnimationCallback != null) {
11713 mListenerInfo.mWindowInsetsAnimationCallback.onEnd(animation);
11714 }
11715 }
11716
11717 /**
11718 * Sets a list of areas within this view's post-layout coordinate space where the system
11719 * should not intercept touch or other pointing device gestures. <em>This method should
11720 * be called by {@link #onLayout(boolean, int, int, int, int)} or {@link #onDraw(Canvas)}.</em>
11721 *
11722 * <p>Use this to tell the system which specific sub-areas of a view need to receive gesture
11723 * input in order to function correctly in the presence of global system gestures that may
11724 * conflict. For example, if the system wishes to capture swipe-in-from-screen-edge gestures
11725 * to provide system-level navigation functionality, a view such as a navigation drawer
11726 * container can mark the left (or starting) edge of itself as requiring gesture capture
11727 * priority using this API. The system may then choose to relax its own gesture recognition
11728 * to allow the app to consume the user's gesture. It is not necessary for an app to register
11729 * exclusion rects for broadly spanning regions such as the entirety of a
11730 * <code>ScrollView</code> or for simple press and release click targets such as
11731 * <code>Button</code>. Mark an exclusion rect when interacting with a view requires
11732 * a precision touch gesture in a small area in either the X or Y dimension, such as
11733 * an edge swipe or dragging a <code>SeekBar</code> thumb.</p>
11734 *
11735 * <p>Note: the system will put a limit of <code>200dp</code> on the vertical extent of the
11736 * exclusions it takes into account. The limit does not apply while the navigation
11737 * bar is {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY stickily} hidden, nor to the
11738 * {@link android.inputmethodservice.InputMethodService input method} and
11739 * {@link Intent#CATEGORY_HOME home activity}.
11740 * </p>
11741 *
11742 * @param rects A list of precision gesture regions that this view needs to function correctly
11743 */
11744 public void setSystemGestureExclusionRects(@NonNull List<Rect> rects) {
11745 if (rects.isEmpty() && mListenerInfo == null) return;
11746
11747 final ListenerInfo info = getListenerInfo();
11748 if (info.mSystemGestureExclusionRects != null) {
11749 info.mSystemGestureExclusionRects.clear();
11750 info.mSystemGestureExclusionRects.addAll(rects);
11751 } else {
11752 info.mSystemGestureExclusionRects = new ArrayList<>(rects);
11753 }
11754
11755 updatePositionUpdateListener();
11756 postUpdate(this::updateSystemGestureExclusionRects);
11757 }
11758
11759 private void updatePositionUpdateListener() {
11760 final ListenerInfo info = getListenerInfo();
11761 if (getSystemGestureExclusionRects().isEmpty()
11762 && collectPreferKeepClearRects().isEmpty()
11763 && collectUnrestrictedPreferKeepClearRects().isEmpty()
11764 && (info.mHandwritingArea == null || !isAutoHandwritingEnabled())) {
11765 if (info.mPositionUpdateListener != null) {
11766 mRenderNode.removePositionUpdateListener(info.mPositionUpdateListener);
11767 info.mPositionUpdateListener = null;
11768 info.mPositionChangedUpdate = null;
11769 }
11770 } else {
11771 if (info.mPositionUpdateListener == null) {
11772 info.mPositionChangedUpdate = () -> {
11773 updateSystemGestureExclusionRects();
11774 updateKeepClearRects();
11775 updateHandwritingArea();
11776 };
11777 info.mPositionUpdateListener = new RenderNode.PositionUpdateListener() {
11778 @Override
11779 public void positionChanged(long n, int l, int t, int r, int b) {
11780 postUpdate(info.mPositionChangedUpdate);
11781 }
11782
11783 @Override
11784 public void positionLost(long frameNumber) {
11785 postUpdate(info.mPositionChangedUpdate);
11786 }
11787 };
11788 mRenderNode.addPositionUpdateListener(info.mPositionUpdateListener);
11789 }
11790 }
11791 }
11792
11793 /**
11794 * WARNING: this can be called by a hwui worker thread, not just the UI thread!
11795 */
11796 private void postUpdate(Runnable r) {
11797 // Potentially racey from a background thread. It's ok if it's not perfect.
11798 final Handler h = getHandler();
11799 if (h != null) {
11800 h.postAtFrontOfQueue(r);
11801 }
11802 }
11803
11804 void updateSystemGestureExclusionRects() {
11805 final AttachInfo ai = mAttachInfo;
11806 if (ai != null) {
11807 ai.mViewRootImpl.updateSystemGestureExclusionRectsForView(this);
11808 }
11809 }
11810
11811 /**
11812 * Retrieve the list of areas within this view's post-layout coordinate space where the system
11813 * should not intercept touch or other pointing device gestures.
11814 *
11815 * <p>Do not modify the returned list.</p>
11816 *
11817 * @return the list set by {@link #setSystemGestureExclusionRects(List)}
11818 */
11819 @NonNull
11820 public List<Rect> getSystemGestureExclusionRects() {
11821 final ListenerInfo info = mListenerInfo;
11822 if (info != null) {
11823 final List<Rect> list = info.mSystemGestureExclusionRects;
11824 if (list != null) {
11825 return list;
11826 }
11827 }
11828 return Collections.emptyList();
11829 }
11830
11831 /**
11832 * Set a preference to keep the bounds of this view clear from floating windows above this
11833 * view's window. This informs the system that the view is considered a vital area for the
11834 * user and that ideally it should not be covered. Setting this is only appropriate for UI
11835 * where the user would likely take action to uncover it.
11836 * <p>
11837 * The system will try to respect this preference, but when not possible will ignore it.
11838 * <p>
11839 * Note: This is independent from {@link #setPreferKeepClearRects}. If both are set, both will
11840 * be taken into account.
11841 * <p>
11842 * @see #setPreferKeepClearRects
11843 * @see #isPreferKeepClear
11844 * @attr ref android.R.styleable#View_preferKeepClear
11845 */
11846 public final void setPreferKeepClear(boolean preferKeepClear) {
11847 getListenerInfo().mPreferKeepClear = preferKeepClear;
11848 updatePositionUpdateListener();
11849 postUpdate(this::updateKeepClearRects);
11850 }
11851
11852 /**
11853 * Retrieve the preference for this view to be kept clear. This is set either by
11854 * {@link #setPreferKeepClear} or via the attribute android.R.styleable#View_preferKeepClear.
11855 * <p>
11856 * If this is {@code true}, the system will ignore the Rects set by
11857 * {@link #setPreferKeepClearRects} and try to keep the whole view clear.
11858 * <p>
11859 * @see #setPreferKeepClear
11860 * @attr ref android.R.styleable#View_preferKeepClear
11861 */
11862 public final boolean isPreferKeepClear() {
11863 return mListenerInfo != null && mListenerInfo.mPreferKeepClear;
11864 }
11865
11866 /**
11867 * Set a preference to keep the provided rects clear from floating windows above this
11868 * view's window. This informs the system that these rects are considered vital areas for the
11869 * user and that ideally they should not be covered. Setting this is only appropriate for UI
11870 * where the user would likely take action to uncover it.
11871 * <p>
11872 * The system will try to respect this preference, but when not possible will ignore it.
11873 * <p>
11874 * Note: This is independent from {@link #setPreferKeepClear}. If both are set, both will be
11875 * taken into account.
11876 * <p>
11877 * @see #setPreferKeepClear
11878 * @see #getPreferKeepClearRects
11879 *
11880 * @param rects A list of rects in this view's local coordinate system
11881 */
11882 public final void setPreferKeepClearRects(@NonNull List<Rect> rects) {
11883 final ListenerInfo info = getListenerInfo();
11884 if (info.mKeepClearRects != null) {
11885 info.mKeepClearRects.clear();
11886 info.mKeepClearRects.addAll(rects);
11887 } else {
11888 info.mKeepClearRects = new ArrayList<>(rects);
11889 }
11890 updatePositionUpdateListener();
11891 postUpdate(this::updateKeepClearRects);
11892 }
11893
11894 /**
11895 * @return the list of rects, set by {@link #setPreferKeepClearRects}.
11896 *
11897 * @see #setPreferKeepClearRects
11898 */
11899 @NonNull
11900 public final List<Rect> getPreferKeepClearRects() {
11901 final ListenerInfo info = mListenerInfo;
11902 if (info != null && info.mKeepClearRects != null) {
11903 return new ArrayList(info.mKeepClearRects);
11904 }
11905
11906 return Collections.emptyList();
11907 }
11908
11909 /**
11910 * Set a preference to keep the provided rects clear from floating windows above this
11911 * view's window. This informs the system that these rects are considered vital areas for the
11912 * user and that ideally they should not be covered. Setting this is only appropriate for UI
11913 * where the user would likely take action to uncover it.
11914 * <p>
11915 * Note: The difference with {@link #setPreferKeepClearRects} is that the system won't apply
11916 * restrictions to the rects set here.
11917 * <p>
11918 * @see #setPreferKeepClear
11919 * @see #getPreferKeepClearRects
11920 *
11921 * @param rects A list of rects in this view's local coordinate system
11922 *
11923 * @hide
11924 */
11925 @SystemApi
11926 @RequiresPermission(android.Manifest.permission.SET_UNRESTRICTED_KEEP_CLEAR_AREAS)
11927 public final void setUnrestrictedPreferKeepClearRects(@NonNull List<Rect> rects) {
11928 final ListenerInfo info = getListenerInfo();
11929 if (info.mUnrestrictedKeepClearRects != null) {
11930 info.mUnrestrictedKeepClearRects.clear();
11931 info.mUnrestrictedKeepClearRects.addAll(rects);
11932 } else {
11933 info.mUnrestrictedKeepClearRects = new ArrayList<>(rects);
11934 }
11935 updatePositionUpdateListener();
11936 postUpdate(this::updateKeepClearRects);
11937 }
11938
11939 /**
11940 * @return the list of rects, set by {@link #setPreferKeepClearRects}.
11941 *
11942 * @see #setPreferKeepClearRects
11943 *
11944 * @hide
11945 */
11946 @SystemApi
11947 @NonNull
11948 public final List<Rect> getUnrestrictedPreferKeepClearRects() {
11949 final ListenerInfo info = mListenerInfo;
11950 if (info != null && info.mUnrestrictedKeepClearRects != null) {
11951 return new ArrayList(info.mUnrestrictedKeepClearRects);
11952 }
11953
11954 return Collections.emptyList();
11955 }
11956
11957 void updateKeepClearRects() {
11958 final AttachInfo ai = mAttachInfo;
11959 if (ai != null) {
11960 ai.mViewRootImpl.updateKeepClearRectsForView(this);
11961 }
11962 }
11963
11964 /**
11965 * Retrieve the list of areas within this view's post-layout coordinate space which the
11966 * system will try to not cover with other floating elements, like the pip window.
11967 */
11968 @NonNull
11969 List<Rect> collectPreferKeepClearRects() {
11970 ListenerInfo info = mListenerInfo;
11971 boolean keepClearForFocus = isFocused()
11972 && ViewConfiguration.get(mContext).isPreferKeepClearForFocusEnabled();
11973 boolean keepBoundsClear = (info != null && info.mPreferKeepClear) || keepClearForFocus;
11974 boolean hasCustomKeepClearRects = info != null && info.mKeepClearRects != null;
11975
11976 if (!keepBoundsClear && !hasCustomKeepClearRects) {
11977 return Collections.emptyList();
11978 } else if (keepBoundsClear && !hasCustomKeepClearRects) {
11979 return Collections.singletonList(new Rect(0, 0, getWidth(), getHeight()));
11980 }
11981
11982 final List<Rect> list = new ArrayList<>();
11983 if (keepBoundsClear) {
11984 list.add(new Rect(0, 0, getWidth(), getHeight()));
11985 }
11986
11987 if (hasCustomKeepClearRects) {
11988 list.addAll(info.mKeepClearRects);
11989 }
11990
11991 return list;
11992 }
11993
11994 private void updatePreferKeepClearForFocus() {
11995 if (ViewConfiguration.get(mContext).isPreferKeepClearForFocusEnabled()) {
11996 updatePositionUpdateListener();
11997 post(this::updateKeepClearRects);
11998 }
11999 }
12000
12001 /**
12002 * Retrieve the list of unrestricted areas within this view's post-layout coordinate space
12003 * which the system will try to not cover with other floating elements, like the pip window.
12004 */
12005 @NonNull
12006 List<Rect> collectUnrestrictedPreferKeepClearRects() {
12007 final ListenerInfo info = mListenerInfo;
12008 if (info != null && info.mUnrestrictedKeepClearRects != null) {
12009 return info.mUnrestrictedKeepClearRects;
12010 }
12011
12012 return Collections.emptyList();
12013 }
12014
12015 /**
12016 * Set a list of handwriting areas in this view. If there is any stylus {@link MotionEvent}
12017 * occurs within those areas, it will trigger stylus handwriting mode. This can be disabled by
12018 * disabling the auto handwriting initiation by calling
12019 * {@link #setAutoHandwritingEnabled(boolean)} with false.
12020 *
12021 * @attr rects a list of handwriting area in the view's local coordiniates.
12022 *
12023 * @see android.view.inputmethod.InputMethodManager#startStylusHandwriting(View)
12024 * @see #setAutoHandwritingEnabled(boolean)
12025 *
12026 * @hide
12027 */
12028 public void setHandwritingArea(@Nullable Rect rect) {
12029 final ListenerInfo info = getListenerInfo();
12030 info.mHandwritingArea = rect;
12031 updatePositionUpdateListener();
12032 postUpdate(this::updateHandwritingArea);
12033 }
12034
12035 /**
12036 * Return the handwriting areas set on this view, in its local coordinates.
12037 * @see #setHandwritingArea(Rect)
12038 *
12039 * @hide
12040 */
12041 @Nullable
12042 public Rect getHandwritingArea() {
12043 final ListenerInfo info = mListenerInfo;
12044 if (info != null && info.mHandwritingArea != null) {
12045 return new Rect(info.mHandwritingArea);
12046 }
12047 return null;
12048 }
12049
12050 void updateHandwritingArea() {
12051 // If autoHandwritingArea is not enabled, do nothing.
12052 if (!isAutoHandwritingEnabled()) return;
12053 final AttachInfo ai = mAttachInfo;
12054 if (ai != null) {
12055 ai.mViewRootImpl.getHandwritingInitiator().updateHandwritingAreasForView(this);
12056 }
12057 }
12058
12059 /**
12060 * Gets the coordinates of this view in the coordinate space of the
12061 * {@link Surface} that contains the view.
12062 *
12063 * <p>In multiple-screen scenarios, if the surface spans multiple screens,
12064 * the coordinate space of the surface also spans multiple screens.
12065 *
12066 * <p>After the method returns, the argument array contains the x and y
12067 * coordinates of the view relative to the view's left and top edges,
12068 * respectively.
12069 *
12070 * @param location A two-element integer array in which the view coordinates
12071 * are stored. The x-coordinate is at index 0; the y-coordinate, at
12072 * index 1.
12073 */
12074 public void getLocationInSurface(@NonNull @Size(2) int[] location) {
12075 getLocationInWindow(location);
12076 if (mAttachInfo != null && mAttachInfo.mViewRootImpl != null) {
12077 location[0] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.left;
12078 location[1] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.top;
12079 }
12080 }
12081
12082 /**
12083 * Provide original WindowInsets that are dispatched to the view hierarchy. The insets are
12084 * only available if the view is attached.
12085 *
12086 * @return WindowInsets from the top of the view hierarchy or null if View is detached
12087 */
12088 public WindowInsets getRootWindowInsets() {
12089 if (mAttachInfo != null) {
12090 return mAttachInfo.mViewRootImpl.getWindowInsets(false /* forceConstruct */);
12091 }
12092 return null;
12093 }
12094
12095 /**
12096 * Retrieves the single {@link WindowInsetsController} of the window this view is attached to.
12097 *
12098 * @return The {@link WindowInsetsController} or {@code null} if the view is neither attached to
12099 * a window nor a view tree with a decor.
12100 * @see Window#getInsetsController()
12101 */
12102 public @Nullable WindowInsetsController getWindowInsetsController() {
12103 if (mAttachInfo != null) {
12104 return mAttachInfo.mViewRootImpl.getInsetsController();
12105 }
12106 ViewParent parent = getParent();
12107 if (parent instanceof View) {
12108 return ((View) parent).getWindowInsetsController();
12109 } else if (parent instanceof ViewRootImpl) {
12110 // Between WindowManager.addView() and the first traversal AttachInfo isn't set yet.
12111 return ((ViewRootImpl) parent).getInsetsController();
12112 }
12113 return null;
12114 }
12115
12116
12117 /**
12118 * Walk up the View hierarchy to find the nearest {@link OnBackInvokedDispatcher}.
12119 *
12120 * @return The {@link OnBackInvokedDispatcher} from this or the nearest
12121 * ancestor, or null if this view is both not attached and have no ancestor providing an
12122 * {@link OnBackInvokedDispatcher}.
12123 */
12124 @Nullable
12125 public final OnBackInvokedDispatcher findOnBackInvokedDispatcher() {
12126 ViewParent parent = getParent();
12127 if (parent != null) {
12128 return parent.findOnBackInvokedDispatcherForChild(this, this);
12129 }
12130 return null;
12131 }
12132
12133 /**
12134 * @hide Compute the insets that should be consumed by this view and the ones
12135 * that should propagate to those under it.
12136 *
12137 * Note: This is used by appcompat's ActionBarOverlayLayout through reflection.
12138 *
12139 * @param inoutInsets the insets given to this view
12140 * @param outLocalInsets the insets that should be applied to this view
12141 * @deprecated use {@link #computeSystemWindowInsets}
12142 * @return
12143 */
12144 @Deprecated
12145 @UnsupportedAppUsage
12146 protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
12147 WindowInsets innerInsets = computeSystemWindowInsets(new WindowInsets(inoutInsets),
12148 outLocalInsets);
12149 inoutInsets.set(innerInsets.getSystemWindowInsetsAsRect());
12150 return innerInsets.isSystemWindowInsetsConsumed();
12151 }
12152
12153 /**
12154 * Compute insets that should be consumed by this view and the ones that should propagate
12155 * to those under it.
12156 *
12157 * @param in Insets currently being processed by this View, likely received as a parameter
12158 * to {@link #onApplyWindowInsets(WindowInsets)}.
12159 * @param outLocalInsets A Rect that will receive the insets that should be consumed
12160 * by this view
12161 * @return Insets that should be passed along to views under this one
12162 */
12163 public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) {
12164 boolean isOptionalFitSystemWindows = (mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) != 0
12165 || (mPrivateFlags4 & PFLAG4_FRAMEWORK_OPTIONAL_FITS_SYSTEM_WINDOWS) != 0;
12166 if (isOptionalFitSystemWindows && mAttachInfo != null) {
12167 OnContentApplyWindowInsetsListener listener =
12168 mAttachInfo.mContentOnApplyWindowInsetsListener;
12169 if (listener == null) {
12170 // The application wants to take care of fitting system window for
12171 // the content.
12172 outLocalInsets.setEmpty();
12173 return in;
12174 }
12175 Pair<Insets, WindowInsets> result = listener.onContentApplyWindowInsets(this, in);
12176 outLocalInsets.set(result.first.toRect());
12177 return result.second;
12178 } else {
12179 outLocalInsets.set(in.getSystemWindowInsetsAsRect());
12180 return in.consumeSystemWindowInsets().inset(outLocalInsets);
12181 }
12182 }
12183
12184 /**
12185 * Sets whether or not this view should account for system screen decorations
12186 * such as the status bar and inset its content; that is, controlling whether
12187 * the default implementation of {@link #fitSystemWindows(Rect)} will be
12188 * executed. See that method for more details.
12189 *
12190 * <p>Note that if you are providing your own implementation of
12191 * {@link #fitSystemWindows(Rect)}, then there is no need to set this
12192 * flag to true -- your implementation will be overriding the default
12193 * implementation that checks this flag.
12194 *
12195 * @param fitSystemWindows If true, then the default implementation of
12196 * {@link #fitSystemWindows(Rect)} will be executed.
12197 *
12198 * @attr ref android.R.styleable#View_fitsSystemWindows
12199 * @see #getFitsSystemWindows()
12200 * @see #fitSystemWindows(Rect)
12201 * @see #setSystemUiVisibility(int)
12202 */
12203 public void setFitsSystemWindows(boolean fitSystemWindows) {
12204 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
12205 }
12206
12207 /**
12208 * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
12209 * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
12210 * will be executed.
12211 *
12212 * @return {@code true} if the default implementation of
12213 * {@link #fitSystemWindows(Rect)} will be executed.
12214 *
12215 * @attr ref android.R.styleable#View_fitsSystemWindows
12216 * @see #setFitsSystemWindows(boolean)
12217 * @see #fitSystemWindows(Rect)
12218 * @see #setSystemUiVisibility(int)
12219 */
12220 @ViewDebug.ExportedProperty
12221 @InspectableProperty
12222 public boolean getFitsSystemWindows() {
12223 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
12224 }
12225
12226 /** @hide */
12227 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
12228 public boolean fitsSystemWindows() {
12229 return getFitsSystemWindows();
12230 }
12231
12232 /**
12233 * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
12234 * @deprecated Use {@link #requestApplyInsets()} for newer platform versions.
12235 */
12236 @Deprecated
12237 public void requestFitSystemWindows() {
12238 if (mParent != null) {
12239 mParent.requestFitSystemWindows();
12240 }
12241 }
12242
12243 /**
12244 * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed.
12245 */
12246 public void requestApplyInsets() {
12247 requestFitSystemWindows();
12248 }
12249
12250 /**
12251 * @see #OPTIONAL_FITS_SYSTEM_WINDOWS
12252 * @hide
12253 */
12254 @UnsupportedAppUsage
12255 public void makeOptionalFitsSystemWindows() {
12256 setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
12257 }
12258
12259 /**
12260 * @see #PFLAG4_FRAMEWORK_OPTIONAL_FITS_SYSTEM_WINDOWS
12261 * @hide
12262 */
12263 public void makeFrameworkOptionalFitsSystemWindows() {
12264 mPrivateFlags4 |= PFLAG4_FRAMEWORK_OPTIONAL_FITS_SYSTEM_WINDOWS;
12265 }
12266
12267 /**
12268 * @hide
12269 */
12270 public boolean isFrameworkOptionalFitsSystemWindows() {
12271 return (mPrivateFlags4 & PFLAG4_FRAMEWORK_OPTIONAL_FITS_SYSTEM_WINDOWS) != 0;
12272 }
12273
12274 /**
12275 * Returns the visibility status for this view.
12276 *
12277 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
12278 * @attr ref android.R.styleable#View_visibility
12279 */
12280 @ViewDebug.ExportedProperty(mapping = {
12281 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"),
12282 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
12283 @ViewDebug.IntToString(from = GONE, to = "GONE")
12284 })
12285 @InspectableProperty(enumMapping = {
12286 @EnumEntry(value = VISIBLE, name = "visible"),
12287 @EnumEntry(value = INVISIBLE, name = "invisible"),
12288 @EnumEntry(value = GONE, name = "gone")
12289 })
12290 @Visibility
12291 public int getVisibility() {
12292 return mViewFlags & VISIBILITY_MASK;
12293 }
12294
12295 /**
12296 * Set the visibility state of this view.
12297 *
12298 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
12299 * @attr ref android.R.styleable#View_visibility
12300 */
12301 @RemotableViewMethod
12302 public void setVisibility(@Visibility int visibility) {
12303 setFlags(visibility, VISIBILITY_MASK);
12304 }
12305
12306 /**
12307 * Returns the enabled status for this view. The interpretation of the
12308 * enabled state varies by subclass.
12309 *
12310 * @return True if this view is enabled, false otherwise.
12311 */
12312 @ViewDebug.ExportedProperty
12313 @InspectableProperty
12314 public boolean isEnabled() {
12315 return (mViewFlags & ENABLED_MASK) == ENABLED;
12316 }
12317
12318 /**
12319 * Set the enabled state of this view. The interpretation of the enabled
12320 * state varies by subclass.
12321 *
12322 * @param enabled True if this view is enabled, false otherwise.
12323 */
12324 @RemotableViewMethod
12325 public void setEnabled(boolean enabled) {
12326 if (enabled == isEnabled()) return;
12327
12328 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
12329
12330 /*
12331 * The View most likely has to change its appearance, so refresh
12332 * the drawable state.
12333 */
12334 refreshDrawableState();
12335
12336 // Invalidate too, since the default behavior for views is to be
12337 // be drawn at 50% alpha rather than to change the drawable.
12338 invalidate(true);
12339
12340 if (!enabled) {
12341 cancelPendingInputEvents();
12342 }
12343 }
12344
12345 /**
12346 * Set whether this view can receive the focus.
12347 * <p>
12348 * Setting this to false will also ensure that this view is not focusable
12349 * in touch mode.
12350 *
12351 * @param focusable If true, this view can receive the focus.
12352 *
12353 * @see #setFocusableInTouchMode(boolean)
12354 * @see #setFocusable(int)
12355 * @attr ref android.R.styleable#View_focusable
12356 */
12357 @RemotableViewMethod
12358 public void setFocusable(boolean focusable) {
12359 setFocusable(focusable ? FOCUSABLE : NOT_FOCUSABLE);
12360 }
12361
12362 /**
12363 * Sets whether this view can receive focus.
12364 * <p>
12365 * Setting this to {@link #FOCUSABLE_AUTO} tells the framework to determine focusability
12366 * automatically based on the view's interactivity. This is the default.
12367 * <p>
12368 * Setting this to NOT_FOCUSABLE will ensure that this view is also not focusable
12369 * in touch mode.
12370 *
12371 * @param focusable One of {@link #NOT_FOCUSABLE}, {@link #FOCUSABLE},
12372 * or {@link #FOCUSABLE_AUTO}.
12373 * @see #setFocusableInTouchMode(boolean)
12374 * @attr ref android.R.styleable#View_focusable
12375 */
12376 @RemotableViewMethod
12377 public void setFocusable(@Focusable int focusable) {
12378 if ((focusable & (FOCUSABLE_AUTO | FOCUSABLE)) == 0) {
12379 setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
12380 }
12381 setFlags(focusable, FOCUSABLE_MASK);
12382 }
12383
12384 /**
12385 * Set whether this view can receive focus while in touch mode.
12386 *
12387 * Setting this to true will also ensure that this view is focusable.
12388 *
12389 * @param focusableInTouchMode If true, this view can receive the focus while
12390 * in touch mode.
12391 *
12392 * @see #setFocusable(boolean)
12393 * @attr ref android.R.styleable#View_focusableInTouchMode
12394 */
12395 @RemotableViewMethod
12396 public void setFocusableInTouchMode(boolean focusableInTouchMode) {
12397 // Focusable in touch mode should always be set before the focusable flag
12398 // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
12399 // which, in touch mode, will not successfully request focus on this view
12400 // because the focusable in touch mode flag is not set
12401 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
12402
12403 // Clear FOCUSABLE_AUTO if set.
12404 if (focusableInTouchMode) {
12405 // Clears FOCUSABLE_AUTO if set.
12406 setFlags(FOCUSABLE, FOCUSABLE_MASK);
12407 }
12408 }
12409
12410 /**
12411 * Sets the hints that help an {@link android.service.autofill.AutofillService} determine how
12412 * to autofill the view with the user's data.
12413 *
12414 * <p>Typically, there is only one way to autofill a view, but there could be more than one.
12415 * For example, if the application accepts either an username or email address to identify
12416 * an user.
12417 *
12418 * <p>These hints are not validated by the Android System, but passed "as is" to the service.
12419 * Hence, they can have any value, but it's recommended to use the {@code AUTOFILL_HINT_}
12420 * constants such as:
12421 * {@link #AUTOFILL_HINT_USERNAME}, {@link #AUTOFILL_HINT_PASSWORD},
12422 * {@link #AUTOFILL_HINT_EMAIL_ADDRESS},
12423 * {@link #AUTOFILL_HINT_NAME},
12424 * {@link #AUTOFILL_HINT_PHONE},
12425 * {@link #AUTOFILL_HINT_POSTAL_ADDRESS}, {@link #AUTOFILL_HINT_POSTAL_CODE},
12426 * {@link #AUTOFILL_HINT_CREDIT_CARD_NUMBER}, {@link #AUTOFILL_HINT_CREDIT_CARD_SECURITY_CODE},
12427 * {@link #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DATE},
12428 * {@link #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DAY},
12429 * {@link #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_MONTH} or
12430 * {@link #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_YEAR}.
12431 *
12432 * @param autofillHints The autofill hints to set. If the array is emtpy, {@code null} is set.
12433 * @attr ref android.R.styleable#View_autofillHints
12434 */
12435 public void setAutofillHints(@Nullable String... autofillHints) {
12436 if (autofillHints == null || autofillHints.length == 0) {
12437 mAutofillHints = null;
12438 } else {
12439 mAutofillHints = autofillHints;
12440 }
12441 }
12442
12443 /**
12444 * @hide
12445 */
12446 @TestApi
12447 public void setAutofilled(boolean isAutofilled, boolean hideHighlight) {
12448 boolean wasChanged = isAutofilled != isAutofilled();
12449
12450 if (wasChanged) {
12451 if (isAutofilled) {
12452 mPrivateFlags3 |= PFLAG3_IS_AUTOFILLED;
12453 } else {
12454 mPrivateFlags3 &= ~PFLAG3_IS_AUTOFILLED;
12455 }
12456
12457 if (hideHighlight) {
12458 mPrivateFlags4 |= PFLAG4_AUTOFILL_HIDE_HIGHLIGHT;
12459 } else {
12460 mPrivateFlags4 &= ~PFLAG4_AUTOFILL_HIDE_HIGHLIGHT;
12461 }
12462
12463 invalidate();
12464 }
12465 }
12466
12467 /**
12468 * Set whether this view should have sound effects enabled for events such as
12469 * clicking and touching.
12470 *
12471 * <p>You may wish to disable sound effects for a view if you already play sounds,
12472 * for instance, a dial key that plays dtmf tones.
12473 *
12474 * @param soundEffectsEnabled whether sound effects are enabled for this view.
12475 * @see #isSoundEffectsEnabled()
12476 * @see #playSoundEffect(int)
12477 * @attr ref android.R.styleable#View_soundEffectsEnabled
12478 */
12479 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
12480 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
12481 }
12482
12483 /**
12484 * @return whether this view should have sound effects enabled for events such as
12485 * clicking and touching.
12486 *
12487 * @see #setSoundEffectsEnabled(boolean)
12488 * @see #playSoundEffect(int)
12489 * @attr ref android.R.styleable#View_soundEffectsEnabled
12490 */
12491 @ViewDebug.ExportedProperty
12492 @InspectableProperty
12493 public boolean isSoundEffectsEnabled() {
12494 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
12495 }
12496
12497 /**
12498 * Set whether this view should have haptic feedback for events such as
12499 * long presses.
12500 *
12501 * <p>You may wish to disable haptic feedback if your view already controls
12502 * its own haptic feedback.
12503 *
12504 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
12505 * @see #isHapticFeedbackEnabled()
12506 * @see #performHapticFeedback(int)
12507 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
12508 */
12509 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
12510 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
12511 }
12512
12513 /**
12514 * @return whether this view should have haptic feedback enabled for events
12515 * such as long presses.
12516 *
12517 * @see #setHapticFeedbackEnabled(boolean)
12518 * @see #performHapticFeedback(int)
12519 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
12520 */
12521 @ViewDebug.ExportedProperty
12522 @InspectableProperty
12523 public boolean isHapticFeedbackEnabled() {
12524 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
12525 }
12526
12527 /**
12528 * Returns the layout direction for this view.
12529 *
12530 * @return One of {@link #LAYOUT_DIRECTION_LTR},
12531 * {@link #LAYOUT_DIRECTION_RTL},
12532 * {@link #LAYOUT_DIRECTION_INHERIT} or
12533 * {@link #LAYOUT_DIRECTION_LOCALE}.
12534 *
12535 * @attr ref android.R.styleable#View_layoutDirection
12536 *
12537 * @hide
12538 */
12539 @ViewDebug.ExportedProperty(category = "layout", mapping = {
12540 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"),
12541 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"),
12542 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
12543 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE")
12544 })
12545 @InspectableProperty(hasAttributeId = false, enumMapping = {
12546 @EnumEntry(value = LAYOUT_DIRECTION_LTR, name = "ltr"),
12547 @EnumEntry(value = LAYOUT_DIRECTION_RTL, name = "rtl"),
12548 @EnumEntry(value = LAYOUT_DIRECTION_INHERIT, name = "inherit"),
12549 @EnumEntry(value = LAYOUT_DIRECTION_LOCALE, name = "locale")
12550 })
12551 @LayoutDir
12552 public int getRawLayoutDirection() {
12553 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
12554 }
12555
12556 /**
12557 * Set the layout direction for this view. This will propagate a reset of layout direction
12558 * resolution to the view's children and resolve layout direction for this view.
12559 *
12560 * @param layoutDirection the layout direction to set. Should be one of:
12561 *
12562 * {@link #LAYOUT_DIRECTION_LTR},
12563 * {@link #LAYOUT_DIRECTION_RTL},
12564 * {@link #LAYOUT_DIRECTION_INHERIT},
12565 * {@link #LAYOUT_DIRECTION_LOCALE}.
12566 *
12567 * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
12568 * proceeds up the parent chain of the view to get the value. If there is no parent, then it
12569 * will return the default {@link #LAYOUT_DIRECTION_LTR}.
12570 *
12571 * @attr ref android.R.styleable#View_layoutDirection
12572 */
12573 @RemotableViewMethod
12574 public void setLayoutDirection(@LayoutDir int layoutDirection) {
12575 if (getRawLayoutDirection() != layoutDirection) {
12576 // Reset the current layout direction and the resolved one
12577 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
12578 resetRtlProperties();
12579 // Set the new layout direction (filtered)
12580 mPrivateFlags2 |=
12581 ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
12582 // We need to resolve all RTL properties as they all depend on layout direction
12583 resolveRtlPropertiesIfNeeded();
12584 requestLayout();
12585 invalidate(true);
12586 }
12587 }
12588
12589 /**
12590 * Returns the resolved layout direction for this view.
12591 *
12592 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
12593 * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
12594 *
12595 * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
12596 * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
12597 *
12598 * @attr ref android.R.styleable#View_layoutDirection
12599 */
12600 @ViewDebug.ExportedProperty(category = "layout", mapping = {
12601 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
12602 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
12603 })
12604 @InspectableProperty(enumMapping = {
12605 @EnumEntry(value = LAYOUT_DIRECTION_LTR, name = "ltr"),
12606 @EnumEntry(value = LAYOUT_DIRECTION_RTL, name = "rtl")
12607 })
12608 @ResolvedLayoutDir
12609 public int getLayoutDirection() {
12610 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
12611 if (targetSdkVersion < Build.VERSION_CODES.JELLY_BEAN_MR1) {
12612 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
12613 return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
12614 }
12615 return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
12616 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
12617 }
12618
12619 /**
12620 * Indicates whether or not this view's layout is right-to-left. This is resolved from
12621 * layout attribute and/or the inherited value from the parent
12622 *
12623 * @return true if the layout is right-to-left.
12624 *
12625 * @hide
12626 */
12627 @ViewDebug.ExportedProperty(category = "layout")
12628 @UnsupportedAppUsage
12629 public boolean isLayoutRtl() {
12630 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
12631 }
12632
12633 /**
12634 * Indicates whether the view is currently tracking transient state that the
12635 * app should not need to concern itself with saving and restoring, but that
12636 * the framework should take special note to preserve when possible.
12637 *
12638 * <p>A view with transient state cannot be trivially rebound from an external
12639 * data source, such as an adapter binding item views in a list. This may be
12640 * because the view is performing an animation, tracking user selection
12641 * of content, or similar.</p>
12642 *
12643 * @return true if the view has transient state
12644 */
12645 @ViewDebug.ExportedProperty(category = "layout")
12646 public boolean hasTransientState() {
12647 return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
12648 }
12649
12650 /**
12651 * Set whether this view is currently tracking transient state that the
12652 * framework should attempt to preserve when possible. This flag is reference counted,
12653 * so every call to setHasTransientState(true) should be paired with a later call
12654 * to setHasTransientState(false).
12655 *
12656 * <p>A view with transient state cannot be trivially rebound from an external
12657 * data source, such as an adapter binding item views in a list. This may be
12658 * because the view is performing an animation, tracking user selection
12659 * of content, or similar.</p>
12660 *
12661 * @param hasTransientState true if this view has transient state
12662 */
12663 public void setHasTransientState(boolean hasTransientState) {
12664 final boolean oldHasTransientState = hasTransientState();
12665 mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
12666 mTransientStateCount - 1;
12667 if (mTransientStateCount < 0) {
12668 mTransientStateCount = 0;
12669 Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
12670 "unmatched pair of setHasTransientState calls");
12671 } else if ((hasTransientState && mTransientStateCount == 1) ||
12672 (!hasTransientState && mTransientStateCount == 0)) {
12673 // update flag if we've just incremented up from 0 or decremented down to 0
12674 mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
12675 (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
12676 final boolean newHasTransientState = hasTransientState();
12677 if (mParent != null && newHasTransientState != oldHasTransientState) {
12678 try {
12679 mParent.childHasTransientStateChanged(this, newHasTransientState);
12680 } catch (AbstractMethodError e) {
12681 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
12682 " does not fully implement ViewParent", e);
12683 }
12684 }
12685 }
12686 }
12687
12688 /**
12689 * Set the view is tracking translation transient state. This flag is used to check if the view
12690 * need to call setHasTransientState(false) to reset transient state that set when starting
12691 * translation.
12692 *
12693 * @param hasTranslationTransientState true if this view has translation transient state
12694 * @hide
12695 */
12696 public void setHasTranslationTransientState(boolean hasTranslationTransientState) {
12697 if (hasTranslationTransientState) {
12698 mPrivateFlags4 |= PFLAG4_HAS_TRANSLATION_TRANSIENT_STATE;
12699 } else {
12700 mPrivateFlags4 &= ~PFLAG4_HAS_TRANSLATION_TRANSIENT_STATE;
12701 }
12702 }
12703
12704 /**
12705 * @hide
12706 */
12707 public boolean hasTranslationTransientState() {
12708 return (mPrivateFlags4 & PFLAG4_HAS_TRANSLATION_TRANSIENT_STATE)
12709 == PFLAG4_HAS_TRANSLATION_TRANSIENT_STATE;
12710 }
12711
12712 /**
12713 * @hide
12714 */
12715 public void clearTranslationState() {
12716 if (mViewTranslationCallback != null) {
12717 mViewTranslationCallback.onClearTranslation(this);
12718 }
12719 clearViewTranslationResponse();
12720 if (hasTranslationTransientState()) {
12721 setHasTransientState(false);
12722 setHasTranslationTransientState(false);
12723 }
12724 }
12725
12726 /**
12727 * Returns true if this view is currently attached to a window.
12728 */
12729 public boolean isAttachedToWindow() {
12730 return mAttachInfo != null;
12731 }
12732
12733 /**
12734 * Returns true if this view has been through at least one layout since it
12735 * was last attached to or detached from a window.
12736 */
12737 public boolean isLaidOut() {
12738 return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
12739 }
12740
12741 /**
12742 * @return {@code true} if laid-out and not about to do another layout.
12743 */
12744 boolean isLayoutValid() {
12745 return isLaidOut() && ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == 0);
12746 }
12747
12748 /**
12749 * If this view doesn't do any drawing on its own, set this flag to
12750 * allow further optimizations. By default, this flag is not set on
12751 * View, but could be set on some View subclasses such as ViewGroup.
12752 *
12753 * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
12754 * you should clear this flag.
12755 *
12756 * @param willNotDraw whether or not this View draw on its own
12757 */
12758 public void setWillNotDraw(boolean willNotDraw) {
12759 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
12760 }
12761
12762 /**
12763 * Returns whether or not this View draws on its own.
12764 *
12765 * @return true if this view has nothing to draw, false otherwise
12766 */
12767 @ViewDebug.ExportedProperty(category = "drawing")
12768 public boolean willNotDraw() {
12769 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
12770 }
12771
12772 /**
12773 * When a View's drawing cache is enabled, drawing is redirected to an
12774 * offscreen bitmap. Some views, like an ImageView, must be able to
12775 * bypass this mechanism if they already draw a single bitmap, to avoid
12776 * unnecessary usage of the memory.
12777 *
12778 * @param willNotCacheDrawing true if this view does not cache its
12779 * drawing, false otherwise
12780 *
12781 * @deprecated The view drawing cache was largely made obsolete with the introduction of
12782 * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
12783 * layers are largely unnecessary and can easily result in a net loss in performance due to the
12784 * cost of creating and updating the layer. In the rare cases where caching layers are useful,
12785 * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
12786 * rendering. For software-rendered snapshots of a small part of the View hierarchy or
12787 * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
12788 * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
12789 * software-rendered usages are discouraged and have compatibility issues with hardware-only
12790 * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
12791 * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
12792 * reports or unit testing the {@link PixelCopy} API is recommended.
12793 */
12794 @Deprecated
12795 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
12796 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
12797 }
12798
12799 /**
12800 * Returns whether or not this View can cache its drawing or not.
12801 *
12802 * @return true if this view does not cache its drawing, false otherwise
12803 *
12804 * @deprecated The view drawing cache was largely made obsolete with the introduction of
12805 * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
12806 * layers are largely unnecessary and can easily result in a net loss in performance due to the
12807 * cost of creating and updating the layer. In the rare cases where caching layers are useful,
12808 * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
12809 * rendering. For software-rendered snapshots of a small part of the View hierarchy or
12810 * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
12811 * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
12812 * software-rendered usages are discouraged and have compatibility issues with hardware-only
12813 * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
12814 * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
12815 * reports or unit testing the {@link PixelCopy} API is recommended.
12816 */
12817 @ViewDebug.ExportedProperty(category = "drawing")
12818 @Deprecated
12819 public boolean willNotCacheDrawing() {
12820 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
12821 }
12822
12823 /**
12824 * Indicates whether this view reacts to click events or not.
12825 *
12826 * @return true if the view is clickable, false otherwise
12827 *
12828 * @see #setClickable(boolean)
12829 * @attr ref android.R.styleable#View_clickable
12830 */
12831 @ViewDebug.ExportedProperty
12832 @InspectableProperty
12833 public boolean isClickable() {
12834 return (mViewFlags & CLICKABLE) == CLICKABLE;
12835 }
12836
12837 /**
12838 * Enables or disables click events for this view. When a view
12839 * is clickable it will change its state to "pressed" on every click.
12840 * Subclasses should set the view clickable to visually react to
12841 * user's clicks.
12842 *
12843 * @param clickable true to make the view clickable, false otherwise
12844 *
12845 * @see #isClickable()
12846 * @attr ref android.R.styleable#View_clickable
12847 */
12848 public void setClickable(boolean clickable) {
12849 setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
12850 }
12851
12852 /**
12853 * Enables or disables click events for this view when disabled.
12854 *
12855 * @param clickableWhenDisabled true to make the view clickable, false otherwise
12856 *
12857 * @attr ref android.R.styleable#View_allowClickWhenDisabled
12858 */
12859 public void setAllowClickWhenDisabled(boolean clickableWhenDisabled) {
12860 if (clickableWhenDisabled) {
12861 mPrivateFlags4 |= PFLAG4_ALLOW_CLICK_WHEN_DISABLED;
12862 } else {
12863 mPrivateFlags4 &= ~PFLAG4_ALLOW_CLICK_WHEN_DISABLED;
12864 }
12865 }
12866
12867 /**
12868 * Indicates whether this view reacts to long click events or not.
12869 *
12870 * @return true if the view is long clickable, false otherwise
12871 *
12872 * @see #setLongClickable(boolean)
12873 * @attr ref android.R.styleable#View_longClickable
12874 */
12875 @InspectableProperty
12876 public boolean isLongClickable() {
12877 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
12878 }
12879
12880 /**
12881 * Enables or disables long click events for this view. When a view is long
12882 * clickable it reacts to the user holding down the button for a longer
12883 * duration than a tap. This event can either launch the listener or a
12884 * context menu.
12885 *
12886 * @param longClickable true to make the view long clickable, false otherwise
12887 * @see #isLongClickable()
12888 * @attr ref android.R.styleable#View_longClickable
12889 */
12890 public void setLongClickable(boolean longClickable) {
12891 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
12892 }
12893
12894 /**
12895 * Indicates whether this view reacts to context clicks or not.
12896 *
12897 * @return true if the view is context clickable, false otherwise
12898 * @see #setContextClickable(boolean)
12899 * @attr ref android.R.styleable#View_contextClickable
12900 */
12901 @InspectableProperty
12902 public boolean isContextClickable() {
12903 return (mViewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
12904 }
12905
12906 /**
12907 * Enables or disables context clicking for this view. This event can launch the listener.
12908 *
12909 * @param contextClickable true to make the view react to a context click, false otherwise
12910 * @see #isContextClickable()
12911 * @attr ref android.R.styleable#View_contextClickable
12912 */
12913 public void setContextClickable(boolean contextClickable) {
12914 setFlags(contextClickable ? CONTEXT_CLICKABLE : 0, CONTEXT_CLICKABLE);
12915 }
12916
12917 /**
12918 * Sets the pressed state for this view and provides a touch coordinate for
12919 * animation hinting.
12920 *
12921 * @param pressed Pass true to set the View's internal state to "pressed",
12922 * or false to reverts the View's internal state from a
12923 * previously set "pressed" state.
12924 * @param x The x coordinate of the touch that caused the press
12925 * @param y The y coordinate of the touch that caused the press
12926 */
12927 private void setPressed(boolean pressed, float x, float y) {
12928 if (pressed) {
12929 drawableHotspotChanged(x, y);
12930 }
12931
12932 setPressed(pressed);
12933 }
12934
12935 /**
12936 * Sets the pressed state for this view.
12937 *
12938 * @see #isClickable()
12939 * @see #setClickable(boolean)
12940 *
12941 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
12942 * the View's internal state from a previously set "pressed" state.
12943 */
12944 public void setPressed(boolean pressed) {
12945 final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
12946
12947 if (pressed) {
12948 mPrivateFlags |= PFLAG_PRESSED;
12949 } else {
12950 mPrivateFlags &= ~PFLAG_PRESSED;
12951 }
12952
12953 if (needsRefresh) {
12954 refreshDrawableState();
12955 }
12956 dispatchSetPressed(pressed);
12957 }
12958
12959 /**
12960 * Dispatch setPressed to all of this View's children.
12961 *
12962 * @see #setPressed(boolean)
12963 *
12964 * @param pressed The new pressed state
12965 */
12966 protected void dispatchSetPressed(boolean pressed) {
12967 }
12968
12969 /**
12970 * Indicates whether the view is currently in pressed state. Unless
12971 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
12972 * the pressed state.
12973 *
12974 * @see #setPressed(boolean)
12975 * @see #isClickable()
12976 * @see #setClickable(boolean)
12977 *
12978 * @return true if the view is currently pressed, false otherwise
12979 */
12980 @ViewDebug.ExportedProperty
12981 @InspectableProperty(hasAttributeId = false)
12982 public boolean isPressed() {
12983 return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
12984 }
12985
12986 /**
12987 * @hide
12988 * Indicates whether this view will participate in data collection through
12989 * {@link ViewStructure}. If true, it will not provide any data
12990 * for itself or its children. If false, the normal data collection will be allowed.
12991 *
12992 * @return Returns false if assist data collection is not blocked, else true.
12993 *
12994 * @see #setAssistBlocked(boolean)
12995 * @attr ref android.R.styleable#View_assistBlocked
12996 */
12997 public boolean isAssistBlocked() {
12998 return (mPrivateFlags3 & PFLAG3_ASSIST_BLOCKED) != 0;
12999 }
13000
13001 /**
13002 * @hide
13003 * Controls whether assist data collection from this view and its children is enabled
13004 * (that is, whether {@link #onProvideStructure} and
13005 * {@link #onProvideVirtualStructure} will be called). The default value is false,
13006 * allowing normal assist collection. Setting this to false will disable assist collection.
13007 *
13008 * @param enabled Set to true to <em>disable</em> assist data collection, or false
13009 * (the default) to allow it.
13010 *
13011 * @see #isAssistBlocked()
13012 * @see #onProvideStructure
13013 * @see #onProvideVirtualStructure
13014 * @attr ref android.R.styleable#View_assistBlocked
13015 */
13016 @UnsupportedAppUsage
13017 public void setAssistBlocked(boolean enabled) {
13018 if (enabled) {
13019 mPrivateFlags3 |= PFLAG3_ASSIST_BLOCKED;
13020 } else {
13021 mPrivateFlags3 &= ~PFLAG3_ASSIST_BLOCKED;
13022 }
13023 }
13024
13025 /**
13026 * Indicates whether this view will save its state (that is,
13027 * whether its {@link #onSaveInstanceState} method will be called).
13028 *
13029 * @return Returns true if the view state saving is enabled, else false.
13030 *
13031 * @see #setSaveEnabled(boolean)
13032 * @attr ref android.R.styleable#View_saveEnabled
13033 */
13034 @InspectableProperty
13035 public boolean isSaveEnabled() {
13036 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
13037 }
13038
13039 /**
13040 * Controls whether the saving of this view's state is
13041 * enabled (that is, whether its {@link #onSaveInstanceState} method
13042 * will be called). Note that even if freezing is enabled, the
13043 * view still must have an id assigned to it (via {@link #setId(int)})
13044 * for its state to be saved. This flag can only disable the
13045 * saving of this view; any child views may still have their state saved.
13046 *
13047 * @param enabled Set to false to <em>disable</em> state saving, or true
13048 * (the default) to allow it.
13049 *
13050 * @see #isSaveEnabled()
13051 * @see #setId(int)
13052 * @see #onSaveInstanceState()
13053 * @attr ref android.R.styleable#View_saveEnabled
13054 */
13055 public void setSaveEnabled(boolean enabled) {
13056 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
13057 }
13058
13059 /**
13060 * Gets whether the framework should discard touches when the view's
13061 * window is obscured by another visible window at the touched location.
13062 * Refer to the {@link View} security documentation for more details.
13063 *
13064 * @return True if touch filtering is enabled.
13065 *
13066 * @see #setFilterTouchesWhenObscured(boolean)
13067 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
13068 */
13069 @ViewDebug.ExportedProperty
13070 @InspectableProperty
13071 public boolean getFilterTouchesWhenObscured() {
13072 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
13073 }
13074
13075 /**
13076 * Sets whether the framework should discard touches when the view's
13077 * window is obscured by another visible window at the touched location.
13078 * Refer to the {@link View} security documentation for more details.
13079 *
13080 * @param enabled True if touch filtering should be enabled.
13081 *
13082 * @see #getFilterTouchesWhenObscured
13083 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
13084 */
13085 public void setFilterTouchesWhenObscured(boolean enabled) {
13086 setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0,
13087 FILTER_TOUCHES_WHEN_OBSCURED);
13088 }
13089
13090 /**
13091 * Indicates whether the entire hierarchy under this view will save its
13092 * state when a state saving traversal occurs from its parent. The default
13093 * is true; if false, these views will not be saved unless
13094 * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
13095 *
13096 * @return Returns true if the view state saving from parent is enabled, else false.
13097 *
13098 * @see #setSaveFromParentEnabled(boolean)
13099 */
13100 public boolean isSaveFromParentEnabled() {
13101 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
13102 }
13103
13104 /**
13105 * Controls whether the entire hierarchy under this view will save its
13106 * state when a state saving traversal occurs from its parent. The default
13107 * is true; if false, these views will not be saved unless
13108 * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
13109 *
13110 * @param enabled Set to false to <em>disable</em> state saving, or true
13111 * (the default) to allow it.
13112 *
13113 * @see #isSaveFromParentEnabled()
13114 * @see #setId(int)
13115 * @see #onSaveInstanceState()
13116 */
13117 public void setSaveFromParentEnabled(boolean enabled) {
13118 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
13119 }
13120
13121
13122 /**
13123 * Returns whether this View is currently able to take focus.
13124 *
13125 * @return True if this view can take focus, or false otherwise.
13126 */
13127 @ViewDebug.ExportedProperty(category = "focus")
13128 public final boolean isFocusable() {
13129 return FOCUSABLE == (mViewFlags & FOCUSABLE);
13130 }
13131
13132 /**
13133 * Returns the focusable setting for this view.
13134 *
13135 * @return One of {@link #NOT_FOCUSABLE}, {@link #FOCUSABLE}, or {@link #FOCUSABLE_AUTO}.
13136 * @attr ref android.R.styleable#View_focusable
13137 */
13138 @ViewDebug.ExportedProperty(mapping = {
13139 @ViewDebug.IntToString(from = NOT_FOCUSABLE, to = "NOT_FOCUSABLE"),
13140 @ViewDebug.IntToString(from = FOCUSABLE, to = "FOCUSABLE"),
13141 @ViewDebug.IntToString(from = FOCUSABLE_AUTO, to = "FOCUSABLE_AUTO")
13142 }, category = "focus")
13143 @InspectableProperty(enumMapping = {
13144 @EnumEntry(value = NOT_FOCUSABLE, name = "false"),
13145 @EnumEntry(value = FOCUSABLE, name = "true"),
13146 @EnumEntry(value = FOCUSABLE_AUTO, name = "auto")
13147 })
13148 @Focusable
13149 public int getFocusable() {
13150 return (mViewFlags & FOCUSABLE_AUTO) > 0 ? FOCUSABLE_AUTO : mViewFlags & FOCUSABLE;
13151 }
13152
13153 /**
13154 * When a view is focusable, it may not want to take focus when in touch mode.
13155 * For example, a button would like focus when the user is navigating via a D-pad
13156 * so that the user can click on it, but once the user starts touching the screen,
13157 * the button shouldn't take focus
13158 * @return Whether the view is focusable in touch mode.
13159 * @attr ref android.R.styleable#View_focusableInTouchMode
13160 */
13161 @ViewDebug.ExportedProperty(category = "focus")
13162 @InspectableProperty
13163 public final boolean isFocusableInTouchMode() {
13164 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
13165 }
13166
13167 /**
13168 * Returns whether the view should be treated as a focusable unit by screen reader
13169 * accessibility tools.
13170 * @see #setScreenReaderFocusable(boolean)
13171 *
13172 * @return Whether the view should be treated as a focusable unit by screen reader.
13173 *
13174 * @attr ref android.R.styleable#View_screenReaderFocusable
13175 */
13176 @InspectableProperty
13177 public boolean isScreenReaderFocusable() {
13178 return (mPrivateFlags3 & PFLAG3_SCREEN_READER_FOCUSABLE) != 0;
13179 }
13180
13181 /**
13182 * Sets whether this View should be a focusable element for screen readers
13183 * and include non-focusable Views from its subtree when providing feedback.
13184 * <p>
13185 * Note: this is similar to using <a href="#attr_android:focusable">{@code android:focusable},
13186 * but does not impact input focus behavior.
13187 *
13188 * @param screenReaderFocusable Whether the view should be treated as a unit by screen reader
13189 * accessibility tools.
13190 *
13191 * @attr ref android.R.styleable#View_screenReaderFocusable
13192 */
13193 public void setScreenReaderFocusable(boolean screenReaderFocusable) {
13194 updatePflags3AndNotifyA11yIfChanged(PFLAG3_SCREEN_READER_FOCUSABLE, screenReaderFocusable);
13195 }
13196
13197 /**
13198 * Gets whether this view is a heading for accessibility purposes.
13199 *
13200 * @return {@code true} if the view is a heading, {@code false} otherwise.
13201 *
13202 * @attr ref android.R.styleable#View_accessibilityHeading
13203 */
13204 @InspectableProperty
13205 public boolean isAccessibilityHeading() {
13206 return (mPrivateFlags3 & PFLAG3_ACCESSIBILITY_HEADING) != 0;
13207 }
13208
13209 /**
13210 * Set if view is a heading for a section of content for accessibility purposes.
13211 * <p>
13212 * Users of some accessibility services can choose to navigate between headings
13213 * instead of between paragraphs, words, etc. Apps that provide headings on
13214 * sections of text can help the text navigation experience.
13215 *
13216 * @param isHeading {@code true} if the view is a heading, {@code false} otherwise.
13217 *
13218 * @attr ref android.R.styleable#View_accessibilityHeading
13219 */
13220 public void setAccessibilityHeading(boolean isHeading) {
13221 updatePflags3AndNotifyA11yIfChanged(PFLAG3_ACCESSIBILITY_HEADING, isHeading);
13222 }
13223
13224 private void updatePflags3AndNotifyA11yIfChanged(int mask, boolean newValue) {
13225 int pflags3 = mPrivateFlags3;
13226 if (newValue) {
13227 pflags3 |= mask;
13228 } else {
13229 pflags3 &= ~mask;
13230 }
13231
13232 if (pflags3 != mPrivateFlags3) {
13233 mPrivateFlags3 = pflags3;
13234 notifyViewAccessibilityStateChangedIfNeeded(
13235 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
13236 }
13237 }
13238
13239 /**
13240 * Find the nearest view in the specified direction that can take focus.
13241 * This does not actually give focus to that view.
13242 *
13243 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
13244 *
13245 * @return The nearest focusable in the specified direction, or null if none
13246 * can be found.
13247 */
13248 public View focusSearch(@FocusRealDirection int direction) {
13249 if (mParent != null) {
13250 return mParent.focusSearch(this, direction);
13251 } else {
13252 return null;
13253 }
13254 }
13255
13256 /**
13257 * Returns whether this View is a root of a keyboard navigation cluster.
13258 *
13259 * @return True if this view is a root of a cluster, or false otherwise.
13260 * @attr ref android.R.styleable#View_keyboardNavigationCluster
13261 */
13262 @ViewDebug.ExportedProperty(category = "focus")
13263 @InspectableProperty
13264 public final boolean isKeyboardNavigationCluster() {
13265 return (mPrivateFlags3 & PFLAG3_CLUSTER) != 0;
13266 }
13267
13268 /**
13269 * Searches up the view hierarchy to find the top-most cluster. All deeper/nested clusters
13270 * will be ignored.
13271 *
13272 * @return the keyboard navigation cluster that this view is in (can be this view)
13273 * or {@code null} if not in one
13274 */
13275 View findKeyboardNavigationCluster() {
13276 if (mParent instanceof View) {
13277 View cluster = ((View) mParent).findKeyboardNavigationCluster();
13278 if (cluster != null) {
13279 return cluster;
13280 } else if (isKeyboardNavigationCluster()) {
13281 return this;
13282 }
13283 }
13284 return null;
13285 }
13286
13287 /**
13288 * Set whether this view is a root of a keyboard navigation cluster.
13289 *
13290 * @param isCluster If true, this view is a root of a cluster.
13291 *
13292 * @attr ref android.R.styleable#View_keyboardNavigationCluster
13293 */
13294 public void setKeyboardNavigationCluster(boolean isCluster) {
13295 if (isCluster) {
13296 mPrivateFlags3 |= PFLAG3_CLUSTER;
13297 } else {
13298 mPrivateFlags3 &= ~PFLAG3_CLUSTER;
13299 }
13300 }
13301
13302 /**
13303 * Sets this View as the one which receives focus the next time cluster navigation jumps
13304 * to the cluster containing this View. This does NOT change focus even if the cluster
13305 * containing this view is current.
13306 *
13307 * @hide
13308 */
13309 @TestApi
13310 public final void setFocusedInCluster() {
13311 setFocusedInCluster(findKeyboardNavigationCluster());
13312 }
13313
13314 private void setFocusedInCluster(View cluster) {
13315 if (this instanceof ViewGroup) {
13316 ((ViewGroup) this).mFocusedInCluster = null;
13317 }
13318 if (cluster == this) {
13319 return;
13320 }
13321 ViewParent parent = mParent;
13322 View child = this;
13323 while (parent instanceof ViewGroup) {
13324 ((ViewGroup) parent).mFocusedInCluster = child;
13325 if (parent == cluster) {
13326 break;
13327 }
13328 child = (View) parent;
13329 parent = parent.getParent();
13330 }
13331 }
13332
13333 private void updateFocusedInCluster(View oldFocus, @FocusDirection int direction) {
13334 if (oldFocus != null) {
13335 View oldCluster = oldFocus.findKeyboardNavigationCluster();
13336 View cluster = findKeyboardNavigationCluster();
13337 if (oldCluster != cluster) {
13338 // Going from one cluster to another, so save last-focused.
13339 // This covers cluster jumps because they are always FOCUS_DOWN
13340 oldFocus.setFocusedInCluster(oldCluster);
13341 if (!(oldFocus.mParent instanceof ViewGroup)) {
13342 return;
13343 }
13344 if (direction == FOCUS_FORWARD || direction == FOCUS_BACKWARD) {
13345 // This is a result of ordered navigation so consider navigation through
13346 // the previous cluster "complete" and clear its last-focused memory.
13347 ((ViewGroup) oldFocus.mParent).clearFocusedInCluster(oldFocus);
13348 } else if (oldFocus instanceof ViewGroup
13349 && ((ViewGroup) oldFocus).getDescendantFocusability()
13350 == ViewGroup.FOCUS_AFTER_DESCENDANTS
13351 && ViewRootImpl.isViewDescendantOf(this, oldFocus)) {
13352 // This means oldFocus is not focusable since it obviously has a focusable
13353 // child (this). Don't restore focus to it in the future.
13354 ((ViewGroup) oldFocus.mParent).clearFocusedInCluster(oldFocus);
13355 }
13356 }
13357 }
13358 }
13359
13360 /**
13361 * Returns whether this View should receive focus when the focus is restored for the view
13362 * hierarchy containing this view.
13363 * <p>
13364 * Focus gets restored for a view hierarchy when the root of the hierarchy gets added to a
13365 * window or serves as a target of cluster navigation.
13366 *
13367 * @see #restoreDefaultFocus()
13368 *
13369 * @return {@code true} if this view is the default-focus view, {@code false} otherwise
13370 * @attr ref android.R.styleable#View_focusedByDefault
13371 */
13372 @ViewDebug.ExportedProperty(category = "focus")
13373 @InspectableProperty
13374 public final boolean isFocusedByDefault() {
13375 return (mPrivateFlags3 & PFLAG3_FOCUSED_BY_DEFAULT) != 0;
13376 }
13377
13378 /**
13379 * Sets whether this View should receive focus when the focus is restored for the view
13380 * hierarchy containing this view.
13381 * <p>
13382 * Focus gets restored for a view hierarchy when the root of the hierarchy gets added to a
13383 * window or serves as a target of cluster navigation.
13384 *
13385 * @param isFocusedByDefault {@code true} to set this view as the default-focus view,
13386 * {@code false} otherwise.
13387 *
13388 * @see #restoreDefaultFocus()
13389 *
13390 * @attr ref android.R.styleable#View_focusedByDefault
13391 */
13392 @RemotableViewMethod
13393 public void setFocusedByDefault(boolean isFocusedByDefault) {
13394 if (isFocusedByDefault == ((mPrivateFlags3 & PFLAG3_FOCUSED_BY_DEFAULT) != 0)) {
13395 return;
13396 }
13397
13398 if (isFocusedByDefault) {
13399 mPrivateFlags3 |= PFLAG3_FOCUSED_BY_DEFAULT;
13400 } else {
13401 mPrivateFlags3 &= ~PFLAG3_FOCUSED_BY_DEFAULT;
13402 }
13403
13404 if (mParent instanceof ViewGroup) {
13405 if (isFocusedByDefault) {
13406 ((ViewGroup) mParent).setDefaultFocus(this);
13407 } else {
13408 ((ViewGroup) mParent).clearDefaultFocus(this);
13409 }
13410 }
13411 }
13412
13413 /**
13414 * Returns whether the view hierarchy with this view as a root contain a default-focus view.
13415 *
13416 * @return {@code true} if this view has default focus, {@code false} otherwise
13417 */
13418 boolean hasDefaultFocus() {
13419 return isFocusedByDefault();
13420 }
13421
13422 /**
13423 * Find the nearest keyboard navigation cluster in the specified direction.
13424 * This does not actually give focus to that cluster.
13425 *
13426 * @param currentCluster The starting point of the search. Null means the current cluster is not
13427 * found yet
13428 * @param direction Direction to look
13429 *
13430 * @return The nearest keyboard navigation cluster in the specified direction, or null if none
13431 * can be found
13432 */
13433 public View keyboardNavigationClusterSearch(View currentCluster,
13434 @FocusDirection int direction) {
13435 if (isKeyboardNavigationCluster()) {
13436 currentCluster = this;
13437 }
13438 if (isRootNamespace()) {
13439 // Root namespace means we should consider ourselves the top of the
13440 // tree for group searching; otherwise we could be group searching
13441 // into other tabs. see LocalActivityManager and TabHost for more info.
13442 return FocusFinder.getInstance().findNextKeyboardNavigationCluster(
13443 this, currentCluster, direction);
13444 } else if (mParent != null) {
13445 return mParent.keyboardNavigationClusterSearch(currentCluster, direction);
13446 }
13447 return null;
13448 }
13449
13450 /**
13451 * This method is the last chance for the focused view and its ancestors to
13452 * respond to an arrow key. This is called when the focused view did not
13453 * consume the key internally, nor could the view system find a new view in
13454 * the requested direction to give focus to.
13455 *
13456 * @param focused The currently focused view.
13457 * @param direction The direction focus wants to move. One of FOCUS_UP,
13458 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
13459 * @return True if the this view consumed this unhandled move.
13460 */
13461 public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) {
13462 return false;
13463 }
13464
13465 /**
13466 * Sets whether this View should use a default focus highlight when it gets focused but doesn't
13467 * have {@link android.R.attr#state_focused} defined in its background.
13468 *
13469 * @param defaultFocusHighlightEnabled {@code true} to set this view to use a default focus
13470 * highlight, {@code false} otherwise.
13471 *
13472 * @attr ref android.R.styleable#View_defaultFocusHighlightEnabled
13473 */
13474 public void setDefaultFocusHighlightEnabled(boolean defaultFocusHighlightEnabled) {
13475 mDefaultFocusHighlightEnabled = defaultFocusHighlightEnabled;
13476 }
13477
13478 /**
13479 * Returns whether this View should use a default focus highlight when it gets focused but
13480 * doesn't have {@link android.R.attr#state_focused} defined in its background.
13481 *
13482 * @return True if this View should use a default focus highlight.
13483 * @attr ref android.R.styleable#View_defaultFocusHighlightEnabled
13484 */
13485 @ViewDebug.ExportedProperty(category = "focus")
13486 @InspectableProperty
13487 public final boolean getDefaultFocusHighlightEnabled() {
13488 return mDefaultFocusHighlightEnabled;
13489 }
13490
13491 /**
13492 * If a user manually specified the next view id for a particular direction,
13493 * use the root to look up the view.
13494 * @param root The root view of the hierarchy containing this view.
13495 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
13496 * or FOCUS_BACKWARD.
13497 * @return The user specified next view, or null if there is none.
13498 */
13499 View findUserSetNextFocus(View root, @FocusDirection int direction) {
13500 switch (direction) {
13501 case FOCUS_LEFT:
13502 if (mNextFocusLeftId == View.NO_ID) return null;
13503 return findViewInsideOutShouldExist(root, mNextFocusLeftId);
13504 case FOCUS_RIGHT:
13505 if (mNextFocusRightId == View.NO_ID) return null;
13506 return findViewInsideOutShouldExist(root, mNextFocusRightId);
13507 case FOCUS_UP:
13508 if (mNextFocusUpId == View.NO_ID) return null;
13509 return findViewInsideOutShouldExist(root, mNextFocusUpId);
13510 case FOCUS_DOWN:
13511 if (mNextFocusDownId == View.NO_ID) return null;
13512 return findViewInsideOutShouldExist(root, mNextFocusDownId);
13513 case FOCUS_FORWARD:
13514 if (mNextFocusForwardId == View.NO_ID) return null;
13515 return findViewInsideOutShouldExist(root, mNextFocusForwardId);
13516 case FOCUS_BACKWARD: {
13517 if (mID == View.NO_ID) return null;
13518 final View rootView = root;
13519 final View startView = this;
13520 // Since we have forward links but no backward links, we need to find the view that
13521 // forward links to this view. We can't just find the view with the specified ID
13522 // because view IDs need not be unique throughout the tree.
13523 return root.findViewByPredicateInsideOut(startView,
13524 t -> findViewInsideOutShouldExist(rootView, t, t.mNextFocusForwardId)
13525 == startView);
13526 }
13527 }
13528 return null;
13529 }
13530
13531 /**
13532 * If a user manually specified the next keyboard-navigation cluster for a particular direction,
13533 * use the root to look up the view.
13534 *
13535 * @param root the root view of the hierarchy containing this view
13536 * @param direction {@link #FOCUS_FORWARD} or {@link #FOCUS_BACKWARD}
13537 * @return the user-specified next cluster, or {@code null} if there is none
13538 */
13539 View findUserSetNextKeyboardNavigationCluster(View root, @FocusDirection int direction) {
13540 switch (direction) {
13541 case FOCUS_FORWARD:
13542 if (mNextClusterForwardId == View.NO_ID) return null;
13543 return findViewInsideOutShouldExist(root, mNextClusterForwardId);
13544 case FOCUS_BACKWARD: {
13545 if (mID == View.NO_ID) return null;
13546 final int id = mID;
13547 return root.findViewByPredicateInsideOut(this,
13548 (Predicate<View>) t -> t.mNextClusterForwardId == id);
13549 }
13550 }
13551 return null;
13552 }
13553
13554 private View findViewInsideOutShouldExist(View root, int id) {
13555 return findViewInsideOutShouldExist(root, this, id);
13556 }
13557
13558 private View findViewInsideOutShouldExist(View root, View start, int id) {
13559 if (mMatchIdPredicate == null) {
13560 mMatchIdPredicate = new MatchIdPredicate();
13561 }
13562 mMatchIdPredicate.mId = id;
13563 View result = root.findViewByPredicateInsideOut(start, mMatchIdPredicate);
13564 if (result == null) {
13565 Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
13566 }
13567 return result;
13568 }
13569
13570 /**
13571 * Find and return all focusable views that are descendants of this view,
13572 * possibly including this view if it is focusable itself.
13573 *
13574 * @param direction The direction of the focus
13575 * @return A list of focusable views
13576 */
13577 public ArrayList<View> getFocusables(@FocusDirection int direction) {
13578 ArrayList<View> result = new ArrayList<View>(24);
13579 addFocusables(result, direction);
13580 return result;
13581 }
13582
13583 /**
13584 * Add any focusable views that are descendants of this view (possibly
13585 * including this view if it is focusable itself) to views. If we are in touch mode,
13586 * only add views that are also focusable in touch mode.
13587 *
13588 * @param views Focusable views found so far
13589 * @param direction The direction of the focus
13590 */
13591 public void addFocusables(ArrayList<View> views, @FocusDirection int direction) {
13592 addFocusables(views, direction, isInTouchMode() ? FOCUSABLES_TOUCH_MODE : FOCUSABLES_ALL);
13593 }
13594
13595 /**
13596 * Adds any focusable views that are descendants of this view (possibly
13597 * including this view if it is focusable itself) to views. This method
13598 * adds all focusable views regardless if we are in touch mode or
13599 * only views focusable in touch mode if we are in touch mode or
13600 * only views that can take accessibility focus if accessibility is enabled
13601 * depending on the focusable mode parameter.
13602 *
13603 * @param views Focusable views found so far or null if all we are interested is
13604 * the number of focusables.
13605 * @param direction The direction of the focus.
13606 * @param focusableMode The type of focusables to be added.
13607 *
13608 * @see #FOCUSABLES_ALL
13609 * @see #FOCUSABLES_TOUCH_MODE
13610 */
13611 public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
13612 @FocusableMode int focusableMode) {
13613 if (views == null) {
13614 return;
13615 }
13616 if (!canTakeFocus()) {
13617 return;
13618 }
13619 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
13620 && !isFocusableInTouchMode()) {
13621 return;
13622 }
13623 views.add(this);
13624 }
13625
13626 /**
13627 * Adds any keyboard navigation cluster roots that are descendants of this view (possibly
13628 * including this view if it is a cluster root itself) to views.
13629 *
13630 * @param views Keyboard navigation cluster roots found so far
13631 * @param direction Direction to look
13632 */
13633 public void addKeyboardNavigationClusters(
13634 @NonNull Collection<View> views,
13635 int direction) {
13636 if (!isKeyboardNavigationCluster()) {
13637 return;
13638 }
13639 if (!hasFocusable()) {
13640 return;
13641 }
13642 views.add(this);
13643 }
13644
13645 /**
13646 * Finds the Views that contain given text. The containment is case insensitive.
13647 * The search is performed by either the text that the View renders or the content
13648 * description that describes the view for accessibility purposes and the view does
13649 * not render or both. Clients can specify how the search is to be performed via
13650 * passing the {@link #FIND_VIEWS_WITH_TEXT} and
13651 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
13652 *
13653 * @param outViews The output list of matching Views.
13654 * @param searched The text to match against.
13655 *
13656 * @see #FIND_VIEWS_WITH_TEXT
13657 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
13658 * @see #setContentDescription(CharSequence)
13659 */
13660 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched,
13661 @FindViewFlags int flags) {
13662 if (getAccessibilityNodeProvider() != null) {
13663 if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
13664 outViews.add(this);
13665 }
13666 } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
13667 && (searched != null && searched.length() > 0)
13668 && (mContentDescription != null && mContentDescription.length() > 0)) {
13669 String searchedLowerCase = searched.toString().toLowerCase();
13670 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
13671 if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
13672 outViews.add(this);
13673 }
13674 }
13675 }
13676
13677 /**
13678 * Find and return all touchable views that are descendants of this view,
13679 * possibly including this view if it is touchable itself.
13680 *
13681 * @return A list of touchable views
13682 */
13683 public ArrayList<View> getTouchables() {
13684 ArrayList<View> result = new ArrayList<View>();
13685 addTouchables(result);
13686 return result;
13687 }
13688
13689 /**
13690 * Add any touchable views that are descendants of this view (possibly
13691 * including this view if it is touchable itself) to views.
13692 *
13693 * @param views Touchable views found so far
13694 */
13695 public void addTouchables(ArrayList<View> views) {
13696 final int viewFlags = mViewFlags;
13697
13698 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE
13699 || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE)
13700 && (viewFlags & ENABLED_MASK) == ENABLED) {
13701 views.add(this);
13702 }
13703 }
13704
13705 /**
13706 * Returns whether this View is accessibility focused.
13707 *
13708 * @return True if this View is accessibility focused.
13709 */
13710 @InspectableProperty(hasAttributeId = false)
13711 public boolean isAccessibilityFocused() {
13712 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
13713 }
13714
13715 /**
13716 * Call this to try to give accessibility focus to this view.
13717 *
13718 * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
13719 * returns false or the view is no visible or the view already has accessibility
13720 * focus.
13721 *
13722 * See also {@link #focusSearch(int)}, which is what you call to say that you
13723 * have focus, and you want your parent to look for the next one.
13724 *
13725 * @return Whether this view actually took accessibility focus.
13726 *
13727 * @hide
13728 */
13729 @UnsupportedAppUsage
13730 public boolean requestAccessibilityFocus() {
13731 AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
13732 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
13733 return false;
13734 }
13735 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
13736 return false;
13737 }
13738 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
13739 mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
13740 ViewRootImpl viewRootImpl = getViewRootImpl();
13741 if (viewRootImpl != null) {
13742 viewRootImpl.setAccessibilityFocus(this, null);
13743 }
13744 invalidate();
13745 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
13746 return true;
13747 }
13748 return false;
13749 }
13750
13751 /**
13752 * Call this to try to clear accessibility focus of this view.
13753 *
13754 * See also {@link #focusSearch(int)}, which is what you call to say that you
13755 * have focus, and you want your parent to look for the next one.
13756 *
13757 * @hide
13758 */
13759 @UnsupportedAppUsage
13760 public void clearAccessibilityFocus() {
13761 clearAccessibilityFocusNoCallbacks(0);
13762
13763 // Clear the global reference of accessibility focus if this view or
13764 // any of its descendants had accessibility focus. This will NOT send
13765 // an event or update internal state if focus is cleared from a
13766 // descendant view, which may leave views in inconsistent states.
13767 final ViewRootImpl viewRootImpl = getViewRootImpl();
13768 if (viewRootImpl != null) {
13769 final View focusHost = viewRootImpl.getAccessibilityFocusedHost();
13770 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
13771 viewRootImpl.setAccessibilityFocus(null, null);
13772 }
13773 }
13774 }
13775
13776 private void sendAccessibilityHoverEvent(int eventType) {
13777 // Since we are not delivering to a client accessibility events from not
13778 // important views (unless the clinet request that) we need to fire the
13779 // event from the deepest view exposed to the client. As a consequence if
13780 // the user crosses a not exposed view the client will see enter and exit
13781 // of the exposed predecessor followed by and enter and exit of that same
13782 // predecessor when entering and exiting the not exposed descendant. This
13783 // is fine since the client has a clear idea which view is hovered at the
13784 // price of a couple more events being sent. This is a simple and
13785 // working solution.
13786 View source = this;
13787 while (true) {
13788 if (source.includeForAccessibility()) {
13789 source.sendAccessibilityEvent(eventType);
13790 return;
13791 }
13792 ViewParent parent = source.getParent();
13793 if (parent instanceof View) {
13794 source = (View) parent;
13795 } else {
13796 return;
13797 }
13798 }
13799 }
13800
13801 /**
13802 * Clears accessibility focus without calling any callback methods
13803 * normally invoked in {@link #clearAccessibilityFocus()}. This method
13804 * is used separately from that one for clearing accessibility focus when
13805 * giving this focus to another view.
13806 *
13807 * @param action The action, if any, that led to focus being cleared. Set to
13808 * AccessibilityNodeInfo#ACTION_ACCESSIBILITY_FOCUS to specify that focus is moving within
13809 * the window.
13810 */
13811 void clearAccessibilityFocusNoCallbacks(int action) {
13812 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
13813 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
13814 invalidate();
13815 if (AccessibilityManager.getInstance(mContext).isEnabled()) {
13816 AccessibilityEvent event = AccessibilityEvent.obtain(
13817 AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
13818 event.setAction(action);
13819 if (mAccessibilityDelegate != null) {
13820 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
13821 } else {
13822 sendAccessibilityEventUnchecked(event);
13823 }
13824 }
13825
13826 updatePreferKeepClearForFocus();
13827 }
13828 }
13829
13830 /**
13831 * Call this to try to give focus to a specific view or to one of its
13832 * descendants.
13833 *
13834 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
13835 * false), or if it can't be focused due to other conditions (not focusable in touch mode
13836 * ({@link #isFocusableInTouchMode}) while the device is in touch mode, not visible, not
13837 * enabled, or has no size).
13838 *
13839 * See also {@link #focusSearch(int)}, which is what you call to say that you
13840 * have focus, and you want your parent to look for the next one.
13841 *
13842 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
13843 * {@link #FOCUS_DOWN} and <code>null</code>.
13844 *
13845 * @return Whether this view or one of its descendants actually took focus.
13846 */
13847 public final boolean requestFocus() {
13848 return requestFocus(View.FOCUS_DOWN);
13849 }
13850
13851 /**
13852 * This will request focus for whichever View was last focused within this
13853 * cluster before a focus-jump out of it.
13854 *
13855 * @hide
13856 */
13857 @TestApi
13858 public boolean restoreFocusInCluster(@FocusRealDirection int direction) {
13859 // Prioritize focusableByDefault over algorithmic focus selection.
13860 if (restoreDefaultFocus()) {
13861 return true;
13862 }
13863 return requestFocus(direction);
13864 }
13865
13866 /**
13867 * This will request focus for whichever View not in a cluster was last focused before a
13868 * focus-jump to a cluster. If no non-cluster View has previously had focus, this will focus
13869 * the "first" focusable view it finds.
13870 *
13871 * @hide
13872 */
13873 @TestApi
13874 public boolean restoreFocusNotInCluster() {
13875 return requestFocus(View.FOCUS_DOWN);
13876 }
13877
13878 /**
13879 * Gives focus to the default-focus view in the view hierarchy that has this view as a root.
13880 * If the default-focus view cannot be found, falls back to calling {@link #requestFocus(int)}.
13881 *
13882 * @return Whether this view or one of its descendants actually took focus
13883 */
13884 public boolean restoreDefaultFocus() {
13885 return requestFocus(View.FOCUS_DOWN);
13886 }
13887
13888 /**
13889 * Call this to try to give focus to a specific view or to one of its
13890 * descendants and give it a hint about what direction focus is heading.
13891 *
13892 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
13893 * false), or if it is focusable and it is not focusable in touch mode
13894 * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
13895 *
13896 * See also {@link #focusSearch(int)}, which is what you call to say that you
13897 * have focus, and you want your parent to look for the next one.
13898 *
13899 * This is equivalent to calling {@link #requestFocus(int, Rect)} with
13900 * <code>null</code> set for the previously focused rectangle.
13901 *
13902 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
13903 * @return Whether this view or one of its descendants actually took focus.
13904 */
13905 public final boolean requestFocus(int direction) {
13906 return requestFocus(direction, null);
13907 }
13908
13909 /**
13910 * Call this to try to give focus to a specific view or to one of its descendants
13911 * and give it hints about the direction and a specific rectangle that the focus
13912 * is coming from. The rectangle can help give larger views a finer grained hint
13913 * about where focus is coming from, and therefore, where to show selection, or
13914 * forward focus change internally.
13915 *
13916 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
13917 * false), or if it is focusable and it is not focusable in touch mode
13918 * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
13919 *
13920 * A View will not take focus if it is not visible.
13921 *
13922 * A View will not take focus if one of its parents has
13923 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
13924 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
13925 *
13926 * See also {@link #focusSearch(int)}, which is what you call to say that you
13927 * have focus, and you want your parent to look for the next one.
13928 *
13929 * You may wish to override this method if your custom {@link View} has an internal
13930 * {@link View} that it wishes to forward the request to.
13931 *
13932 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
13933 * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
13934 * to give a finer grained hint about where focus is coming from. May be null
13935 * if there is no hint.
13936 * @return Whether this view or one of its descendants actually took focus.
13937 */
13938 public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
13939 return requestFocusNoSearch(direction, previouslyFocusedRect);
13940 }
13941
13942 private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
13943 // need to be focusable
13944 if (!canTakeFocus()) {
13945 return false;
13946 }
13947
13948 // need to be focusable in touch mode if in touch mode
13949 if (isInTouchMode() &&
13950 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
13951 return false;
13952 }
13953
13954 // need to not have any parents blocking us
13955 if (hasAncestorThatBlocksDescendantFocus()) {
13956 return false;
13957 }
13958
13959 if (!isLayoutValid()) {
13960 mPrivateFlags |= PFLAG_WANTS_FOCUS;
13961 } else {
13962 clearParentsWantFocus();
13963 }
13964
13965 handleFocusGainInternal(direction, previouslyFocusedRect);
13966 return true;
13967 }
13968
13969 void clearParentsWantFocus() {
13970 if (mParent instanceof View) {
13971 ((View) mParent).mPrivateFlags &= ~PFLAG_WANTS_FOCUS;
13972 ((View) mParent).clearParentsWantFocus();
13973 }
13974 }
13975
13976 /**
13977 * Call this to try to give focus to a specific view or to one of its descendants. This is a
13978 * special variant of {@link #requestFocus() } that will allow views that are not focusable in
13979 * touch mode to request focus when they are touched.
13980 *
13981 * @return Whether this view or one of its descendants actually took focus.
13982 *
13983 * @see #isInTouchMode()
13984 *
13985 */
13986 public final boolean requestFocusFromTouch() {
13987 // Leave touch mode if we need to
13988 if (isInTouchMode()) {
13989 ViewRootImpl viewRoot = getViewRootImpl();
13990 if (viewRoot != null) {
13991 viewRoot.ensureTouchMode(false);
13992 }
13993 }
13994 return requestFocus(View.FOCUS_DOWN);
13995 }
13996
13997 /**
13998 * @return Whether any ancestor of this view blocks descendant focus.
13999 */
14000 private boolean hasAncestorThatBlocksDescendantFocus() {
14001 final boolean focusableInTouchMode = isFocusableInTouchMode();
14002 ViewParent ancestor = mParent;
14003 while (ancestor instanceof ViewGroup) {
14004 final ViewGroup vgAncestor = (ViewGroup) ancestor;
14005 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS
14006 || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) {
14007 return true;
14008 } else {
14009 ancestor = vgAncestor.getParent();
14010 }
14011 }
14012 return false;
14013 }
14014
14015 /**
14016 * Gets the mode for determining whether this View is important for accessibility.
14017 * A view is important for accessibility if it fires accessibility events and if it
14018 * is reported to accessibility services that query the screen.
14019 *
14020 * @return The mode for determining whether a view is important for accessibility, one
14021 * of {@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, {@link #IMPORTANT_FOR_ACCESSIBILITY_YES},
14022 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO}, or
14023 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}.
14024 *
14025 * @attr ref android.R.styleable#View_importantForAccessibility
14026 *
14027 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
14028 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
14029 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
14030 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
14031 */
14032 @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
14033 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
14034 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
14035 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"),
14036 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
14037 to = "noHideDescendants")
14038 })
14039 @InspectableProperty(enumMapping = {
14040 @EnumEntry(value = IMPORTANT_FOR_ACCESSIBILITY_AUTO, name = "auto"),
14041 @EnumEntry(value = IMPORTANT_FOR_ACCESSIBILITY_YES, name = "yes"),
14042 @EnumEntry(value = IMPORTANT_FOR_ACCESSIBILITY_NO, name = "no"),
14043 @EnumEntry(value = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
14044 name = "noHideDescendants"),
14045 })
14046 public int getImportantForAccessibility() {
14047 return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
14048 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
14049 }
14050
14051 /**
14052 * Sets the live region mode for this view. This indicates to accessibility
14053 * services whether they should automatically notify the user about changes
14054 * to the view's content description or text, or to the content descriptions
14055 * or text of the view's children (where applicable).
14056 * <p>
14057 * For example, in a login screen with a TextView that displays an "incorrect
14058 * password" notification, that view should be marked as a live region with
14059 * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
14060 * <p>
14061 * To disable change notifications for this view, use
14062 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
14063 * mode for most views.
14064 * <p>
14065 * To indicate that the user should be notified of changes, use
14066 * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
14067 * <p>
14068 * If the view's changes should interrupt ongoing speech and notify the user
14069 * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
14070 *
14071 * @param mode The live region mode for this view, one of:
14072 * <ul>
14073 * <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
14074 * <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
14075 * <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
14076 * </ul>
14077 * @attr ref android.R.styleable#View_accessibilityLiveRegion
14078 */
14079 public void setAccessibilityLiveRegion(int mode) {
14080 if (mode != getAccessibilityLiveRegion()) {
14081 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
14082 mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
14083 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
14084 notifyViewAccessibilityStateChangedIfNeeded(
14085 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
14086 }
14087 }
14088
14089 /**
14090 * Gets the live region mode for this View.
14091 *
14092 * @return The live region mode for the view.
14093 *
14094 * @attr ref android.R.styleable#View_accessibilityLiveRegion
14095 *
14096 * @see #setAccessibilityLiveRegion(int)
14097 */
14098 @InspectableProperty(enumMapping = {
14099 @EnumEntry(value = ACCESSIBILITY_LIVE_REGION_NONE, name = "none"),
14100 @EnumEntry(value = ACCESSIBILITY_LIVE_REGION_POLITE, name = "polite"),
14101 @EnumEntry(value = ACCESSIBILITY_LIVE_REGION_ASSERTIVE, name = "assertive")
14102 })
14103 public int getAccessibilityLiveRegion() {
14104 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
14105 >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
14106 }
14107
14108 /**
14109 * Sets how to determine whether this view is important for accessibility
14110 * which is if it fires accessibility events and if it is reported to
14111 * accessibility services that query the screen.
14112 *
14113 * @param mode How to determine whether this view is important for accessibility.
14114 *
14115 * @attr ref android.R.styleable#View_importantForAccessibility
14116 *
14117 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
14118 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
14119 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
14120 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
14121 */
14122 public void setImportantForAccessibility(int mode) {
14123 final int oldMode = getImportantForAccessibility();
14124 if (mode != oldMode) {
14125 final boolean hideDescendants =
14126 mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS;
14127
14128 // If this node or its descendants are no longer important, try to
14129 // clear accessibility focus.
14130 if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO || hideDescendants) {
14131 final View focusHost = findAccessibilityFocusHost(hideDescendants);
14132 if (focusHost != null) {
14133 focusHost.clearAccessibilityFocus();
14134 }
14135 }
14136
14137 // If we're moving between AUTO and another state, we might not need
14138 // to send a subtree changed notification. We'll store the computed
14139 // importance, since we'll need to check it later to make sure.
14140 final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO
14141 || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO;
14142 final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility();
14143 mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
14144 mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
14145 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
14146 if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) {
14147 notifySubtreeAccessibilityStateChangedIfNeeded();
14148 } else {
14149 notifyViewAccessibilityStateChangedIfNeeded(
14150 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
14151 }
14152 }
14153 }
14154
14155 /**
14156 * Returns the view within this view's hierarchy that is hosting
14157 * accessibility focus.
14158 *
14159 * @param searchDescendants whether to search for focus in descendant views
14160 * @return the view hosting accessibility focus, or {@code null}
14161 */
14162 private View findAccessibilityFocusHost(boolean searchDescendants) {
14163 if (isAccessibilityFocusedViewOrHost()) {
14164 return this;
14165 }
14166
14167 if (searchDescendants) {
14168 final ViewRootImpl viewRoot = getViewRootImpl();
14169 if (viewRoot != null) {
14170 final View focusHost = viewRoot.getAccessibilityFocusedHost();
14171 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
14172 return focusHost;
14173 }
14174 }
14175 }
14176
14177 return null;
14178 }
14179
14180 /**
14181 * Computes whether this view should be exposed for accessibility. In
14182 * general, views that are interactive or provide information are exposed
14183 * while views that serve only as containers are hidden.
14184 * <p>
14185 * If an ancestor of this view has importance
14186 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method
14187 * returns <code>false</code>.
14188 * <p>
14189 * Otherwise, the value is computed according to the view's
14190 * {@link #getImportantForAccessibility()} value:
14191 * <ol>
14192 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or
14193 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false
14194 * </code>
14195 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code>
14196 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if
14197 * view satisfies any of the following:
14198 * <ul>
14199 * <li>Is actionable, e.g. {@link #isClickable()},
14200 * {@link #isLongClickable()}, or {@link #isFocusable()}
14201 * <li>Has an {@link AccessibilityDelegate}
14202 * <li>Has an interaction listener, e.g. {@link OnTouchListener},
14203 * {@link OnKeyListener}, etc.
14204 * <li>Is an accessibility live region, e.g.
14205 * {@link #getAccessibilityLiveRegion()} is not
14206 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}.
14207 * </ul>
14208 * <li>Has an accessibility pane title, see {@link #setAccessibilityPaneTitle}</li>
14209 * </ol>
14210 *
14211 * @return Whether the view is exposed for accessibility.
14212 * @see #setImportantForAccessibility(int)
14213 * @see #getImportantForAccessibility()
14214 */
14215 public boolean isImportantForAccessibility() {
14216 final int mode = getImportantForAccessibility();
14217 if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO
14218 || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
14219 return false;
14220 }
14221
14222 // Check parent mode to ensure we're not hidden.
14223 ViewParent parent = mParent;
14224 while (parent instanceof View) {
14225 if (((View) parent).getImportantForAccessibility()
14226 == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
14227 return false;
14228 }
14229 parent = parent.getParent();
14230 }
14231
14232 return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
14233 || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
14234 || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE
14235 || isAccessibilityPane();
14236 }
14237
14238 /**
14239 * Gets the parent for accessibility purposes. Note that the parent for
14240 * accessibility is not necessary the immediate parent. It is the first
14241 * predecessor that is important for accessibility.
14242 *
14243 * @return The parent for accessibility purposes.
14244 */
14245 public ViewParent getParentForAccessibility() {
14246 if (mParent instanceof View) {
14247 View parentView = (View) mParent;
14248 if (parentView.includeForAccessibility()) {
14249 return mParent;
14250 } else {
14251 return mParent.getParentForAccessibility();
14252 }
14253 }
14254 return null;
14255 }
14256
14257 /** @hide */
14258 View getSelfOrParentImportantForA11y() {
14259 if (isImportantForAccessibility()) return this;
14260 ViewParent parent = getParentForAccessibility();
14261 if (parent instanceof View) return (View) parent;
14262 return null;
14263 }
14264
14265 /**
14266 * Adds the children of this View relevant for accessibility to the given list
14267 * as output. Since some Views are not important for accessibility the added
14268 * child views are not necessarily direct children of this view, rather they are
14269 * the first level of descendants important for accessibility.
14270 *
14271 * @param outChildren The output list that will receive children for accessibility.
14272 */
14273 public void addChildrenForAccessibility(ArrayList<View> outChildren) {
14274
14275 }
14276
14277 /**
14278 * Whether to regard this view for accessibility. A view is regarded for
14279 * accessibility if it is important for accessibility or the querying
14280 * accessibility service has explicitly requested that view not
14281 * important for accessibility are regarded.
14282 *
14283 * @return Whether to regard the view for accessibility.
14284 *
14285 * @hide
14286 */
14287 @UnsupportedAppUsage
14288 public boolean includeForAccessibility() {
14289 if (mAttachInfo != null) {
14290 return (mAttachInfo.mAccessibilityFetchFlags
14291 & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
14292 || isImportantForAccessibility();
14293 }
14294 return false;
14295 }
14296
14297 /**
14298 * Returns whether the View is considered actionable from
14299 * accessibility perspective. Such view are important for
14300 * accessibility.
14301 *
14302 * @return True if the view is actionable for accessibility.
14303 *
14304 * @hide
14305 */
14306 public boolean isActionableForAccessibility() {
14307 return (isClickable() || isLongClickable() || isFocusable());
14308 }
14309
14310 /**
14311 * Returns whether the View has registered callbacks which makes it
14312 * important for accessibility.
14313 *
14314 * @return True if the view is actionable for accessibility.
14315 */
14316 private boolean hasListenersForAccessibility() {
14317 ListenerInfo info = getListenerInfo();
14318 return mTouchDelegate != null || info.mOnKeyListener != null
14319 || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
14320 || info.mOnHoverListener != null || info.mOnDragListener != null;
14321 }
14322
14323 /**
14324 * Notifies that the accessibility state of this view changed. The change
14325 * is local to this view and does not represent structural changes such
14326 * as children and parent. For example, the view became focusable. The
14327 * notification is at at most once every
14328 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
14329 * to avoid unnecessary load to the system. Also once a view has a pending
14330 * notification this method is a NOP until the notification has been sent.
14331 *
14332 * @hide
14333 */
14334 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
14335 public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
14336 if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) {
14337 return;
14338 }
14339
14340 // Changes to views with a pane title count as window state changes, as the pane title
14341 // marks them as significant parts of the UI. A visible view with a nulled title may send
14342 // a disappeared event.
14343 if ((changeType != AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE)
14344 && (isAccessibilityPane()
14345 || (changeType == AccessibilityEvent.CONTENT_CHANGE_TYPE_PANE_DISAPPEARED)
14346 && isAggregatedVisible())) {
14347 // If the pane isn't visible, content changed events are sufficient unless we're
14348 // reporting that the view just disappeared
14349 if ((isAggregatedVisible())
14350 || (changeType == AccessibilityEvent.CONTENT_CHANGE_TYPE_PANE_DISAPPEARED)) {
14351 final AccessibilityEvent event = AccessibilityEvent.obtain();
14352 onInitializeAccessibilityEvent(event);
14353 event.setEventType(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
14354 event.setContentChangeTypes(changeType);
14355 event.setSource(this);
14356 onPopulateAccessibilityEvent(event);
14357 if (mParent != null) {
14358 try {
14359 mParent.requestSendAccessibilityEvent(this, event);
14360 } catch (AbstractMethodError e) {
14361 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName()
14362 + " does not fully implement ViewParent", e);
14363 }
14364 }
14365 return;
14366 }
14367 }
14368
14369 // If this is a live region, we should send a subtree change event
14370 // from this view immediately. Otherwise, we can let it propagate up.
14371 if (getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE) {
14372 final AccessibilityEvent event = AccessibilityEvent.obtain();
14373 event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
14374 event.setContentChangeTypes(changeType);
14375 sendAccessibilityEventUnchecked(event);
14376 } else if (mParent != null) {
14377 try {
14378 mParent.notifySubtreeAccessibilityStateChanged(this, this, changeType);
14379 } catch (AbstractMethodError e) {
14380 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
14381 " does not fully implement ViewParent", e);
14382 }
14383 }
14384 }
14385
14386 /**
14387 * Notifies that the accessibility state of this view changed. The change
14388 * is *not* local to this view and does represent structural changes such
14389 * as children and parent. For example, the view size changed. The
14390 * notification is at at most once every
14391 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
14392 * to avoid unnecessary load to the system. Also once a view has a pending
14393 * notification this method is a NOP until the notification has been sent.
14394 *
14395 * @hide
14396 */
14397 @UnsupportedAppUsage
14398 public void notifySubtreeAccessibilityStateChangedIfNeeded() {
14399 if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) {
14400 return;
14401 }
14402
14403 if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
14404 mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
14405 if (mParent != null) {
14406 try {
14407 mParent.notifySubtreeAccessibilityStateChanged(
14408 this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
14409 } catch (AbstractMethodError e) {
14410 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
14411 " does not fully implement ViewParent", e);
14412 }
14413 }
14414 }
14415 }
14416
14417 private void notifySubtreeAccessibilityStateChangedByParentIfNeeded() {
14418 if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
14419 return;
14420 }
14421
14422 final View sendA11yEventView = (View) getParentForAccessibility();
14423 if (sendA11yEventView != null && sendA11yEventView.isShown()) {
14424 sendA11yEventView.notifySubtreeAccessibilityStateChangedIfNeeded();
14425 }
14426 }
14427
14428 /**
14429 * Changes the visibility of this View without triggering any other changes. This should only
14430 * be used by animation frameworks, such as {@link android.transition.Transition}, where
14431 * visibility changes should not adjust focus or trigger a new layout. Application developers
14432 * should use {@link #setVisibility} instead to ensure that the hierarchy is correctly updated.
14433 *
14434 * <p>Only call this method when a temporary visibility must be applied during an
14435 * animation and the original visibility value is guaranteed to be reset after the
14436 * animation completes. Use {@link #setVisibility} in all other cases.</p>
14437 *
14438 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
14439 * @see #setVisibility(int)
14440 */
14441 public void setTransitionVisibility(@Visibility int visibility) {
14442 mViewFlags = (mViewFlags & ~View.VISIBILITY_MASK) | visibility;
14443 }
14444
14445 /**
14446 * Reset the flag indicating the accessibility state of the subtree rooted
14447 * at this view changed.
14448 */
14449 void resetSubtreeAccessibilityStateChanged() {
14450 mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
14451 }
14452
14453 /**
14454 * Report an accessibility action to this view's parents for delegated processing.
14455 *
14456 * <p>Implementations of {@link #performAccessibilityAction(int, Bundle)} may internally
14457 * call this method to delegate an accessibility action to a supporting parent. If the parent
14458 * returns true from its
14459 * {@link ViewParent#onNestedPrePerformAccessibilityAction(View, int, android.os.Bundle)}
14460 * method this method will return true to signify that the action was consumed.</p>
14461 *
14462 * <p>This method is useful for implementing nested scrolling child views. If
14463 * {@link #isNestedScrollingEnabled()} returns true and the action is a scrolling action
14464 * a custom view implementation may invoke this method to allow a parent to consume the
14465 * scroll first. If this method returns true the custom view should skip its own scrolling
14466 * behavior.</p>
14467 *
14468 * @param action Accessibility action to delegate
14469 * @param arguments Optional action arguments
14470 * @return true if the action was consumed by a parent
14471 */
14472 public boolean dispatchNestedPrePerformAccessibilityAction(int action,
14473 @Nullable Bundle arguments) {
14474 for (ViewParent p = getParent(); p != null; p = p.getParent()) {
14475 if (p.onNestedPrePerformAccessibilityAction(this, action, arguments)) {
14476 return true;
14477 }
14478 }
14479 return false;
14480 }
14481
14482 /**
14483 * Performs the specified accessibility action on the view. For
14484 * possible accessibility actions look at {@link AccessibilityNodeInfo}.
14485 * <p>
14486 * If an {@link AccessibilityDelegate} has been specified via calling
14487 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
14488 * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
14489 * is responsible for handling this call.
14490 * </p>
14491 *
14492 * <p>The default implementation will delegate
14493 * {@link AccessibilityNodeInfo#ACTION_SCROLL_BACKWARD} and
14494 * {@link AccessibilityNodeInfo#ACTION_SCROLL_FORWARD} to nested scrolling parents if
14495 * {@link #isNestedScrollingEnabled() nested scrolling is enabled} on this view.</p>
14496 *
14497 * @param action The action to perform.
14498 * @param arguments Optional action arguments.
14499 * @return Whether the action was performed.
14500 */
14501 public boolean performAccessibilityAction(int action, @Nullable Bundle arguments) {
14502 if (mAccessibilityDelegate != null) {
14503 return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
14504 } else {
14505 return performAccessibilityActionInternal(action, arguments);
14506 }
14507 }
14508
14509 /**
14510 * @see #performAccessibilityAction(int, Bundle)
14511 *
14512 * Note: Called from the default {@link AccessibilityDelegate}.
14513 *
14514 * @hide
14515 */
14516 @UnsupportedAppUsage
14517 public boolean performAccessibilityActionInternal(int action, @Nullable Bundle arguments) {
14518 if (isNestedScrollingEnabled()
14519 && (action == AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD
14520 || action == AccessibilityNodeInfo.ACTION_SCROLL_FORWARD
14521 || action == R.id.accessibilityActionScrollUp
14522 || action == R.id.accessibilityActionScrollLeft
14523 || action == R.id.accessibilityActionScrollDown
14524 || action == R.id.accessibilityActionScrollRight)) {
14525 if (dispatchNestedPrePerformAccessibilityAction(action, arguments)) {
14526 return true;
14527 }
14528 }
14529
14530 switch (action) {
14531 case AccessibilityNodeInfo.ACTION_CLICK: {
14532 if (isClickable()) {
14533 performClickInternal();
14534 return true;
14535 }
14536 } break;
14537 case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
14538 if (isLongClickable()) {
14539 performLongClick();
14540 return true;
14541 }
14542 } break;
14543 case AccessibilityNodeInfo.ACTION_FOCUS: {
14544 if (!hasFocus()) {
14545 // Get out of touch mode since accessibility
14546 // wants to move focus around.
14547 getViewRootImpl().ensureTouchMode(false);
14548 return requestFocus();
14549 }
14550 } break;
14551 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
14552 if (hasFocus()) {
14553 clearFocus();
14554 return !isFocused();
14555 }
14556 } break;
14557 case AccessibilityNodeInfo.ACTION_SELECT: {
14558 if (!isSelected()) {
14559 setSelected(true);
14560 return isSelected();
14561 }
14562 } break;
14563 case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
14564 if (isSelected()) {
14565 setSelected(false);
14566 return !isSelected();
14567 }
14568 } break;
14569 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
14570 if (!isAccessibilityFocused()) {
14571 return requestAccessibilityFocus();
14572 }
14573 } break;
14574 case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
14575 if (isAccessibilityFocused()) {
14576 clearAccessibilityFocus();
14577 return true;
14578 }
14579 } break;
14580 case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
14581 if (arguments != null) {
14582 final int granularity = arguments.getInt(
14583 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
14584 final boolean extendSelection = arguments.getBoolean(
14585 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
14586 return traverseAtGranularity(granularity, true, extendSelection);
14587 }
14588 } break;
14589 case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
14590 if (arguments != null) {
14591 final int granularity = arguments.getInt(
14592 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
14593 final boolean extendSelection = arguments.getBoolean(
14594 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
14595 return traverseAtGranularity(granularity, false, extendSelection);
14596 }
14597 } break;
14598 case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
14599 CharSequence text = getIterableTextForAccessibility();
14600 if (text == null) {
14601 return false;
14602 }
14603 final int start = (arguments != null) ? arguments.getInt(
14604 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
14605 final int end = (arguments != null) ? arguments.getInt(
14606 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
14607 // Only cursor position can be specified (selection length == 0)
14608 if ((getAccessibilitySelectionStart() != start
14609 || getAccessibilitySelectionEnd() != end)
14610 && (start == end)) {
14611 setAccessibilitySelection(start, end);
14612 notifyViewAccessibilityStateChangedIfNeeded(
14613 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
14614 return true;
14615 }
14616 } break;
14617 case R.id.accessibilityActionShowOnScreen: {
14618 if (mAttachInfo != null) {
14619 final Rect r = mAttachInfo.mTmpInvalRect;
14620 getDrawingRect(r);
14621 return requestRectangleOnScreen(r, true);
14622 }
14623 } break;
14624 case R.id.accessibilityActionContextClick: {
14625 if (isContextClickable()) {
14626 performContextClick();
14627 return true;
14628 }
14629 } break;
14630 case R.id.accessibilityActionShowTooltip: {
14631 if ((mTooltipInfo != null) && (mTooltipInfo.mTooltipPopup != null)) {
14632 // Tooltip already showing
14633 return false;
14634 }
14635 return showLongClickTooltip(0, 0);
14636 }
14637 case R.id.accessibilityActionHideTooltip: {
14638 if ((mTooltipInfo == null) || (mTooltipInfo.mTooltipPopup == null)) {
14639 // No tooltip showing
14640 return false;
14641 }
14642 hideTooltip();
14643 return true;
14644 }
14645 case R.id.accessibilityActionDragDrop: {
14646 if (!canAcceptAccessibilityDrop()) {
14647 return false;
14648 }
14649 try {
14650 if (mAttachInfo != null && mAttachInfo.mSession != null) {
14651 final int[] location = new int[2];
14652 getLocationInWindow(location);
14653 final int centerX = location[0] + getWidth() / 2;
14654 final int centerY = location[1] + getHeight() / 2;
14655 return mAttachInfo.mSession.dropForAccessibility(mAttachInfo.mWindow,
14656 centerX, centerY);
14657 }
14658 } catch (RemoteException e) {
14659 Log.e(VIEW_LOG_TAG, "Unable to drop for accessibility", e);
14660 }
14661 return false;
14662 }
14663 case R.id.accessibilityActionDragCancel: {
14664 if (!startedSystemDragForAccessibility()) {
14665 return false;
14666 }
14667 if (mAttachInfo != null && mAttachInfo.mDragToken != null) {
14668 cancelDragAndDrop();
14669 return true;
14670 }
14671 return false;
14672 }
14673 }
14674 return false;
14675 }
14676
14677 private boolean canAcceptAccessibilityDrop() {
14678 if (!canAcceptDrag()) {
14679 return false;
14680 }
14681 ListenerInfo li = mListenerInfo;
14682 return (li != null) && (li.mOnDragListener != null || li.mOnReceiveContentListener != null);
14683 }
14684
14685 private boolean traverseAtGranularity(int granularity, boolean forward,
14686 boolean extendSelection) {
14687 CharSequence text = getIterableTextForAccessibility();
14688 if (text == null || text.length() == 0) {
14689 return false;
14690 }
14691 TextSegmentIterator iterator = getIteratorForGranularity(granularity);
14692 if (iterator == null) {
14693 return false;
14694 }
14695 int current = getAccessibilitySelectionEnd();
14696 if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
14697 current = forward ? 0 : text.length();
14698 }
14699 final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
14700 if (range == null) {
14701 return false;
14702 }
14703 final int segmentStart = range[0];
14704 final int segmentEnd = range[1];
14705 int selectionStart;
14706 int selectionEnd;
14707 if (extendSelection && isAccessibilitySelectionExtendable()) {
14708 prepareForExtendedAccessibilitySelection();
14709 selectionStart = getAccessibilitySelectionStart();
14710 if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
14711 selectionStart = forward ? segmentStart : segmentEnd;
14712 }
14713 selectionEnd = forward ? segmentEnd : segmentStart;
14714 } else {
14715 selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
14716 }
14717 setAccessibilitySelection(selectionStart, selectionEnd);
14718 final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
14719 : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
14720 sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
14721 return true;
14722 }
14723
14724 /**
14725 * Gets the text reported for accessibility purposes.
14726 *
14727 * @return The accessibility text.
14728 *
14729 * @hide
14730 */
14731 @UnsupportedAppUsage
14732 public CharSequence getIterableTextForAccessibility() {
14733 return getContentDescription();
14734 }
14735
14736 /**
14737 * Gets whether accessibility selection can be extended.
14738 *
14739 * @return If selection is extensible.
14740 *
14741 * @hide
14742 */
14743 public boolean isAccessibilitySelectionExtendable() {
14744 return false;
14745 }
14746
14747 /**
14748 * Prepare for extended selection.
14749 * @hide
14750 */
14751 public void prepareForExtendedAccessibilitySelection() {
14752 return;
14753 }
14754
14755 /**
14756 * @hide
14757 */
14758 public int getAccessibilitySelectionStart() {
14759 return mAccessibilityCursorPosition;
14760 }
14761
14762 /**
14763 * @hide
14764 */
14765 public int getAccessibilitySelectionEnd() {
14766 return getAccessibilitySelectionStart();
14767 }
14768
14769 /**
14770 * @hide
14771 */
14772 public void setAccessibilitySelection(int start, int end) {
14773 if (start == end && end == mAccessibilityCursorPosition) {
14774 return;
14775 }
14776 if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
14777 mAccessibilityCursorPosition = start;
14778 } else {
14779 mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
14780 }
14781 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
14782 }
14783
14784 private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
14785 int fromIndex, int toIndex) {
14786 if (mParent == null) {
14787 return;
14788 }
14789 AccessibilityEvent event = AccessibilityEvent.obtain(
14790 AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
14791 onInitializeAccessibilityEvent(event);
14792 onPopulateAccessibilityEvent(event);
14793 event.setFromIndex(fromIndex);
14794 event.setToIndex(toIndex);
14795 event.setAction(action);
14796 event.setMovementGranularity(granularity);
14797 mParent.requestSendAccessibilityEvent(this, event);
14798 }
14799
14800 /**
14801 * @hide
14802 */
14803 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
14804 public TextSegmentIterator getIteratorForGranularity(int granularity) {
14805 switch (granularity) {
14806 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
14807 CharSequence text = getIterableTextForAccessibility();
14808 if (text != null && text.length() > 0) {
14809 CharacterTextSegmentIterator iterator =
14810 CharacterTextSegmentIterator.getInstance(
14811 mContext.getResources().getConfiguration().locale);
14812 iterator.initialize(text.toString());
14813 return iterator;
14814 }
14815 } break;
14816 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
14817 CharSequence text = getIterableTextForAccessibility();
14818 if (text != null && text.length() > 0) {
14819 WordTextSegmentIterator iterator =
14820 WordTextSegmentIterator.getInstance(
14821 mContext.getResources().getConfiguration().locale);
14822 iterator.initialize(text.toString());
14823 return iterator;
14824 }
14825 } break;
14826 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
14827 CharSequence text = getIterableTextForAccessibility();
14828 if (text != null && text.length() > 0) {
14829 ParagraphTextSegmentIterator iterator =
14830 ParagraphTextSegmentIterator.getInstance();
14831 iterator.initialize(text.toString());
14832 return iterator;
14833 }
14834 } break;
14835 }
14836 return null;
14837 }
14838
14839 /**
14840 * Tells whether the {@link View} is in the state between {@link #onStartTemporaryDetach()}
14841 * and {@link #onFinishTemporaryDetach()}.
14842 *
14843 * <p>This method always returns {@code true} when called directly or indirectly from
14844 * {@link #onStartTemporaryDetach()}. The return value when called directly or indirectly from
14845 * {@link #onFinishTemporaryDetach()}, however, depends on the OS version.
14846 * <ul>
14847 * <li>{@code true} on {@link android.os.Build.VERSION_CODES#N API 24}</li>
14848 * <li>{@code false} on {@link android.os.Build.VERSION_CODES#N_MR1 API 25}} and later</li>
14849 * </ul>
14850 * </p>
14851 *
14852 * @return {@code true} when the View is in the state between {@link #onStartTemporaryDetach()}
14853 * and {@link #onFinishTemporaryDetach()}.
14854 */
14855 public final boolean isTemporarilyDetached() {
14856 return (mPrivateFlags3 & PFLAG3_TEMPORARY_DETACH) != 0;
14857 }
14858
14859 /**
14860 * Dispatch {@link #onStartTemporaryDetach()} to this View and its direct children if this is
14861 * a container View.
14862 */
14863 @CallSuper
14864 public void dispatchStartTemporaryDetach() {
14865 mPrivateFlags3 |= PFLAG3_TEMPORARY_DETACH;
14866 notifyEnterOrExitForAutoFillIfNeeded(false);
14867 notifyAppearedOrDisappearedForContentCaptureIfNeeded(false);
14868 onStartTemporaryDetach();
14869 }
14870
14871 /**
14872 * This is called when a container is going to temporarily detach a child, with
14873 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
14874 * It will either be followed by {@link #onFinishTemporaryDetach()} or
14875 * {@link #onDetachedFromWindow()} when the container is done.
14876 */
14877 public void onStartTemporaryDetach() {
14878 removeUnsetPressCallback();
14879 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
14880 }
14881
14882 /**
14883 * Dispatch {@link #onFinishTemporaryDetach()} to this View and its direct children if this is
14884 * a container View.
14885 */
14886 @CallSuper
14887 public void dispatchFinishTemporaryDetach() {
14888 mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH;
14889 onFinishTemporaryDetach();
14890 if (hasWindowFocus() && hasFocus()) {
14891 notifyFocusChangeToImeFocusController(true /* hasFocus */);
14892 }
14893 notifyEnterOrExitForAutoFillIfNeeded(true);
14894 notifyAppearedOrDisappearedForContentCaptureIfNeeded(true);
14895 }
14896
14897 /**
14898 * Called after {@link #onStartTemporaryDetach} when the container is done
14899 * changing the view.
14900 */
14901 public void onFinishTemporaryDetach() {
14902 }
14903
14904 /**
14905 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
14906 * for this view's window. Returns null if the view is not currently attached
14907 * to the window. Normally you will not need to use this directly, but
14908 * just use the standard high-level event callbacks like
14909 * {@link #onKeyDown(int, KeyEvent)}.
14910 */
14911 public KeyEvent.DispatcherState getKeyDispatcherState() {
14912 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
14913 }
14914
14915 /**
14916 * Dispatch a key event before it is processed by any input method
14917 * associated with the view hierarchy. This can be used to intercept
14918 * key events in special situations before the IME consumes them; a
14919 * typical example would be handling the BACK key to update the application's
14920 * UI instead of allowing the IME to see it and close itself.
14921 *
14922 * @param event The key event to be dispatched.
14923 * @return True if the event was handled, false otherwise.
14924 */
14925 public boolean dispatchKeyEventPreIme(KeyEvent event) {
14926 return onKeyPreIme(event.getKeyCode(), event);
14927 }
14928
14929 /**
14930 * Dispatch a key event to the next view on the focus path. This path runs
14931 * from the top of the view tree down to the currently focused view. If this
14932 * view has focus, it will dispatch to itself. Otherwise it will dispatch
14933 * the next node down the focus path. This method also fires any key
14934 * listeners.
14935 *
14936 * @param event The key event to be dispatched.
14937 * @return True if the event was handled, false otherwise.
14938 */
14939 public boolean dispatchKeyEvent(KeyEvent event) {
14940 if (mInputEventConsistencyVerifier != null) {
14941 mInputEventConsistencyVerifier.onKeyEvent(event, 0);
14942 }
14943
14944 // Give any attached key listener a first crack at the event.
14945 //noinspection SimplifiableIfStatement
14946 ListenerInfo li = mListenerInfo;
14947 if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
14948 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
14949 return true;
14950 }
14951
14952 if (event.dispatch(this, mAttachInfo != null
14953 ? mAttachInfo.mKeyDispatchState : null, this)) {
14954 return true;
14955 }
14956
14957 if (mInputEventConsistencyVerifier != null) {
14958 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
14959 }
14960 return false;
14961 }
14962
14963 /**
14964 * Dispatches a key shortcut event.
14965 *
14966 * @param event The key event to be dispatched.
14967 * @return True if the event was handled by the view, false otherwise.
14968 */
14969 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
14970 return onKeyShortcut(event.getKeyCode(), event);
14971 }
14972
14973 /**
14974 * Pass the touch screen motion event down to the target view, or this
14975 * view if it is the target.
14976 *
14977 * @param event The motion event to be dispatched.
14978 * @return True if the event was handled by the view, false otherwise.
14979 */
14980 public boolean dispatchTouchEvent(MotionEvent event) {
14981 // If the event should be handled by accessibility focus first.
14982 if (event.isTargetAccessibilityFocus()) {
14983 // We don't have focus or no virtual descendant has it, do not handle the event.
14984 if (!isAccessibilityFocusedViewOrHost()) {
14985 return false;
14986 }
14987 // We have focus and got the event, then use normal event dispatch.
14988 event.setTargetAccessibilityFocus(false);
14989 }
14990 boolean result = false;
14991
14992 if (mInputEventConsistencyVerifier != null) {
14993 mInputEventConsistencyVerifier.onTouchEvent(event, 0);
14994 }
14995
14996 final int actionMasked = event.getActionMasked();
14997 if (actionMasked == MotionEvent.ACTION_DOWN) {
14998 // Defensive cleanup for new gesture
14999 stopNestedScroll();
15000 }
15001
15002 if (onFilterTouchEventForSecurity(event)) {
15003 if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
15004 result = true;
15005 }
15006 //noinspection SimplifiableIfStatement
15007 ListenerInfo li = mListenerInfo;
15008 if (li != null && li.mOnTouchListener != null
15009 && (mViewFlags & ENABLED_MASK) == ENABLED
15010 && li.mOnTouchListener.onTouch(this, event)) {
15011 result = true;
15012 }
15013
15014 if (!result && onTouchEvent(event)) {
15015 result = true;
15016 }
15017 }
15018
15019 if (!result && mInputEventConsistencyVerifier != null) {
15020 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
15021 }
15022
15023 // Clean up after nested scrolls if this is the end of a gesture;
15024 // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
15025 // of the gesture.
15026 if (actionMasked == MotionEvent.ACTION_UP ||
15027 actionMasked == MotionEvent.ACTION_CANCEL ||
15028 (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
15029 stopNestedScroll();
15030 }
15031
15032 return result;
15033 }
15034
15035 boolean isAccessibilityFocusedViewOrHost() {
15036 return isAccessibilityFocused() || (getViewRootImpl() != null && getViewRootImpl()
15037 .getAccessibilityFocusedHost() == this);
15038 }
15039
15040 /**
15041 * Returns whether this view can receive pointer events.
15042 *
15043 * @return {@code true} if this view can receive pointer events.
15044 * @hide
15045 */
15046 protected boolean canReceivePointerEvents() {
15047 return (mViewFlags & VISIBILITY_MASK) == VISIBLE || getAnimation() != null;
15048 }
15049
15050 /**
15051 * Filter the touch event to apply security policies.
15052 *
15053 * @param event The motion event to be filtered.
15054 * @return True if the event should be dispatched, false if the event should be dropped.
15055 *
15056 * @see #getFilterTouchesWhenObscured
15057 */
15058 public boolean onFilterTouchEventForSecurity(MotionEvent event) {
15059 //noinspection RedundantIfStatement
15060 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
15061 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
15062 // Window is obscured, drop this touch.
15063 return false;
15064 }
15065 return true;
15066 }
15067
15068 /**
15069 * Pass a trackball motion event down to the focused view.
15070 *
15071 * @param event The motion event to be dispatched.
15072 * @return True if the event was handled by the view, false otherwise.
15073 */
15074 public boolean dispatchTrackballEvent(MotionEvent event) {
15075 if (mInputEventConsistencyVerifier != null) {
15076 mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
15077 }
15078
15079 return onTrackballEvent(event);
15080 }
15081
15082 /**
15083 * Pass a captured pointer event down to the focused view.
15084 *
15085 * @param event The motion event to be dispatched.
15086 * @return True if the event was handled by the view, false otherwise.
15087 */
15088 public boolean dispatchCapturedPointerEvent(MotionEvent event) {
15089 if (!hasPointerCapture()) {
15090 return false;
15091 }
15092 //noinspection SimplifiableIfStatement
15093 ListenerInfo li = mListenerInfo;
15094 if (li != null && li.mOnCapturedPointerListener != null
15095 && li.mOnCapturedPointerListener.onCapturedPointer(this, event)) {
15096 return true;
15097 }
15098 return onCapturedPointerEvent(event);
15099 }
15100
15101 /**
15102 * Dispatch a generic motion event.
15103 * <p>
15104 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
15105 * are delivered to the view under the pointer. All other generic motion events are
15106 * delivered to the focused view. Hover events are handled specially and are delivered
15107 * to {@link #onHoverEvent(MotionEvent)}.
15108 * </p>
15109 *
15110 * @param event The motion event to be dispatched.
15111 * @return True if the event was handled by the view, false otherwise.
15112 */
15113 public boolean dispatchGenericMotionEvent(MotionEvent event) {
15114 if (mInputEventConsistencyVerifier != null) {
15115 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
15116 }
15117
15118 final int source = event.getSource();
15119 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
15120 final int action = event.getAction();
15121 if (action == MotionEvent.ACTION_HOVER_ENTER
15122 || action == MotionEvent.ACTION_HOVER_MOVE
15123 || action == MotionEvent.ACTION_HOVER_EXIT) {
15124 if (dispatchHoverEvent(event)) {
15125 return true;
15126 }
15127 } else if (dispatchGenericPointerEvent(event)) {
15128 return true;
15129 }
15130 } else if (dispatchGenericFocusedEvent(event)) {
15131 return true;
15132 }
15133
15134 if (dispatchGenericMotionEventInternal(event)) {
15135 return true;
15136 }
15137
15138 if (mInputEventConsistencyVerifier != null) {
15139 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
15140 }
15141 return false;
15142 }
15143
15144 private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
15145 //noinspection SimplifiableIfStatement
15146 ListenerInfo li = mListenerInfo;
15147 if (li != null && li.mOnGenericMotionListener != null
15148 && (mViewFlags & ENABLED_MASK) == ENABLED
15149 && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
15150 return true;
15151 }
15152
15153 if (onGenericMotionEvent(event)) {
15154 return true;
15155 }
15156
15157 final int actionButton = event.getActionButton();
15158 switch (event.getActionMasked()) {
15159 case MotionEvent.ACTION_BUTTON_PRESS:
15160 if (isContextClickable() && !mInContextButtonPress && !mHasPerformedLongPress
15161 && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY
15162 || actionButton == MotionEvent.BUTTON_SECONDARY)) {
15163 if (performContextClick(event.getX(), event.getY())) {
15164 mInContextButtonPress = true;
15165 setPressed(true, event.getX(), event.getY());
15166 removeTapCallback();
15167 removeLongPressCallback();
15168 return true;
15169 }
15170 }
15171 break;
15172
15173 case MotionEvent.ACTION_BUTTON_RELEASE:
15174 if (mInContextButtonPress && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY
15175 || actionButton == MotionEvent.BUTTON_SECONDARY)) {
15176 mInContextButtonPress = false;
15177 mIgnoreNextUpEvent = true;
15178 }
15179 break;
15180 }
15181
15182 if (mInputEventConsistencyVerifier != null) {
15183 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
15184 }
15185 return false;
15186 }
15187
15188 /**
15189 * Dispatch a hover event.
15190 * <p>
15191 * Do not call this method directly.
15192 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
15193 * </p>
15194 *
15195 * @param event The motion event to be dispatched.
15196 * @return True if the event was handled by the view, false otherwise.
15197 */
15198 protected boolean dispatchHoverEvent(MotionEvent event) {
15199 ListenerInfo li = mListenerInfo;
15200 //noinspection SimplifiableIfStatement
15201 if (li != null && li.mOnHoverListener != null
15202 && (mViewFlags & ENABLED_MASK) == ENABLED
15203 && li.mOnHoverListener.onHover(this, event)) {
15204 return true;
15205 }
15206
15207 return onHoverEvent(event);
15208 }
15209
15210 /**
15211 * Returns true if the view has a child to which it has recently sent
15212 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and
15213 * it does not have a hovered child, then it must be the innermost hovered view.
15214 * @hide
15215 */
15216 protected boolean hasHoveredChild() {
15217 return false;
15218 }
15219
15220 /**
15221 * Returns true if the given point, in local coordinates, is inside the hovered child.
15222 *
15223 * @hide
15224 */
15225 protected boolean pointInHoveredChild(MotionEvent event) {
15226 return false;
15227 }
15228
15229 /**
15230 * Dispatch a generic motion event to the view under the first pointer.
15231 * <p>
15232 * Do not call this method directly.
15233 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
15234 * </p>
15235 *
15236 * @param event The motion event to be dispatched.
15237 * @return True if the event was handled by the view, false otherwise.
15238 */
15239 protected boolean dispatchGenericPointerEvent(MotionEvent event) {
15240 return false;
15241 }
15242
15243 /**
15244 * Dispatch a generic motion event to the currently focused view.
15245 * <p>
15246 * Do not call this method directly.
15247 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
15248 * </p>
15249 *
15250 * @param event The motion event to be dispatched.
15251 * @return True if the event was handled by the view, false otherwise.
15252 */
15253 protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
15254 return false;
15255 }
15256
15257 /**
15258 * Dispatch a pointer event.
15259 * <p>
15260 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
15261 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns
15262 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
15263 * and should not be expected to handle other pointing device features.
15264 * </p>
15265 *
15266 * @param event The motion event to be dispatched.
15267 * @return True if the event was handled by the view, false otherwise.
15268 * @hide
15269 */
15270 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
15271 public final boolean dispatchPointerEvent(MotionEvent event) {
15272 if (event.isTouchEvent()) {
15273 return dispatchTouchEvent(event);
15274 } else {
15275 return dispatchGenericMotionEvent(event);
15276 }
15277 }
15278
15279 /**
15280 * Called when the window containing this view gains or loses window focus.
15281 * ViewGroups should override to route to their children.
15282 *
15283 * @param hasFocus True if the window containing this view now has focus,
15284 * false otherwise.
15285 */
15286 public void dispatchWindowFocusChanged(boolean hasFocus) {
15287 onWindowFocusChanged(hasFocus);
15288 }
15289
15290 /**
15291 * Called when the window containing this view gains or loses focus. Note
15292 * that this is separate from view focus: to receive key events, both
15293 * your view and its window must have focus. If a window is displayed
15294 * on top of yours that takes input focus, then your own window will lose
15295 * focus but the view focus will remain unchanged.
15296 *
15297 * @param hasWindowFocus True if the window containing this view now has
15298 * focus, false otherwise.
15299 */
15300 public void onWindowFocusChanged(boolean hasWindowFocus) {
15301 if (!hasWindowFocus) {
15302 if (isPressed()) {
15303 setPressed(false);
15304 }
15305 mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
15306 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
15307 notifyFocusChangeToImeFocusController(false /* hasFocus */);
15308 }
15309 removeLongPressCallback();
15310 removeTapCallback();
15311 onFocusLost();
15312 } else if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
15313 notifyFocusChangeToImeFocusController(true /* hasFocus */);
15314 }
15315
15316 refreshDrawableState();
15317 }
15318
15319 /**
15320 * Returns true if this view is in a window that currently has window focus.
15321 * Note that this is not the same as the view itself having focus.
15322 *
15323 * @return True if this view is in a window that currently has window focus.
15324 */
15325 public boolean hasWindowFocus() {
15326 return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
15327 }
15328
15329 /**
15330 * @return {@code true} if this view is in a window that currently has IME focusable state.
15331 * @hide
15332 */
15333 public boolean hasImeFocus() {
15334 return getViewRootImpl() != null && getViewRootImpl().getImeFocusController().hasImeFocus();
15335 }
15336
15337 /**
15338 * Dispatch a view visibility change down the view hierarchy.
15339 * ViewGroups should override to route to their children.
15340 * @param changedView The view whose visibility changed. Could be 'this' or
15341 * an ancestor view.
15342 * @param visibility The new visibility of changedView: {@link #VISIBLE},
15343 * {@link #INVISIBLE} or {@link #GONE}.
15344 */
15345 protected void dispatchVisibilityChanged(@NonNull View changedView,
15346 @Visibility int visibility) {
15347 onVisibilityChanged(changedView, visibility);
15348 }
15349
15350 /**
15351 * Called when the visibility of the view or an ancestor of the view has
15352 * changed.
15353 *
15354 * @param changedView The view whose visibility changed. May be
15355 * {@code this} or an ancestor view.
15356 * @param visibility The new visibility, one of {@link #VISIBLE},
15357 * {@link #INVISIBLE} or {@link #GONE}.
15358 */
15359 protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) {
15360 }
15361
15362 /**
15363 * Dispatch a hint about whether this view is displayed. For instance, when
15364 * a View moves out of the screen, it might receives a display hint indicating
15365 * the view is not displayed. Applications should not <em>rely</em> on this hint
15366 * as there is no guarantee that they will receive one.
15367 *
15368 * @param hint A hint about whether or not this view is displayed:
15369 * {@link #VISIBLE} or {@link #INVISIBLE}.
15370 */
15371 public void dispatchDisplayHint(@Visibility int hint) {
15372 onDisplayHint(hint);
15373 }
15374
15375 /**
15376 * Gives this view a hint about whether is displayed or not. For instance, when
15377 * a View moves out of the screen, it might receives a display hint indicating
15378 * the view is not displayed. Applications should not <em>rely</em> on this hint
15379 * as there is no guarantee that they will receive one.
15380 *
15381 * @param hint A hint about whether or not this view is displayed:
15382 * {@link #VISIBLE} or {@link #INVISIBLE}.
15383 */
15384 protected void onDisplayHint(@Visibility int hint) {
15385 }
15386
15387 /**
15388 * Dispatch a window visibility change down the view hierarchy.
15389 * ViewGroups should override to route to their children.
15390 *
15391 * @param visibility The new visibility of the window.
15392 *
15393 * @see #onWindowVisibilityChanged(int)
15394 */
15395 public void dispatchWindowVisibilityChanged(@Visibility int visibility) {
15396 onWindowVisibilityChanged(visibility);
15397 }
15398
15399 /**
15400 * Called when the window containing has change its visibility
15401 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note
15402 * that this tells you whether or not your window is being made visible
15403 * to the window manager; this does <em>not</em> tell you whether or not
15404 * your window is obscured by other windows on the screen, even if it
15405 * is itself visible.
15406 *
15407 * @param visibility The new visibility of the window.
15408 */
15409 protected void onWindowVisibilityChanged(@Visibility int visibility) {
15410 if (visibility == VISIBLE) {
15411 initialAwakenScrollBars();
15412 }
15413 }
15414
15415 /**
15416 * @return true if this view and all ancestors are visible as of the last
15417 * {@link #onVisibilityAggregated(boolean)} call.
15418 *
15419 * @hide
15420 */
15421 public boolean isAggregatedVisible() {
15422 return (mPrivateFlags3 & PFLAG3_AGGREGATED_VISIBLE) != 0;
15423 }
15424
15425 /**
15426 * Internal dispatching method for {@link #onVisibilityAggregated}. Overridden by
15427 * ViewGroup. Intended to only be called when {@link #isAttachedToWindow()},
15428 * {@link #getWindowVisibility()} is {@link #VISIBLE} and this view's parent {@link #isShown()}.
15429 *
15430 * @param isVisible true if this view's visibility to the user is uninterrupted by its
15431 * ancestors or by window visibility
15432 * @return true if this view is visible to the user, not counting clipping or overlapping
15433 */
15434 boolean dispatchVisibilityAggregated(boolean isVisible) {
15435 final boolean thisVisible = getVisibility() == VISIBLE;
15436 // If we're not visible but something is telling us we are, ignore it.
15437 if (thisVisible || !isVisible) {
15438 onVisibilityAggregated(isVisible);
15439 }
15440 return thisVisible && isVisible;
15441 }
15442
15443 /**
15444 * Called when the user-visibility of this View is potentially affected by a change
15445 * to this view itself, an ancestor view or the window this view is attached to.
15446 *
15447 * @param isVisible true if this view and all of its ancestors are {@link #VISIBLE}
15448 * and this view's window is also visible
15449 */
15450 @CallSuper
15451 public void onVisibilityAggregated(boolean isVisible) {
15452 // Update our internal visibility tracking so we can detect changes
15453 boolean oldVisible = isAggregatedVisible();
15454 mPrivateFlags3 = isVisible ? (mPrivateFlags3 | PFLAG3_AGGREGATED_VISIBLE)
15455 : (mPrivateFlags3 & ~PFLAG3_AGGREGATED_VISIBLE);
15456 if (isVisible && mAttachInfo != null) {
15457 initialAwakenScrollBars();
15458 }
15459
15460 final Drawable dr = mBackground;
15461 if (dr != null && isVisible != dr.isVisible()) {
15462 dr.setVisible(isVisible, false);
15463 }
15464 final Drawable hl = mDefaultFocusHighlight;
15465 if (hl != null && isVisible != hl.isVisible()) {
15466 hl.setVisible(isVisible, false);
15467 }
15468 final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
15469 if (fg != null && isVisible != fg.isVisible()) {
15470 fg.setVisible(isVisible, false);
15471 }
15472
15473 if (isAutofillable()) {
15474 AutofillManager afm = getAutofillManager();
15475
15476 if (afm != null && getAutofillViewId() > LAST_APP_AUTOFILL_ID) {
15477 if (mVisibilityChangeForAutofillHandler != null) {
15478 mVisibilityChangeForAutofillHandler.removeMessages(0);
15479 }
15480
15481 // If the view is in the background but still part of the hierarchy this is called
15482 // with isVisible=false. Hence visibility==false requires further checks
15483 if (isVisible) {
15484 afm.notifyViewVisibilityChanged(this, true);
15485 } else {
15486 if (mVisibilityChangeForAutofillHandler == null) {
15487 mVisibilityChangeForAutofillHandler =
15488 new VisibilityChangeForAutofillHandler(afm, this);
15489 }
15490 // Let current operation (e.g. removal of the view from the hierarchy)
15491 // finish before checking state
15492 mVisibilityChangeForAutofillHandler.obtainMessage(0, this).sendToTarget();
15493 }
15494 }
15495 }
15496
15497 if (isVisible != oldVisible) {
15498 if (isAccessibilityPane()) {
15499 notifyViewAccessibilityStateChangedIfNeeded(isVisible
15500 ? AccessibilityEvent.CONTENT_CHANGE_TYPE_PANE_APPEARED
15501 : AccessibilityEvent.CONTENT_CHANGE_TYPE_PANE_DISAPPEARED);
15502 }
15503
15504 notifyAppearedOrDisappearedForContentCaptureIfNeeded(isVisible);
15505
15506 if (!getSystemGestureExclusionRects().isEmpty()) {
15507 postUpdate(this::updateSystemGestureExclusionRects);
15508 }
15509
15510 if (!collectPreferKeepClearRects().isEmpty()) {
15511 postUpdate(this::updateKeepClearRects);
15512 }
15513 }
15514 }
15515
15516 /**
15517 * Returns the current visibility of the window this view is attached to
15518 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
15519 *
15520 * @return Returns the current visibility of the view's window.
15521 */
15522 @Visibility
15523 public int getWindowVisibility() {
15524 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
15525 }
15526
15527 /**
15528 * Retrieve the overall visible display size in which the window this view is
15529 * attached to has been positioned in. This takes into account screen
15530 * decorations above the window, for both cases where the window itself
15531 * is being position inside of them or the window is being placed under
15532 * then and covered insets are used for the window to position its content
15533 * inside. In effect, this tells you the available area where content can
15534 * be placed and remain visible to users.
15535 *
15536 * @param outRect Filled in with the visible display frame. If the view
15537 * is not attached to a window, this is simply the raw display size.
15538 */
15539 public void getWindowVisibleDisplayFrame(Rect outRect) {
15540 if (mAttachInfo != null) {
15541 mAttachInfo.mViewRootImpl.getWindowVisibleDisplayFrame(outRect);
15542 return;
15543 }
15544 // The view is not attached to a display so we don't have a context.
15545 // Make a best guess about the display size.
15546 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
15547 d.getRectSize(outRect);
15548 }
15549
15550 /**
15551 * Like {@link #getWindowVisibleDisplayFrame}, but returns the "full" display frame this window
15552 * is currently in without any insets.
15553 *
15554 * @hide
15555 */
15556 @UnsupportedAppUsage
15557 public void getWindowDisplayFrame(Rect outRect) {
15558 if (mAttachInfo != null) {
15559 mAttachInfo.mViewRootImpl.getDisplayFrame(outRect);
15560 return;
15561 }
15562 // The view is not attached to a display so we don't have a context.
15563 // Make a best guess about the display size.
15564 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
15565 d.getRectSize(outRect);
15566 }
15567
15568 /**
15569 * Dispatch a notification about a resource configuration change down
15570 * the view hierarchy.
15571 * ViewGroups should override to route to their children.
15572 *
15573 * @param newConfig The new resource configuration.
15574 *
15575 * @see #onConfigurationChanged(android.content.res.Configuration)
15576 */
15577 public void dispatchConfigurationChanged(Configuration newConfig) {
15578 onConfigurationChanged(newConfig);
15579 }
15580
15581 /**
15582 * Called when the current configuration of the resources being used
15583 * by the application have changed. You can use this to decide when
15584 * to reload resources that can changed based on orientation and other
15585 * configuration characteristics. You only need to use this if you are
15586 * not relying on the normal {@link android.app.Activity} mechanism of
15587 * recreating the activity instance upon a configuration change.
15588 *
15589 * @param newConfig The new resource configuration.
15590 */
15591 protected void onConfigurationChanged(Configuration newConfig) {
15592 }
15593
15594 /**
15595 * Private function to aggregate all per-view attributes in to the view
15596 * root.
15597 */
15598 void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
15599 performCollectViewAttributes(attachInfo, visibility);
15600 }
15601
15602 void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
15603 if ((visibility & VISIBILITY_MASK) == VISIBLE) {
15604 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
15605 attachInfo.mKeepScreenOn = true;
15606 }
15607 attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
15608 ListenerInfo li = mListenerInfo;
15609 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
15610 attachInfo.mHasSystemUiListeners = true;
15611 }
15612 }
15613 }
15614
15615 void needGlobalAttributesUpdate(boolean force) {
15616 final AttachInfo ai = mAttachInfo;
15617 if (ai != null && !ai.mRecomputeGlobalAttributes) {
15618 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
15619 || ai.mHasSystemUiListeners) {
15620 ai.mRecomputeGlobalAttributes = true;
15621 }
15622 }
15623 }
15624
15625 /**
15626 * Returns whether the device is currently in touch mode. Touch mode is entered
15627 * once the user begins interacting with the device by touch, and affects various
15628 * things like whether focus is always visible to the user.
15629 *
15630 * @return Whether the device is in touch mode.
15631 */
15632 @ViewDebug.ExportedProperty
15633 public boolean isInTouchMode() {
15634 if (mAttachInfo != null) {
15635 return mAttachInfo.mInTouchMode;
15636 } else {
15637 return ViewRootImpl.isInTouchMode();
15638 }
15639 }
15640
15641 /**
15642 * Returns the context the view is running in, through which it can
15643 * access the current theme, resources, etc.
15644 *
15645 * @return The view's Context.
15646 */
15647 @ViewDebug.CapturedViewProperty
15648 @UiContext
15649 public final Context getContext() {
15650 return mContext;
15651 }
15652
15653 /**
15654 * Handle a key event before it is processed by any input method
15655 * associated with the view hierarchy. This can be used to intercept
15656 * key events in special situations before the IME consumes them; a
15657 * typical example would be handling the BACK key to update the application's
15658 * UI instead of allowing the IME to see it and close itself.
15659 *
15660 * @param keyCode The value in event.getKeyCode().
15661 * @param event Description of the key event.
15662 * @return If you handled the event, return true. If you want to allow the
15663 * event to be handled by the next receiver, return false.
15664 */
15665 public boolean onKeyPreIme(int keyCode, KeyEvent event) {
15666 return false;
15667 }
15668
15669 /**
15670 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
15671 * KeyEvent.Callback.onKeyDown()}: perform press of the view
15672 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
15673 * is released, if the view is enabled and clickable.
15674 * <p>
15675 * Key presses in software keyboards will generally NOT trigger this
15676 * listener, although some may elect to do so in some situations. Do not
15677 * rely on this to catch software key presses.
15678 *
15679 * @param keyCode a key code that represents the button pressed, from
15680 * {@link android.view.KeyEvent}
15681 * @param event the KeyEvent object that defines the button action
15682 */
15683 public boolean onKeyDown(int keyCode, KeyEvent event) {
15684 if (KeyEvent.isConfirmKey(keyCode) && event.hasNoModifiers()) {
15685 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
15686 return true;
15687 }
15688
15689 if (event.getRepeatCount() == 0) {
15690 // Long clickable items don't necessarily have to be clickable.
15691 final boolean clickable = (mViewFlags & CLICKABLE) == CLICKABLE
15692 || (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
15693 if (clickable || (mViewFlags & TOOLTIP) == TOOLTIP) {
15694 // For the purposes of menu anchoring and drawable hotspots,
15695 // key events are considered to be at the center of the view.
15696 final float x = getWidth() / 2f;
15697 final float y = getHeight() / 2f;
15698 if (clickable) {
15699 setPressed(true, x, y);
15700 }
15701 checkForLongClick(
15702 ViewConfiguration.getLongPressTimeout(),
15703 x,
15704 y,
15705 // This is not a touch gesture -- do not classify it as one.
15706 TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__UNKNOWN_CLASSIFICATION);
15707 return true;
15708 }
15709 }
15710 }
15711
15712 return false;
15713 }
15714
15715 /**
15716 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
15717 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
15718 * the event).
15719 * <p>Key presses in software keyboards will generally NOT trigger this listener,
15720 * although some may elect to do so in some situations. Do not rely on this to
15721 * catch software key presses.
15722 */
15723 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
15724 return false;
15725 }
15726
15727 /**
15728 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
15729 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
15730 * when {@link KeyEvent#KEYCODE_DPAD_CENTER}, {@link KeyEvent#KEYCODE_ENTER}
15731 * or {@link KeyEvent#KEYCODE_SPACE} is released.
15732 * <p>Key presses in software keyboards will generally NOT trigger this listener,
15733 * although some may elect to do so in some situations. Do not rely on this to
15734 * catch software key presses.
15735 *
15736 * @param keyCode A key code that represents the button pressed, from
15737 * {@link android.view.KeyEvent}.
15738 * @param event The KeyEvent object that defines the button action.
15739 */
15740 public boolean onKeyUp(int keyCode, KeyEvent event) {
15741 if (KeyEvent.isConfirmKey(keyCode) && event.hasNoModifiers()) {
15742 if ((mViewFlags & ENABLED_MASK) == DISABLED) {
15743 return true;
15744 }
15745 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
15746 setPressed(false);
15747
15748 if (!mHasPerformedLongPress) {
15749 // This is a tap, so remove the longpress check
15750 removeLongPressCallback();
15751 if (!event.isCanceled()) {
15752 return performClickInternal();
15753 }
15754 }
15755 }
15756 }
15757 return false;
15758 }
15759
15760 /**
15761 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
15762 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
15763 * the event).
15764 * <p>Key presses in software keyboards will generally NOT trigger this listener,
15765 * although some may elect to do so in some situations. Do not rely on this to
15766 * catch software key presses.
15767 *
15768 * @param keyCode A key code that represents the button pressed, from
15769 * {@link android.view.KeyEvent}.
15770 * @param repeatCount The number of times the action was made.
15771 * @param event The KeyEvent object that defines the button action.
15772 */
15773 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
15774 return false;
15775 }
15776
15777 /**
15778 * Called on the focused view when a key shortcut event is not handled.
15779 * Override this method to implement local key shortcuts for the View.
15780 * Key shortcuts can also be implemented by setting the
15781 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
15782 *
15783 * @param keyCode The value in event.getKeyCode().
15784 * @param event Description of the key event.
15785 * @return If you handled the event, return true. If you want to allow the
15786 * event to be handled by the next receiver, return false.
15787 */
15788 public boolean onKeyShortcut(int keyCode, KeyEvent event) {
15789 return false;
15790 }
15791
15792 /**
15793 * Check whether the called view is a text editor, in which case it
15794 * would make sense to automatically display a soft input window for
15795 * it. Subclasses should override this if they implement
15796 * {@link #onCreateInputConnection(EditorInfo)} to return true if
15797 * a call on that method would return a non-null InputConnection, and
15798 * they are really a first-class editor that the user would normally
15799 * start typing on when the go into a window containing your view.
15800 *
15801 * <p>The default implementation always returns false. This does
15802 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
15803 * will not be called or the user can not otherwise perform edits on your
15804 * view; it is just a hint to the system that this is not the primary
15805 * purpose of this view.
15806 *
15807 * @return Returns true if this view is a text editor, else false.
15808 */
15809 public boolean onCheckIsTextEditor() {
15810 return false;
15811 }
15812
15813 /**
15814 * Create a new InputConnection for an InputMethod to interact
15815 * with the view. The default implementation returns null, since it doesn't
15816 * support input methods. You can override this to implement such support.
15817 * This is only needed for views that take focus and text input.
15818 *
15819 * <p>When implementing this, you probably also want to implement
15820 * {@link #onCheckIsTextEditor()} to indicate you will return a
15821 * non-null InputConnection.</p>
15822 *
15823 * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo}
15824 * object correctly and in its entirety, so that the connected IME can rely
15825 * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart}
15826 * and {@link android.view.inputmethod.EditorInfo#initialSelEnd} members
15827 * must be filled in with the correct cursor position for IMEs to work correctly
15828 * with your application.</p>
15829 *
15830 * @param outAttrs Fill in with attribute information about the connection.
15831 */
15832 public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
15833 return null;
15834 }
15835
15836 /**
15837 * Called by the {@link android.view.inputmethod.InputMethodManager} to notify the application
15838 * that the system has successfully initialized an {@link InputConnection} and it is ready for
15839 * use.
15840 *
15841 * <p>The default implementation does nothing, since a view doesn't support input methods by
15842 * default (see {@link #onCreateInputConnection}).
15843 *
15844 * @param inputConnection The {@link InputConnection} from {@link #onCreateInputConnection},
15845 * after it's been fully initialized by the system.
15846 * @param editorInfo The {@link EditorInfo} that was used to create the {@link InputConnection}.
15847 * @param handler The dedicated {@link Handler} on which IPC method calls from input methods
15848 * will be dispatched. This is the handler returned by {@link InputConnection#getHandler()}. If
15849 * that method returns null, this parameter will be null also.
15850 *
15851 * @hide
15852 */
15853 public void onInputConnectionOpenedInternal(@NonNull InputConnection inputConnection,
15854 @NonNull EditorInfo editorInfo, @Nullable Handler handler) {}
15855
15856 /**
15857 * Called by the {@link android.view.inputmethod.InputMethodManager} to notify the application
15858 * that the {@link InputConnection} has been closed.
15859 *
15860 * <p>The default implementation does nothing, since a view doesn't support input methods by
15861 * default (see {@link #onCreateInputConnection}).
15862 *
15863 * <p><strong>Note:</strong> This callback is not invoked if the view is already detached when
15864 * the {@link InputConnection} is closed or the connection is not valid and managed by
15865 * {@link com.android.server.inputmethod.InputMethodManagerService}.
15866 * TODO(b/170645312): Before un-hiding this API, handle the detached view scenario.
15867 *
15868 * @hide
15869 */
15870 public void onInputConnectionClosedInternal() {}
15871
15872 /**
15873 * Called by the {@link android.view.inputmethod.InputMethodManager}
15874 * when a view who is not the current
15875 * input connection target is trying to make a call on the manager. The
15876 * default implementation returns false; you can override this to return
15877 * true for certain views if you are performing InputConnection proxying
15878 * to them.
15879 * @param view The View that is making the InputMethodManager call.
15880 * @return Return true to allow the call, false to reject.
15881 */
15882 public boolean checkInputConnectionProxy(View view) {
15883 return false;
15884 }
15885
15886 /**
15887 * Show the context menu for this view. It is not safe to hold on to the
15888 * menu after returning from this method.
15889 *
15890 * You should normally not overload this method. Overload
15891 * {@link #onCreateContextMenu(ContextMenu)} or define an
15892 * {@link OnCreateContextMenuListener} to add items to the context menu.
15893 *
15894 * @param menu The context menu to populate
15895 */
15896 public void createContextMenu(ContextMenu menu) {
15897 ContextMenuInfo menuInfo = getContextMenuInfo();
15898
15899 // Sets the current menu info so all items added to menu will have
15900 // my extra info set.
15901 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
15902
15903 onCreateContextMenu(menu);
15904 ListenerInfo li = mListenerInfo;
15905 if (li != null && li.mOnCreateContextMenuListener != null) {
15906 li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
15907 }
15908
15909 // Clear the extra information so subsequent items that aren't mine don't
15910 // have my extra info.
15911 ((MenuBuilder)menu).setCurrentMenuInfo(null);
15912
15913 if (mParent != null) {
15914 mParent.createContextMenu(menu);
15915 }
15916 }
15917
15918 /**
15919 * Views should implement this if they have extra information to associate
15920 * with the context menu. The return result is supplied as a parameter to
15921 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
15922 * callback.
15923 *
15924 * @return Extra information about the item for which the context menu
15925 * should be shown. This information will vary across different
15926 * subclasses of View.
15927 */
15928 protected ContextMenuInfo getContextMenuInfo() {
15929 return null;
15930 }
15931
15932 /**
15933 * Views should implement this if the view itself is going to add items to
15934 * the context menu.
15935 *
15936 * @param menu the context menu to populate
15937 */
15938 protected void onCreateContextMenu(ContextMenu menu) {
15939 }
15940
15941 /**
15942 * Implement this method to handle trackball motion events. The
15943 * <em>relative</em> movement of the trackball since the last event
15944 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
15945 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so
15946 * that a movement of 1 corresponds to the user pressing one DPAD key (so
15947 * they will often be fractional values, representing the more fine-grained
15948 * movement information available from a trackball).
15949 *
15950 * @param event The motion event.
15951 * @return True if the event was handled, false otherwise.
15952 */
15953 public boolean onTrackballEvent(MotionEvent event) {
15954 return false;
15955 }
15956
15957 /**
15958 * Implement this method to handle generic motion events.
15959 * <p>
15960 * Generic motion events describe joystick movements, mouse hovers, track pad
15961 * touches, scroll wheel movements and other input events. The
15962 * {@link MotionEvent#getSource() source} of the motion event specifies
15963 * the class of input that was received. Implementations of this method
15964 * must examine the bits in the source before processing the event.
15965 * The following code example shows how this is done.
15966 * </p><p>
15967 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
15968 * are delivered to the view under the pointer. All other generic motion events are
15969 * delivered to the focused view.
15970 * </p>
15971 * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
15972 * if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
15973 * if (event.getAction() == MotionEvent.ACTION_MOVE) {
15974 * // process the joystick movement...
15975 * return true;
15976 * }
15977 * }
15978 * if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
15979 * switch (event.getAction()) {
15980 * case MotionEvent.ACTION_HOVER_MOVE:
15981 * // process the mouse hover movement...
15982 * return true;
15983 * case MotionEvent.ACTION_SCROLL:
15984 * // process the scroll wheel movement...
15985 * return true;
15986 * }
15987 * }
15988 * return super.onGenericMotionEvent(event);
15989 * }</pre>
15990 *
15991 * @param event The generic motion event being processed.
15992 * @return True if the event was handled, false otherwise.
15993 */
15994 public boolean onGenericMotionEvent(MotionEvent event) {
15995 return false;
15996 }
15997
15998 /**
15999 * Dispatching hover events to {@link TouchDelegate} to improve accessibility.
16000 * <p>
16001 * This method is dispatching hover events to the delegate target to support explore by touch.
16002 * Similar to {@link ViewGroup#dispatchTouchEvent}, this method send proper hover events to
16003 * the delegate target according to the pointer and the touch area of the delegate while touch
16004 * exploration enabled.
16005 * </p>
16006 *
16007 * @param event The motion event dispatch to the delegate target.
16008 * @return True if the event was handled, false otherwise.
16009 *
16010 * @see #onHoverEvent
16011 */
16012 private boolean dispatchTouchExplorationHoverEvent(MotionEvent event) {
16013 final AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
16014 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
16015 return false;
16016 }
16017
16018 final boolean oldHoveringTouchDelegate = mHoveringTouchDelegate;
16019 final int action = event.getActionMasked();
16020 boolean pointInDelegateRegion = false;
16021 boolean handled = false;
16022
16023 final AccessibilityNodeInfo.TouchDelegateInfo info = mTouchDelegate.getTouchDelegateInfo();
16024 for (int i = 0; i < info.getRegionCount(); i++) {
16025 Region r = info.getRegionAt(i);
16026 if (r.contains((int) event.getX(), (int) event.getY())) {
16027 pointInDelegateRegion = true;
16028 }
16029 }
16030
16031 // Explore by touch should dispatch events to children under the pointer first if any
16032 // before dispatching to TouchDelegate. For non-hoverable views that do not consume
16033 // hover events but receive accessibility focus, it should also not delegate to these
16034 // views when hovered.
16035 if (!oldHoveringTouchDelegate) {
16036 if ((action == MotionEvent.ACTION_HOVER_ENTER
16037 || action == MotionEvent.ACTION_HOVER_MOVE)
16038 && !pointInHoveredChild(event)
16039 && pointInDelegateRegion) {
16040 mHoveringTouchDelegate = true;
16041 }
16042 } else {
16043 if (action == MotionEvent.ACTION_HOVER_EXIT
16044 || (action == MotionEvent.ACTION_HOVER_MOVE
16045 && (pointInHoveredChild(event) || !pointInDelegateRegion))) {
16046 mHoveringTouchDelegate = false;
16047 }
16048 }
16049 switch (action) {
16050 case MotionEvent.ACTION_HOVER_MOVE:
16051 if (oldHoveringTouchDelegate && mHoveringTouchDelegate) {
16052 // Inside bounds, dispatch as is.
16053 handled = mTouchDelegate.onTouchExplorationHoverEvent(event);
16054 } else if (!oldHoveringTouchDelegate && mHoveringTouchDelegate) {
16055 // Moving inbound, synthesize hover enter.
16056 MotionEvent eventNoHistory = (event.getHistorySize() == 0)
16057 ? event : MotionEvent.obtainNoHistory(event);
16058 eventNoHistory.setAction(MotionEvent.ACTION_HOVER_ENTER);
16059 handled = mTouchDelegate.onTouchExplorationHoverEvent(eventNoHistory);
16060 eventNoHistory.setAction(action);
16061 handled |= mTouchDelegate.onTouchExplorationHoverEvent(eventNoHistory);
16062 } else if (oldHoveringTouchDelegate && !mHoveringTouchDelegate) {
16063 // Moving outbound, synthesize hover exit.
16064 final boolean hoverExitPending = event.isHoverExitPending();
16065 event.setHoverExitPending(true);
16066 mTouchDelegate.onTouchExplorationHoverEvent(event);
16067 MotionEvent eventNoHistory = (event.getHistorySize() == 0)
16068 ? event : MotionEvent.obtainNoHistory(event);
16069 eventNoHistory.setHoverExitPending(hoverExitPending);
16070 eventNoHistory.setAction(MotionEvent.ACTION_HOVER_EXIT);
16071 mTouchDelegate.onTouchExplorationHoverEvent(eventNoHistory);
16072 } // else: outside bounds, do nothing.
16073 break;
16074 case MotionEvent.ACTION_HOVER_ENTER:
16075 if (!oldHoveringTouchDelegate && mHoveringTouchDelegate) {
16076 handled = mTouchDelegate.onTouchExplorationHoverEvent(event);
16077 }
16078 break;
16079 case MotionEvent.ACTION_HOVER_EXIT:
16080 if (oldHoveringTouchDelegate) {
16081 mTouchDelegate.onTouchExplorationHoverEvent(event);
16082 }
16083 break;
16084 }
16085 return handled;
16086 }
16087
16088 /**
16089 * Implement this method to handle hover events.
16090 * <p>
16091 * This method is called whenever a pointer is hovering into, over, or out of the
16092 * bounds of a view and the view is not currently being touched.
16093 * Hover events are represented as pointer events with action
16094 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
16095 * or {@link MotionEvent#ACTION_HOVER_EXIT}.
16096 * </p>
16097 * <ul>
16098 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
16099 * when the pointer enters the bounds of the view.</li>
16100 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
16101 * when the pointer has already entered the bounds of the view and has moved.</li>
16102 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
16103 * when the pointer has exited the bounds of the view or when the pointer is
16104 * about to go down due to a button click, tap, or similar user action that
16105 * causes the view to be touched.</li>
16106 * </ul>
16107 * <p>
16108 * The view should implement this method to return true to indicate that it is
16109 * handling the hover event, such as by changing its drawable state.
16110 * </p><p>
16111 * The default implementation calls {@link #setHovered} to update the hovered state
16112 * of the view when a hover enter or hover exit event is received, if the view
16113 * is enabled and is clickable. The default implementation also sends hover
16114 * accessibility events.
16115 * </p>
16116 *
16117 * @param event The motion event that describes the hover.
16118 * @return True if the view handled the hover event.
16119 *
16120 * @see #isHovered
16121 * @see #setHovered
16122 * @see #onHoverChanged
16123 */
16124 public boolean onHoverEvent(MotionEvent event) {
16125 if (mTouchDelegate != null && dispatchTouchExplorationHoverEvent(event)) {
16126 return true;
16127 }
16128
16129 // The root view may receive hover (or touch) events that are outside the bounds of
16130 // the window. This code ensures that we only send accessibility events for
16131 // hovers that are actually within the bounds of the root view.
16132 final int action = event.getActionMasked();
16133 if (!mSendingHoverAccessibilityEvents) {
16134 if ((action == MotionEvent.ACTION_HOVER_ENTER
16135 || action == MotionEvent.ACTION_HOVER_MOVE)
16136 && !hasHoveredChild()
16137 && pointInView(event.getX(), event.getY())) {
16138 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
16139 mSendingHoverAccessibilityEvents = true;
16140 }
16141 } else {
16142 if (action == MotionEvent.ACTION_HOVER_EXIT
16143 || (action == MotionEvent.ACTION_HOVER_MOVE
16144 && !pointInView(event.getX(), event.getY()))) {
16145 mSendingHoverAccessibilityEvents = false;
16146 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
16147 }
16148 }
16149
16150 if ((action == MotionEvent.ACTION_HOVER_ENTER || action == MotionEvent.ACTION_HOVER_MOVE)
16151 && event.isFromSource(InputDevice.SOURCE_MOUSE)
16152 && isOnScrollbar(event.getX(), event.getY())) {
16153 awakenScrollBars();
16154 }
16155
16156 // If we consider ourself hoverable, or if we we're already hovered,
16157 // handle changing state in response to ENTER and EXIT events.
16158 if (isHoverable() || isHovered()) {
16159 switch (action) {
16160 case MotionEvent.ACTION_HOVER_ENTER:
16161 setHovered(true);
16162 break;
16163 case MotionEvent.ACTION_HOVER_EXIT:
16164 setHovered(false);
16165 break;
16166 }
16167
16168 // Dispatch the event to onGenericMotionEvent before returning true.
16169 // This is to provide compatibility with existing applications that
16170 // handled HOVER_MOVE events in onGenericMotionEvent and that would
16171 // break because of the new default handling for hoverable views
16172 // in onHoverEvent.
16173 // Note that onGenericMotionEvent will be called by default when
16174 // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
16175 dispatchGenericMotionEventInternal(event);
16176 // The event was already handled by calling setHovered(), so always
16177 // return true.
16178 return true;
16179 }
16180
16181 return false;
16182 }
16183
16184 /**
16185 * Returns true if the view should handle {@link #onHoverEvent}
16186 * by calling {@link #setHovered} to change its hovered state.
16187 *
16188 * @return True if the view is hoverable.
16189 */
16190 private boolean isHoverable() {
16191 final int viewFlags = mViewFlags;
16192 if ((viewFlags & ENABLED_MASK) == DISABLED) {
16193 return false;
16194 }
16195
16196 return (viewFlags & CLICKABLE) == CLICKABLE
16197 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE
16198 || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
16199 }
16200
16201 /**
16202 * Returns true if the view is currently hovered.
16203 *
16204 * @return True if the view is currently hovered.
16205 *
16206 * @see #setHovered
16207 * @see #onHoverChanged
16208 */
16209 @ViewDebug.ExportedProperty
16210 public boolean isHovered() {
16211 return (mPrivateFlags & PFLAG_HOVERED) != 0;
16212 }
16213
16214 /**
16215 * Sets whether the view is currently hovered.
16216 * <p>
16217 * Calling this method also changes the drawable state of the view. This
16218 * enables the view to react to hover by using different drawable resources
16219 * to change its appearance.
16220 * </p><p>
16221 * The {@link #onHoverChanged} method is called when the hovered state changes.
16222 * </p>
16223 *
16224 * @param hovered True if the view is hovered.
16225 *
16226 * @see #isHovered
16227 * @see #onHoverChanged
16228 */
16229 public void setHovered(boolean hovered) {
16230 if (hovered) {
16231 if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
16232 mPrivateFlags |= PFLAG_HOVERED;
16233 refreshDrawableState();
16234 onHoverChanged(true);
16235 }
16236 } else {
16237 if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
16238 mPrivateFlags &= ~PFLAG_HOVERED;
16239 refreshDrawableState();
16240 onHoverChanged(false);
16241 }
16242 }
16243 }
16244
16245 /**
16246 * Implement this method to handle hover state changes.
16247 * <p>
16248 * This method is called whenever the hover state changes as a result of a
16249 * call to {@link #setHovered}.
16250 * </p>
16251 *
16252 * @param hovered The current hover state, as returned by {@link #isHovered}.
16253 *
16254 * @see #isHovered
16255 * @see #setHovered
16256 */
16257 public void onHoverChanged(boolean hovered) {
16258 }
16259
16260 /**
16261 * Handles scroll bar dragging by mouse input.
16262 *
16263 * @hide
16264 * @param event The motion event.
16265 *
16266 * @return true if the event was handled as a scroll bar dragging, false otherwise.
16267 */
16268 protected boolean handleScrollBarDragging(MotionEvent event) {
16269 if (mScrollCache == null) {
16270 return false;
16271 }
16272 final float x = event.getX();
16273 final float y = event.getY();
16274 final int action = event.getAction();
16275 if ((mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING
16276 && action != MotionEvent.ACTION_DOWN)
16277 || !event.isFromSource(InputDevice.SOURCE_MOUSE)
16278 || !event.isButtonPressed(MotionEvent.BUTTON_PRIMARY)) {
16279 mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING;
16280 return false;
16281 }
16282
16283 switch (action) {
16284 case MotionEvent.ACTION_MOVE:
16285 if (mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING) {
16286 return false;
16287 }
16288 if (mScrollCache.mScrollBarDraggingState
16289 == ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR) {
16290 final Rect bounds = mScrollCache.mScrollBarBounds;
16291 getVerticalScrollBarBounds(bounds, null);
16292 final int range = computeVerticalScrollRange();
16293 final int offset = computeVerticalScrollOffset();
16294 final int extent = computeVerticalScrollExtent();
16295
16296 final int thumbLength = ScrollBarUtils.getThumbLength(
16297 bounds.height(), bounds.width(), extent, range);
16298 final int thumbOffset = ScrollBarUtils.getThumbOffset(
16299 bounds.height(), thumbLength, extent, range, offset);
16300
16301 final float diff = y - mScrollCache.mScrollBarDraggingPos;
16302 final float maxThumbOffset = bounds.height() - thumbLength;
16303 final float newThumbOffset =
16304 Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset);
16305 final int height = getHeight();
16306 if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0
16307 && height > 0 && extent > 0) {
16308 final int newY = Math.round((range - extent)
16309 / ((float)extent / height) * (newThumbOffset / maxThumbOffset));
16310 if (newY != getScrollY()) {
16311 mScrollCache.mScrollBarDraggingPos = y;
16312 setScrollY(newY);
16313 }
16314 }
16315 return true;
16316 }
16317 if (mScrollCache.mScrollBarDraggingState
16318 == ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR) {
16319 final Rect bounds = mScrollCache.mScrollBarBounds;
16320 getHorizontalScrollBarBounds(bounds, null);
16321 final int range = computeHorizontalScrollRange();
16322 final int offset = computeHorizontalScrollOffset();
16323 final int extent = computeHorizontalScrollExtent();
16324
16325 final int thumbLength = ScrollBarUtils.getThumbLength(
16326 bounds.width(), bounds.height(), extent, range);
16327 final int thumbOffset = ScrollBarUtils.getThumbOffset(
16328 bounds.width(), thumbLength, extent, range, offset);
16329
16330 final float diff = x - mScrollCache.mScrollBarDraggingPos;
16331 final float maxThumbOffset = bounds.width() - thumbLength;
16332 final float newThumbOffset =
16333 Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset);
16334 final int width = getWidth();
16335 if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0
16336 && width > 0 && extent > 0) {
16337 final int newX = Math.round((range - extent)
16338 / ((float)extent / width) * (newThumbOffset / maxThumbOffset));
16339 if (newX != getScrollX()) {
16340 mScrollCache.mScrollBarDraggingPos = x;
16341 setScrollX(newX);
16342 }
16343 }
16344 return true;
16345 }
16346 case MotionEvent.ACTION_DOWN:
16347 if (mScrollCache.state == ScrollabilityCache.OFF) {
16348 return false;
16349 }
16350 if (isOnVerticalScrollbarThumb(x, y)) {
16351 mScrollCache.mScrollBarDraggingState =
16352 ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR;
16353 mScrollCache.mScrollBarDraggingPos = y;
16354 return true;
16355 }
16356 if (isOnHorizontalScrollbarThumb(x, y)) {
16357 mScrollCache.mScrollBarDraggingState =
16358 ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR;
16359 mScrollCache.mScrollBarDraggingPos = x;
16360 return true;
16361 }
16362 }
16363 mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING;
16364 return false;
16365 }
16366
16367 /**
16368 * Implement this method to handle touch screen motion events.
16369 * <p>
16370 * If this method is used to detect click actions, it is recommended that
16371 * the actions be performed by implementing and calling
16372 * {@link #performClick()}. This will ensure consistent system behavior,
16373 * including:
16374 * <ul>
16375 * <li>obeying click sound preferences
16376 * <li>dispatching OnClickListener calls
16377 * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
16378 * accessibility features are enabled
16379 * </ul>
16380 *
16381 * @param event The motion event.
16382 * @return True if the event was handled, false otherwise.
16383 */
16384 public boolean onTouchEvent(MotionEvent event) {
16385 final float x = event.getX();
16386 final float y = event.getY();
16387 final int viewFlags = mViewFlags;
16388 final int action = event.getAction();
16389
16390 final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE
16391 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
16392 || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
16393
16394 if ((viewFlags & ENABLED_MASK) == DISABLED
16395 && (mPrivateFlags4 & PFLAG4_ALLOW_CLICK_WHEN_DISABLED) == 0) {
16396 if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
16397 setPressed(false);
16398 }
16399 mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
16400 // A disabled view that is clickable still consumes the touch
16401 // events, it just doesn't respond to them.
16402 return clickable;
16403 }
16404 if (mTouchDelegate != null) {
16405 if (mTouchDelegate.onTouchEvent(event)) {
16406 return true;
16407 }
16408 }
16409
16410 if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
16411 switch (action) {
16412 case MotionEvent.ACTION_UP:
16413 mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
16414 if ((viewFlags & TOOLTIP) == TOOLTIP) {
16415 handleTooltipUp();
16416 }
16417 if (!clickable) {
16418 removeTapCallback();
16419 removeLongPressCallback();
16420 mInContextButtonPress = false;
16421 mHasPerformedLongPress = false;
16422 mIgnoreNextUpEvent = false;
16423 break;
16424 }
16425 boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
16426 if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
16427 // take focus if we don't have it already and we should in
16428 // touch mode.
16429 boolean focusTaken = false;
16430 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
16431 focusTaken = requestFocus();
16432 }
16433
16434 if (prepressed) {
16435 // The button is being released before we actually
16436 // showed it as pressed. Make it show the pressed
16437 // state now (before scheduling the click) to ensure
16438 // the user sees it.
16439 setPressed(true, x, y);
16440 }
16441
16442 if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
16443 // This is a tap, so remove the longpress check
16444 removeLongPressCallback();
16445
16446 // Only perform take click actions if we were in the pressed state
16447 if (!focusTaken) {
16448 // Use a Runnable and post this rather than calling
16449 // performClick directly. This lets other visual state
16450 // of the view update before click actions start.
16451 if (mPerformClick == null) {
16452 mPerformClick = new PerformClick();
16453 }
16454 if (!post(mPerformClick)) {
16455 performClickInternal();
16456 }
16457 }
16458 }
16459
16460 if (mUnsetPressedState == null) {
16461 mUnsetPressedState = new UnsetPressedState();
16462 }
16463
16464 if (prepressed) {
16465 postDelayed(mUnsetPressedState,
16466 ViewConfiguration.getPressedStateDuration());
16467 } else if (!post(mUnsetPressedState)) {
16468 // If the post failed, unpress right now
16469 mUnsetPressedState.run();
16470 }
16471
16472 removeTapCallback();
16473 }
16474 mIgnoreNextUpEvent = false;
16475 break;
16476
16477 case MotionEvent.ACTION_DOWN:
16478 if (event.getSource() == InputDevice.SOURCE_TOUCHSCREEN) {
16479 mPrivateFlags3 |= PFLAG3_FINGER_DOWN;
16480 }
16481 mHasPerformedLongPress = false;
16482
16483 if (!clickable) {
16484 checkForLongClick(
16485 ViewConfiguration.getLongPressTimeout(),
16486 x,
16487 y,
16488 TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__LONG_PRESS);
16489 break;
16490 }
16491
16492 if (performButtonActionOnTouchDown(event)) {
16493 break;
16494 }
16495
16496 // Walk up the hierarchy to determine if we're inside a scrolling container.
16497 boolean isInScrollingContainer = isInScrollingContainer();
16498
16499 // For views inside a scrolling container, delay the pressed feedback for
16500 // a short period in case this is a scroll.
16501 if (isInScrollingContainer) {
16502 mPrivateFlags |= PFLAG_PREPRESSED;
16503 if (mPendingCheckForTap == null) {
16504 mPendingCheckForTap = new CheckForTap();
16505 }
16506 mPendingCheckForTap.x = event.getX();
16507 mPendingCheckForTap.y = event.getY();
16508 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
16509 } else {
16510 // Not inside a scrolling container, so show the feedback right away
16511 setPressed(true, x, y);
16512 checkForLongClick(
16513 ViewConfiguration.getLongPressTimeout(),
16514 x,
16515 y,
16516 TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__LONG_PRESS);
16517 }
16518 break;
16519
16520 case MotionEvent.ACTION_CANCEL:
16521 if (clickable) {
16522 setPressed(false);
16523 }
16524 removeTapCallback();
16525 removeLongPressCallback();
16526 mInContextButtonPress = false;
16527 mHasPerformedLongPress = false;
16528 mIgnoreNextUpEvent = false;
16529 mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
16530 break;
16531
16532 case MotionEvent.ACTION_MOVE:
16533 if (clickable) {
16534 drawableHotspotChanged(x, y);
16535 }
16536
16537 final int motionClassification = event.getClassification();
16538 final boolean ambiguousGesture =
16539 motionClassification == MotionEvent.CLASSIFICATION_AMBIGUOUS_GESTURE;
16540 int touchSlop = mTouchSlop;
16541 if (ambiguousGesture && hasPendingLongPressCallback()) {
16542 if (!pointInView(x, y, touchSlop)) {
16543 // The default action here is to cancel long press. But instead, we
16544 // just extend the timeout here, in case the classification
16545 // stays ambiguous.
16546 removeLongPressCallback();
16547 long delay = (long) (ViewConfiguration.getLongPressTimeout()
16548 * mAmbiguousGestureMultiplier);
16549 // Subtract the time already spent
16550 delay -= event.getEventTime() - event.getDownTime();
16551 checkForLongClick(
16552 delay,
16553 x,
16554 y,
16555 TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__LONG_PRESS);
16556 }
16557 touchSlop *= mAmbiguousGestureMultiplier;
16558 }
16559
16560 // Be lenient about moving outside of buttons
16561 if (!pointInView(x, y, touchSlop)) {
16562 // Outside button
16563 // Remove any future long press/tap checks
16564 removeTapCallback();
16565 removeLongPressCallback();
16566 if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
16567 setPressed(false);
16568 }
16569 mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
16570 }
16571
16572 final boolean deepPress =
16573 motionClassification == MotionEvent.CLASSIFICATION_DEEP_PRESS;
16574 if (deepPress && hasPendingLongPressCallback()) {
16575 // process the long click action immediately
16576 removeLongPressCallback();
16577 checkForLongClick(
16578 0 /* send immediately */,
16579 x,
16580 y,
16581 TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__DEEP_PRESS);
16582 }
16583
16584 break;
16585 }
16586
16587 return true;
16588 }
16589
16590 return false;
16591 }
16592
16593 /**
16594 * @hide
16595 */
16596 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
16597 public boolean isInScrollingContainer() {
16598 ViewParent p = getParent();
16599 while (p != null && p instanceof ViewGroup) {
16600 if (((ViewGroup) p).shouldDelayChildPressedState()) {
16601 return true;
16602 }
16603 p = p.getParent();
16604 }
16605 return false;
16606 }
16607
16608 /**
16609 * Remove the longpress detection timer.
16610 */
16611 private void removeLongPressCallback() {
16612 if (mPendingCheckForLongPress != null) {
16613 removeCallbacks(mPendingCheckForLongPress);
16614 }
16615 }
16616
16617 /**
16618 * Return true if the long press callback is scheduled to run sometime in the future.
16619 * Return false if there is no scheduled long press callback at the moment.
16620 */
16621 private boolean hasPendingLongPressCallback() {
16622 if (mPendingCheckForLongPress == null) {
16623 return false;
16624 }
16625 final AttachInfo attachInfo = mAttachInfo;
16626 if (attachInfo == null) {
16627 return false;
16628 }
16629 return attachInfo.mHandler.hasCallbacks(mPendingCheckForLongPress);
16630 }
16631
16632 /**
16633 * Remove the pending click action
16634 */
16635 @UnsupportedAppUsage
16636 private void removePerformClickCallback() {
16637 if (mPerformClick != null) {
16638 removeCallbacks(mPerformClick);
16639 }
16640 }
16641
16642 /**
16643 * Remove the prepress detection timer.
16644 */
16645 private void removeUnsetPressCallback() {
16646 if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
16647 setPressed(false);
16648 removeCallbacks(mUnsetPressedState);
16649 }
16650 }
16651
16652 /**
16653 * Remove the tap detection timer.
16654 */
16655 private void removeTapCallback() {
16656 if (mPendingCheckForTap != null) {
16657 mPrivateFlags &= ~PFLAG_PREPRESSED;
16658 removeCallbacks(mPendingCheckForTap);
16659 }
16660 }
16661
16662 /**
16663 * Cancels a pending long press. Your subclass can use this if you
16664 * want the context menu to come up if the user presses and holds
16665 * at the same place, but you don't want it to come up if they press
16666 * and then move around enough to cause scrolling.
16667 */
16668 public void cancelLongPress() {
16669 removeLongPressCallback();
16670
16671 /*
16672 * The prepressed state handled by the tap callback is a display
16673 * construct, but the tap callback will post a long press callback
16674 * less its own timeout. Remove it here.
16675 */
16676 removeTapCallback();
16677 }
16678
16679 /**
16680 * Sets the TouchDelegate for this View.
16681 */
16682 public void setTouchDelegate(TouchDelegate delegate) {
16683 mTouchDelegate = delegate;
16684 }
16685
16686 /**
16687 * Gets the TouchDelegate for this View.
16688 */
16689 public TouchDelegate getTouchDelegate() {
16690 return mTouchDelegate;
16691 }
16692
16693 /**
16694 * Request unbuffered dispatch of the given stream of MotionEvents to this View.
16695 *
16696 * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input
16697 * system not batch {@link MotionEvent}s but instead deliver them as soon as they're
16698 * available. This method should only be called for touch events.
16699 *
16700 * <p class="note">This API is not intended for most applications. Buffered dispatch
16701 * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent
16702 * streams will not improve your input latency. Side effects include: increased latency,
16703 * jittery scrolls and inability to take advantage of system resampling. Talk to your input
16704 * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for
16705 * you.</p>
16706 *
16707 * To receive unbuffered events for arbitrary input device source classes, use
16708 * {@link #requestUnbufferedDispatch(int)},
16709 *
16710 * @see View#requestUnbufferedDispatch(int)
16711 */
16712 public final void requestUnbufferedDispatch(MotionEvent event) {
16713 final int action = event.getAction();
16714 if (mAttachInfo == null
16715 || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE
16716 || !event.isTouchEvent()) {
16717 return;
16718 }
16719 mAttachInfo.mUnbufferedDispatchRequested = true;
16720 }
16721
16722 /**
16723 * Request unbuffered dispatch of the given event source class to this view.
16724 * This is similar to {@link View#requestUnbufferedDispatch(MotionEvent)}, but does not
16725 * automatically terminate, and allows the specification of arbitrary input source classes.
16726 *
16727 * @param source The combined input source class to request unbuffered dispatch for. All
16728 * events coming from these source classes will not be buffered. Set to
16729 * {@link InputDevice#SOURCE_CLASS_NONE} in order to return to default behaviour.
16730 *
16731 * @see View#requestUnbufferedDispatch(MotionEvent)
16732 */
16733 public final void requestUnbufferedDispatch(@InputSourceClass int source) {
16734 if (mUnbufferedInputSource == source) {
16735 return;
16736 }
16737 mUnbufferedInputSource = source;
16738 if (mParent != null) {
16739 mParent.onDescendantUnbufferedRequested();
16740 }
16741 }
16742
16743 private boolean hasSize() {
16744 return (mBottom > mTop) && (mRight > mLeft);
16745 }
16746
16747 private boolean canTakeFocus() {
16748 return ((mViewFlags & VISIBILITY_MASK) == VISIBLE)
16749 && ((mViewFlags & FOCUSABLE) == FOCUSABLE)
16750 && ((mViewFlags & ENABLED_MASK) == ENABLED)
16751 && (sCanFocusZeroSized || !isLayoutValid() || hasSize());
16752 }
16753
16754 /**
16755 * Set flags controlling behavior of this view.
16756 *
16757 * @param flags Constant indicating the value which should be set
16758 * @param mask Constant indicating the bit range that should be changed
16759 */
16760 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
16761 void setFlags(int flags, int mask) {
16762 final boolean accessibilityEnabled =
16763 AccessibilityManager.getInstance(mContext).isEnabled();
16764 final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
16765
16766 int old = mViewFlags;
16767 mViewFlags = (mViewFlags & ~mask) | (flags & mask);
16768
16769 int changed = mViewFlags ^ old;
16770 if (changed == 0) {
16771 return;
16772 }
16773 int privateFlags = mPrivateFlags;
16774 boolean shouldNotifyFocusableAvailable = false;
16775
16776 // If focusable is auto, update the FOCUSABLE bit.
16777 int focusableChangedByAuto = 0;
16778 if (((mViewFlags & FOCUSABLE_AUTO) != 0)
16779 && (changed & (FOCUSABLE_MASK | CLICKABLE)) != 0) {
16780 // Heuristic only takes into account whether view is clickable.
16781 final int newFocus;
16782 if ((mViewFlags & CLICKABLE) != 0) {
16783 newFocus = FOCUSABLE;
16784 } else {
16785 newFocus = NOT_FOCUSABLE;
16786 }
16787 mViewFlags = (mViewFlags & ~FOCUSABLE) | newFocus;
16788 focusableChangedByAuto = (old & FOCUSABLE) ^ (newFocus & FOCUSABLE);
16789 changed = (changed & ~FOCUSABLE) | focusableChangedByAuto;
16790 }
16791
16792 /* Check if the FOCUSABLE bit has changed */
16793 if (((changed & FOCUSABLE) != 0) && ((privateFlags & PFLAG_HAS_BOUNDS) != 0)) {
16794 if (((old & FOCUSABLE) == FOCUSABLE)
16795 && ((privateFlags & PFLAG_FOCUSED) != 0)) {
16796 /* Give up focus if we are no longer focusable */
16797 clearFocus();
16798 if (mParent instanceof ViewGroup) {
16799 ((ViewGroup) mParent).clearFocusedInCluster();
16800 }
16801 } else if (((old & FOCUSABLE) == NOT_FOCUSABLE)
16802 && ((privateFlags & PFLAG_FOCUSED) == 0)) {
16803 /*
16804 * Tell the view system that we are now available to take focus
16805 * if no one else already has it.
16806 */
16807 if (mParent != null) {
16808 ViewRootImpl viewRootImpl = getViewRootImpl();
16809 if (!sAutoFocusableOffUIThreadWontNotifyParents
16810 || focusableChangedByAuto == 0
16811 || viewRootImpl == null
16812 || viewRootImpl.mThread == Thread.currentThread()) {
16813 shouldNotifyFocusableAvailable = canTakeFocus();
16814 }
16815 }
16816 }
16817 }
16818
16819 final int newVisibility = flags & VISIBILITY_MASK;
16820 if (newVisibility == VISIBLE) {
16821 if ((changed & VISIBILITY_MASK) != 0) {
16822 /*
16823 * If this view is becoming visible, invalidate it in case it changed while
16824 * it was not visible. Marking it drawn ensures that the invalidation will
16825 * go through.
16826 */
16827 mPrivateFlags |= PFLAG_DRAWN;
16828 invalidate(true);
16829
16830 needGlobalAttributesUpdate(true);
16831
16832 // a view becoming visible is worth notifying the parent about in case nothing has
16833 // focus. Even if this specific view isn't focusable, it may contain something that
16834 // is, so let the root view try to give this focus if nothing else does.
16835 shouldNotifyFocusableAvailable = hasSize();
16836 }
16837 }
16838
16839 if ((changed & ENABLED_MASK) != 0) {
16840 if ((mViewFlags & ENABLED_MASK) == ENABLED) {
16841 // a view becoming enabled should notify the parent as long as the view is also
16842 // visible and the parent wasn't already notified by becoming visible during this
16843 // setFlags invocation.
16844 shouldNotifyFocusableAvailable = canTakeFocus();
16845 } else {
16846 if (isFocused()) clearFocus();
16847 }
16848 }
16849
16850 if (shouldNotifyFocusableAvailable && mParent != null) {
16851 mParent.focusableViewAvailable(this);
16852 }
16853
16854 /* Check if the GONE bit has changed */
16855 if ((changed & GONE) != 0) {
16856 needGlobalAttributesUpdate(false);
16857 requestLayout();
16858
16859 if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
16860 if (hasFocus()) {
16861 clearFocus();
16862 if (mParent instanceof ViewGroup) {
16863 ((ViewGroup) mParent).clearFocusedInCluster();
16864 }
16865 }
16866 clearAccessibilityFocus();
16867 destroyDrawingCache();
16868 if (mParent instanceof View) {
16869 // GONE views noop invalidation, so invalidate the parent
16870 ((View) mParent).invalidate(true);
16871 }
16872 // Mark the view drawn to ensure that it gets invalidated properly the next
16873 // time it is visible and gets invalidated
16874 mPrivateFlags |= PFLAG_DRAWN;
16875 }
16876 if (mAttachInfo != null) {
16877 mAttachInfo.mViewVisibilityChanged = true;
16878 }
16879 }
16880
16881 /* Check if the VISIBLE bit has changed */
16882 if ((changed & INVISIBLE) != 0) {
16883 needGlobalAttributesUpdate(false);
16884 /*
16885 * If this view is becoming invisible, set the DRAWN flag so that
16886 * the next invalidate() will not be skipped.
16887 */
16888 mPrivateFlags |= PFLAG_DRAWN;
16889
16890 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
16891 // root view becoming invisible shouldn't clear focus and accessibility focus
16892 if (getRootView() != this) {
16893 if (hasFocus()) {
16894 clearFocus();
16895 if (mParent instanceof ViewGroup) {
16896 ((ViewGroup) mParent).clearFocusedInCluster();
16897 }
16898 }
16899 clearAccessibilityFocus();
16900 }
16901 }
16902 if (mAttachInfo != null) {
16903 mAttachInfo.mViewVisibilityChanged = true;
16904 }
16905 }
16906
16907 if ((changed & VISIBILITY_MASK) != 0) {
16908 // If the view is invisible, cleanup its display list to free up resources
16909 if (newVisibility != VISIBLE && mAttachInfo != null) {
16910 cleanupDraw();
16911 }
16912
16913 if (mParent instanceof ViewGroup) {
16914 ViewGroup parent = (ViewGroup) mParent;
16915 parent.onChildVisibilityChanged(this, (changed & VISIBILITY_MASK),
16916 newVisibility);
16917 parent.invalidate(true);
16918 } else if (mParent != null) {
16919 mParent.invalidateChild(this, null);
16920 }
16921
16922 if (mAttachInfo != null) {
16923 dispatchVisibilityChanged(this, newVisibility);
16924
16925 // Aggregated visibility changes are dispatched to attached views
16926 // in visible windows where the parent is currently shown/drawn
16927 // or the parent is not a ViewGroup (and therefore assumed to be a ViewRoot),
16928 // discounting clipping or overlapping. This makes it a good place
16929 // to change animation states.
16930 if (mParent != null && getWindowVisibility() == VISIBLE &&
16931 ((!(mParent instanceof ViewGroup)) || ((ViewGroup) mParent).isShown())) {
16932 dispatchVisibilityAggregated(newVisibility == VISIBLE);
16933 }
16934 // If this view is invisible from visible, then sending the A11y event by its
16935 // parent which is shown and has the accessibility important.
16936 if ((old & VISIBILITY_MASK) == VISIBLE) {
16937 notifySubtreeAccessibilityStateChangedByParentIfNeeded();
16938 } else {
16939 notifySubtreeAccessibilityStateChangedIfNeeded();
16940 }
16941 }
16942 }
16943
16944 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
16945 destroyDrawingCache();
16946 }
16947
16948 if ((changed & DRAWING_CACHE_ENABLED) != 0) {
16949 destroyDrawingCache();
16950 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
16951 invalidateParentCaches();
16952 }
16953
16954 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
16955 destroyDrawingCache();
16956 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
16957 }
16958
16959 if ((changed & DRAW_MASK) != 0) {
16960 if ((mViewFlags & WILL_NOT_DRAW) != 0) {
16961 if (mBackground != null
16962 || mDefaultFocusHighlight != null
16963 || (mForegroundInfo != null && mForegroundInfo.mDrawable != null)) {
16964 mPrivateFlags &= ~PFLAG_SKIP_DRAW;
16965 } else {
16966 mPrivateFlags |= PFLAG_SKIP_DRAW;
16967 }
16968 } else {
16969 mPrivateFlags &= ~PFLAG_SKIP_DRAW;
16970 }
16971 requestLayout();
16972 invalidate(true);
16973 }
16974
16975 if ((changed & KEEP_SCREEN_ON) != 0) {
16976 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
16977 mParent.recomputeViewAttributes(this);
16978 }
16979 }
16980
16981 if (accessibilityEnabled) {
16982 // If we're an accessibility pane and the visibility changed, we already have sent
16983 // a state change, so we really don't need to report other changes.
16984 if (isAccessibilityPane()) {
16985 changed &= ~VISIBILITY_MASK;
16986 }
16987 if ((changed & FOCUSABLE) != 0 || (changed & VISIBILITY_MASK) != 0
16988 || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0
16989 || (changed & CONTEXT_CLICKABLE) != 0) {
16990 if (oldIncludeForAccessibility != includeForAccessibility()) {
16991 notifySubtreeAccessibilityStateChangedIfNeeded();
16992 } else {
16993 notifyViewAccessibilityStateChangedIfNeeded(
16994 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
16995 }
16996 } else if ((changed & ENABLED_MASK) != 0) {
16997 notifyViewAccessibilityStateChangedIfNeeded(
16998 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
16999 }
17000 }
17001 }
17002
17003 /**
17004 * Change the view's z order in the tree, so it's on top of other sibling
17005 * views. This ordering change may affect layout, if the parent container
17006 * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
17007 * to {@link android.os.Build.VERSION_CODES#KITKAT} this
17008 * method should be followed by calls to {@link #requestLayout()} and
17009 * {@link View#invalidate()} on the view's parent to force the parent to redraw
17010 * with the new child ordering.
17011 *
17012 * @see ViewGroup#bringChildToFront(View)
17013 */
17014 public void bringToFront() {
17015 if (mParent != null) {
17016 mParent.bringChildToFront(this);
17017 }
17018 }
17019
17020 /**
17021 * This is called in response to an internal scroll in this view (i.e., the
17022 * view scrolled its own contents). This is typically as a result of
17023 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
17024 * called.
17025 *
17026 * @param l Current horizontal scroll origin.
17027 * @param t Current vertical scroll origin.
17028 * @param oldl Previous horizontal scroll origin.
17029 * @param oldt Previous vertical scroll origin.
17030 */
17031 protected void onScrollChanged(int l, int t, int oldl, int oldt) {
17032 notifySubtreeAccessibilityStateChangedIfNeeded();
17033 postSendViewScrolledAccessibilityEventCallback(l - oldl, t - oldt);
17034
17035 mBackgroundSizeChanged = true;
17036 mDefaultFocusHighlightSizeChanged = true;
17037 if (mForegroundInfo != null) {
17038 mForegroundInfo.mBoundsChanged = true;
17039 }
17040
17041 final AttachInfo ai = mAttachInfo;
17042 if (ai != null) {
17043 ai.mViewScrollChanged = true;
17044 }
17045
17046 if (mListenerInfo != null && mListenerInfo.mOnScrollChangeListener != null) {
17047 mListenerInfo.mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt);
17048 }
17049 }
17050
17051 /**
17052 * Interface definition for a callback to be invoked when the scroll
17053 * X or Y positions of a view change.
17054 * <p>
17055 * <b>Note:</b> Some views handle scrolling independently from View and may
17056 * have their own separate listeners for scroll-type events. For example,
17057 * {@link android.widget.ListView ListView} allows clients to register an
17058 * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
17059 * to listen for changes in list scroll position.
17060 *
17061 * @see #setOnScrollChangeListener(View.OnScrollChangeListener)
17062 */
17063 public interface OnScrollChangeListener {
17064 /**
17065 * Called when the scroll position of a view changes.
17066 *
17067 * @param v The view whose scroll position has changed.
17068 * @param scrollX Current horizontal scroll origin.
17069 * @param scrollY Current vertical scroll origin.
17070 * @param oldScrollX Previous horizontal scroll origin.
17071 * @param oldScrollY Previous vertical scroll origin.
17072 */
17073 void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY);
17074 }
17075
17076 /**
17077 * Interface definition for a callback to be invoked when the layout bounds of a view
17078 * changes due to layout processing.
17079 */
17080 public interface OnLayoutChangeListener {
17081 /**
17082 * Called when the layout bounds of a view changes due to layout processing.
17083 *
17084 * @param v The view whose bounds have changed.
17085 * @param left The new value of the view's left property.
17086 * @param top The new value of the view's top property.
17087 * @param right The new value of the view's right property.
17088 * @param bottom The new value of the view's bottom property.
17089 * @param oldLeft The previous value of the view's left property.
17090 * @param oldTop The previous value of the view's top property.
17091 * @param oldRight The previous value of the view's right property.
17092 * @param oldBottom The previous value of the view's bottom property.
17093 */
17094 void onLayoutChange(View v, int left, int top, int right, int bottom,
17095 int oldLeft, int oldTop, int oldRight, int oldBottom);
17096 }
17097
17098 /**
17099 * This is called during layout when the size of this view has changed. If
17100 * you were just added to the view hierarchy, you're called with the old
17101 * values of 0.
17102 *
17103 * @param w Current width of this view.
17104 * @param h Current height of this view.
17105 * @param oldw Old width of this view.
17106 * @param oldh Old height of this view.
17107 */
17108 protected void onSizeChanged(int w, int h, int oldw, int oldh) {
17109 }
17110
17111 /**
17112 * Called by draw to draw the child views. This may be overridden
17113 * by derived classes to gain control just before its children are drawn
17114 * (but after its own view has been drawn).
17115 * @param canvas the canvas on which to draw the view
17116 */
17117 protected void dispatchDraw(Canvas canvas) {
17118
17119 }
17120
17121 /**
17122 * Gets the parent of this view. Note that the parent is a
17123 * ViewParent and not necessarily a View.
17124 *
17125 * @return Parent of this view.
17126 */
17127 public final ViewParent getParent() {
17128 return mParent;
17129 }
17130
17131 /**
17132 * Set the horizontal scrolled position of your view. This will cause a call to
17133 * {@link #onScrollChanged(int, int, int, int)} and the view will be
17134 * invalidated.
17135 * @param value the x position to scroll to
17136 */
17137 public void setScrollX(int value) {
17138 scrollTo(value, mScrollY);
17139 }
17140
17141 /**
17142 * Set the vertical scrolled position of your view. This will cause a call to
17143 * {@link #onScrollChanged(int, int, int, int)} and the view will be
17144 * invalidated.
17145 * @param value the y position to scroll to
17146 */
17147 public void setScrollY(int value) {
17148 scrollTo(mScrollX, value);
17149 }
17150
17151 /**
17152 * Return the scrolled left position of this view. This is the left edge of
17153 * the displayed part of your view. You do not need to draw any pixels
17154 * farther left, since those are outside of the frame of your view on
17155 * screen.
17156 *
17157 * @return The left edge of the displayed part of your view, in pixels.
17158 */
17159 @InspectableProperty
17160 public final int getScrollX() {
17161 return mScrollX;
17162 }
17163
17164 /**
17165 * Return the scrolled top position of this view. This is the top edge of
17166 * the displayed part of your view. You do not need to draw any pixels above
17167 * it, since those are outside of the frame of your view on screen.
17168 *
17169 * @return The top edge of the displayed part of your view, in pixels.
17170 */
17171 @InspectableProperty
17172 public final int getScrollY() {
17173 return mScrollY;
17174 }
17175
17176 /**
17177 * Return the width of your view.
17178 *
17179 * @return The width of your view, in pixels.
17180 */
17181 @ViewDebug.ExportedProperty(category = "layout")
17182 public final int getWidth() {
17183 return mRight - mLeft;
17184 }
17185
17186 /**
17187 * Return the height of your view.
17188 *
17189 * @return The height of your view, in pixels.
17190 */
17191 @ViewDebug.ExportedProperty(category = "layout")
17192 public final int getHeight() {
17193 return mBottom - mTop;
17194 }
17195
17196 /**
17197 * Return the visible drawing bounds of your view. Fills in the output
17198 * rectangle with the values from getScrollX(), getScrollY(),
17199 * getWidth(), and getHeight(). These bounds do not account for any
17200 * transformation properties currently set on the view, such as
17201 * {@link #setScaleX(float)} or {@link #setRotation(float)}.
17202 *
17203 * @param outRect The (scrolled) drawing bounds of the view.
17204 */
17205 public void getDrawingRect(Rect outRect) {
17206 outRect.left = mScrollX;
17207 outRect.top = mScrollY;
17208 outRect.right = mScrollX + (mRight - mLeft);
17209 outRect.bottom = mScrollY + (mBottom - mTop);
17210 }
17211
17212 /**
17213 * Like {@link #getMeasuredWidthAndState()}, but only returns the
17214 * raw width component (that is the result is masked by
17215 * {@link #MEASURED_SIZE_MASK}).
17216 *
17217 * @return The raw measured width of this view.
17218 */
17219 public final int getMeasuredWidth() {
17220 return mMeasuredWidth & MEASURED_SIZE_MASK;
17221 }
17222
17223 /**
17224 * Return the full width measurement information for this view as computed
17225 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask
17226 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
17227 * This should be used during measurement and layout calculations only. Use
17228 * {@link #getWidth()} to see how wide a view is after layout.
17229 *
17230 * @return The measured width of this view as a bit mask.
17231 */
17232 @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
17233 @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
17234 name = "MEASURED_STATE_TOO_SMALL"),
17235 })
17236 public final int getMeasuredWidthAndState() {
17237 return mMeasuredWidth;
17238 }
17239
17240 /**
17241 * Like {@link #getMeasuredHeightAndState()}, but only returns the
17242 * raw height component (that is the result is masked by
17243 * {@link #MEASURED_SIZE_MASK}).
17244 *
17245 * @return The raw measured height of this view.
17246 */
17247 public final int getMeasuredHeight() {
17248 return mMeasuredHeight & MEASURED_SIZE_MASK;
17249 }
17250
17251 /**
17252 * Return the full height measurement information for this view as computed
17253 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask
17254 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
17255 * This should be used during measurement and layout calculations only. Use
17256 * {@link #getHeight()} to see how high a view is after layout.
17257 *
17258 * @return The measured height of this view as a bit mask.
17259 */
17260 @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
17261 @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
17262 name = "MEASURED_STATE_TOO_SMALL"),
17263 })
17264 public final int getMeasuredHeightAndState() {
17265 return mMeasuredHeight;
17266 }
17267
17268 /**
17269 * Return only the state bits of {@link #getMeasuredWidthAndState()}
17270 * and {@link #getMeasuredHeightAndState()}, combined into one integer.
17271 * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
17272 * and the height component is at the shifted bits
17273 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
17274 */
17275 public final int getMeasuredState() {
17276 return (mMeasuredWidth&MEASURED_STATE_MASK)
17277 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
17278 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
17279 }
17280
17281 /**
17282 * The transform matrix of this view, which is calculated based on the current
17283 * rotation, scale, and pivot properties.
17284 *
17285 * @see #getRotation()
17286 * @see #getScaleX()
17287 * @see #getScaleY()
17288 * @see #getPivotX()
17289 * @see #getPivotY()
17290 * @return The current transform matrix for the view
17291 */
17292 public Matrix getMatrix() {
17293 ensureTransformationInfo();
17294 final Matrix matrix = mTransformationInfo.mMatrix;
17295 mRenderNode.getMatrix(matrix);
17296 return matrix;
17297 }
17298
17299 /**
17300 * Returns true if the transform matrix is the identity matrix.
17301 * Recomputes the matrix if necessary.
17302 *
17303 * @return True if the transform matrix is the identity matrix, false otherwise.
17304 * @hide
17305 */
17306 @UnsupportedAppUsage
17307 public final boolean hasIdentityMatrix() {
17308 return mRenderNode.hasIdentityMatrix();
17309 }
17310
17311 @UnsupportedAppUsage
17312 void ensureTransformationInfo() {
17313 if (mTransformationInfo == null) {
17314 mTransformationInfo = new TransformationInfo();
17315 }
17316 }
17317
17318 /**
17319 * Utility method to retrieve the inverse of the current mMatrix property.
17320 * We cache the matrix to avoid recalculating it when transform properties
17321 * have not changed.
17322 *
17323 * @return The inverse of the current matrix of this view.
17324 * @hide
17325 */
17326 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
17327 public final Matrix getInverseMatrix() {
17328 ensureTransformationInfo();
17329 if (mTransformationInfo.mInverseMatrix == null) {
17330 mTransformationInfo.mInverseMatrix = new Matrix();
17331 }
17332 final Matrix matrix = mTransformationInfo.mInverseMatrix;
17333 mRenderNode.getInverseMatrix(matrix);
17334 return matrix;
17335 }
17336
17337 /**
17338 * Gets the distance along the Z axis from the camera to this view.
17339 *
17340 * @see #setCameraDistance(float)
17341 *
17342 * @return The distance along the Z axis.
17343 */
17344 public float getCameraDistance() {
17345 final float dpi = mResources.getDisplayMetrics().densityDpi;
17346 return mRenderNode.getCameraDistance() * dpi;
17347 }
17348
17349 /**
17350 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
17351 * views are drawn) from the camera to this view. The camera's distance
17352 * affects 3D transformations, for instance rotations around the X and Y
17353 * axis. If the rotationX or rotationY properties are changed and this view is
17354 * large (more than half the size of the screen), it is recommended to always
17355 * use a camera distance that's greater than the height (X axis rotation) or
17356 * the width (Y axis rotation) of this view.</p>
17357 *
17358 * <p>The distance of the camera from the view plane can have an affect on the
17359 * perspective distortion of the view when it is rotated around the x or y axis.
17360 * For example, a large distance will result in a large viewing angle, and there
17361 * will not be much perspective distortion of the view as it rotates. A short
17362 * distance may cause much more perspective distortion upon rotation, and can
17363 * also result in some drawing artifacts if the rotated view ends up partially
17364 * behind the camera (which is why the recommendation is to use a distance at
17365 * least as far as the size of the view, if the view is to be rotated.)</p>
17366 *
17367 * <p>The distance is expressed in "depth pixels." The default distance depends
17368 * on the screen density. For instance, on a medium density display, the
17369 * default distance is 1280. On a high density display, the default distance
17370 * is 1920.</p>
17371 *
17372 * <p>If you want to specify a distance that leads to visually consistent
17373 * results across various densities, use the following formula:</p>
17374 * <pre>
17375 * float scale = context.getResources().getDisplayMetrics().density;
17376 * view.setCameraDistance(distance * scale);
17377 * </pre>
17378 *
17379 * <p>The density scale factor of a high density display is 1.5,
17380 * and 1920 = 1280 * 1.5.</p>
17381 *
17382 * @param distance The distance in "depth pixels", if negative the opposite
17383 * value is used
17384 *
17385 * @see #setRotationX(float)
17386 * @see #setRotationY(float)
17387 */
17388 public void setCameraDistance(float distance) {
17389 final float dpi = mResources.getDisplayMetrics().densityDpi;
17390
17391 invalidateViewProperty(true, false);
17392 mRenderNode.setCameraDistance(Math.abs(distance) / dpi);
17393 invalidateViewProperty(false, false);
17394
17395 invalidateParentIfNeededAndWasQuickRejected();
17396 }
17397
17398 /**
17399 * The degrees that the view is rotated around the pivot point.
17400 *
17401 * @see #setRotation(float)
17402 * @see #getPivotX()
17403 * @see #getPivotY()
17404 *
17405 * @return The degrees of rotation.
17406 */
17407 @ViewDebug.ExportedProperty(category = "drawing")
17408 @InspectableProperty
17409 public float getRotation() {
17410 return mRenderNode.getRotationZ();
17411 }
17412
17413 /**
17414 * Sets the degrees that the view is rotated around the pivot point. Increasing values
17415 * result in clockwise rotation.
17416 *
17417 * @param rotation The degrees of rotation.
17418 *
17419 * @see #getRotation()
17420 * @see #getPivotX()
17421 * @see #getPivotY()
17422 * @see #setRotationX(float)
17423 * @see #setRotationY(float)
17424 *
17425 * @attr ref android.R.styleable#View_rotation
17426 */
17427 @RemotableViewMethod
17428 public void setRotation(float rotation) {
17429 if (rotation != getRotation()) {
17430 // Double-invalidation is necessary to capture view's old and new areas
17431 invalidateViewProperty(true, false);
17432 mRenderNode.setRotationZ(rotation);
17433 invalidateViewProperty(false, true);
17434
17435 invalidateParentIfNeededAndWasQuickRejected();
17436 notifySubtreeAccessibilityStateChangedIfNeeded();
17437 }
17438 }
17439
17440 /**
17441 * The degrees that the view is rotated around the vertical axis through the pivot point.
17442 *
17443 * @see #getPivotX()
17444 * @see #getPivotY()
17445 * @see #setRotationY(float)
17446 *
17447 * @return The degrees of Y rotation.
17448 */
17449 @ViewDebug.ExportedProperty(category = "drawing")
17450 @InspectableProperty
17451 public float getRotationY() {
17452 return mRenderNode.getRotationY();
17453 }
17454
17455 /**
17456 * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
17457 * Increasing values result in counter-clockwise rotation from the viewpoint of looking
17458 * down the y axis.
17459 *
17460 * When rotating large views, it is recommended to adjust the camera distance
17461 * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
17462 *
17463 * @param rotationY The degrees of Y rotation.
17464 *
17465 * @see #getRotationY()
17466 * @see #getPivotX()
17467 * @see #getPivotY()
17468 * @see #setRotation(float)
17469 * @see #setRotationX(float)
17470 * @see #setCameraDistance(float)
17471 *
17472 * @attr ref android.R.styleable#View_rotationY
17473 */
17474 @RemotableViewMethod
17475 public void setRotationY(float rotationY) {
17476 if (rotationY != getRotationY()) {
17477 invalidateViewProperty(true, false);
17478 mRenderNode.setRotationY(rotationY);
17479 invalidateViewProperty(false, true);
17480
17481 invalidateParentIfNeededAndWasQuickRejected();
17482 notifySubtreeAccessibilityStateChangedIfNeeded();
17483 }
17484 }
17485
17486 /**
17487 * The degrees that the view is rotated around the horizontal axis through the pivot point.
17488 *
17489 * @see #getPivotX()
17490 * @see #getPivotY()
17491 * @see #setRotationX(float)
17492 *
17493 * @return The degrees of X rotation.
17494 */
17495 @ViewDebug.ExportedProperty(category = "drawing")
17496 @InspectableProperty
17497 public float getRotationX() {
17498 return mRenderNode.getRotationX();
17499 }
17500
17501 /**
17502 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
17503 * Increasing values result in clockwise rotation from the viewpoint of looking down the
17504 * x axis.
17505 *
17506 * When rotating large views, it is recommended to adjust the camera distance
17507 * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
17508 *
17509 * @param rotationX The degrees of X rotation.
17510 *
17511 * @see #getRotationX()
17512 * @see #getPivotX()
17513 * @see #getPivotY()
17514 * @see #setRotation(float)
17515 * @see #setRotationY(float)
17516 * @see #setCameraDistance(float)
17517 *
17518 * @attr ref android.R.styleable#View_rotationX
17519 */
17520 @RemotableViewMethod
17521 public void setRotationX(float rotationX) {
17522 if (rotationX != getRotationX()) {
17523 invalidateViewProperty(true, false);
17524 mRenderNode.setRotationX(rotationX);
17525 invalidateViewProperty(false, true);
17526
17527 invalidateParentIfNeededAndWasQuickRejected();
17528 notifySubtreeAccessibilityStateChangedIfNeeded();
17529 }
17530 }
17531
17532 /**
17533 * The amount that the view is scaled in x around the pivot point, as a proportion of
17534 * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
17535 *
17536 * <p>By default, this is 1.0f.
17537 *
17538 * @see #getPivotX()
17539 * @see #getPivotY()
17540 * @return The scaling factor.
17541 */
17542 @ViewDebug.ExportedProperty(category = "drawing")
17543 @InspectableProperty
17544 public float getScaleX() {
17545 return mRenderNode.getScaleX();
17546 }
17547
17548 /**
17549 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
17550 * the view's unscaled width. A value of 1 means that no scaling is applied.
17551 *
17552 * @param scaleX The scaling factor.
17553 * @see #getPivotX()
17554 * @see #getPivotY()
17555 *
17556 * @attr ref android.R.styleable#View_scaleX
17557 */
17558 @RemotableViewMethod
17559 public void setScaleX(float scaleX) {
17560 if (scaleX != getScaleX()) {
17561 scaleX = sanitizeFloatPropertyValue(scaleX, "scaleX");
17562 invalidateViewProperty(true, false);
17563 mRenderNode.setScaleX(scaleX);
17564 invalidateViewProperty(false, true);
17565
17566 invalidateParentIfNeededAndWasQuickRejected();
17567 notifySubtreeAccessibilityStateChangedIfNeeded();
17568 }
17569 }
17570
17571 /**
17572 * The amount that the view is scaled in y around the pivot point, as a proportion of
17573 * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
17574 *
17575 * <p>By default, this is 1.0f.
17576 *
17577 * @see #getPivotX()
17578 * @see #getPivotY()
17579 * @return The scaling factor.
17580 */
17581 @ViewDebug.ExportedProperty(category = "drawing")
17582 @InspectableProperty
17583 public float getScaleY() {
17584 return mRenderNode.getScaleY();
17585 }
17586
17587 /**
17588 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
17589 * the view's unscaled width. A value of 1 means that no scaling is applied.
17590 *
17591 * @param scaleY The scaling factor.
17592 * @see #getPivotX()
17593 * @see #getPivotY()
17594 *
17595 * @attr ref android.R.styleable#View_scaleY
17596 */
17597 @RemotableViewMethod
17598 public void setScaleY(float scaleY) {
17599 if (scaleY != getScaleY()) {
17600 scaleY = sanitizeFloatPropertyValue(scaleY, "scaleY");
17601 invalidateViewProperty(true, false);
17602 mRenderNode.setScaleY(scaleY);
17603 invalidateViewProperty(false, true);
17604
17605 invalidateParentIfNeededAndWasQuickRejected();
17606 notifySubtreeAccessibilityStateChangedIfNeeded();
17607 }
17608 }
17609
17610 /**
17611 * The x location of the point around which the view is {@link #setRotation(float) rotated}
17612 * and {@link #setScaleX(float) scaled}.
17613 *
17614 * @see #getRotation()
17615 * @see #getScaleX()
17616 * @see #getScaleY()
17617 * @see #getPivotY()
17618 * @return The x location of the pivot point.
17619 *
17620 * @attr ref android.R.styleable#View_transformPivotX
17621 */
17622 @ViewDebug.ExportedProperty(category = "drawing")
17623 @InspectableProperty(name = "transformPivotX")
17624 public float getPivotX() {
17625 return mRenderNode.getPivotX();
17626 }
17627
17628 /**
17629 * Sets the x location of the point around which the view is
17630 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
17631 * By default, the pivot point is centered on the object.
17632 * Setting this property disables this behavior and causes the view to use only the
17633 * explicitly set pivotX and pivotY values.
17634 *
17635 * @param pivotX The x location of the pivot point.
17636 * @see #getRotation()
17637 * @see #getScaleX()
17638 * @see #getScaleY()
17639 * @see #getPivotY()
17640 *
17641 * @attr ref android.R.styleable#View_transformPivotX
17642 */
17643 @RemotableViewMethod
17644 public void setPivotX(float pivotX) {
17645 if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) {
17646 invalidateViewProperty(true, false);
17647 mRenderNode.setPivotX(pivotX);
17648 invalidateViewProperty(false, true);
17649
17650 invalidateParentIfNeededAndWasQuickRejected();
17651 }
17652 }
17653
17654 /**
17655 * The y location of the point around which the view is {@link #setRotation(float) rotated}
17656 * and {@link #setScaleY(float) scaled}.
17657 *
17658 * @see #getRotation()
17659 * @see #getScaleX()
17660 * @see #getScaleY()
17661 * @see #getPivotY()
17662 * @return The y location of the pivot point.
17663 *
17664 * @attr ref android.R.styleable#View_transformPivotY
17665 */
17666 @ViewDebug.ExportedProperty(category = "drawing")
17667 @InspectableProperty(name = "transformPivotY")
17668 public float getPivotY() {
17669 return mRenderNode.getPivotY();
17670 }
17671
17672 /**
17673 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
17674 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
17675 * Setting this property disables this behavior and causes the view to use only the
17676 * explicitly set pivotX and pivotY values.
17677 *
17678 * @param pivotY The y location of the pivot point.
17679 * @see #getRotation()
17680 * @see #getScaleX()
17681 * @see #getScaleY()
17682 * @see #getPivotY()
17683 *
17684 * @attr ref android.R.styleable#View_transformPivotY
17685 */
17686 @RemotableViewMethod
17687 public void setPivotY(float pivotY) {
17688 if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) {
17689 invalidateViewProperty(true, false);
17690 mRenderNode.setPivotY(pivotY);
17691 invalidateViewProperty(false, true);
17692
17693 invalidateParentIfNeededAndWasQuickRejected();
17694 }
17695 }
17696
17697 /**
17698 * Returns whether or not a pivot has been set by a call to {@link #setPivotX(float)} or
17699 * {@link #setPivotY(float)}. If no pivot has been set then the pivot will be the center
17700 * of the view.
17701 *
17702 * @return True if a pivot has been set, false if the default pivot is being used
17703 */
17704 public boolean isPivotSet() {
17705 return mRenderNode.isPivotExplicitlySet();
17706 }
17707
17708 /**
17709 * Clears any pivot previously set by a call to {@link #setPivotX(float)} or
17710 * {@link #setPivotY(float)}. After calling this {@link #isPivotSet()} will be false
17711 * and the pivot used for rotation will return to default of being centered on the view.
17712 */
17713 public void resetPivot() {
17714 if (mRenderNode.resetPivot()) {
17715 invalidateViewProperty(false, false);
17716 }
17717 }
17718
17719 /**
17720 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
17721 * completely transparent and 1 means the view is completely opaque.
17722 *
17723 * <p>By default this is 1.0f.
17724 * @return The opacity of the view.
17725 */
17726 @ViewDebug.ExportedProperty(category = "drawing")
17727 @InspectableProperty
17728 public float getAlpha() {
17729 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
17730 }
17731
17732 /**
17733 * Sets the behavior for overlapping rendering for this view (see {@link
17734 * #hasOverlappingRendering()} for more details on this behavior). Calling this method
17735 * is an alternative to overriding {@link #hasOverlappingRendering()} in a subclass,
17736 * providing the value which is then used internally. That is, when {@link
17737 * #forceHasOverlappingRendering(boolean)} is called, the value of {@link
17738 * #hasOverlappingRendering()} is ignored and the value passed into this method is used
17739 * instead.
17740 *
17741 * @param hasOverlappingRendering The value for overlapping rendering to be used internally
17742 * instead of that returned by {@link #hasOverlappingRendering()}.
17743 *
17744 * @attr ref android.R.styleable#View_forceHasOverlappingRendering
17745 */
17746 public void forceHasOverlappingRendering(boolean hasOverlappingRendering) {
17747 mPrivateFlags3 |= PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED;
17748 if (hasOverlappingRendering) {
17749 mPrivateFlags3 |= PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE;
17750 } else {
17751 mPrivateFlags3 &= ~PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE;
17752 }
17753 }
17754
17755 /**
17756 * Returns the value for overlapping rendering that is used internally. This is either
17757 * the value passed into {@link #forceHasOverlappingRendering(boolean)}, if called, or
17758 * the return value of {@link #hasOverlappingRendering()}, otherwise.
17759 *
17760 * @return The value for overlapping rendering being used internally.
17761 */
17762 public final boolean getHasOverlappingRendering() {
17763 return (mPrivateFlags3 & PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED) != 0 ?
17764 (mPrivateFlags3 & PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE) != 0 :
17765 hasOverlappingRendering();
17766 }
17767
17768 /**
17769 * Returns whether this View has content which overlaps.
17770 *
17771 * <p>This function, intended to be overridden by specific View types, is an optimization when
17772 * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
17773 * an offscreen buffer and then composited into place, which can be expensive. If the view has
17774 * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
17775 * directly. An example of overlapping rendering is a TextView with a background image, such as
17776 * a Button. An example of non-overlapping rendering is a TextView with no background, or an
17777 * ImageView with only the foreground image. The default implementation returns true; subclasses
17778 * should override if they have cases which can be optimized.</p>
17779 *
17780 * <p><strong>Note:</strong> The return value of this method is ignored if {@link
17781 * #forceHasOverlappingRendering(boolean)} has been called on this view.</p>
17782 *
17783 * @return true if the content in this view might overlap, false otherwise.
17784 */
17785 @ViewDebug.ExportedProperty(category = "drawing")
17786 public boolean hasOverlappingRendering() {
17787 return true;
17788 }
17789
17790 /**
17791 * Sets the opacity of the view to a value from 0 to 1, where 0 means the view is
17792 * completely transparent and 1 means the view is completely opaque.
17793 *
17794 * <p class="note"><strong>Note:</strong> setting alpha to a translucent value (0 < alpha < 1)
17795 * can have significant performance implications, especially for large views. It is best to use
17796 * the alpha property sparingly and transiently, as in the case of fading animations.</p>
17797 *
17798 * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
17799 * strongly recommended for performance reasons to either override
17800 * {@link #hasOverlappingRendering()} to return <code>false</code> if appropriate, or setting a
17801 * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view for the duration
17802 * of the animation. On versions {@link android.os.Build.VERSION_CODES#M} and below,
17803 * the default path for rendering an unlayered View with alpha could add multiple milliseconds
17804 * of rendering cost, even for simple or small views. Starting with
17805 * {@link android.os.Build.VERSION_CODES#M}, {@link #LAYER_TYPE_HARDWARE} is automatically
17806 * applied to the view at the rendering level.</p>
17807 *
17808 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
17809 * responsible for applying the opacity itself.</p>
17810 *
17811 * <p>On versions {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} and below, note that if
17812 * the view is backed by a {@link #setLayerType(int, android.graphics.Paint) layer} and is
17813 * associated with a {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an
17814 * alpha value less than 1.0 will supersede the alpha of the layer paint.</p>
17815 *
17816 * <p>Starting with {@link android.os.Build.VERSION_CODES#M}, setting a translucent alpha
17817 * value will clip a View to its bounds, unless the View returns <code>false</code> from
17818 * {@link #hasOverlappingRendering}.</p>
17819 *
17820 * @param alpha The opacity of the view.
17821 *
17822 * @see #hasOverlappingRendering()
17823 * @see #setLayerType(int, android.graphics.Paint)
17824 *
17825 * @attr ref android.R.styleable#View_alpha
17826 */
17827 @RemotableViewMethod
17828 public void setAlpha(@FloatRange(from=0.0, to=1.0) float alpha) {
17829 ensureTransformationInfo();
17830 if (mTransformationInfo.mAlpha != alpha) {
17831 setAlphaInternal(alpha);
17832 if (onSetAlpha((int) (alpha * 255))) {
17833 mPrivateFlags |= PFLAG_ALPHA_SET;
17834 // subclass is handling alpha - don't optimize rendering cache invalidation
17835 invalidateParentCaches();
17836 invalidate(true);
17837 } else {
17838 mPrivateFlags &= ~PFLAG_ALPHA_SET;
17839 invalidateViewProperty(true, false);
17840 mRenderNode.setAlpha(getFinalAlpha());
17841 }
17842 }
17843 }
17844
17845 /**
17846 * Faster version of setAlpha() which performs the same steps except there are
17847 * no calls to invalidate(). The caller of this function should perform proper invalidation
17848 * on the parent and this object. The return value indicates whether the subclass handles
17849 * alpha (the return value for onSetAlpha()).
17850 *
17851 * @param alpha The new value for the alpha property
17852 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
17853 * the new value for the alpha property is different from the old value
17854 */
17855 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 123768435)
17856 boolean setAlphaNoInvalidation(float alpha) {
17857 ensureTransformationInfo();
17858 if (mTransformationInfo.mAlpha != alpha) {
17859 setAlphaInternal(alpha);
17860 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
17861 if (subclassHandlesAlpha) {
17862 mPrivateFlags |= PFLAG_ALPHA_SET;
17863 return true;
17864 } else {
17865 mPrivateFlags &= ~PFLAG_ALPHA_SET;
17866 mRenderNode.setAlpha(getFinalAlpha());
17867 }
17868 }
17869 return false;
17870 }
17871
17872 void setAlphaInternal(float alpha) {
17873 float oldAlpha = mTransformationInfo.mAlpha;
17874 mTransformationInfo.mAlpha = alpha;
17875 // Report visibility changes, which can affect children, to accessibility
17876 if ((alpha == 0) ^ (oldAlpha == 0)) {
17877 notifySubtreeAccessibilityStateChangedIfNeeded();
17878 }
17879 }
17880
17881 /**
17882 * This property is intended only for use by the Fade transition, which animates it
17883 * to produce a visual translucency that does not side-effect (or get affected by)
17884 * the real alpha property. This value is composited with the other alpha value
17885 * (and the AlphaAnimation value, when that is present) to produce a final visual
17886 * translucency result, which is what is passed into the DisplayList.
17887 */
17888 public void setTransitionAlpha(float alpha) {
17889 ensureTransformationInfo();
17890 if (mTransformationInfo.mTransitionAlpha != alpha) {
17891 mTransformationInfo.mTransitionAlpha = alpha;
17892 mPrivateFlags &= ~PFLAG_ALPHA_SET;
17893 invalidateViewProperty(true, false);
17894 mRenderNode.setAlpha(getFinalAlpha());
17895 }
17896 }
17897
17898 /**
17899 * Calculates the visual alpha of this view, which is a combination of the actual
17900 * alpha value and the transitionAlpha value (if set).
17901 */
17902 private float getFinalAlpha() {
17903 if (mTransformationInfo != null) {
17904 return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
17905 }
17906 return 1;
17907 }
17908
17909 /**
17910 * This property is intended only for use by the Fade transition, which animates
17911 * it to produce a visual translucency that does not side-effect (or get affected
17912 * by) the real alpha property. This value is composited with the other alpha
17913 * value (and the AlphaAnimation value, when that is present) to produce a final
17914 * visual translucency result, which is what is passed into the DisplayList.
17915 */
17916 @ViewDebug.ExportedProperty(category = "drawing")
17917 public float getTransitionAlpha() {
17918 return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
17919 }
17920
17921 /**
17922 * Sets whether or not to allow force dark to apply to this view.
17923 *
17924 * Setting this to false will disable the auto-dark feature on everything this view
17925 * draws, including any descendants.
17926 *
17927 * Setting this to true will allow this view to be automatically made dark, however
17928 * a value of 'true' will not override any 'false' value in its parent chain nor will
17929 * it prevent any 'false' in any of its children.
17930 *
17931 * The default behavior of force dark is also influenced by the Theme's
17932 * {@link android.R.styleable#Theme_isLightTheme isLightTheme} attribute.
17933 * If a theme is isLightTheme="false", then force dark is globally disabled for that theme.
17934 *
17935 * @param allow Whether or not to allow force dark.
17936 */
17937 public void setForceDarkAllowed(boolean allow) {
17938 if (mRenderNode.setForceDarkAllowed(allow)) {
17939 // Currently toggling force-dark requires a new display list push to apply
17940 // TODO: Make it not clobber the display list so this is just a damageSelf() instead
17941 invalidate();
17942 }
17943 }
17944
17945 /**
17946 * See {@link #setForceDarkAllowed(boolean)}
17947 *
17948 * @return true if force dark is allowed (default), false if it is disabled
17949 */
17950 @ViewDebug.ExportedProperty(category = "drawing")
17951 @InspectableProperty
17952 public boolean isForceDarkAllowed() {
17953 return mRenderNode.isForceDarkAllowed();
17954 }
17955
17956 /**
17957 * Top position of this view relative to its parent.
17958 *
17959 * @return The top of this view, in pixels.
17960 */
17961 @ViewDebug.CapturedViewProperty
17962 public final int getTop() {
17963 return mTop;
17964 }
17965
17966 /**
17967 * Sets the top position of this view relative to its parent. This method is meant to be called
17968 * by the layout system and should not generally be called otherwise, because the property
17969 * may be changed at any time by the layout.
17970 *
17971 * @param top The top of this view, in pixels.
17972 */
17973 public final void setTop(int top) {
17974 if (top != mTop) {
17975 final boolean matrixIsIdentity = hasIdentityMatrix();
17976 if (matrixIsIdentity) {
17977 if (mAttachInfo != null) {
17978 int minTop;
17979 int yLoc;
17980 if (top < mTop) {
17981 minTop = top;
17982 yLoc = top - mTop;
17983 } else {
17984 minTop = mTop;
17985 yLoc = 0;
17986 }
17987 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
17988 }
17989 } else {
17990 // Double-invalidation is necessary to capture view's old and new areas
17991 invalidate(true);
17992 }
17993
17994 int width = mRight - mLeft;
17995 int oldHeight = mBottom - mTop;
17996
17997 mTop = top;
17998 mRenderNode.setTop(mTop);
17999
18000 sizeChange(width, mBottom - mTop, width, oldHeight);
18001
18002 if (!matrixIsIdentity) {
18003 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
18004 invalidate(true);
18005 }
18006 mBackgroundSizeChanged = true;
18007 mDefaultFocusHighlightSizeChanged = true;
18008 if (mForegroundInfo != null) {
18009 mForegroundInfo.mBoundsChanged = true;
18010 }
18011 invalidateParentIfNeeded();
18012 }
18013 }
18014
18015 /**
18016 * Bottom position of this view relative to its parent.
18017 *
18018 * @return The bottom of this view, in pixels.
18019 */
18020 @ViewDebug.CapturedViewProperty
18021 public final int getBottom() {
18022 return mBottom;
18023 }
18024
18025 /**
18026 * True if this view has changed since the last time being drawn.
18027 *
18028 * @return The dirty state of this view.
18029 */
18030 public boolean isDirty() {
18031 return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
18032 }
18033
18034 /**
18035 * Sets the bottom position of this view relative to its parent. This method is meant to be
18036 * called by the layout system and should not generally be called otherwise, because the
18037 * property may be changed at any time by the layout.
18038 *
18039 * @param bottom The bottom of this view, in pixels.
18040 */
18041 public final void setBottom(int bottom) {
18042 if (bottom != mBottom) {
18043 final boolean matrixIsIdentity = hasIdentityMatrix();
18044 if (matrixIsIdentity) {
18045 if (mAttachInfo != null) {
18046 int maxBottom;
18047 if (bottom < mBottom) {
18048 maxBottom = mBottom;
18049 } else {
18050 maxBottom = bottom;
18051 }
18052 invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
18053 }
18054 } else {
18055 // Double-invalidation is necessary to capture view's old and new areas
18056 invalidate(true);
18057 }
18058
18059 int width = mRight - mLeft;
18060 int oldHeight = mBottom - mTop;
18061
18062 mBottom = bottom;
18063 mRenderNode.setBottom(mBottom);
18064
18065 sizeChange(width, mBottom - mTop, width, oldHeight);
18066
18067 if (!matrixIsIdentity) {
18068 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
18069 invalidate(true);
18070 }
18071 mBackgroundSizeChanged = true;
18072 mDefaultFocusHighlightSizeChanged = true;
18073 if (mForegroundInfo != null) {
18074 mForegroundInfo.mBoundsChanged = true;
18075 }
18076 invalidateParentIfNeeded();
18077 }
18078 }
18079
18080 /**
18081 * Left position of this view relative to its parent.
18082 *
18083 * @return The left edge of this view, in pixels.
18084 */
18085 @ViewDebug.CapturedViewProperty
18086 public final int getLeft() {
18087 return mLeft;
18088 }
18089
18090 /**
18091 * Sets the left position of this view relative to its parent. This method is meant to be called
18092 * by the layout system and should not generally be called otherwise, because the property
18093 * may be changed at any time by the layout.
18094 *
18095 * @param left The left of this view, in pixels.
18096 */
18097 public final void setLeft(int left) {
18098 if (left != mLeft) {
18099 final boolean matrixIsIdentity = hasIdentityMatrix();
18100 if (matrixIsIdentity) {
18101 if (mAttachInfo != null) {
18102 int minLeft;
18103 int xLoc;
18104 if (left < mLeft) {
18105 minLeft = left;
18106 xLoc = left - mLeft;
18107 } else {
18108 minLeft = mLeft;
18109 xLoc = 0;
18110 }
18111 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
18112 }
18113 } else {
18114 // Double-invalidation is necessary to capture view's old and new areas
18115 invalidate(true);
18116 }
18117
18118 int oldWidth = mRight - mLeft;
18119 int height = mBottom - mTop;
18120
18121 mLeft = left;
18122 mRenderNode.setLeft(left);
18123
18124 sizeChange(mRight - mLeft, height, oldWidth, height);
18125
18126 if (!matrixIsIdentity) {
18127 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
18128 invalidate(true);
18129 }
18130 mBackgroundSizeChanged = true;
18131 mDefaultFocusHighlightSizeChanged = true;
18132 if (mForegroundInfo != null) {
18133 mForegroundInfo.mBoundsChanged = true;
18134 }
18135 invalidateParentIfNeeded();
18136 }
18137 }
18138
18139 /**
18140 * Right position of this view relative to its parent.
18141 *
18142 * @return The right edge of this view, in pixels.
18143 */
18144 @ViewDebug.CapturedViewProperty
18145 public final int getRight() {
18146 return mRight;
18147 }
18148
18149 /**
18150 * Sets the right position of this view relative to its parent. This method is meant to be called
18151 * by the layout system and should not generally be called otherwise, because the property
18152 * may be changed at any time by the layout.
18153 *
18154 * @param right The right of this view, in pixels.
18155 */
18156 public final void setRight(int right) {
18157 if (right != mRight) {
18158 final boolean matrixIsIdentity = hasIdentityMatrix();
18159 if (matrixIsIdentity) {
18160 if (mAttachInfo != null) {
18161 int maxRight;
18162 if (right < mRight) {
18163 maxRight = mRight;
18164 } else {
18165 maxRight = right;
18166 }
18167 invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
18168 }
18169 } else {
18170 // Double-invalidation is necessary to capture view's old and new areas
18171 invalidate(true);
18172 }
18173
18174 int oldWidth = mRight - mLeft;
18175 int height = mBottom - mTop;
18176
18177 mRight = right;
18178 mRenderNode.setRight(mRight);
18179
18180 sizeChange(mRight - mLeft, height, oldWidth, height);
18181
18182 if (!matrixIsIdentity) {
18183 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
18184 invalidate(true);
18185 }
18186 mBackgroundSizeChanged = true;
18187 mDefaultFocusHighlightSizeChanged = true;
18188 if (mForegroundInfo != null) {
18189 mForegroundInfo.mBoundsChanged = true;
18190 }
18191 invalidateParentIfNeeded();
18192 }
18193 }
18194
18195 private static float sanitizeFloatPropertyValue(float value, String propertyName) {
18196 return sanitizeFloatPropertyValue(value, propertyName, -Float.MAX_VALUE, Float.MAX_VALUE);
18197 }
18198
18199 private static float sanitizeFloatPropertyValue(float value, String propertyName,
18200 float min, float max) {
18201 // The expected "nothing bad happened" path
18202 if (value >= min && value <= max) return value;
18203
18204 if (value < min || value == Float.NEGATIVE_INFINITY) {
18205 if (sThrowOnInvalidFloatProperties) {
18206 throw new IllegalArgumentException("Cannot set '" + propertyName + "' to "
18207 + value + ", the value must be >= " + min);
18208 }
18209 return min;
18210 }
18211
18212 if (value > max || value == Float.POSITIVE_INFINITY) {
18213 if (sThrowOnInvalidFloatProperties) {
18214 throw new IllegalArgumentException("Cannot set '" + propertyName + "' to "
18215 + value + ", the value must be <= " + max);
18216 }
18217 return max;
18218 }
18219
18220 if (Float.isNaN(value)) {
18221 if (sThrowOnInvalidFloatProperties) {
18222 throw new IllegalArgumentException(
18223 "Cannot set '" + propertyName + "' to Float.NaN");
18224 }
18225 return 0; // Unclear which direction this NaN went so... 0?
18226 }
18227
18228 // Shouldn't be possible to reach this.
18229 throw new IllegalStateException("How do you get here?? " + value);
18230 }
18231
18232 /**
18233 * The visual x position of this view, in pixels. This is equivalent to the
18234 * {@link #setTranslationX(float) translationX} property plus the current
18235 * {@link #getLeft() left} property.
18236 *
18237 * @return The visual x position of this view, in pixels.
18238 */
18239 @ViewDebug.ExportedProperty(category = "drawing")
18240 public float getX() {
18241 return mLeft + getTranslationX();
18242 }
18243
18244 /**
18245 * Sets the visual x position of this view, in pixels. This is equivalent to setting the
18246 * {@link #setTranslationX(float) translationX} property to be the difference between
18247 * the x value passed in and the current {@link #getLeft() left} property.
18248 *
18249 * @param x The visual x position of this view, in pixels.
18250 */
18251 public void setX(float x) {
18252 setTranslationX(x - mLeft);
18253 }
18254
18255 /**
18256 * The visual y position of this view, in pixels. This is equivalent to the
18257 * {@link #setTranslationY(float) translationY} property plus the current
18258 * {@link #getTop() top} property.
18259 *
18260 * @return The visual y position of this view, in pixels.
18261 */
18262 @ViewDebug.ExportedProperty(category = "drawing")
18263 public float getY() {
18264 return mTop + getTranslationY();
18265 }
18266
18267 /**
18268 * Sets the visual y position of this view, in pixels. This is equivalent to setting the
18269 * {@link #setTranslationY(float) translationY} property to be the difference between
18270 * the y value passed in and the current {@link #getTop() top} property.
18271 *
18272 * @param y The visual y position of this view, in pixels.
18273 */
18274 public void setY(float y) {
18275 setTranslationY(y - mTop);
18276 }
18277
18278 /**
18279 * The visual z position of this view, in pixels. This is equivalent to the
18280 * {@link #setTranslationZ(float) translationZ} property plus the current
18281 * {@link #getElevation() elevation} property.
18282 *
18283 * @return The visual z position of this view, in pixels.
18284 */
18285 @ViewDebug.ExportedProperty(category = "drawing")
18286 public float getZ() {
18287 return getElevation() + getTranslationZ();
18288 }
18289
18290 /**
18291 * Sets the visual z position of this view, in pixels. This is equivalent to setting the
18292 * {@link #setTranslationZ(float) translationZ} property to be the difference between
18293 * the z value passed in and the current {@link #getElevation() elevation} property.
18294 *
18295 * @param z The visual z position of this view, in pixels.
18296 */
18297 public void setZ(float z) {
18298 setTranslationZ(z - getElevation());
18299 }
18300
18301 /**
18302 * The base elevation of this view relative to its parent, in pixels.
18303 *
18304 * @return The base depth position of the view, in pixels.
18305 */
18306 @ViewDebug.ExportedProperty(category = "drawing")
18307 @InspectableProperty
18308 public float getElevation() {
18309 return mRenderNode.getElevation();
18310 }
18311
18312 /**
18313 * Sets the base elevation of this view, in pixels.
18314 *
18315 * @attr ref android.R.styleable#View_elevation
18316 */
18317 @RemotableViewMethod
18318 public void setElevation(float elevation) {
18319 if (elevation != getElevation()) {
18320 elevation = sanitizeFloatPropertyValue(elevation, "elevation");
18321 invalidateViewProperty(true, false);
18322 mRenderNode.setElevation(elevation);
18323 invalidateViewProperty(false, true);
18324
18325 invalidateParentIfNeededAndWasQuickRejected();
18326 }
18327 }
18328
18329 /**
18330 * The horizontal location of this view relative to its {@link #getLeft() left} position.
18331 * This position is post-layout, in addition to wherever the object's
18332 * layout placed it.
18333 *
18334 * @return The horizontal position of this view relative to its left position, in pixels.
18335 */
18336 @ViewDebug.ExportedProperty(category = "drawing")
18337 @InspectableProperty
18338 public float getTranslationX() {
18339 return mRenderNode.getTranslationX();
18340 }
18341
18342 /**
18343 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
18344 * This effectively positions the object post-layout, in addition to wherever the object's
18345 * layout placed it.
18346 *
18347 * @param translationX The horizontal position of this view relative to its left position,
18348 * in pixels.
18349 *
18350 * @attr ref android.R.styleable#View_translationX
18351 */
18352 @RemotableViewMethod
18353 public void setTranslationX(float translationX) {
18354 if (translationX != getTranslationX()) {
18355 invalidateViewProperty(true, false);
18356 mRenderNode.setTranslationX(translationX);
18357 invalidateViewProperty(false, true);
18358
18359 invalidateParentIfNeededAndWasQuickRejected();
18360 notifySubtreeAccessibilityStateChangedIfNeeded();
18361 }
18362 }
18363
18364 /**
18365 * The vertical location of this view relative to its {@link #getTop() top} position.
18366 * This position is post-layout, in addition to wherever the object's
18367 * layout placed it.
18368 *
18369 * @return The vertical position of this view relative to its top position,
18370 * in pixels.
18371 */
18372 @ViewDebug.ExportedProperty(category = "drawing")
18373 @InspectableProperty
18374 public float getTranslationY() {
18375 return mRenderNode.getTranslationY();
18376 }
18377
18378 /**
18379 * Sets the vertical location of this view relative to its {@link #getTop() top} position.
18380 * This effectively positions the object post-layout, in addition to wherever the object's
18381 * layout placed it.
18382 *
18383 * @param translationY The vertical position of this view relative to its top position,
18384 * in pixels.
18385 *
18386 * @attr ref android.R.styleable#View_translationY
18387 */
18388 @RemotableViewMethod
18389 public void setTranslationY(float translationY) {
18390 if (translationY != getTranslationY()) {
18391 invalidateViewProperty(true, false);
18392 mRenderNode.setTranslationY(translationY);
18393 invalidateViewProperty(false, true);
18394
18395 invalidateParentIfNeededAndWasQuickRejected();
18396 notifySubtreeAccessibilityStateChangedIfNeeded();
18397 }
18398 }
18399
18400 /**
18401 * The depth location of this view relative to its {@link #getElevation() elevation}.
18402 *
18403 * @return The depth of this view relative to its elevation.
18404 */
18405 @ViewDebug.ExportedProperty(category = "drawing")
18406 @InspectableProperty
18407 public float getTranslationZ() {
18408 return mRenderNode.getTranslationZ();
18409 }
18410
18411 /**
18412 * Sets the depth location of this view relative to its {@link #getElevation() elevation}.
18413 *
18414 * @attr ref android.R.styleable#View_translationZ
18415 */
18416 @RemotableViewMethod
18417 public void setTranslationZ(float translationZ) {
18418 if (translationZ != getTranslationZ()) {
18419 translationZ = sanitizeFloatPropertyValue(translationZ, "translationZ");
18420 invalidateViewProperty(true, false);
18421 mRenderNode.setTranslationZ(translationZ);
18422 invalidateViewProperty(false, true);
18423
18424 invalidateParentIfNeededAndWasQuickRejected();
18425 }
18426 }
18427
18428 /**
18429 * Changes the transformation matrix on the view. This is used in animation frameworks,
18430 * such as {@link android.transition.Transition}. When the animation finishes, the matrix
18431 * should be cleared by calling this method with <code>null</code> as the matrix parameter.
18432 * Application developers should use transformation methods like {@link #setRotation(float)},
18433 * {@link #setScaleX(float)}, {@link #setScaleX(float)}, {@link #setTranslationX(float)}}
18434 * and {@link #setTranslationY(float)} (float)}} instead.
18435 *
18436 * @param matrix The matrix, null indicates that the matrix should be cleared.
18437 * @see #getAnimationMatrix()
18438 */
18439 public void setAnimationMatrix(@Nullable Matrix matrix) {
18440 invalidateViewProperty(true, false);
18441 mRenderNode.setAnimationMatrix(matrix);
18442 invalidateViewProperty(false, true);
18443
18444 invalidateParentIfNeededAndWasQuickRejected();
18445 }
18446
18447 /**
18448 * Return the current transformation matrix of the view. This is used in animation frameworks,
18449 * such as {@link android.transition.Transition}. Returns <code>null</code> when there is no
18450 * transformation provided by {@link #setAnimationMatrix(Matrix)}.
18451 * Application developers should use transformation methods like {@link #setRotation(float)},
18452 * {@link #setScaleX(float)}, {@link #setScaleX(float)}, {@link #setTranslationX(float)}}
18453 * and {@link #setTranslationY(float)} (float)}} instead.
18454 *
18455 * @return the Matrix, null indicates there is no transformation
18456 * @see #setAnimationMatrix(Matrix)
18457 */
18458 @Nullable
18459 public Matrix getAnimationMatrix() {
18460 return mRenderNode.getAnimationMatrix();
18461 }
18462
18463 /**
18464 * Returns the current StateListAnimator if exists.
18465 *
18466 * @return StateListAnimator or null if it does not exists
18467 * @see #setStateListAnimator(android.animation.StateListAnimator)
18468 */
18469 @InspectableProperty
18470 public StateListAnimator getStateListAnimator() {
18471 return mStateListAnimator;
18472 }
18473
18474 /**
18475 * Attaches the provided StateListAnimator to this View.
18476 * <p>
18477 * Any previously attached StateListAnimator will be detached.
18478 *
18479 * @param stateListAnimator The StateListAnimator to update the view
18480 * @see android.animation.StateListAnimator
18481 */
18482 public void setStateListAnimator(StateListAnimator stateListAnimator) {
18483 if (mStateListAnimator == stateListAnimator) {
18484 return;
18485 }
18486 if (mStateListAnimator != null) {
18487 mStateListAnimator.setTarget(null);
18488 }
18489 mStateListAnimator = stateListAnimator;
18490 if (stateListAnimator != null) {
18491 stateListAnimator.setTarget(this);
18492 if (isAttachedToWindow()) {
18493 stateListAnimator.setState(getDrawableState());
18494 }
18495 }
18496 }
18497
18498 /**
18499 * Returns whether the Outline should be used to clip the contents of the View.
18500 * <p>
18501 * Note that this flag will only be respected if the View's Outline returns true from
18502 * {@link Outline#canClip()}.
18503 *
18504 * @see #setOutlineProvider(ViewOutlineProvider)
18505 * @see #setClipToOutline(boolean)
18506 */
18507 public final boolean getClipToOutline() {
18508 return mRenderNode.getClipToOutline();
18509 }
18510
18511 /**
18512 * Sets whether the View's Outline should be used to clip the contents of the View.
18513 * <p>
18514 * Only a single non-rectangular clip can be applied on a View at any time.
18515 * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float)
18516 * circular reveal} animation take priority over Outline clipping, and
18517 * child Outline clipping takes priority over Outline clipping done by a
18518 * parent.
18519 * <p>
18520 * Note that this flag will only be respected if the View's Outline returns true from
18521 * {@link Outline#canClip()}.
18522 *
18523 * @see #setOutlineProvider(ViewOutlineProvider)
18524 * @see #getClipToOutline()
18525 *
18526 * @attr ref android.R.styleable#View_clipToOutline
18527 */
18528 @RemotableViewMethod
18529 public void setClipToOutline(boolean clipToOutline) {
18530 damageInParent();
18531 if (getClipToOutline() != clipToOutline) {
18532 mRenderNode.setClipToOutline(clipToOutline);
18533 }
18534 }
18535
18536 // correspond to the enum values of View_outlineProvider
18537 private static final int PROVIDER_BACKGROUND = 0;
18538 private static final int PROVIDER_NONE = 1;
18539 private static final int PROVIDER_BOUNDS = 2;
18540 private static final int PROVIDER_PADDED_BOUNDS = 3;
18541 private void setOutlineProviderFromAttribute(int providerInt) {
18542 switch (providerInt) {
18543 case PROVIDER_BACKGROUND:
18544 setOutlineProvider(ViewOutlineProvider.BACKGROUND);
18545 break;
18546 case PROVIDER_NONE:
18547 setOutlineProvider(null);
18548 break;
18549 case PROVIDER_BOUNDS:
18550 setOutlineProvider(ViewOutlineProvider.BOUNDS);
18551 break;
18552 case PROVIDER_PADDED_BOUNDS:
18553 setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS);
18554 break;
18555 }
18556 }
18557
18558 /**
18559 * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines
18560 * the shape of the shadow it casts, and enables outline clipping.
18561 * <p>
18562 * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline
18563 * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the
18564 * outline provider with this method allows this behavior to be overridden.
18565 * <p>
18566 * If the ViewOutlineProvider is null, if querying it for an outline returns false,
18567 * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast.
18568 * <p>
18569 * Only outlines that return true from {@link Outline#canClip()} may be used for clipping.
18570 *
18571 * @see #setClipToOutline(boolean)
18572 * @see #getClipToOutline()
18573 * @see #getOutlineProvider()
18574 */
18575 public void setOutlineProvider(ViewOutlineProvider provider) {
18576 mOutlineProvider = provider;
18577 invalidateOutline();
18578 }
18579
18580 /**
18581 * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline
18582 * that defines the shape of the shadow it casts, and enables outline clipping.
18583 *
18584 * @see #setOutlineProvider(ViewOutlineProvider)
18585 */
18586 @InspectableProperty
18587 public ViewOutlineProvider getOutlineProvider() {
18588 return mOutlineProvider;
18589 }
18590
18591 /**
18592 * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider}
18593 *
18594 * @see #setOutlineProvider(ViewOutlineProvider)
18595 */
18596 public void invalidateOutline() {
18597 rebuildOutline();
18598
18599 notifySubtreeAccessibilityStateChangedIfNeeded();
18600 invalidateViewProperty(false, false);
18601 }
18602
18603 /**
18604 * Internal version of {@link #invalidateOutline()} which invalidates the
18605 * outline without invalidating the view itself. This is intended to be called from
18606 * within methods in the View class itself which are the result of the view being
18607 * invalidated already. For example, when we are drawing the background of a View,
18608 * we invalidate the outline in case it changed in the meantime, but we do not
18609 * need to invalidate the view because we're already drawing the background as part
18610 * of drawing the view in response to an earlier invalidation of the view.
18611 */
18612 private void rebuildOutline() {
18613 // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow()
18614 if (mAttachInfo == null) return;
18615
18616 if (mOutlineProvider == null) {
18617 // no provider, remove outline
18618 mRenderNode.setOutline(null);
18619 } else {
18620 final Outline outline = mAttachInfo.mTmpOutline;
18621 outline.setEmpty();
18622 outline.setAlpha(1.0f);
18623
18624 mOutlineProvider.getOutline(this, outline);
18625 mRenderNode.setOutline(outline);
18626 }
18627 }
18628
18629 /**
18630 * HierarchyViewer only
18631 *
18632 * @hide
18633 */
18634 @ViewDebug.ExportedProperty(category = "drawing")
18635 public boolean hasShadow() {
18636 return mRenderNode.hasShadow();
18637 }
18638
18639 /**
18640 * Sets the color of the spot shadow that is drawn when the view has a positive Z or
18641 * elevation value.
18642 * <p>
18643 * By default the shadow color is black. Generally, this color will be opaque so the intensity
18644 * of the shadow is consistent between different views with different colors.
18645 * <p>
18646 * The opacity of the final spot shadow is a function of the shadow caster height, the
18647 * alpha channel of the outlineSpotShadowColor (typically opaque), and the
18648 * {@link android.R.attr#spotShadowAlpha} theme attribute.
18649 *
18650 * @attr ref android.R.styleable#View_outlineSpotShadowColor
18651 * @param color The color this View will cast for its elevation spot shadow.
18652 */
18653 public void setOutlineSpotShadowColor(@ColorInt int color) {
18654 if (mRenderNode.setSpotShadowColor(color)) {
18655 invalidateViewProperty(true, true);
18656 }
18657 }
18658
18659 /**
18660 * @return The shadow color set by {@link #setOutlineSpotShadowColor(int)}, or black if nothing
18661 * was set
18662 */
18663 @InspectableProperty
18664 public @ColorInt int getOutlineSpotShadowColor() {
18665 return mRenderNode.getSpotShadowColor();
18666 }
18667
18668 /**
18669 * Sets the color of the ambient shadow that is drawn when the view has a positive Z or
18670 * elevation value.
18671 * <p>
18672 * By default the shadow color is black. Generally, this color will be opaque so the intensity
18673 * of the shadow is consistent between different views with different colors.
18674 * <p>
18675 * The opacity of the final ambient shadow is a function of the shadow caster height, the
18676 * alpha channel of the outlineAmbientShadowColor (typically opaque), and the
18677 * {@link android.R.attr#ambientShadowAlpha} theme attribute.
18678 *
18679 * @attr ref android.R.styleable#View_outlineAmbientShadowColor
18680 * @param color The color this View will cast for its elevation shadow.
18681 */
18682 public void setOutlineAmbientShadowColor(@ColorInt int color) {
18683 if (mRenderNode.setAmbientShadowColor(color)) {
18684 invalidateViewProperty(true, true);
18685 }
18686 }
18687
18688 /**
18689 * @return The shadow color set by {@link #setOutlineAmbientShadowColor(int)}, or black if
18690 * nothing was set
18691 */
18692 @InspectableProperty
18693 public @ColorInt int getOutlineAmbientShadowColor() {
18694 return mRenderNode.getAmbientShadowColor();
18695 }
18696
18697
18698 /** @hide */
18699 public void setRevealClip(boolean shouldClip, float x, float y, float radius) {
18700 mRenderNode.setRevealClip(shouldClip, x, y, radius);
18701 invalidateViewProperty(false, false);
18702 }
18703
18704 /**
18705 * Hit rectangle in parent's coordinates
18706 *
18707 * @param outRect The hit rectangle of the view.
18708 */
18709 public void getHitRect(Rect outRect) {
18710 if (hasIdentityMatrix() || mAttachInfo == null) {
18711 outRect.set(mLeft, mTop, mRight, mBottom);
18712 } else {
18713 final RectF tmpRect = mAttachInfo.mTmpTransformRect;
18714 tmpRect.set(0, 0, getWidth(), getHeight());
18715 getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect)
18716 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
18717 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
18718 }
18719 }
18720
18721 /**
18722 * Determines whether the given point, in local coordinates is inside the view.
18723 */
18724 /*package*/ final boolean pointInView(float localX, float localY) {
18725 return pointInView(localX, localY, 0);
18726 }
18727
18728 /**
18729 * Utility method to determine whether the given point, in local coordinates,
18730 * is inside the view, where the area of the view is expanded by the slop factor.
18731 * This method is called while processing touch-move events to determine if the event
18732 * is still within the view.
18733 *
18734 * @hide
18735 */
18736 @UnsupportedAppUsage
18737 public boolean pointInView(float localX, float localY, float slop) {
18738 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
18739 localY < ((mBottom - mTop) + slop);
18740 }
18741
18742 /**
18743 * When a view has focus and the user navigates away from it, the next view is searched for
18744 * starting from the rectangle filled in by this method.
18745 *
18746 * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
18747 * of the view. However, if your view maintains some idea of internal selection,
18748 * such as a cursor, or a selected row or column, you should override this method and
18749 * fill in a more specific rectangle.
18750 *
18751 * @param r The rectangle to fill in, in this view's coordinates.
18752 */
18753 public void getFocusedRect(Rect r) {
18754 getDrawingRect(r);
18755 }
18756
18757 /**
18758 * Sets {@code r} to the coordinates of the non-clipped area of this view in
18759 * the coordinate space of the view's root view. Sets {@code globalOffset}
18760 * to the offset of the view's x and y coordinates from the coordinate space
18761 * origin, which is the top left corner of the root view irrespective of
18762 * screen decorations and system UI elements.
18763 *
18764 * <p>To convert {@code r} to coordinates relative to the top left corner of
18765 * this view (without taking view rotations into account), offset {@code r}
18766 * by the inverse values of
18767 * {@code globalOffset}&mdash;{@code r.offset(-globalOffset.x,
18768 * -globalOffset.y)}&mdash;which is equivalent to calling
18769 * {@link #getLocalVisibleRect(Rect) getLocalVisibleRect(Rect)}.
18770 *
18771 * <p><b>Note:</b> Do not use this method to determine the size of a window
18772 * in multi-window mode; use
18773 * {@link WindowManager#getCurrentWindowMetrics()}.
18774 *
18775 * @param r If the method returns true, contains the coordinates of the
18776 * visible portion of this view in the coordinate space of the view's
18777 * root view. If the method returns false, the contents of {@code r}
18778 * are undefined.
18779 * @param globalOffset If the method returns true, contains the offset of
18780 * the x and y coordinates of this view from the top left corner of the
18781 * view's root view. If the method returns false, the contents of
18782 * {@code globalOffset} are undefined. The argument can be null (see
18783 * {@link #getGlobalVisibleRect(Rect) getGlobalVisibleRect(Rect)}.
18784 * @return true if at least part of the view is visible within the root
18785 * view; false if the view is completely clipped or translated out of
18786 * the visible area of the root view.
18787 *
18788 * @see #getLocalVisibleRect(Rect)
18789 */
18790 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
18791 int width = mRight - mLeft;
18792 int height = mBottom - mTop;
18793 if (width > 0 && height > 0) {
18794 r.set(0, 0, width, height);
18795 if (globalOffset != null) {
18796 globalOffset.set(-mScrollX, -mScrollY);
18797 }
18798 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
18799 }
18800 return false;
18801 }
18802
18803 /**
18804 * Sets {@code r} to the coordinates of the non-clipped area of this view in
18805 * the coordinate space of the view's root view.
18806 *
18807 * <p>See {@link #getGlobalVisibleRect(Rect, Point)
18808 * getGlobalVisibleRect(Rect, Point)} for more information.
18809 *
18810 * @param r If the method returns true, contains the coordinates of the
18811 * visible portion of this view in the coordinate space of the view's
18812 * root view. If the method returns false, the contents of {@code r}
18813 * are undefined.
18814 * @return true if at least part of the view is visible within the root
18815 * view; otherwise false.
18816 */
18817 public final boolean getGlobalVisibleRect(Rect r) {
18818 return getGlobalVisibleRect(r, null);
18819 }
18820
18821 /**
18822 * Sets {@code r} to the coordinates of the non-clipped area of this view
18823 * relative to the top left corner of the view.
18824 *
18825 * <p>If the view is clipped on the left or top, the left and top
18826 * coordinates are offset from 0 by the clipped amount. For example, if the
18827 * view is off screen 50px on the left and 30px at the top, the left and top
18828 * coordinates are 50 and 30 respectively.
18829 *
18830 * <p>If the view is clipped on the right or bottom, the right and bottom
18831 * coordinates are reduced by the clipped amount. For example, if the view
18832 * is off screen 40px on the right and 20px at the bottom, the right
18833 * coordinate is the view width - 40, and the bottom coordinate is the view
18834 * height - 20.
18835 *
18836 * @param r If the method returns true, contains the coordinates of the
18837 * visible portion of this view relative to the top left corner of the
18838 * view. If the method returns false, the contents of {@code r} are
18839 * undefined.
18840 * @return true if at least part of the view is visible; false if the view
18841 * is completely clipped or translated out of the visible area.
18842 *
18843 * @see #getGlobalVisibleRect(Rect, Point)
18844 */
18845 public final boolean getLocalVisibleRect(Rect r) {
18846 final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
18847 if (getGlobalVisibleRect(r, offset)) {
18848 r.offset(-offset.x, -offset.y); // make r local
18849 return true;
18850 }
18851 return false;
18852 }
18853
18854 /**
18855 * Offset this view's vertical location by the specified number of pixels.
18856 *
18857 * @param offset the number of pixels to offset the view by
18858 */
18859 public void offsetTopAndBottom(int offset) {
18860 if (offset != 0) {
18861 final boolean matrixIsIdentity = hasIdentityMatrix();
18862 if (matrixIsIdentity) {
18863 if (isHardwareAccelerated()) {
18864 invalidateViewProperty(false, false);
18865 } else {
18866 final ViewParent p = mParent;
18867 if (p != null && mAttachInfo != null) {
18868 final Rect r = mAttachInfo.mTmpInvalRect;
18869 int minTop;
18870 int maxBottom;
18871 int yLoc;
18872 if (offset < 0) {
18873 minTop = mTop + offset;
18874 maxBottom = mBottom;
18875 yLoc = offset;
18876 } else {
18877 minTop = mTop;
18878 maxBottom = mBottom + offset;
18879 yLoc = 0;
18880 }
18881 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
18882 p.invalidateChild(this, r);
18883 }
18884 }
18885 } else {
18886 invalidateViewProperty(false, false);
18887 }
18888
18889 mTop += offset;
18890 mBottom += offset;
18891 mRenderNode.offsetTopAndBottom(offset);
18892 if (isHardwareAccelerated()) {
18893 invalidateViewProperty(false, false);
18894 invalidateParentIfNeededAndWasQuickRejected();
18895 } else {
18896 if (!matrixIsIdentity) {
18897 invalidateViewProperty(false, true);
18898 }
18899 invalidateParentIfNeeded();
18900 }
18901 notifySubtreeAccessibilityStateChangedIfNeeded();
18902 }
18903 }
18904
18905 /**
18906 * Offset this view's horizontal location by the specified amount of pixels.
18907 *
18908 * @param offset the number of pixels to offset the view by
18909 */
18910 public void offsetLeftAndRight(int offset) {
18911 if (offset != 0) {
18912 final boolean matrixIsIdentity = hasIdentityMatrix();
18913 if (matrixIsIdentity) {
18914 if (isHardwareAccelerated()) {
18915 invalidateViewProperty(false, false);
18916 } else {
18917 final ViewParent p = mParent;
18918 if (p != null && mAttachInfo != null) {
18919 final Rect r = mAttachInfo.mTmpInvalRect;
18920 int minLeft;
18921 int maxRight;
18922 if (offset < 0) {
18923 minLeft = mLeft + offset;
18924 maxRight = mRight;
18925 } else {
18926 minLeft = mLeft;
18927 maxRight = mRight + offset;
18928 }
18929 r.set(0, 0, maxRight - minLeft, mBottom - mTop);
18930 p.invalidateChild(this, r);
18931 }
18932 }
18933 } else {
18934 invalidateViewProperty(false, false);
18935 }
18936
18937 mLeft += offset;
18938 mRight += offset;
18939 mRenderNode.offsetLeftAndRight(offset);
18940 if (isHardwareAccelerated()) {
18941 invalidateViewProperty(false, false);
18942 invalidateParentIfNeededAndWasQuickRejected();
18943 } else {
18944 if (!matrixIsIdentity) {
18945 invalidateViewProperty(false, true);
18946 }
18947 invalidateParentIfNeeded();
18948 }
18949 notifySubtreeAccessibilityStateChangedIfNeeded();
18950 }
18951 }
18952
18953 /**
18954 * Get the LayoutParams associated with this view. All views should have
18955 * layout parameters. These supply parameters to the <i>parent</i> of this
18956 * view specifying how it should be arranged. There are many subclasses of
18957 * ViewGroup.LayoutParams, and these correspond to the different subclasses
18958 * of ViewGroup that are responsible for arranging their children.
18959 *
18960 * This method may return null if this View is not attached to a parent
18961 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
18962 * was not invoked successfully. When a View is attached to a parent
18963 * ViewGroup, this method must not return null.
18964 *
18965 * @return The LayoutParams associated with this view, or null if no
18966 * parameters have been set yet
18967 */
18968 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
18969 public ViewGroup.LayoutParams getLayoutParams() {
18970 return mLayoutParams;
18971 }
18972
18973 /**
18974 * Set the layout parameters associated with this view. These supply
18975 * parameters to the <i>parent</i> of this view specifying how it should be
18976 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
18977 * correspond to the different subclasses of ViewGroup that are responsible
18978 * for arranging their children.
18979 *
18980 * @param params The layout parameters for this view, cannot be null
18981 */
18982 public void setLayoutParams(ViewGroup.LayoutParams params) {
18983 if (params == null) {
18984 throw new NullPointerException("Layout parameters cannot be null");
18985 }
18986 mLayoutParams = params;
18987 resolveLayoutParams();
18988 if (mParent instanceof ViewGroup) {
18989 ((ViewGroup) mParent).onSetLayoutParams(this, params);
18990 }
18991 requestLayout();
18992 }
18993
18994 /**
18995 * Resolve the layout parameters depending on the resolved layout direction
18996 *
18997 * @hide
18998 */
18999 public void resolveLayoutParams() {
19000 if (mLayoutParams != null) {
19001 mLayoutParams.resolveLayoutDirection(getLayoutDirection());
19002 }
19003 }
19004
19005 /**
19006 * Set the scrolled position of your view. This will cause a call to
19007 * {@link #onScrollChanged(int, int, int, int)} and the view will be
19008 * invalidated.
19009 * @param x the x position to scroll to
19010 * @param y the y position to scroll to
19011 */
19012 public void scrollTo(int x, int y) {
19013 if (mScrollX != x || mScrollY != y) {
19014 int oldX = mScrollX;
19015 int oldY = mScrollY;
19016 mScrollX = x;
19017 mScrollY = y;
19018 invalidateParentCaches();
19019 onScrollChanged(mScrollX, mScrollY, oldX, oldY);
19020 if (!awakenScrollBars()) {
19021 postInvalidateOnAnimation();
19022 }
19023 }
19024 }
19025
19026 /**
19027 * Move the scrolled position of your view. This will cause a call to
19028 * {@link #onScrollChanged(int, int, int, int)} and the view will be
19029 * invalidated.
19030 * @param x the amount of pixels to scroll by horizontally
19031 * @param y the amount of pixels to scroll by vertically
19032 */
19033 public void scrollBy(int x, int y) {
19034 scrollTo(mScrollX + x, mScrollY + y);
19035 }
19036
19037 /**
19038 * <p>Trigger the scrollbars to draw. When invoked this method starts an
19039 * animation to fade the scrollbars out after a default delay. If a subclass
19040 * provides animated scrolling, the start delay should equal the duration
19041 * of the scrolling animation.</p>
19042 *
19043 * <p>The animation starts only if at least one of the scrollbars is
19044 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
19045 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
19046 * this method returns true, and false otherwise. If the animation is
19047 * started, this method calls {@link #invalidate()}; in that case the
19048 * caller should not call {@link #invalidate()}.</p>
19049 *
19050 * <p>This method should be invoked every time a subclass directly updates
19051 * the scroll parameters.</p>
19052 *
19053 * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
19054 * and {@link #scrollTo(int, int)}.</p>
19055 *
19056 * @return true if the animation is played, false otherwise
19057 *
19058 * @see #awakenScrollBars(int)
19059 * @see #scrollBy(int, int)
19060 * @see #scrollTo(int, int)
19061 * @see #isHorizontalScrollBarEnabled()
19062 * @see #isVerticalScrollBarEnabled()
19063 * @see #setHorizontalScrollBarEnabled(boolean)
19064 * @see #setVerticalScrollBarEnabled(boolean)
19065 */
19066 protected boolean awakenScrollBars() {
19067 return mScrollCache != null &&
19068 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
19069 }
19070
19071 /**
19072 * Trigger the scrollbars to draw.
19073 * This method differs from awakenScrollBars() only in its default duration.
19074 * initialAwakenScrollBars() will show the scroll bars for longer than
19075 * usual to give the user more of a chance to notice them.
19076 *
19077 * @return true if the animation is played, false otherwise.
19078 */
19079 private boolean initialAwakenScrollBars() {
19080 return mScrollCache != null &&
19081 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
19082 }
19083
19084 /**
19085 * <p>
19086 * Trigger the scrollbars to draw. When invoked this method starts an
19087 * animation to fade the scrollbars out after a fixed delay. If a subclass
19088 * provides animated scrolling, the start delay should equal the duration of
19089 * the scrolling animation.
19090 * </p>
19091 *
19092 * <p>
19093 * The animation starts only if at least one of the scrollbars is enabled,
19094 * as specified by {@link #isHorizontalScrollBarEnabled()} and
19095 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
19096 * this method returns true, and false otherwise. If the animation is
19097 * started, this method calls {@link #invalidate()}; in that case the caller
19098 * should not call {@link #invalidate()}.
19099 * </p>
19100 *
19101 * <p>
19102 * This method should be invoked every time a subclass directly updates the
19103 * scroll parameters.
19104 * </p>
19105 *
19106 * @param startDelay the delay, in milliseconds, after which the animation
19107 * should start; when the delay is 0, the animation starts
19108 * immediately
19109 * @return true if the animation is played, false otherwise
19110 *
19111 * @see #scrollBy(int, int)
19112 * @see #scrollTo(int, int)
19113 * @see #isHorizontalScrollBarEnabled()
19114 * @see #isVerticalScrollBarEnabled()
19115 * @see #setHorizontalScrollBarEnabled(boolean)
19116 * @see #setVerticalScrollBarEnabled(boolean)
19117 */
19118 protected boolean awakenScrollBars(int startDelay) {
19119 return awakenScrollBars(startDelay, true);
19120 }
19121
19122 /**
19123 * <p>
19124 * Trigger the scrollbars to draw. When invoked this method starts an
19125 * animation to fade the scrollbars out after a fixed delay. If a subclass
19126 * provides animated scrolling, the start delay should equal the duration of
19127 * the scrolling animation.
19128 * </p>
19129 *
19130 * <p>
19131 * The animation starts only if at least one of the scrollbars is enabled,
19132 * as specified by {@link #isHorizontalScrollBarEnabled()} and
19133 * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
19134 * this method returns true, and false otherwise. If the animation is
19135 * started, this method calls {@link #invalidate()} if the invalidate parameter
19136 * is set to true; in that case the caller
19137 * should not call {@link #invalidate()}.
19138 * </p>
19139 *
19140 * <p>
19141 * This method should be invoked every time a subclass directly updates the
19142 * scroll parameters.
19143 * </p>
19144 *
19145 * @param startDelay the delay, in milliseconds, after which the animation
19146 * should start; when the delay is 0, the animation starts
19147 * immediately
19148 *
19149 * @param invalidate Whether this method should call invalidate
19150 *
19151 * @return true if the animation is played, false otherwise
19152 *
19153 * @see #scrollBy(int, int)
19154 * @see #scrollTo(int, int)
19155 * @see #isHorizontalScrollBarEnabled()
19156 * @see #isVerticalScrollBarEnabled()
19157 * @see #setHorizontalScrollBarEnabled(boolean)
19158 * @see #setVerticalScrollBarEnabled(boolean)
19159 */
19160 protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
19161 final ScrollabilityCache scrollCache = mScrollCache;
19162
19163 if (scrollCache == null || !scrollCache.fadeScrollBars) {
19164 return false;
19165 }
19166
19167 if (scrollCache.scrollBar == null) {
19168 scrollCache.scrollBar = new ScrollBarDrawable();
19169 scrollCache.scrollBar.setState(getDrawableState());
19170 scrollCache.scrollBar.setCallback(this);
19171 }
19172
19173 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
19174
19175 if (invalidate) {
19176 // Invalidate to show the scrollbars
19177 postInvalidateOnAnimation();
19178 }
19179
19180 if (scrollCache.state == ScrollabilityCache.OFF) {
19181 // FIXME: this is copied from WindowManagerService.
19182 // We should get this value from the system when it
19183 // is possible to do so.
19184 final int KEY_REPEAT_FIRST_DELAY = 750;
19185 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
19186 }
19187
19188 // Tell mScrollCache when we should start fading. This may
19189 // extend the fade start time if one was already scheduled
19190 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
19191 scrollCache.fadeStartTime = fadeStartTime;
19192 scrollCache.state = ScrollabilityCache.ON;
19193
19194 // Schedule our fader to run, unscheduling any old ones first
19195 if (mAttachInfo != null) {
19196 mAttachInfo.mHandler.removeCallbacks(scrollCache);
19197 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
19198 }
19199
19200 return true;
19201 }
19202
19203 return false;
19204 }
19205
19206 /**
19207 * Do not invalidate views which are not visible and which are not running an animation. They
19208 * will not get drawn and they should not set dirty flags as if they will be drawn
19209 */
19210 private boolean skipInvalidate() {
19211 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
19212 (!(mParent instanceof ViewGroup) ||
19213 !((ViewGroup) mParent).isViewTransitioning(this));
19214 }
19215
19216 /**
19217 * Mark the area defined by dirty as needing to be drawn. If the view is
19218 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
19219 * point in the future.
19220 * <p>
19221 * This must be called from a UI thread. To call from a non-UI thread, call
19222 * {@link #postInvalidate()}.
19223 * <p>
19224 * <b>WARNING:</b> In API 19 and below, this method may be destructive to
19225 * {@code dirty}.
19226 *
19227 * @param dirty the rectangle representing the bounds of the dirty region
19228 *
19229 * @deprecated The switch to hardware accelerated rendering in API 14 reduced
19230 * the importance of the dirty rectangle. In API 21 the given rectangle is
19231 * ignored entirely in favor of an internally-calculated area instead.
19232 * Because of this, clients are encouraged to just call {@link #invalidate()}.
19233 */
19234 @Deprecated
19235 public void invalidate(Rect dirty) {
19236 final int scrollX = mScrollX;
19237 final int scrollY = mScrollY;
19238 invalidateInternal(dirty.left - scrollX, dirty.top - scrollY,
19239 dirty.right - scrollX, dirty.bottom - scrollY, true, false);
19240 }
19241
19242 /**
19243 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The
19244 * coordinates of the dirty rect are relative to the view. If the view is
19245 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
19246 * point in the future.
19247 * <p>
19248 * This must be called from a UI thread. To call from a non-UI thread, call
19249 * {@link #postInvalidate()}.
19250 *
19251 * @param l the left position of the dirty region
19252 * @param t the top position of the dirty region
19253 * @param r the right position of the dirty region
19254 * @param b the bottom position of the dirty region
19255 *
19256 * @deprecated The switch to hardware accelerated rendering in API 14 reduced
19257 * the importance of the dirty rectangle. In API 21 the given rectangle is
19258 * ignored entirely in favor of an internally-calculated area instead.
19259 * Because of this, clients are encouraged to just call {@link #invalidate()}.
19260 */
19261 @Deprecated
19262 public void invalidate(int l, int t, int r, int b) {
19263 final int scrollX = mScrollX;
19264 final int scrollY = mScrollY;
19265 invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false);
19266 }
19267
19268 /**
19269 * Invalidate the whole view. If the view is visible,
19270 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
19271 * the future.
19272 * <p>
19273 * This must be called from a UI thread. To call from a non-UI thread, call
19274 * {@link #postInvalidate()}.
19275 */
19276 public void invalidate() {
19277 invalidate(true);
19278 }
19279
19280 /**
19281 * This is where the invalidate() work actually happens. A full invalidate()
19282 * causes the drawing cache to be invalidated, but this function can be
19283 * called with invalidateCache set to false to skip that invalidation step
19284 * for cases that do not need it (for example, a component that remains at
19285 * the same dimensions with the same content).
19286 *
19287 * @param invalidateCache Whether the drawing cache for this view should be
19288 * invalidated as well. This is usually true for a full
19289 * invalidate, but may be set to false if the View's contents or
19290 * dimensions have not changed.
19291 * @hide
19292 */
19293 @UnsupportedAppUsage
19294 public void invalidate(boolean invalidateCache) {
19295 invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
19296 }
19297
19298 void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
19299 boolean fullInvalidate) {
19300 if (mGhostView != null) {
19301 mGhostView.invalidate(true);
19302 return;
19303 }
19304
19305 if (skipInvalidate()) {
19306 return;
19307 }
19308
19309 // Reset content capture caches
19310 mPrivateFlags4 &= ~PFLAG4_CONTENT_CAPTURE_IMPORTANCE_MASK;
19311 mContentCaptureSessionCached = false;
19312
19313 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)
19314 || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID)
19315 || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED
19316 || (fullInvalidate && isOpaque() != mLastIsOpaque)) {
19317 if (fullInvalidate) {
19318 mLastIsOpaque = isOpaque();
19319 mPrivateFlags &= ~PFLAG_DRAWN;
19320 }
19321
19322 mPrivateFlags |= PFLAG_DIRTY;
19323
19324 if (invalidateCache) {
19325 mPrivateFlags |= PFLAG_INVALIDATED;
19326 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
19327 }
19328
19329 // Propagate the damage rectangle to the parent view.
19330 final AttachInfo ai = mAttachInfo;
19331 final ViewParent p = mParent;
19332 if (p != null && ai != null && l < r && t < b) {
19333 final Rect damage = ai.mTmpInvalRect;
19334 damage.set(l, t, r, b);
19335 p.invalidateChild(this, damage);
19336 }
19337
19338 // Damage the entire projection receiver, if necessary.
19339 if (mBackground != null && mBackground.isProjected()) {
19340 final View receiver = getProjectionReceiver();
19341 if (receiver != null) {
19342 receiver.damageInParent();
19343 }
19344 }
19345 }
19346 }
19347
19348 /**
19349 * @return this view's projection receiver, or {@code null} if none exists
19350 */
19351 private View getProjectionReceiver() {
19352 ViewParent p = getParent();
19353 while (p != null && p instanceof View) {
19354 final View v = (View) p;
19355 if (v.isProjectionReceiver()) {
19356 return v;
19357 }
19358 p = p.getParent();
19359 }
19360
19361 return null;
19362 }
19363
19364 /**
19365 * @return whether the view is a projection receiver
19366 */
19367 private boolean isProjectionReceiver() {
19368 return mBackground != null;
19369 }
19370
19371 /**
19372 * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
19373 * set any flags or handle all of the cases handled by the default invalidation methods.
19374 * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
19375 * dirty rect. This method calls into fast invalidation methods in ViewGroup that
19376 * walk up the hierarchy, transforming the dirty rect as necessary.
19377 *
19378 * The method also handles normal invalidation logic if display list properties are not
19379 * being used in this view. The invalidateParent and forceRedraw flags are used by that
19380 * backup approach, to handle these cases used in the various property-setting methods.
19381 *
19382 * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
19383 * are not being used in this view
19384 * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
19385 * list properties are not being used in this view
19386 */
19387 @UnsupportedAppUsage
19388 void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
19389 if (!isHardwareAccelerated()
19390 || !mRenderNode.hasDisplayList()
19391 || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) {
19392 if (invalidateParent) {
19393 invalidateParentCaches();
19394 }
19395 if (forceRedraw) {
19396 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
19397 }
19398 invalidate(false);
19399 } else {
19400 damageInParent();
19401 }
19402 }
19403
19404 /**
19405 * Tells the parent view to damage this view's bounds.
19406 *
19407 * @hide
19408 */
19409 protected void damageInParent() {
19410 if (mParent != null && mAttachInfo != null) {
19411 mParent.onDescendantInvalidated(this, this);
19412 }
19413 }
19414
19415 /**
19416 * Used to indicate that the parent of this view should clear its caches. This functionality
19417 * is used to force the parent to rebuild its display list (when hardware-accelerated),
19418 * which is necessary when various parent-managed properties of the view change, such as
19419 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
19420 * clears the parent caches and does not causes an invalidate event.
19421 *
19422 * @hide
19423 */
19424 @UnsupportedAppUsage
19425 protected void invalidateParentCaches() {
19426 if (mParent instanceof View) {
19427 ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
19428 }
19429 }
19430
19431 /**
19432 * Used to indicate that the parent of this view should be invalidated. This functionality
19433 * is used to force the parent to rebuild its display list (when hardware-accelerated),
19434 * which is necessary when various parent-managed properties of the view change, such as
19435 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
19436 * an invalidation event to the parent.
19437 *
19438 * @hide
19439 */
19440 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
19441 protected void invalidateParentIfNeeded() {
19442 if (isHardwareAccelerated() && mParent instanceof View) {
19443 ((View) mParent).invalidate(true);
19444 }
19445 }
19446
19447 /**
19448 * @hide
19449 */
19450 protected void invalidateParentIfNeededAndWasQuickRejected() {
19451 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) {
19452 // View was rejected last time it was drawn by its parent; this may have changed
19453 invalidateParentIfNeeded();
19454 }
19455 }
19456
19457 /**
19458 * Indicates whether this View is opaque. An opaque View guarantees that it will
19459 * draw all the pixels overlapping its bounds using a fully opaque color.
19460 *
19461 * Subclasses of View should override this method whenever possible to indicate
19462 * whether an instance is opaque. Opaque Views are treated in a special way by
19463 * the View hierarchy, possibly allowing it to perform optimizations during
19464 * invalidate/draw passes.
19465 *
19466 * @return True if this View is guaranteed to be fully opaque, false otherwise.
19467 */
19468 @ViewDebug.ExportedProperty(category = "drawing")
19469 public boolean isOpaque() {
19470 return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
19471 getFinalAlpha() >= 1.0f;
19472 }
19473
19474 /**
19475 * @hide
19476 */
19477 @UnsupportedAppUsage
19478 protected void computeOpaqueFlags() {
19479 // Opaque if:
19480 // - Has a background
19481 // - Background is opaque
19482 // - Doesn't have scrollbars or scrollbars overlay
19483
19484 if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
19485 mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
19486 } else {
19487 mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
19488 }
19489
19490 final int flags = mViewFlags;
19491 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
19492 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
19493 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
19494 mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
19495 } else {
19496 mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
19497 }
19498 }
19499
19500 /**
19501 * @hide
19502 */
19503 protected boolean hasOpaqueScrollbars() {
19504 return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
19505 }
19506
19507 /**
19508 * @return A handler associated with the thread running the View. This
19509 * handler can be used to pump events in the UI events queue.
19510 */
19511 public Handler getHandler() {
19512 final AttachInfo attachInfo = mAttachInfo;
19513 if (attachInfo != null) {
19514 return attachInfo.mHandler;
19515 }
19516 return null;
19517 }
19518
19519 /**
19520 * Returns the queue of runnable for this view.
19521 *
19522 * @return the queue of runnables for this view
19523 */
19524 private HandlerActionQueue getRunQueue() {
19525 if (mRunQueue == null) {
19526 mRunQueue = new HandlerActionQueue();
19527 }
19528 return mRunQueue;
19529 }
19530
19531 /**
19532 * Gets the view root associated with the View.
19533 * @return The view root, or null if none.
19534 * @hide
19535 */
19536 @UnsupportedAppUsage
19537 public ViewRootImpl getViewRootImpl() {
19538 if (mAttachInfo != null) {
19539 return mAttachInfo.mViewRootImpl;
19540 }
19541 return null;
19542 }
19543
19544 /**
19545 * @hide
19546 */
19547 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
19548 public ThreadedRenderer getThreadedRenderer() {
19549 return mAttachInfo != null ? mAttachInfo.mThreadedRenderer : null;
19550 }
19551
19552 /**
19553 * <p>Causes the Runnable to be added to the message queue.
19554 * The runnable will be run on the user interface thread.</p>
19555 *
19556 * @param action The Runnable that will be executed.
19557 *
19558 * @return Returns true if the Runnable was successfully placed in to the
19559 * message queue. Returns false on failure, usually because the
19560 * looper processing the message queue is exiting.
19561 *
19562 * @see #postDelayed
19563 * @see #removeCallbacks
19564 */
19565 public boolean post(Runnable action) {
19566 final AttachInfo attachInfo = mAttachInfo;
19567 if (attachInfo != null) {
19568 return attachInfo.mHandler.post(action);
19569 }
19570
19571 // Postpone the runnable until we know on which thread it needs to run.
19572 // Assume that the runnable will be successfully placed after attach.
19573 getRunQueue().post(action);
19574 return true;
19575 }
19576
19577 /**
19578 * <p>Causes the Runnable to be added to the message queue, to be run
19579 * after the specified amount of time elapses.
19580 * The runnable will be run on the user interface thread.</p>
19581 *
19582 * @param action The Runnable that will be executed.
19583 * @param delayMillis The delay (in milliseconds) until the Runnable
19584 * will be executed.
19585 *
19586 * @return true if the Runnable was successfully placed in to the
19587 * message queue. Returns false on failure, usually because the
19588 * looper processing the message queue is exiting. Note that a
19589 * result of true does not mean the Runnable will be processed --
19590 * if the looper is quit before the delivery time of the message
19591 * occurs then the message will be dropped.
19592 *
19593 * @see #post
19594 * @see #removeCallbacks
19595 */
19596 public boolean postDelayed(Runnable action, long delayMillis) {
19597 final AttachInfo attachInfo = mAttachInfo;
19598 if (attachInfo != null) {
19599 return attachInfo.mHandler.postDelayed(action, delayMillis);
19600 }
19601
19602 // Postpone the runnable until we know on which thread it needs to run.
19603 // Assume that the runnable will be successfully placed after attach.
19604 getRunQueue().postDelayed(action, delayMillis);
19605 return true;
19606 }
19607
19608 /**
19609 * <p>Causes the Runnable to execute on the next animation time step.
19610 * The runnable will be run on the user interface thread.</p>
19611 *
19612 * @param action The Runnable that will be executed.
19613 *
19614 * @see #postOnAnimationDelayed
19615 * @see #removeCallbacks
19616 */
19617 public void postOnAnimation(Runnable action) {
19618 final AttachInfo attachInfo = mAttachInfo;
19619 if (attachInfo != null) {
19620 attachInfo.mViewRootImpl.mChoreographer.postCallback(
19621 Choreographer.CALLBACK_ANIMATION, action, null);
19622 } else {
19623 // Postpone the runnable until we know
19624 // on which thread it needs to run.
19625 getRunQueue().post(action);
19626 }
19627 }
19628
19629 /**
19630 * <p>Causes the Runnable to execute on the next animation time step,
19631 * after the specified amount of time elapses.
19632 * The runnable will be run on the user interface thread.</p>
19633 *
19634 * @param action The Runnable that will be executed.
19635 * @param delayMillis The delay (in milliseconds) until the Runnable
19636 * will be executed.
19637 *
19638 * @see #postOnAnimation
19639 * @see #removeCallbacks
19640 */
19641 public void postOnAnimationDelayed(Runnable action, long delayMillis) {
19642 final AttachInfo attachInfo = mAttachInfo;
19643 if (attachInfo != null) {
19644 attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
19645 Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
19646 } else {
19647 // Postpone the runnable until we know
19648 // on which thread it needs to run.
19649 getRunQueue().postDelayed(action, delayMillis);
19650 }
19651 }
19652
19653 /**
19654 * <p>Removes the specified Runnable from the message queue.</p>
19655 *
19656 * @param action The Runnable to remove from the message handling queue
19657 *
19658 * @return true if this view could ask the Handler to remove the Runnable,
19659 * false otherwise. When the returned value is true, the Runnable
19660 * may or may not have been actually removed from the message queue
19661 * (for instance, if the Runnable was not in the queue already.)
19662 *
19663 * @see #post
19664 * @see #postDelayed
19665 * @see #postOnAnimation
19666 * @see #postOnAnimationDelayed
19667 */
19668 public boolean removeCallbacks(Runnable action) {
19669 if (action != null) {
19670 final AttachInfo attachInfo = mAttachInfo;
19671 if (attachInfo != null) {
19672 attachInfo.mHandler.removeCallbacks(action);
19673 attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
19674 Choreographer.CALLBACK_ANIMATION, action, null);
19675 }
19676 getRunQueue().removeCallbacks(action);
19677 }
19678 return true;
19679 }
19680
19681 /**
19682 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
19683 * Use this to invalidate the View from a non-UI thread.</p>
19684 *
19685 * <p>This method can be invoked from outside of the UI thread
19686 * only when this View is attached to a window.</p>
19687 *
19688 * @see #invalidate()
19689 * @see #postInvalidateDelayed(long)
19690 */
19691 public void postInvalidate() {
19692 postInvalidateDelayed(0);
19693 }
19694
19695 /**
19696 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
19697 * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
19698 *
19699 * <p>This method can be invoked from outside of the UI thread
19700 * only when this View is attached to a window.</p>
19701 *
19702 * @param left The left coordinate of the rectangle to invalidate.
19703 * @param top The top coordinate of the rectangle to invalidate.
19704 * @param right The right coordinate of the rectangle to invalidate.
19705 * @param bottom The bottom coordinate of the rectangle to invalidate.
19706 *
19707 * @see #invalidate(int, int, int, int)
19708 * @see #invalidate(Rect)
19709 * @see #postInvalidateDelayed(long, int, int, int, int)
19710 */
19711 public void postInvalidate(int left, int top, int right, int bottom) {
19712 postInvalidateDelayed(0, left, top, right, bottom);
19713 }
19714
19715 /**
19716 * <p>Cause an invalidate to happen on a subsequent cycle through the event
19717 * loop. Waits for the specified amount of time.</p>
19718 *
19719 * <p>This method can be invoked from outside of the UI thread
19720 * only when this View is attached to a window.</p>
19721 *
19722 * @param delayMilliseconds the duration in milliseconds to delay the
19723 * invalidation by
19724 *
19725 * @see #invalidate()
19726 * @see #postInvalidate()
19727 */
19728 public void postInvalidateDelayed(long delayMilliseconds) {
19729 // We try only with the AttachInfo because there's no point in invalidating
19730 // if we are not attached to our window
19731 final AttachInfo attachInfo = mAttachInfo;
19732 if (attachInfo != null) {
19733 attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
19734 }
19735 }
19736
19737 /**
19738 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
19739 * through the event loop. Waits for the specified amount of time.</p>
19740 *
19741 * <p>This method can be invoked from outside of the UI thread
19742 * only when this View is attached to a window.</p>
19743 *
19744 * @param delayMilliseconds the duration in milliseconds to delay the
19745 * invalidation by
19746 * @param left The left coordinate of the rectangle to invalidate.
19747 * @param top The top coordinate of the rectangle to invalidate.
19748 * @param right The right coordinate of the rectangle to invalidate.
19749 * @param bottom The bottom coordinate of the rectangle to invalidate.
19750 *
19751 * @see #invalidate(int, int, int, int)
19752 * @see #invalidate(Rect)
19753 * @see #postInvalidate(int, int, int, int)
19754 */
19755 public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
19756 int right, int bottom) {
19757
19758 // We try only with the AttachInfo because there's no point in invalidating
19759 // if we are not attached to our window
19760 final AttachInfo attachInfo = mAttachInfo;
19761 if (attachInfo != null) {
19762 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
19763 info.target = this;
19764 info.left = left;
19765 info.top = top;
19766 info.right = right;
19767 info.bottom = bottom;
19768
19769 attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
19770 }
19771 }
19772
19773 /**
19774 * <p>Cause an invalidate to happen on the next animation time step, typically the
19775 * next display frame.</p>
19776 *
19777 * <p>This method can be invoked from outside of the UI thread
19778 * only when this View is attached to a window.</p>
19779 *
19780 * @see #invalidate()
19781 */
19782 public void postInvalidateOnAnimation() {
19783 // We try only with the AttachInfo because there's no point in invalidating
19784 // if we are not attached to our window
19785 final AttachInfo attachInfo = mAttachInfo;
19786 if (attachInfo != null) {
19787 attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
19788 }
19789 }
19790
19791 /**
19792 * <p>Cause an invalidate of the specified area to happen on the next animation
19793 * time step, typically the next display frame.</p>
19794 *
19795 * <p>This method can be invoked from outside of the UI thread
19796 * only when this View is attached to a window.</p>
19797 *
19798 * @param left The left coordinate of the rectangle to invalidate.
19799 * @param top The top coordinate of the rectangle to invalidate.
19800 * @param right The right coordinate of the rectangle to invalidate.
19801 * @param bottom The bottom coordinate of the rectangle to invalidate.
19802 *
19803 * @see #invalidate(int, int, int, int)
19804 * @see #invalidate(Rect)
19805 */
19806 public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
19807 // We try only with the AttachInfo because there's no point in invalidating
19808 // if we are not attached to our window
19809 final AttachInfo attachInfo = mAttachInfo;
19810 if (attachInfo != null) {
19811 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
19812 info.target = this;
19813 info.left = left;
19814 info.top = top;
19815 info.right = right;
19816 info.bottom = bottom;
19817
19818 attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
19819 }
19820 }
19821
19822 /**
19823 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
19824 * This event is sent at most once every
19825 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
19826 */
19827 private void postSendViewScrolledAccessibilityEventCallback(int dx, int dy) {
19828 if (AccessibilityManager.getInstance(mContext).isEnabled()) {
19829 AccessibilityEvent event =
19830 AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_SCROLLED);
19831 event.setScrollDeltaX(dx);
19832 event.setScrollDeltaY(dy);
19833 sendAccessibilityEventUnchecked(event);
19834 }
19835 }
19836
19837 /**
19838 * Called by a parent to request that a child update its values for mScrollX
19839 * and mScrollY if necessary. This will typically be done if the child is
19840 * animating a scroll using a {@link android.widget.Scroller Scroller}
19841 * object.
19842 */
19843 public void computeScroll() {
19844 }
19845
19846 /**
19847 * <p>Indicate whether the horizontal edges are faded when the view is
19848 * scrolled horizontally.</p>
19849 *
19850 * @return true if the horizontal edges should are faded on scroll, false
19851 * otherwise
19852 *
19853 * @see #setHorizontalFadingEdgeEnabled(boolean)
19854 *
19855 * @attr ref android.R.styleable#View_requiresFadingEdge
19856 */
19857 public boolean isHorizontalFadingEdgeEnabled() {
19858 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
19859 }
19860
19861 /**
19862 * <p>Define whether the horizontal edges should be faded when this view
19863 * is scrolled horizontally.</p>
19864 *
19865 * @param horizontalFadingEdgeEnabled true if the horizontal edges should
19866 * be faded when the view is scrolled
19867 * horizontally
19868 *
19869 * @see #isHorizontalFadingEdgeEnabled()
19870 *
19871 * @attr ref android.R.styleable#View_requiresFadingEdge
19872 */
19873 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
19874 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
19875 if (horizontalFadingEdgeEnabled) {
19876 initScrollCache();
19877 }
19878
19879 mViewFlags ^= FADING_EDGE_HORIZONTAL;
19880 }
19881 }
19882
19883 /**
19884 * <p>Indicate whether the vertical edges are faded when the view is
19885 * scrolled horizontally.</p>
19886 *
19887 * @return true if the vertical edges should are faded on scroll, false
19888 * otherwise
19889 *
19890 * @see #setVerticalFadingEdgeEnabled(boolean)
19891 *
19892 * @attr ref android.R.styleable#View_requiresFadingEdge
19893 */
19894 public boolean isVerticalFadingEdgeEnabled() {
19895 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
19896 }
19897
19898 /**
19899 * <p>Define whether the vertical edges should be faded when this view
19900 * is scrolled vertically.</p>
19901 *
19902 * @param verticalFadingEdgeEnabled true if the vertical edges should
19903 * be faded when the view is scrolled
19904 * vertically
19905 *
19906 * @see #isVerticalFadingEdgeEnabled()
19907 *
19908 * @attr ref android.R.styleable#View_requiresFadingEdge
19909 */
19910 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
19911 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
19912 if (verticalFadingEdgeEnabled) {
19913 initScrollCache();
19914 }
19915
19916 mViewFlags ^= FADING_EDGE_VERTICAL;
19917 }
19918 }
19919
19920 /**
19921 * Get the fading edge flags, used for inspection.
19922 *
19923 * @return One of {@link #FADING_EDGE_NONE}, {@link #FADING_EDGE_VERTICAL},
19924 * or {@link #FADING_EDGE_HORIZONTAL}
19925 * @hide
19926 */
19927 @InspectableProperty(name = "requiresFadingEdge", flagMapping = {
19928 @FlagEntry(target = FADING_EDGE_NONE, mask = FADING_EDGE_MASK, name = "none"),
19929 @FlagEntry(target = FADING_EDGE_VERTICAL, name = "vertical"),
19930 @FlagEntry(target = FADING_EDGE_HORIZONTAL, name = "horizontal")
19931 })
19932 public int getFadingEdge() {
19933 return mViewFlags & FADING_EDGE_MASK;
19934 }
19935
19936 /**
19937 * Get the fading edge length, used for inspection
19938 *
19939 * @return The fading edge length or 0
19940 * @hide
19941 */
19942 @InspectableProperty
19943 public int getFadingEdgeLength() {
19944 if (mScrollCache != null && (mViewFlags & FADING_EDGE_MASK) != FADING_EDGE_NONE) {
19945 return mScrollCache.fadingEdgeLength;
19946 }
19947 return 0;
19948 }
19949
19950 /**
19951 * Returns the strength, or intensity, of the top faded edge. The strength is
19952 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
19953 * returns 0.0 or 1.0 but no value in between.
19954 *
19955 * Subclasses should override this method to provide a smoother fade transition
19956 * when scrolling occurs.
19957 *
19958 * @return the intensity of the top fade as a float between 0.0f and 1.0f
19959 */
19960 protected float getTopFadingEdgeStrength() {
19961 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
19962 }
19963
19964 /**
19965 * Returns the strength, or intensity, of the bottom faded edge. The strength is
19966 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
19967 * returns 0.0 or 1.0 but no value in between.
19968 *
19969 * Subclasses should override this method to provide a smoother fade transition
19970 * when scrolling occurs.
19971 *
19972 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
19973 */
19974 protected float getBottomFadingEdgeStrength() {
19975 return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
19976 computeVerticalScrollRange() ? 1.0f : 0.0f;
19977 }
19978
19979 /**
19980 * Returns the strength, or intensity, of the left faded edge. The strength is
19981 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
19982 * returns 0.0 or 1.0 but no value in between.
19983 *
19984 * Subclasses should override this method to provide a smoother fade transition
19985 * when scrolling occurs.
19986 *
19987 * @return the intensity of the left fade as a float between 0.0f and 1.0f
19988 */
19989 protected float getLeftFadingEdgeStrength() {
19990 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
19991 }
19992
19993 /**
19994 * Returns the strength, or intensity, of the right faded edge. The strength is
19995 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
19996 * returns 0.0 or 1.0 but no value in between.
19997 *
19998 * Subclasses should override this method to provide a smoother fade transition
19999 * when scrolling occurs.
20000 *
20001 * @return the intensity of the right fade as a float between 0.0f and 1.0f
20002 */
20003 protected float getRightFadingEdgeStrength() {
20004 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
20005 computeHorizontalScrollRange() ? 1.0f : 0.0f;
20006 }
20007
20008 /**
20009 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
20010 * scrollbar is not drawn by default.</p>
20011 *
20012 * @return true if the horizontal scrollbar should be painted, false
20013 * otherwise
20014 *
20015 * @see #setHorizontalScrollBarEnabled(boolean)
20016 */
20017 public boolean isHorizontalScrollBarEnabled() {
20018 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
20019 }
20020
20021 /**
20022 * <p>Define whether the horizontal scrollbar should be drawn or not. The
20023 * scrollbar is not drawn by default.</p>
20024 *
20025 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
20026 * be painted
20027 *
20028 * @see #isHorizontalScrollBarEnabled()
20029 */
20030 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
20031 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
20032 mViewFlags ^= SCROLLBARS_HORIZONTAL;
20033 computeOpaqueFlags();
20034 resolvePadding();
20035 }
20036 }
20037
20038 /**
20039 * <p>Indicate whether the vertical scrollbar should be drawn or not. The
20040 * scrollbar is not drawn by default.</p>
20041 *
20042 * @return true if the vertical scrollbar should be painted, false
20043 * otherwise
20044 *
20045 * @see #setVerticalScrollBarEnabled(boolean)
20046 */
20047 public boolean isVerticalScrollBarEnabled() {
20048 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
20049 }
20050
20051 /**
20052 * <p>Define whether the vertical scrollbar should be drawn or not. The
20053 * scrollbar is not drawn by default.</p>
20054 *
20055 * @param verticalScrollBarEnabled true if the vertical scrollbar should
20056 * be painted
20057 *
20058 * @see #isVerticalScrollBarEnabled()
20059 */
20060 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
20061 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
20062 mViewFlags ^= SCROLLBARS_VERTICAL;
20063 computeOpaqueFlags();
20064 resolvePadding();
20065 }
20066 }
20067
20068 /**
20069 * @hide
20070 */
20071 @UnsupportedAppUsage
20072 protected void recomputePadding() {
20073 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
20074 }
20075
20076 /**
20077 * Define whether scrollbars will fade when the view is not scrolling.
20078 *
20079 * @param fadeScrollbars whether to enable fading
20080 *
20081 * @attr ref android.R.styleable#View_fadeScrollbars
20082 */
20083 public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
20084 initScrollCache();
20085 final ScrollabilityCache scrollabilityCache = mScrollCache;
20086 scrollabilityCache.fadeScrollBars = fadeScrollbars;
20087 if (fadeScrollbars) {
20088 scrollabilityCache.state = ScrollabilityCache.OFF;
20089 } else {
20090 scrollabilityCache.state = ScrollabilityCache.ON;
20091 }
20092 }
20093
20094 /**
20095 *
20096 * Returns true if scrollbars will fade when this view is not scrolling
20097 *
20098 * @return true if scrollbar fading is enabled
20099 *
20100 * @attr ref android.R.styleable#View_fadeScrollbars
20101 */
20102 public boolean isScrollbarFadingEnabled() {
20103 return mScrollCache != null && mScrollCache.fadeScrollBars;
20104 }
20105
20106 /**
20107 *
20108 * Returns the delay before scrollbars fade.
20109 *
20110 * @return the delay before scrollbars fade
20111 *
20112 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
20113 */
20114 @InspectableProperty(name = "scrollbarDefaultDelayBeforeFade")
20115 public int getScrollBarDefaultDelayBeforeFade() {
20116 return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
20117 mScrollCache.scrollBarDefaultDelayBeforeFade;
20118 }
20119
20120 /**
20121 * Define the delay before scrollbars fade.
20122 *
20123 * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
20124 *
20125 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
20126 */
20127 public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
20128 getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
20129 }
20130
20131 /**
20132 *
20133 * Returns the scrollbar fade duration.
20134 *
20135 * @return the scrollbar fade duration, in milliseconds
20136 *
20137 * @attr ref android.R.styleable#View_scrollbarFadeDuration
20138 */
20139 @InspectableProperty(name = "scrollbarFadeDuration")
20140 public int getScrollBarFadeDuration() {
20141 return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
20142 mScrollCache.scrollBarFadeDuration;
20143 }
20144
20145 /**
20146 * Define the scrollbar fade duration.
20147 *
20148 * @param scrollBarFadeDuration - the scrollbar fade duration, in milliseconds
20149 *
20150 * @attr ref android.R.styleable#View_scrollbarFadeDuration
20151 */
20152 public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
20153 getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
20154 }
20155
20156 /**
20157 *
20158 * Returns the scrollbar size.
20159 *
20160 * @return the scrollbar size
20161 *
20162 * @attr ref android.R.styleable#View_scrollbarSize
20163 */
20164 @InspectableProperty(name = "scrollbarSize")
20165 public int getScrollBarSize() {
20166 return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
20167 mScrollCache.scrollBarSize;
20168 }
20169
20170 /**
20171 * Define the scrollbar size.
20172 *
20173 * @param scrollBarSize - the scrollbar size
20174 *
20175 * @attr ref android.R.styleable#View_scrollbarSize
20176 */
20177 public void setScrollBarSize(int scrollBarSize) {
20178 getScrollCache().scrollBarSize = scrollBarSize;
20179 }
20180
20181 /**
20182 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
20183 * inset. When inset, they add to the padding of the view. And the scrollbars
20184 * can be drawn inside the padding area or on the edge of the view. For example,
20185 * if a view has a background drawable and you want to draw the scrollbars
20186 * inside the padding specified by the drawable, you can use
20187 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
20188 * appear at the edge of the view, ignoring the padding, then you can use
20189 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
20190 * @param style the style of the scrollbars. Should be one of
20191 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
20192 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
20193 * @see #SCROLLBARS_INSIDE_OVERLAY
20194 * @see #SCROLLBARS_INSIDE_INSET
20195 * @see #SCROLLBARS_OUTSIDE_OVERLAY
20196 * @see #SCROLLBARS_OUTSIDE_INSET
20197 *
20198 * @attr ref android.R.styleable#View_scrollbarStyle
20199 */
20200 public void setScrollBarStyle(@ScrollBarStyle int style) {
20201 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
20202 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
20203 computeOpaqueFlags();
20204 resolvePadding();
20205 }
20206 }
20207
20208 /**
20209 * <p>Returns the current scrollbar style.</p>
20210 * @return the current scrollbar style
20211 * @see #SCROLLBARS_INSIDE_OVERLAY
20212 * @see #SCROLLBARS_INSIDE_INSET
20213 * @see #SCROLLBARS_OUTSIDE_OVERLAY
20214 * @see #SCROLLBARS_OUTSIDE_INSET
20215 *
20216 * @attr ref android.R.styleable#View_scrollbarStyle
20217 */
20218 @ViewDebug.ExportedProperty(mapping = {
20219 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
20220 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
20221 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
20222 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
20223 })
20224 @InspectableProperty(name = "scrollbarStyle", enumMapping = {
20225 @EnumEntry(value = SCROLLBARS_INSIDE_OVERLAY, name = "insideOverlay"),
20226 @EnumEntry(value = SCROLLBARS_INSIDE_INSET, name = "insideInset"),
20227 @EnumEntry(value = SCROLLBARS_OUTSIDE_OVERLAY, name = "outsideOverlay"),
20228 @EnumEntry(value = SCROLLBARS_OUTSIDE_INSET, name = "outsideInset")
20229 })
20230 @ScrollBarStyle
20231 public int getScrollBarStyle() {
20232 return mViewFlags & SCROLLBARS_STYLE_MASK;
20233 }
20234
20235 /**
20236 * <p>Compute the horizontal range that the horizontal scrollbar
20237 * represents.</p>
20238 *
20239 * <p>The range is expressed in arbitrary units that must be the same as the
20240 * units used by {@link #computeHorizontalScrollExtent()} and
20241 * {@link #computeHorizontalScrollOffset()}.</p>
20242 *
20243 * <p>The default range is the drawing width of this view.</p>
20244 *
20245 * @return the total horizontal range represented by the horizontal
20246 * scrollbar
20247 *
20248 * @see #computeHorizontalScrollExtent()
20249 * @see #computeHorizontalScrollOffset()
20250 */
20251 protected int computeHorizontalScrollRange() {
20252 return getWidth();
20253 }
20254
20255 /**
20256 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
20257 * within the horizontal range. This value is used to compute the position
20258 * of the thumb within the scrollbar's track.</p>
20259 *
20260 * <p>The range is expressed in arbitrary units that must be the same as the
20261 * units used by {@link #computeHorizontalScrollRange()} and
20262 * {@link #computeHorizontalScrollExtent()}.</p>
20263 *
20264 * <p>The default offset is the scroll offset of this view.</p>
20265 *
20266 * @return the horizontal offset of the scrollbar's thumb
20267 *
20268 * @see #computeHorizontalScrollRange()
20269 * @see #computeHorizontalScrollExtent()
20270 */
20271 protected int computeHorizontalScrollOffset() {
20272 return mScrollX;
20273 }
20274
20275 /**
20276 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
20277 * within the horizontal range. This value is used to compute the length
20278 * of the thumb within the scrollbar's track.</p>
20279 *
20280 * <p>The range is expressed in arbitrary units that must be the same as the
20281 * units used by {@link #computeHorizontalScrollRange()} and
20282 * {@link #computeHorizontalScrollOffset()}.</p>
20283 *
20284 * <p>The default extent is the drawing width of this view.</p>
20285 *
20286 * @return the horizontal extent of the scrollbar's thumb
20287 *
20288 * @see #computeHorizontalScrollRange()
20289 * @see #computeHorizontalScrollOffset()
20290 */
20291 protected int computeHorizontalScrollExtent() {
20292 return getWidth();
20293 }
20294
20295 /**
20296 * <p>Compute the vertical range that the vertical scrollbar represents.</p>
20297 *
20298 * <p>The range is expressed in arbitrary units that must be the same as the
20299 * units used by {@link #computeVerticalScrollExtent()} and
20300 * {@link #computeVerticalScrollOffset()}.</p>
20301 *
20302 * @return the total vertical range represented by the vertical scrollbar
20303 *
20304 * <p>The default range is the drawing height of this view.</p>
20305 *
20306 * @see #computeVerticalScrollExtent()
20307 * @see #computeVerticalScrollOffset()
20308 */
20309 protected int computeVerticalScrollRange() {
20310 return getHeight();
20311 }
20312
20313 /**
20314 * <p>Compute the vertical offset of the vertical scrollbar's thumb
20315 * within the horizontal range. This value is used to compute the position
20316 * of the thumb within the scrollbar's track.</p>
20317 *
20318 * <p>The range is expressed in arbitrary units that must be the same as the
20319 * units used by {@link #computeVerticalScrollRange()} and
20320 * {@link #computeVerticalScrollExtent()}.</p>
20321 *
20322 * <p>The default offset is the scroll offset of this view.</p>
20323 *
20324 * @return the vertical offset of the scrollbar's thumb
20325 *
20326 * @see #computeVerticalScrollRange()
20327 * @see #computeVerticalScrollExtent()
20328 */
20329 protected int computeVerticalScrollOffset() {
20330 return mScrollY;
20331 }
20332
20333 /**
20334 * <p>Compute the vertical extent of the vertical scrollbar's thumb
20335 * within the vertical range. This value is used to compute the length
20336 * of the thumb within the scrollbar's track.</p>
20337 *
20338 * <p>The range is expressed in arbitrary units that must be the same as the
20339 * units used by {@link #computeVerticalScrollRange()} and
20340 * {@link #computeVerticalScrollOffset()}.</p>
20341 *
20342 * <p>The default extent is the drawing height of this view.</p>
20343 *
20344 * @return the vertical extent of the scrollbar's thumb
20345 *
20346 * @see #computeVerticalScrollRange()
20347 * @see #computeVerticalScrollOffset()
20348 */
20349 protected int computeVerticalScrollExtent() {
20350 return getHeight();
20351 }
20352
20353 /**
20354 * Check if this view can be scrolled horizontally in a certain direction.
20355 *
20356 * <p>This is without regard to whether the view is enabled or not, or if it will scroll
20357 * in response to user input or not.
20358 *
20359 * @param direction Negative to check scrolling left, positive to check scrolling right.
20360 * @return true if this view can be scrolled in the specified direction, false otherwise.
20361 */
20362 public boolean canScrollHorizontally(int direction) {
20363 final int offset = computeHorizontalScrollOffset();
20364 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
20365 if (range == 0) return false;
20366 if (direction < 0) {
20367 return offset > 0;
20368 } else {
20369 return offset < range - 1;
20370 }
20371 }
20372
20373 /**
20374 * Check if this view can be scrolled vertically in a certain direction.
20375 *
20376 * <p>This is without regard to whether the view is enabled or not, or if it will scroll
20377 * in response to user input or not.
20378 *
20379 * @param direction Negative to check scrolling up, positive to check scrolling down.
20380 * @return true if this view can be scrolled in the specified direction, false otherwise.
20381 */
20382 public boolean canScrollVertically(int direction) {
20383 final int offset = computeVerticalScrollOffset();
20384 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
20385 if (range == 0) return false;
20386 if (direction < 0) {
20387 return offset > 0;
20388 } else {
20389 return offset < range - 1;
20390 }
20391 }
20392
20393 void getScrollIndicatorBounds(@NonNull Rect out) {
20394 out.left = mScrollX;
20395 out.right = mScrollX + mRight - mLeft;
20396 out.top = mScrollY;
20397 out.bottom = mScrollY + mBottom - mTop;
20398 }
20399
20400 private void onDrawScrollIndicators(Canvas c) {
20401 if ((mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK) == 0) {
20402 // No scroll indicators enabled.
20403 return;
20404 }
20405
20406 final Drawable dr = mScrollIndicatorDrawable;
20407 if (dr == null) {
20408 // Scroll indicators aren't supported here.
20409 return;
20410 }
20411
20412 if (mAttachInfo == null) {
20413 // View is not attached.
20414 return;
20415 }
20416
20417 final int h = dr.getIntrinsicHeight();
20418 final int w = dr.getIntrinsicWidth();
20419 final Rect rect = mAttachInfo.mTmpInvalRect;
20420 getScrollIndicatorBounds(rect);
20421
20422 if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_TOP) != 0) {
20423 final boolean canScrollUp = canScrollVertically(-1);
20424 if (canScrollUp) {
20425 dr.setBounds(rect.left, rect.top, rect.right, rect.top + h);
20426 dr.draw(c);
20427 }
20428 }
20429
20430 if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_BOTTOM) != 0) {
20431 final boolean canScrollDown = canScrollVertically(1);
20432 if (canScrollDown) {
20433 dr.setBounds(rect.left, rect.bottom - h, rect.right, rect.bottom);
20434 dr.draw(c);
20435 }
20436 }
20437
20438 final int leftRtl;
20439 final int rightRtl;
20440 if (getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
20441 leftRtl = PFLAG3_SCROLL_INDICATOR_END;
20442 rightRtl = PFLAG3_SCROLL_INDICATOR_START;
20443 } else {
20444 leftRtl = PFLAG3_SCROLL_INDICATOR_START;
20445 rightRtl = PFLAG3_SCROLL_INDICATOR_END;
20446 }
20447
20448 final int leftMask = PFLAG3_SCROLL_INDICATOR_LEFT | leftRtl;
20449 if ((mPrivateFlags3 & leftMask) != 0) {
20450 final boolean canScrollLeft = canScrollHorizontally(-1);
20451 if (canScrollLeft) {
20452 dr.setBounds(rect.left, rect.top, rect.left + w, rect.bottom);
20453 dr.draw(c);
20454 }
20455 }
20456
20457 final int rightMask = PFLAG3_SCROLL_INDICATOR_RIGHT | rightRtl;
20458 if ((mPrivateFlags3 & rightMask) != 0) {
20459 final boolean canScrollRight = canScrollHorizontally(1);
20460 if (canScrollRight) {
20461 dr.setBounds(rect.right - w, rect.top, rect.right, rect.bottom);
20462 dr.draw(c);
20463 }
20464 }
20465 }
20466
20467 private void getHorizontalScrollBarBounds(@Nullable Rect drawBounds,
20468 @Nullable Rect touchBounds) {
20469 final Rect bounds = drawBounds != null ? drawBounds : touchBounds;
20470 if (bounds == null) {
20471 return;
20472 }
20473 final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
20474 final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled()
20475 && !isVerticalScrollBarHidden();
20476 final int size = getHorizontalScrollbarHeight();
20477 final int verticalScrollBarGap = drawVerticalScrollBar ?
20478 getVerticalScrollbarWidth() : 0;
20479 final int width = mRight - mLeft;
20480 final int height = mBottom - mTop;
20481 bounds.top = mScrollY + height - size - (mUserPaddingBottom & inside);
20482 bounds.left = mScrollX + (mPaddingLeft & inside);
20483 bounds.right = mScrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
20484 bounds.bottom = bounds.top + size;
20485
20486 if (touchBounds == null) {
20487 return;
20488 }
20489 if (touchBounds != bounds) {
20490 touchBounds.set(bounds);
20491 }
20492 final int minTouchTarget = mScrollCache.scrollBarMinTouchTarget;
20493 if (touchBounds.height() < minTouchTarget) {
20494 final int adjust = (minTouchTarget - touchBounds.height()) / 2;
20495 touchBounds.bottom = Math.min(touchBounds.bottom + adjust, mScrollY + height);
20496 touchBounds.top = touchBounds.bottom - minTouchTarget;
20497 }
20498 if (touchBounds.width() < minTouchTarget) {
20499 final int adjust = (minTouchTarget - touchBounds.width()) / 2;
20500 touchBounds.left -= adjust;
20501 touchBounds.right = touchBounds.left + minTouchTarget;
20502 }
20503 }
20504
20505 private void getVerticalScrollBarBounds(@Nullable Rect bounds, @Nullable Rect touchBounds) {
20506 if (mRoundScrollbarRenderer == null) {
20507 getStraightVerticalScrollBarBounds(bounds, touchBounds);
20508 } else {
20509 getRoundVerticalScrollBarBounds(bounds != null ? bounds : touchBounds);
20510 }
20511 }
20512
20513 private void getRoundVerticalScrollBarBounds(Rect bounds) {
20514 final int width = mRight - mLeft;
20515 final int height = mBottom - mTop;
20516 // Do not take padding into account as we always want the scrollbars
20517 // to hug the screen for round wearable devices.
20518 bounds.left = mScrollX;
20519 bounds.top = mScrollY;
20520 bounds.right = bounds.left + width;
20521 bounds.bottom = mScrollY + height;
20522 }
20523
20524 private void getStraightVerticalScrollBarBounds(@Nullable Rect drawBounds,
20525 @Nullable Rect touchBounds) {
20526 final Rect bounds = drawBounds != null ? drawBounds : touchBounds;
20527 if (bounds == null) {
20528 return;
20529 }
20530 final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
20531 final int size = getVerticalScrollbarWidth();
20532 int verticalScrollbarPosition = mVerticalScrollbarPosition;
20533 if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
20534 verticalScrollbarPosition = isLayoutRtl() ?
20535 SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
20536 }
20537 final int width = mRight - mLeft;
20538 final int height = mBottom - mTop;
20539 switch (verticalScrollbarPosition) {
20540 default:
20541 case SCROLLBAR_POSITION_RIGHT:
20542 bounds.left = mScrollX + width - size - (mUserPaddingRight & inside);
20543 break;
20544 case SCROLLBAR_POSITION_LEFT:
20545 bounds.left = mScrollX + (mUserPaddingLeft & inside);
20546 break;
20547 }
20548 bounds.top = mScrollY + (mPaddingTop & inside);
20549 bounds.right = bounds.left + size;
20550 bounds.bottom = mScrollY + height - (mUserPaddingBottom & inside);
20551
20552 if (touchBounds == null) {
20553 return;
20554 }
20555 if (touchBounds != bounds) {
20556 touchBounds.set(bounds);
20557 }
20558 final int minTouchTarget = mScrollCache.scrollBarMinTouchTarget;
20559 if (touchBounds.width() < minTouchTarget) {
20560 final int adjust = (minTouchTarget - touchBounds.width()) / 2;
20561 if (verticalScrollbarPosition == SCROLLBAR_POSITION_RIGHT) {
20562 touchBounds.right = Math.min(touchBounds.right + adjust, mScrollX + width);
20563 touchBounds.left = touchBounds.right - minTouchTarget;
20564 } else {
20565 touchBounds.left = Math.max(touchBounds.left + adjust, mScrollX);
20566 touchBounds.right = touchBounds.left + minTouchTarget;
20567 }
20568 }
20569 if (touchBounds.height() < minTouchTarget) {
20570 final int adjust = (minTouchTarget - touchBounds.height()) / 2;
20571 touchBounds.top -= adjust;
20572 touchBounds.bottom = touchBounds.top + minTouchTarget;
20573 }
20574 }
20575
20576 /**
20577 * <p>Request the drawing of the horizontal and the vertical scrollbar. The
20578 * scrollbars are painted only if they have been awakened first.</p>
20579 *
20580 * @param canvas the canvas on which to draw the scrollbars
20581 *
20582 * @see #awakenScrollBars(int)
20583 */
20584 protected final void onDrawScrollBars(Canvas canvas) {
20585 // scrollbars are drawn only when the animation is running
20586 final ScrollabilityCache cache = mScrollCache;
20587
20588 if (cache != null) {
20589
20590 int state = cache.state;
20591
20592 if (state == ScrollabilityCache.OFF) {
20593 return;
20594 }
20595
20596 boolean invalidate = false;
20597
20598 if (state == ScrollabilityCache.FADING) {
20599 // We're fading -- get our fade interpolation
20600 if (cache.interpolatorValues == null) {
20601 cache.interpolatorValues = new float[1];
20602 }
20603
20604 float[] values = cache.interpolatorValues;
20605
20606 // Stops the animation if we're done
20607 if (cache.scrollBarInterpolator.timeToValues(values) ==
20608 Interpolator.Result.FREEZE_END) {
20609 cache.state = ScrollabilityCache.OFF;
20610 } else {
20611 cache.scrollBar.mutate().setAlpha(Math.round(values[0]));
20612 }
20613
20614 // This will make the scroll bars inval themselves after
20615 // drawing. We only want this when we're fading so that
20616 // we prevent excessive redraws
20617 invalidate = true;
20618 } else {
20619 // We're just on -- but we may have been fading before so
20620 // reset alpha
20621 cache.scrollBar.mutate().setAlpha(255);
20622 }
20623
20624 final boolean drawHorizontalScrollBar = isHorizontalScrollBarEnabled();
20625 final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled()
20626 && !isVerticalScrollBarHidden();
20627
20628 // Fork out the scroll bar drawing for round wearable devices.
20629 if (mRoundScrollbarRenderer != null) {
20630 if (drawVerticalScrollBar) {
20631 final Rect bounds = cache.mScrollBarBounds;
20632 getVerticalScrollBarBounds(bounds, null);
20633 mRoundScrollbarRenderer.drawRoundScrollbars(
20634 canvas, (float) cache.scrollBar.getAlpha() / 255f, bounds);
20635 if (invalidate) {
20636 invalidate();
20637 }
20638 }
20639 // Do not draw horizontal scroll bars for round wearable devices.
20640 } else if (drawVerticalScrollBar || drawHorizontalScrollBar) {
20641 final ScrollBarDrawable scrollBar = cache.scrollBar;
20642
20643 if (drawHorizontalScrollBar) {
20644 scrollBar.setParameters(computeHorizontalScrollRange(),
20645 computeHorizontalScrollOffset(),
20646 computeHorizontalScrollExtent(), false);
20647 final Rect bounds = cache.mScrollBarBounds;
20648 getHorizontalScrollBarBounds(bounds, null);
20649 onDrawHorizontalScrollBar(canvas, scrollBar, bounds.left, bounds.top,
20650 bounds.right, bounds.bottom);
20651 if (invalidate) {
20652 invalidate(bounds);
20653 }
20654 }
20655
20656 if (drawVerticalScrollBar) {
20657 scrollBar.setParameters(computeVerticalScrollRange(),
20658 computeVerticalScrollOffset(),
20659 computeVerticalScrollExtent(), true);
20660 final Rect bounds = cache.mScrollBarBounds;
20661 getVerticalScrollBarBounds(bounds, null);
20662 onDrawVerticalScrollBar(canvas, scrollBar, bounds.left, bounds.top,
20663 bounds.right, bounds.bottom);
20664 if (invalidate) {
20665 invalidate(bounds);
20666 }
20667 }
20668 }
20669 }
20670 }
20671
20672 /**
20673 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
20674 * FastScroller is visible.
20675 * @return whether to temporarily hide the vertical scrollbar
20676 * @hide
20677 */
20678 protected boolean isVerticalScrollBarHidden() {
20679 return false;
20680 }
20681
20682 /**
20683 * <p>Draw the horizontal scrollbar if
20684 * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
20685 *
20686 * @param canvas the canvas on which to draw the scrollbar
20687 * @param scrollBar the scrollbar's drawable
20688 *
20689 * @see #isHorizontalScrollBarEnabled()
20690 * @see #computeHorizontalScrollRange()
20691 * @see #computeHorizontalScrollExtent()
20692 * @see #computeHorizontalScrollOffset()
20693 * @hide
20694 */
20695 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
20696 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
20697 int l, int t, int r, int b) {
20698 scrollBar.setBounds(l, t, r, b);
20699 scrollBar.draw(canvas);
20700 }
20701
20702 /**
20703 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
20704 * returns true.</p>
20705 *
20706 * @param canvas the canvas on which to draw the scrollbar
20707 * @param scrollBar the scrollbar's drawable
20708 *
20709 * @see #isVerticalScrollBarEnabled()
20710 * @see #computeVerticalScrollRange()
20711 * @see #computeVerticalScrollExtent()
20712 * @see #computeVerticalScrollOffset()
20713 * @hide
20714 */
20715 @UnsupportedAppUsage
20716 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
20717 int l, int t, int r, int b) {
20718 scrollBar.setBounds(l, t, r, b);
20719 scrollBar.draw(canvas);
20720 }
20721
20722 /**
20723 * Implement this to do your drawing.
20724 *
20725 * @param canvas the canvas on which the background will be drawn
20726 */
20727 protected void onDraw(Canvas canvas) {
20728 }
20729
20730 /*
20731 * Caller is responsible for calling requestLayout if necessary.
20732 * (This allows addViewInLayout to not request a new layout.)
20733 */
20734 @UnsupportedAppUsage
20735 void assignParent(ViewParent parent) {
20736 if (mParent == null) {
20737 mParent = parent;
20738 } else if (parent == null) {
20739 mParent = null;
20740 } else {
20741 throw new RuntimeException("view " + this + " being added, but"
20742 + " it already has a parent");
20743 }
20744 }
20745
20746 /**
20747 * This is called when the view is attached to a window. At this point it
20748 * has a Surface and will start drawing. Note that this function is
20749 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
20750 * however it may be called any time before the first onDraw -- including
20751 * before or after {@link #onMeasure(int, int)}.
20752 *
20753 * @see #onDetachedFromWindow()
20754 */
20755 @CallSuper
20756 protected void onAttachedToWindow() {
20757 if (mParent != null && (mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
20758 mParent.requestTransparentRegion(this);
20759 }
20760
20761 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
20762
20763 jumpDrawablesToCurrentState();
20764
20765 AccessibilityNodeIdManager.getInstance().registerViewWithId(this, getAccessibilityViewId());
20766 resetSubtreeAccessibilityStateChanged();
20767
20768 // rebuild, since Outline not maintained while View is detached
20769 rebuildOutline();
20770
20771 if (isFocused()) {
20772 notifyFocusChangeToImeFocusController(true /* hasFocus */);
20773 }
20774 }
20775
20776 /**
20777 * Resolve all RTL related properties.
20778 *
20779 * @return true if resolution of RTL properties has been done
20780 *
20781 * @hide
20782 */
20783 public boolean resolveRtlPropertiesIfNeeded() {
20784 if (!needRtlPropertiesResolution()) return false;
20785
20786 // Order is important here: LayoutDirection MUST be resolved first
20787 if (!isLayoutDirectionResolved()) {
20788 resolveLayoutDirection();
20789 resolveLayoutParams();
20790 }
20791 // ... then we can resolve the others properties depending on the resolved LayoutDirection.
20792 if (!isTextDirectionResolved()) {
20793 resolveTextDirection();
20794 }
20795 if (!isTextAlignmentResolved()) {
20796 resolveTextAlignment();
20797 }
20798 // Should resolve Drawables before Padding because we need the layout direction of the
20799 // Drawable to correctly resolve Padding.
20800 if (!areDrawablesResolved()) {
20801 resolveDrawables();
20802 }
20803 if (!isPaddingResolved()) {
20804 resolvePadding();
20805 }
20806 onRtlPropertiesChanged(getLayoutDirection());
20807 return true;
20808 }
20809
20810 /**
20811 * Reset resolution of all RTL related properties.
20812 *
20813 * @hide
20814 */
20815 @TestApi
20816 public void resetRtlProperties() {
20817 resetResolvedLayoutDirection();
20818 resetResolvedTextDirection();
20819 resetResolvedTextAlignment();
20820 resetResolvedPadding();
20821 resetResolvedDrawables();
20822 }
20823
20824 /**
20825 * @see #onScreenStateChanged(int)
20826 */
20827 void dispatchScreenStateChanged(int screenState) {
20828 onScreenStateChanged(screenState);
20829 }
20830
20831 /**
20832 * This method is called whenever the state of the screen this view is
20833 * attached to changes. A state change will usually occurs when the screen
20834 * turns on or off (whether it happens automatically or the user does it
20835 * manually.)
20836 *
20837 * @param screenState The new state of the screen. Can be either
20838 * {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
20839 */
20840 public void onScreenStateChanged(int screenState) {
20841 }
20842
20843 /**
20844 * @see #onMovedToDisplay(int, Configuration)
20845 */
20846 void dispatchMovedToDisplay(Display display, Configuration config) {
20847 mAttachInfo.mDisplay = display;
20848 mAttachInfo.mDisplayState = display.getState();
20849 onMovedToDisplay(display.getDisplayId(), config);
20850 }
20851
20852 /**
20853 * Called by the system when the hosting activity is moved from one display to another without
20854 * recreation. This means that the activity is declared to handle all changes to configuration
20855 * that happened when it was switched to another display, so it wasn't destroyed and created
20856 * again.
20857 *
20858 * <p>This call will be followed by {@link #onConfigurationChanged(Configuration)} if the
20859 * applied configuration actually changed. It is up to app developer to choose whether to handle
20860 * the change in this method or in the following {@link #onConfigurationChanged(Configuration)}
20861 * call.
20862 *
20863 * <p>Use this callback to track changes to the displays if some functionality relies on an
20864 * association with some display properties.
20865 *
20866 * @param displayId The id of the display to which the view was moved.
20867 * @param config Configuration of the resources on new display after move.
20868 *
20869 * @see #onConfigurationChanged(Configuration)
20870 * @hide
20871 */
20872 public void onMovedToDisplay(int displayId, Configuration config) {
20873 }
20874
20875 /**
20876 * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
20877 */
20878 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
20879 private boolean hasRtlSupport() {
20880 return mContext.getApplicationInfo().hasRtlSupport();
20881 }
20882
20883 /**
20884 * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
20885 * RTL not supported)
20886 */
20887 private boolean isRtlCompatibilityMode() {
20888 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
20889 return targetSdkVersion < Build.VERSION_CODES.JELLY_BEAN_MR1 || !hasRtlSupport();
20890 }
20891
20892 /**
20893 * @return true if RTL properties need resolution.
20894 *
20895 */
20896 private boolean needRtlPropertiesResolution() {
20897 return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
20898 }
20899
20900 /**
20901 * Called when any RTL property (layout direction or text direction or text alignment) has
20902 * been changed.
20903 *
20904 * Subclasses need to override this method to take care of cached information that depends on the
20905 * resolved layout direction, or to inform child views that inherit their layout direction.
20906 *
20907 * The default implementation does nothing.
20908 *
20909 * @param layoutDirection the direction of the layout
20910 *
20911 * @see #LAYOUT_DIRECTION_LTR
20912 * @see #LAYOUT_DIRECTION_RTL
20913 */
20914 public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
20915 }
20916
20917 /**
20918 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
20919 * that the parent directionality can and will be resolved before its children.
20920 *
20921 * @return true if resolution has been done, false otherwise.
20922 *
20923 * @hide
20924 */
20925 public boolean resolveLayoutDirection() {
20926 // Clear any previous layout direction resolution
20927 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
20928
20929 if (hasRtlSupport()) {
20930 // Set resolved depending on layout direction
20931 switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
20932 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
20933 case LAYOUT_DIRECTION_INHERIT:
20934 // We cannot resolve yet. LTR is by default and let the resolution happen again
20935 // later to get the correct resolved value
20936 if (!canResolveLayoutDirection()) return false;
20937
20938 // Parent has not yet resolved, LTR is still the default
20939 try {
20940 if (!mParent.isLayoutDirectionResolved()) return false;
20941
20942 if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
20943 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
20944 }
20945 } catch (AbstractMethodError e) {
20946 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
20947 " does not fully implement ViewParent", e);
20948 }
20949 break;
20950 case LAYOUT_DIRECTION_RTL:
20951 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
20952 break;
20953 case LAYOUT_DIRECTION_LOCALE:
20954 if((LAYOUT_DIRECTION_RTL ==
20955 TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
20956 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
20957 }
20958 break;
20959 default:
20960 // Nothing to do, LTR by default
20961 }
20962 }
20963
20964 // Set to resolved
20965 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
20966 return true;
20967 }
20968
20969 /**
20970 * Check if layout direction resolution can be done.
20971 *
20972 * @return true if layout direction resolution can be done otherwise return false.
20973 */
20974 public boolean canResolveLayoutDirection() {
20975 switch (getRawLayoutDirection()) {
20976 case LAYOUT_DIRECTION_INHERIT:
20977 if (mParent != null) {
20978 try {
20979 return mParent.canResolveLayoutDirection();
20980 } catch (AbstractMethodError e) {
20981 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
20982 " does not fully implement ViewParent", e);
20983 }
20984 }
20985 return false;
20986
20987 default:
20988 return true;
20989 }
20990 }
20991
20992 /**
20993 * Reset the resolved layout direction. Layout direction will be resolved during a call to
20994 * {@link #onMeasure(int, int)}.
20995 *
20996 * @hide
20997 */
20998 @TestApi
20999 public void resetResolvedLayoutDirection() {
21000 // Reset the current resolved bits
21001 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
21002 }
21003
21004 /**
21005 * @return true if the layout direction is inherited.
21006 *
21007 * @hide
21008 */
21009 public boolean isLayoutDirectionInherited() {
21010 return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
21011 }
21012
21013 /**
21014 * @return true if layout direction has been resolved.
21015 */
21016 public boolean isLayoutDirectionResolved() {
21017 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
21018 }
21019
21020 /**
21021 * Return if padding has been resolved
21022 *
21023 * @hide
21024 */
21025 @UnsupportedAppUsage
21026 boolean isPaddingResolved() {
21027 return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
21028 }
21029
21030 /**
21031 * Resolves padding depending on layout direction, if applicable, and
21032 * recomputes internal padding values to adjust for scroll bars.
21033 *
21034 * @hide
21035 */
21036 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
21037 public void resolvePadding() {
21038 final int resolvedLayoutDirection = getLayoutDirection();
21039
21040 if (!isRtlCompatibilityMode()) {
21041 // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
21042 // If start / end padding are defined, they will be resolved (hence overriding) to
21043 // left / right or right / left depending on the resolved layout direction.
21044 // If start / end padding are not defined, use the left / right ones.
21045 if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
21046 Rect padding = sThreadLocal.get();
21047 if (padding == null) {
21048 padding = new Rect();
21049 sThreadLocal.set(padding);
21050 }
21051 mBackground.getPadding(padding);
21052 if (!mLeftPaddingDefined) {
21053 mUserPaddingLeftInitial = padding.left;
21054 }
21055 if (!mRightPaddingDefined) {
21056 mUserPaddingRightInitial = padding.right;
21057 }
21058 }
21059 switch (resolvedLayoutDirection) {
21060 case LAYOUT_DIRECTION_RTL:
21061 if (mUserPaddingStart != UNDEFINED_PADDING) {
21062 mUserPaddingRight = mUserPaddingStart;
21063 } else {
21064 mUserPaddingRight = mUserPaddingRightInitial;
21065 }
21066 if (mUserPaddingEnd != UNDEFINED_PADDING) {
21067 mUserPaddingLeft = mUserPaddingEnd;
21068 } else {
21069 mUserPaddingLeft = mUserPaddingLeftInitial;
21070 }
21071 break;
21072 case LAYOUT_DIRECTION_LTR:
21073 default:
21074 if (mUserPaddingStart != UNDEFINED_PADDING) {
21075 mUserPaddingLeft = mUserPaddingStart;
21076 } else {
21077 mUserPaddingLeft = mUserPaddingLeftInitial;
21078 }
21079 if (mUserPaddingEnd != UNDEFINED_PADDING) {
21080 mUserPaddingRight = mUserPaddingEnd;
21081 } else {
21082 mUserPaddingRight = mUserPaddingRightInitial;
21083 }
21084 }
21085
21086 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
21087 }
21088
21089 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
21090 onRtlPropertiesChanged(resolvedLayoutDirection);
21091
21092 mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
21093 }
21094
21095 /**
21096 * Reset the resolved layout direction.
21097 *
21098 * @hide
21099 */
21100 @TestApi
21101 public void resetResolvedPadding() {
21102 resetResolvedPaddingInternal();
21103 }
21104
21105 /**
21106 * Used when we only want to reset *this* view's padding and not trigger overrides
21107 * in ViewGroup that reset children too.
21108 */
21109 void resetResolvedPaddingInternal() {
21110 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
21111 }
21112
21113 /**
21114 * This is called when the view is detached from a window. At this point it
21115 * no longer has a surface for drawing.
21116 *
21117 * @see #onAttachedToWindow()
21118 */
21119 @CallSuper
21120 protected void onDetachedFromWindow() {
21121 }
21122
21123 /**
21124 * This is a framework-internal mirror of onDetachedFromWindow() that's called
21125 * after onDetachedFromWindow().
21126 *
21127 * If you override this you *MUST* call super.onDetachedFromWindowInternal()!
21128 * The super method should be called at the end of the overridden method to ensure
21129 * subclasses are destroyed first
21130 *
21131 * @hide
21132 */
21133 @CallSuper
21134 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
21135 protected void onDetachedFromWindowInternal() {
21136 mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
21137 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
21138 mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH;
21139
21140 removeUnsetPressCallback();
21141 removeLongPressCallback();
21142 removePerformClickCallback();
21143 clearAccessibilityThrottles();
21144 stopNestedScroll();
21145
21146 // Anything that started animating right before detach should already
21147 // be in its final state when re-attached.
21148 jumpDrawablesToCurrentState();
21149
21150 destroyDrawingCache();
21151
21152 cleanupDraw();
21153 mCurrentAnimation = null;
21154
21155 if ((mViewFlags & TOOLTIP) == TOOLTIP) {
21156 hideTooltip();
21157 }
21158
21159 AccessibilityNodeIdManager.getInstance().unregisterViewWithId(getAccessibilityViewId());
21160
21161 if (mBackgroundRenderNode != null) {
21162 mBackgroundRenderNode.forceEndAnimators();
21163 }
21164 mRenderNode.forceEndAnimators();
21165 }
21166
21167 private void cleanupDraw() {
21168 resetDisplayList();
21169 if (mAttachInfo != null) {
21170 mAttachInfo.mViewRootImpl.cancelInvalidate(this);
21171 }
21172 }
21173
21174 void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
21175 }
21176
21177 /**
21178 * @return The number of times this view has been attached to a window
21179 */
21180 protected int getWindowAttachCount() {
21181 return mWindowAttachCount;
21182 }
21183
21184 /**
21185 * Retrieve a unique token identifying the window this view is attached to.
21186 * @return Return the window's token for use in
21187 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
21188 */
21189 public IBinder getWindowToken() {
21190 return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
21191 }
21192
21193 /**
21194 * Retrieve the {@link WindowId} for the window this view is
21195 * currently attached to.
21196 */
21197 public WindowId getWindowId() {
21198 AttachInfo ai = mAttachInfo;
21199 if (ai == null) {
21200 return null;
21201 }
21202 if (ai.mWindowId == null) {
21203 try {
21204 ai.mIWindowId = ai.mSession.getWindowId(ai.mWindowToken);
21205 if (ai.mIWindowId != null) {
21206 ai.mWindowId = new WindowId(ai.mIWindowId);
21207 }
21208 } catch (RemoteException e) {
21209 }
21210 }
21211 return ai.mWindowId;
21212 }
21213
21214 /**
21215 * Retrieve a unique token identifying the top-level "real" window of
21216 * the window that this view is attached to. That is, this is like
21217 * {@link #getWindowToken}, except if the window this view in is a panel
21218 * window (attached to another containing window), then the token of
21219 * the containing window is returned instead.
21220 *
21221 * @return Returns the associated window token, either
21222 * {@link #getWindowToken()} or the containing window's token.
21223 */
21224 public IBinder getApplicationWindowToken() {
21225 AttachInfo ai = mAttachInfo;
21226 if (ai != null) {
21227 IBinder appWindowToken = ai.mPanelParentWindowToken;
21228 if (appWindowToken == null) {
21229 appWindowToken = ai.mWindowToken;
21230 }
21231 return appWindowToken;
21232 }
21233 return null;
21234 }
21235
21236 /**
21237 * Gets the logical display to which the view's window has been attached.
21238 *
21239 * @return The logical display, or null if the view is not currently attached to a window.
21240 */
21241 public Display getDisplay() {
21242 return mAttachInfo != null ? mAttachInfo.mDisplay : null;
21243 }
21244
21245 /**
21246 * Retrieve private session object this view hierarchy is using to
21247 * communicate with the window manager.
21248 * @return the session object to communicate with the window manager
21249 */
21250 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
21251 /*package*/ IWindowSession getWindowSession() {
21252 return mAttachInfo != null ? mAttachInfo.mSession : null;
21253 }
21254
21255 /**
21256 * Return the window this view is currently attached to.
21257 * @hide
21258 */
21259 protected IWindow getWindow() {
21260 return mAttachInfo != null ? mAttachInfo.mWindow : null;
21261 }
21262
21263 /**
21264 * Return the visibility value of the least visible component passed.
21265 */
21266 int combineVisibility(int vis1, int vis2) {
21267 // This works because VISIBLE < INVISIBLE < GONE.
21268 return Math.max(vis1, vis2);
21269 }
21270
21271 private boolean mShouldFakeFocus = false;
21272
21273 /**
21274 * Fake send a focus event after attaching to window.
21275 * See {@link android.view.ViewRootImpl#dispatchCompatFakeFocus()} for details.
21276 * @hide
21277 */
21278 public void fakeFocusAfterAttachingToWindow() {
21279 mShouldFakeFocus = true;
21280 }
21281
21282 /**
21283 * @param info the {@link android.view.View.AttachInfo} to associated with
21284 * this view
21285 */
21286 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
21287 void dispatchAttachedToWindow(AttachInfo info, int visibility) {
21288 mAttachInfo = info;
21289 if (mOverlay != null) {
21290 mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
21291 }
21292 mWindowAttachCount++;
21293 // We will need to evaluate the drawable state at least once.
21294 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
21295 if (mFloatingTreeObserver != null) {
21296 info.mTreeObserver.merge(mFloatingTreeObserver);
21297 mFloatingTreeObserver = null;
21298 }
21299
21300 registerPendingFrameMetricsObservers();
21301
21302 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
21303 mAttachInfo.mScrollContainers.add(this);
21304 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
21305 }
21306 // Transfer all pending runnables.
21307 if (mRunQueue != null) {
21308 mRunQueue.executeActions(info.mHandler);
21309 mRunQueue = null;
21310 }
21311 performCollectViewAttributes(mAttachInfo, visibility);
21312 onAttachedToWindow();
21313
21314 ListenerInfo li = mListenerInfo;
21315 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
21316 li != null ? li.mOnAttachStateChangeListeners : null;
21317 if (listeners != null && listeners.size() > 0) {
21318 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
21319 // perform the dispatching. The iterator is a safe guard against listeners that
21320 // could mutate the list by calling the various add/remove methods. This prevents
21321 // the array from being modified while we iterate it.
21322 for (OnAttachStateChangeListener listener : listeners) {
21323 listener.onViewAttachedToWindow(this);
21324 }
21325 }
21326
21327 int vis = info.mWindowVisibility;
21328 if (vis != GONE) {
21329 onWindowVisibilityChanged(vis);
21330 if (isShown()) {
21331 // Calling onVisibilityAggregated directly here since the subtree will also
21332 // receive dispatchAttachedToWindow and this same call
21333 onVisibilityAggregated(vis == VISIBLE);
21334 }
21335 }
21336
21337 // Send onVisibilityChanged directly instead of dispatchVisibilityChanged.
21338 // As all views in the subtree will already receive dispatchAttachedToWindow
21339 // traversing the subtree again here is not desired.
21340 onVisibilityChanged(this, visibility);
21341
21342 if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
21343 // If nobody has evaluated the drawable state yet, then do it now.
21344 refreshDrawableState();
21345 }
21346 needGlobalAttributesUpdate(false);
21347
21348 notifyEnterOrExitForAutoFillIfNeeded(true);
21349 notifyAppearedOrDisappearedForContentCaptureIfNeeded(true);
21350
21351 if (mShouldFakeFocus) {
21352 getViewRootImpl().dispatchCompatFakeFocus();
21353 mShouldFakeFocus = false;
21354 }
21355 }
21356
21357 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
21358 void dispatchDetachedFromWindow() {
21359 AttachInfo info = mAttachInfo;
21360 if (info != null) {
21361 int vis = info.mWindowVisibility;
21362 if (vis != GONE) {
21363 onWindowVisibilityChanged(GONE);
21364 if (isShown()) {
21365 // Invoking onVisibilityAggregated directly here since the subtree
21366 // will also receive detached from window
21367 onVisibilityAggregated(false);
21368 }
21369 }
21370 }
21371
21372 onDetachedFromWindow();
21373 onDetachedFromWindowInternal();
21374
21375 if (info != null) {
21376 info.mViewRootImpl.getImeFocusController().onViewDetachedFromWindow(this);
21377 }
21378
21379 ListenerInfo li = mListenerInfo;
21380 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
21381 li != null ? li.mOnAttachStateChangeListeners : null;
21382 if (listeners != null && listeners.size() > 0) {
21383 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
21384 // perform the dispatching. The iterator is a safe guard against listeners that
21385 // could mutate the list by calling the various add/remove methods. This prevents
21386 // the array from being modified while we iterate it.
21387 for (OnAttachStateChangeListener listener : listeners) {
21388 listener.onViewDetachedFromWindow(this);
21389 }
21390 }
21391
21392 if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
21393 mAttachInfo.mScrollContainers.remove(this);
21394 mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
21395 }
21396
21397 notifyAppearedOrDisappearedForContentCaptureIfNeeded(false);
21398
21399 mAttachInfo = null;
21400 if (mOverlay != null) {
21401 mOverlay.getOverlayView().dispatchDetachedFromWindow();
21402 }
21403
21404 notifyEnterOrExitForAutoFillIfNeeded(false);
21405
21406 if (info != null && !collectPreferKeepClearRects().isEmpty()) {
21407 info.mViewRootImpl.updateKeepClearRectsForView(this);
21408 }
21409 }
21410
21411 /**
21412 * Cancel any deferred high-level input events that were previously posted to the event queue.
21413 *
21414 * <p>Many views post high-level events such as click handlers to the event queue
21415 * to run deferred in order to preserve a desired user experience - clearing visible
21416 * pressed states before executing, etc. This method will abort any events of this nature
21417 * that are currently in flight.</p>
21418 *
21419 * <p>Custom views that generate their own high-level deferred input events should override
21420 * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
21421 *
21422 * <p>This will also cancel pending input events for any child views.</p>
21423 *
21424 * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
21425 * This will not impact newer events posted after this call that may occur as a result of
21426 * lower-level input events still waiting in the queue. If you are trying to prevent
21427 * double-submitted events for the duration of some sort of asynchronous transaction
21428 * you should also take other steps to protect against unexpected double inputs e.g. calling
21429 * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
21430 * the transaction completes, tracking already submitted transaction IDs, etc.</p>
21431 */
21432 public final void cancelPendingInputEvents() {
21433 dispatchCancelPendingInputEvents();
21434 }
21435
21436 /**
21437 * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
21438 * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
21439 */
21440 void dispatchCancelPendingInputEvents() {
21441 mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
21442 onCancelPendingInputEvents();
21443 if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
21444 throw new SuperNotCalledException("View " + getClass().getSimpleName() +
21445 " did not call through to super.onCancelPendingInputEvents()");
21446 }
21447 }
21448
21449 /**
21450 * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
21451 * a parent view.
21452 *
21453 * <p>This method is responsible for removing any pending high-level input events that were
21454 * posted to the event queue to run later. Custom view classes that post their own deferred
21455 * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
21456 * {@link android.os.Handler} should override this method, call
21457 * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
21458 * </p>
21459 */
21460 public void onCancelPendingInputEvents() {
21461 removePerformClickCallback();
21462 cancelLongPress();
21463 mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
21464 }
21465
21466 /**
21467 * Store this view hierarchy's frozen state into the given container.
21468 *
21469 * @param container The SparseArray in which to save the view's state.
21470 *
21471 * @see #restoreHierarchyState(android.util.SparseArray)
21472 * @see #dispatchSaveInstanceState(android.util.SparseArray)
21473 * @see #onSaveInstanceState()
21474 */
21475 public void saveHierarchyState(SparseArray<Parcelable> container) {
21476 dispatchSaveInstanceState(container);
21477 }
21478
21479 /**
21480 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
21481 * this view and its children. May be overridden to modify how freezing happens to a
21482 * view's children; for example, some views may want to not store state for their children.
21483 *
21484 * @param container The SparseArray in which to save the view's state.
21485 *
21486 * @see #dispatchRestoreInstanceState(android.util.SparseArray)
21487 * @see #saveHierarchyState(android.util.SparseArray)
21488 * @see #onSaveInstanceState()
21489 */
21490 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
21491 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
21492 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
21493 Parcelable state = onSaveInstanceState();
21494 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
21495 throw new IllegalStateException(
21496 "Derived class did not call super.onSaveInstanceState()");
21497 }
21498 if (state != null) {
21499 // Log.i("View", "Freezing #" + Integer.toHexString(mID)
21500 // + ": " + state);
21501 container.put(mID, state);
21502 }
21503 }
21504 }
21505
21506 /**
21507 * Hook allowing a view to generate a representation of its internal state
21508 * that can later be used to create a new instance with that same state.
21509 * This state should only contain information that is not persistent or can
21510 * not be reconstructed later. For example, you will never store your
21511 * current position on screen because that will be computed again when a
21512 * new instance of the view is placed in its view hierarchy.
21513 * <p>
21514 * Some examples of things you may store here: the current cursor position
21515 * in a text view (but usually not the text itself since that is stored in a
21516 * content provider or other persistent storage), the currently selected
21517 * item in a list view.
21518 *
21519 * @return Returns a Parcelable object containing the view's current dynamic
21520 * state, or null if there is nothing interesting to save.
21521 * @see #onRestoreInstanceState(Parcelable)
21522 * @see #saveHierarchyState(SparseArray)
21523 * @see #dispatchSaveInstanceState(SparseArray)
21524 * @see #setSaveEnabled(boolean)
21525 */
21526 @CallSuper
21527 @Nullable protected Parcelable onSaveInstanceState() {
21528 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
21529 if (mStartActivityRequestWho != null || isAutofilled()
21530 || mAutofillViewId > LAST_APP_AUTOFILL_ID) {
21531 BaseSavedState state = new BaseSavedState(AbsSavedState.EMPTY_STATE);
21532
21533 if (mStartActivityRequestWho != null) {
21534 state.mSavedData |= BaseSavedState.START_ACTIVITY_REQUESTED_WHO_SAVED;
21535 }
21536
21537 if (isAutofilled()) {
21538 state.mSavedData |= BaseSavedState.IS_AUTOFILLED;
21539 }
21540
21541 if (mAutofillViewId > LAST_APP_AUTOFILL_ID) {
21542 state.mSavedData |= BaseSavedState.AUTOFILL_ID;
21543 }
21544
21545 state.mStartActivityRequestWhoSaved = mStartActivityRequestWho;
21546 state.mIsAutofilled = isAutofilled();
21547 state.mHideHighlight = hideAutofillHighlight();
21548 state.mAutofillViewId = mAutofillViewId;
21549 return state;
21550 }
21551 return BaseSavedState.EMPTY_STATE;
21552 }
21553
21554 /**
21555 * Restore this view hierarchy's frozen state from the given container.
21556 *
21557 * @param container The SparseArray which holds previously frozen states.
21558 *
21559 * @see #saveHierarchyState(android.util.SparseArray)
21560 * @see #dispatchRestoreInstanceState(android.util.SparseArray)
21561 * @see #onRestoreInstanceState(android.os.Parcelable)
21562 */
21563 public void restoreHierarchyState(SparseArray<Parcelable> container) {
21564 dispatchRestoreInstanceState(container);
21565 }
21566
21567 /**
21568 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
21569 * state for this view and its children. May be overridden to modify how restoring
21570 * happens to a view's children; for example, some views may want to not store state
21571 * for their children.
21572 *
21573 * @param container The SparseArray which holds previously saved state.
21574 *
21575 * @see #dispatchSaveInstanceState(android.util.SparseArray)
21576 * @see #restoreHierarchyState(android.util.SparseArray)
21577 * @see #onRestoreInstanceState(android.os.Parcelable)
21578 */
21579 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
21580 if (mID != NO_ID) {
21581 Parcelable state = container.get(mID);
21582 if (state != null) {
21583 // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
21584 // + ": " + state);
21585 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
21586 onRestoreInstanceState(state);
21587 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
21588 throw new IllegalStateException(
21589 "Derived class did not call super.onRestoreInstanceState()");
21590 }
21591 }
21592 }
21593 }
21594
21595 /**
21596 * Hook allowing a view to re-apply a representation of its internal state that had previously
21597 * been generated by {@link #onSaveInstanceState}. This function will never be called with a
21598 * null state.
21599 *
21600 * @param state The frozen state that had previously been returned by
21601 * {@link #onSaveInstanceState}.
21602 *
21603 * @see #onSaveInstanceState()
21604 * @see #restoreHierarchyState(android.util.SparseArray)
21605 * @see #dispatchRestoreInstanceState(android.util.SparseArray)
21606 */
21607 @CallSuper
21608 protected void onRestoreInstanceState(Parcelable state) {
21609 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
21610 if (state != null && !(state instanceof AbsSavedState)) {
21611 throw new IllegalArgumentException("Wrong state class, expecting View State but "
21612 + "received " + state.getClass().toString() + " instead. This usually happens "
21613 + "when two views of different type have the same id in the same hierarchy. "
21614 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
21615 + "other views do not use the same id.");
21616 }
21617 if (state != null && state instanceof BaseSavedState) {
21618 BaseSavedState baseState = (BaseSavedState) state;
21619
21620 if ((baseState.mSavedData & BaseSavedState.START_ACTIVITY_REQUESTED_WHO_SAVED) != 0) {
21621 mStartActivityRequestWho = baseState.mStartActivityRequestWhoSaved;
21622 }
21623 if ((baseState.mSavedData & BaseSavedState.IS_AUTOFILLED) != 0) {
21624 setAutofilled(baseState.mIsAutofilled, baseState.mHideHighlight);
21625 }
21626 if ((baseState.mSavedData & BaseSavedState.AUTOFILL_ID) != 0) {
21627 // It can happen that views have the same view id and the restoration path will not
21628 // be able to distinguish between them. The autofill id needs to be unique though.
21629 // Hence prevent the same autofill view id from being restored multiple times.
21630 ((BaseSavedState) state).mSavedData &= ~BaseSavedState.AUTOFILL_ID;
21631
21632 if ((mPrivateFlags3 & PFLAG3_AUTOFILLID_EXPLICITLY_SET) != 0) {
21633 // Ignore when view already set it through setAutofillId();
21634 if (Log.isLoggable(AUTOFILL_LOG_TAG, Log.DEBUG)) {
21635 Log.d(AUTOFILL_LOG_TAG, "onRestoreInstanceState(): not setting autofillId "
21636 + "to " + baseState.mAutofillViewId + " because view explicitly set"
21637 + " it to " + mAutofillId);
21638 }
21639 } else {
21640 mAutofillViewId = baseState.mAutofillViewId;
21641 mAutofillId = null; // will be set on demand by getAutofillId()
21642 }
21643 }
21644 }
21645 }
21646
21647 /**
21648 * <p>Return the time at which the drawing of the view hierarchy started.</p>
21649 *
21650 * @return the drawing start time in milliseconds
21651 */
21652 public long getDrawingTime() {
21653 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
21654 }
21655
21656 /**
21657 * <p>Enables or disables the duplication of the parent's state into this view. When
21658 * duplication is enabled, this view gets its drawable state from its parent rather
21659 * than from its own internal properties.</p>
21660 *
21661 * <p>Note: in the current implementation, setting this property to true after the
21662 * view was added to a ViewGroup might have no effect at all. This property should
21663 * always be used from XML or set to true before adding this view to a ViewGroup.</p>
21664 *
21665 * <p>Note: if this view's parent addStateFromChildren property is enabled and this
21666 * property is enabled, an exception will be thrown.</p>
21667 *
21668 * <p>Note: if the child view uses and updates additional states which are unknown to the
21669 * parent, these states should not be affected by this method.</p>
21670 *
21671 * @param enabled True to enable duplication of the parent's drawable state, false
21672 * to disable it.
21673 *
21674 * @see #getDrawableState()
21675 * @see #isDuplicateParentStateEnabled()
21676 */
21677 public void setDuplicateParentStateEnabled(boolean enabled) {
21678 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
21679 }
21680
21681 /**
21682 * <p>Indicates whether this duplicates its drawable state from its parent.</p>
21683 *
21684 * @return True if this view's drawable state is duplicated from the parent,
21685 * false otherwise
21686 *
21687 * @see #getDrawableState()
21688 * @see #setDuplicateParentStateEnabled(boolean)
21689 */
21690 @InspectableProperty(name = "duplicateParentState")
21691 public boolean isDuplicateParentStateEnabled() {
21692 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
21693 }
21694
21695 /**
21696 * <p>Specifies the type of layer backing this view. The layer can be
21697 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
21698 * {@link #LAYER_TYPE_HARDWARE}.</p>
21699 *
21700 * <p>A layer is associated with an optional {@link android.graphics.Paint}
21701 * instance that controls how the layer is composed on screen. The following
21702 * properties of the paint are taken into account when composing the layer:</p>
21703 * <ul>
21704 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
21705 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
21706 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
21707 * </ul>
21708 *
21709 * <p>If this view has an alpha value set to < 1.0 by calling
21710 * {@link #setAlpha(float)}, the alpha value of the layer's paint is superseded
21711 * by this view's alpha value.</p>
21712 *
21713 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
21714 * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
21715 * for more information on when and how to use layers.</p>
21716 *
21717 * @param layerType The type of layer to use with this view, must be one of
21718 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
21719 * {@link #LAYER_TYPE_HARDWARE}
21720 * @param paint The paint used to compose the layer. This argument is optional
21721 * and can be null. It is ignored when the layer type is
21722 * {@link #LAYER_TYPE_NONE}
21723 *
21724 * @see #getLayerType()
21725 * @see #LAYER_TYPE_NONE
21726 * @see #LAYER_TYPE_SOFTWARE
21727 * @see #LAYER_TYPE_HARDWARE
21728 * @see #setAlpha(float)
21729 *
21730 * @attr ref android.R.styleable#View_layerType
21731 */
21732 public void setLayerType(@LayerType int layerType, @Nullable Paint paint) {
21733 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
21734 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
21735 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
21736 }
21737
21738 boolean typeChanged = mRenderNode.setLayerType(layerType);
21739
21740 if (!typeChanged) {
21741 setLayerPaint(paint);
21742 return;
21743 }
21744
21745 if (layerType != LAYER_TYPE_SOFTWARE) {
21746 // Destroy any previous software drawing cache if present
21747 // NOTE: even if previous layer type is HW, we do this to ensure we've cleaned up
21748 // drawing cache created in View#draw when drawing to a SW canvas.
21749 destroyDrawingCache();
21750 }
21751
21752 mLayerType = layerType;
21753 mLayerPaint = mLayerType == LAYER_TYPE_NONE ? null : paint;
21754 mRenderNode.setLayerPaint(mLayerPaint);
21755
21756 // draw() behaves differently if we are on a layer, so we need to
21757 // invalidate() here
21758 invalidateParentCaches();
21759 invalidate(true);
21760 }
21761
21762 /**
21763 * Configure the {@link android.graphics.RenderEffect} to apply to this View.
21764 * This will apply a visual effect to the results of the View before it is drawn. For example if
21765 * {@link RenderEffect#createBlurEffect(float, float, RenderEffect, Shader.TileMode)}
21766 * is provided, the contents will be drawn in a separate layer, then this layer will be blurred
21767 * when this View is drawn.
21768 * @param renderEffect to be applied to the View. Passing null clears the previously configured
21769 * {@link RenderEffect}
21770 */
21771 public void setRenderEffect(@Nullable RenderEffect renderEffect) {
21772 if (mRenderNode.setRenderEffect(renderEffect)) {
21773 invalidateViewProperty(true, true);
21774 }
21775 }
21776
21777 /**
21778 * Updates the {@link Paint} object used with the current layer (used only if the current
21779 * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
21780 * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
21781 * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
21782 * ensure that the view gets redrawn immediately.
21783 *
21784 * <p>A layer is associated with an optional {@link android.graphics.Paint}
21785 * instance that controls how the layer is composed on screen. The following
21786 * properties of the paint are taken into account when composing the layer:</p>
21787 * <ul>
21788 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
21789 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
21790 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
21791 * </ul>
21792 *
21793 * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
21794 * alpha value of the layer's paint is superseded by this view's alpha value.</p>
21795 *
21796 * @param paint The paint used to compose the layer. This argument is optional
21797 * and can be null. It is ignored when the layer type is
21798 * {@link #LAYER_TYPE_NONE}
21799 *
21800 * @see #setLayerType(int, android.graphics.Paint)
21801 */
21802 public void setLayerPaint(@Nullable Paint paint) {
21803 int layerType = getLayerType();
21804 if (layerType != LAYER_TYPE_NONE) {
21805 mLayerPaint = paint;
21806 if (layerType == LAYER_TYPE_HARDWARE) {
21807 if (mRenderNode.setLayerPaint(paint)) {
21808 invalidateViewProperty(false, false);
21809 }
21810 } else {
21811 invalidate();
21812 }
21813 }
21814 }
21815
21816 /**
21817 * Indicates what type of layer is currently associated with this view. By default
21818 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
21819 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
21820 * for more information on the different types of layers.
21821 *
21822 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
21823 * {@link #LAYER_TYPE_HARDWARE}
21824 *
21825 * @see #setLayerType(int, android.graphics.Paint)
21826 * @see #buildLayer()
21827 * @see #LAYER_TYPE_NONE
21828 * @see #LAYER_TYPE_SOFTWARE
21829 * @see #LAYER_TYPE_HARDWARE
21830 */
21831 @InspectableProperty(enumMapping = {
21832 @EnumEntry(value = LAYER_TYPE_NONE, name = "none"),
21833 @EnumEntry(value = LAYER_TYPE_SOFTWARE, name = "software"),
21834 @EnumEntry(value = LAYER_TYPE_HARDWARE, name = "hardware")
21835 })
21836 @LayerType
21837 public int getLayerType() {
21838 return mLayerType;
21839 }
21840
21841 /**
21842 * Forces this view's layer to be created and this view to be rendered
21843 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
21844 * invoking this method will have no effect.
21845 *
21846 * This method can for instance be used to render a view into its layer before
21847 * starting an animation. If this view is complex, rendering into the layer
21848 * before starting the animation will avoid skipping frames.
21849 *
21850 * @throws IllegalStateException If this view is not attached to a window
21851 *
21852 * @see #setLayerType(int, android.graphics.Paint)
21853 */
21854 public void buildLayer() {
21855 if (mLayerType == LAYER_TYPE_NONE) return;
21856
21857 final AttachInfo attachInfo = mAttachInfo;
21858 if (attachInfo == null) {
21859 throw new IllegalStateException("This view must be attached to a window first");
21860 }
21861
21862 if (getWidth() == 0 || getHeight() == 0) {
21863 return;
21864 }
21865
21866 switch (mLayerType) {
21867 case LAYER_TYPE_HARDWARE:
21868 updateDisplayListIfDirty();
21869 if (attachInfo.mThreadedRenderer != null && mRenderNode.hasDisplayList()) {
21870 attachInfo.mThreadedRenderer.buildLayer(mRenderNode);
21871 }
21872 break;
21873 case LAYER_TYPE_SOFTWARE:
21874 buildDrawingCache(true);
21875 break;
21876 }
21877 }
21878
21879 /**
21880 * Destroys all hardware rendering resources. This method is invoked
21881 * when the system needs to reclaim resources. Upon execution of this
21882 * method, you should free any OpenGL resources created by the view.
21883 *
21884 * Note: you <strong>must</strong> call
21885 * <code>super.destroyHardwareResources()</code> when overriding
21886 * this method.
21887 *
21888 * @hide
21889 */
21890 @CallSuper
21891 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
21892 protected void destroyHardwareResources() {
21893 if (mOverlay != null) {
21894 mOverlay.getOverlayView().destroyHardwareResources();
21895 }
21896 if (mGhostView != null) {
21897 mGhostView.destroyHardwareResources();
21898 }
21899 }
21900
21901 /**
21902 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
21903 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
21904 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
21905 * the cache is enabled. To benefit from the cache, you must request the drawing cache by
21906 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
21907 * null.</p>
21908 *
21909 * <p>Enabling the drawing cache is similar to
21910 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
21911 * acceleration is turned off. When hardware acceleration is turned on, enabling the
21912 * drawing cache has no effect on rendering because the system uses a different mechanism
21913 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
21914 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
21915 * for information on how to enable software and hardware layers.</p>
21916 *
21917 * <p>This API can be used to manually generate
21918 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
21919 * {@link #getDrawingCache()}.</p>
21920 *
21921 * @param enabled true to enable the drawing cache, false otherwise
21922 *
21923 * @see #isDrawingCacheEnabled()
21924 * @see #getDrawingCache()
21925 * @see #buildDrawingCache()
21926 * @see #setLayerType(int, android.graphics.Paint)
21927 *
21928 * @deprecated The view drawing cache was largely made obsolete with the introduction of
21929 * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
21930 * layers are largely unnecessary and can easily result in a net loss in performance due to the
21931 * cost of creating and updating the layer. In the rare cases where caching layers are useful,
21932 * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
21933 * rendering. For software-rendered snapshots of a small part of the View hierarchy or
21934 * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
21935 * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
21936 * software-rendered usages are discouraged and have compatibility issues with hardware-only
21937 * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
21938 * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
21939 * reports or unit testing the {@link PixelCopy} API is recommended.
21940 */
21941 @Deprecated
21942 public void setDrawingCacheEnabled(boolean enabled) {
21943 mCachingFailed = false;
21944 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
21945 }
21946
21947 /**
21948 * <p>Indicates whether the drawing cache is enabled for this view.</p>
21949 *
21950 * @return true if the drawing cache is enabled
21951 *
21952 * @see #setDrawingCacheEnabled(boolean)
21953 * @see #getDrawingCache()
21954 *
21955 * @deprecated The view drawing cache was largely made obsolete with the introduction of
21956 * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
21957 * layers are largely unnecessary and can easily result in a net loss in performance due to the
21958 * cost of creating and updating the layer. In the rare cases where caching layers are useful,
21959 * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
21960 * rendering. For software-rendered snapshots of a small part of the View hierarchy or
21961 * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
21962 * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
21963 * software-rendered usages are discouraged and have compatibility issues with hardware-only
21964 * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
21965 * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
21966 * reports or unit testing the {@link PixelCopy} API is recommended.
21967 */
21968 @Deprecated
21969 @ViewDebug.ExportedProperty(category = "drawing")
21970 public boolean isDrawingCacheEnabled() {
21971 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
21972 }
21973
21974 /**
21975 * Debugging utility which recursively outputs the dirty state of a view and its
21976 * descendants.
21977 *
21978 * @hide
21979 */
21980 @SuppressWarnings({"UnusedDeclaration"})
21981 public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
21982 Log.d(VIEW_LOG_TAG, indent + this + " DIRTY("
21983 + (mPrivateFlags & View.PFLAG_DIRTY_MASK)
21984 + ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID("
21985 + (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID)
21986 + ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
21987 if (clear) {
21988 mPrivateFlags &= clearMask;
21989 }
21990 if (this instanceof ViewGroup) {
21991 ViewGroup parent = (ViewGroup) this;
21992 final int count = parent.getChildCount();
21993 for (int i = 0; i < count; i++) {
21994 final View child = parent.getChildAt(i);
21995 child.outputDirtyFlags(indent + " ", clear, clearMask);
21996 }
21997 }
21998 }
21999
22000 /**
22001 * This method is used by ViewGroup to cause its children to restore or recreate their
22002 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
22003 * to recreate its own display list, which would happen if it went through the normal
22004 * draw/dispatchDraw mechanisms.
22005 *
22006 * @hide
22007 */
22008 protected void dispatchGetDisplayList() {}
22009
22010 /**
22011 * A view that is not attached or hardware accelerated cannot create a display list.
22012 * This method checks these conditions and returns the appropriate result.
22013 *
22014 * @return true if view has the ability to create a display list, false otherwise.
22015 *
22016 * @hide
22017 */
22018 public boolean canHaveDisplayList() {
22019 return !(mAttachInfo == null || mAttachInfo.mThreadedRenderer == null);
22020 }
22021
22022 /**
22023 * Gets the RenderNode for the view, and updates its DisplayList (if needed and supported)
22024 * @hide
22025 */
22026 @NonNull
22027 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
22028 public RenderNode updateDisplayListIfDirty() {
22029 final RenderNode renderNode = mRenderNode;
22030 if (!canHaveDisplayList()) {
22031 // can't populate RenderNode, don't try
22032 return renderNode;
22033 }
22034
22035 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0
22036 || !renderNode.hasDisplayList()
22037 || (mRecreateDisplayList)) {
22038 // Don't need to recreate the display list, just need to tell our
22039 // children to restore/recreate theirs
22040 if (renderNode.hasDisplayList()
22041 && !mRecreateDisplayList) {
22042 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
22043 mPrivateFlags &= ~PFLAG_DIRTY_MASK;
22044 dispatchGetDisplayList();
22045
22046 return renderNode; // no work needed
22047 }
22048
22049 // If we got here, we're recreating it. Mark it as such to ensure that
22050 // we copy in child display lists into ours in drawChild()
22051 mRecreateDisplayList = true;
22052
22053 int width = mRight - mLeft;
22054 int height = mBottom - mTop;
22055 int layerType = getLayerType();
22056
22057 // Hacky hack: Reset any stretch effects as those are applied during the draw pass
22058 // instead of being "stateful" like other RenderNode properties
22059 renderNode.clearStretch();
22060
22061 final RecordingCanvas canvas = renderNode.beginRecording(width, height);
22062
22063 try {
22064 if (layerType == LAYER_TYPE_SOFTWARE) {
22065 buildDrawingCache(true);
22066 Bitmap cache = getDrawingCache(true);
22067 if (cache != null) {
22068 canvas.drawBitmap(cache, 0, 0, mLayerPaint);
22069 }
22070 } else {
22071 computeScroll();
22072
22073 canvas.translate(-mScrollX, -mScrollY);
22074 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
22075 mPrivateFlags &= ~PFLAG_DIRTY_MASK;
22076
22077 // Fast path for layouts with no backgrounds
22078 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
22079 dispatchDraw(canvas);
22080 drawAutofilledHighlight(canvas);
22081 if (mOverlay != null && !mOverlay.isEmpty()) {
22082 mOverlay.getOverlayView().draw(canvas);
22083 }
22084 if (isShowingLayoutBounds()) {
22085 debugDrawFocus(canvas);
22086 }
22087 } else {
22088 draw(canvas);
22089 }
22090 }
22091 } finally {
22092 renderNode.endRecording();
22093 setDisplayListProperties(renderNode);
22094 }
22095 } else {
22096 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
22097 mPrivateFlags &= ~PFLAG_DIRTY_MASK;
22098 }
22099 return renderNode;
22100 }
22101
22102 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
22103 private void resetDisplayList() {
22104 mRenderNode.discardDisplayList();
22105 if (mBackgroundRenderNode != null) {
22106 mBackgroundRenderNode.discardDisplayList();
22107 }
22108 }
22109
22110 /**
22111 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
22112 *
22113 * @return A non-scaled bitmap representing this view or null if cache is disabled.
22114 *
22115 * @see #getDrawingCache(boolean)
22116 *
22117 * @deprecated The view drawing cache was largely made obsolete with the introduction of
22118 * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
22119 * layers are largely unnecessary and can easily result in a net loss in performance due to the
22120 * cost of creating and updating the layer. In the rare cases where caching layers are useful,
22121 * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
22122 * rendering. For software-rendered snapshots of a small part of the View hierarchy or
22123 * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
22124 * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
22125 * software-rendered usages are discouraged and have compatibility issues with hardware-only
22126 * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
22127 * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
22128 * reports or unit testing the {@link PixelCopy} API is recommended.
22129 */
22130 @Deprecated
22131 public Bitmap getDrawingCache() {
22132 return getDrawingCache(false);
22133 }
22134
22135 /**
22136 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
22137 * is null when caching is disabled. If caching is enabled and the cache is not ready,
22138 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
22139 * draw from the cache when the cache is enabled. To benefit from the cache, you must
22140 * request the drawing cache by calling this method and draw it on screen if the
22141 * returned bitmap is not null.</p>
22142 *
22143 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
22144 * this method will create a bitmap of the same size as this view. Because this bitmap
22145 * will be drawn scaled by the parent ViewGroup, the result on screen might show
22146 * scaling artifacts. To avoid such artifacts, you should call this method by setting
22147 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
22148 * size than the view. This implies that your application must be able to handle this
22149 * size.</p>
22150 *
22151 * @param autoScale Indicates whether the generated bitmap should be scaled based on
22152 * the current density of the screen when the application is in compatibility
22153 * mode.
22154 *
22155 * @return A bitmap representing this view or null if cache is disabled.
22156 *
22157 * @see #setDrawingCacheEnabled(boolean)
22158 * @see #isDrawingCacheEnabled()
22159 * @see #buildDrawingCache(boolean)
22160 * @see #destroyDrawingCache()
22161 *
22162 * @deprecated The view drawing cache was largely made obsolete with the introduction of
22163 * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
22164 * layers are largely unnecessary and can easily result in a net loss in performance due to the
22165 * cost of creating and updating the layer. In the rare cases where caching layers are useful,
22166 * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
22167 * rendering. For software-rendered snapshots of a small part of the View hierarchy or
22168 * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
22169 * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
22170 * software-rendered usages are discouraged and have compatibility issues with hardware-only
22171 * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
22172 * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
22173 * reports or unit testing the {@link PixelCopy} API is recommended.
22174 */
22175 @Deprecated
22176 public Bitmap getDrawingCache(boolean autoScale) {
22177 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
22178 return null;
22179 }
22180 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
22181 buildDrawingCache(autoScale);
22182 }
22183 return autoScale ? mDrawingCache : mUnscaledDrawingCache;
22184 }
22185
22186 /**
22187 * <p>Frees the resources used by the drawing cache. If you call
22188 * {@link #buildDrawingCache()} manually without calling
22189 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
22190 * should cleanup the cache with this method afterwards.</p>
22191 *
22192 * @see #setDrawingCacheEnabled(boolean)
22193 * @see #buildDrawingCache()
22194 * @see #getDrawingCache()
22195 *
22196 * @deprecated The view drawing cache was largely made obsolete with the introduction of
22197 * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
22198 * layers are largely unnecessary and can easily result in a net loss in performance due to the
22199 * cost of creating and updating the layer. In the rare cases where caching layers are useful,
22200 * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
22201 * rendering. For software-rendered snapshots of a small part of the View hierarchy or
22202 * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
22203 * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
22204 * software-rendered usages are discouraged and have compatibility issues with hardware-only
22205 * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
22206 * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
22207 * reports or unit testing the {@link PixelCopy} API is recommended.
22208 */
22209 @Deprecated
22210 public void destroyDrawingCache() {
22211 if (mDrawingCache != null) {
22212 mDrawingCache.recycle();
22213 mDrawingCache = null;
22214 }
22215 if (mUnscaledDrawingCache != null) {
22216 mUnscaledDrawingCache.recycle();
22217 mUnscaledDrawingCache = null;
22218 }
22219 }
22220
22221 /**
22222 * Setting a solid background color for the drawing cache's bitmaps will improve
22223 * performance and memory usage. Note, though that this should only be used if this
22224 * view will always be drawn on top of a solid color.
22225 *
22226 * @param color The background color to use for the drawing cache's bitmap
22227 *
22228 * @see #setDrawingCacheEnabled(boolean)
22229 * @see #buildDrawingCache()
22230 * @see #getDrawingCache()
22231 *
22232 * @deprecated The view drawing cache was largely made obsolete with the introduction of
22233 * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
22234 * layers are largely unnecessary and can easily result in a net loss in performance due to the
22235 * cost of creating and updating the layer. In the rare cases where caching layers are useful,
22236 * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
22237 * rendering. For software-rendered snapshots of a small part of the View hierarchy or
22238 * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
22239 * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
22240 * software-rendered usages are discouraged and have compatibility issues with hardware-only
22241 * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
22242 * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
22243 * reports or unit testing the {@link PixelCopy} API is recommended.
22244 */
22245 @Deprecated
22246 public void setDrawingCacheBackgroundColor(@ColorInt int color) {
22247 if (color != mDrawingCacheBackgroundColor) {
22248 mDrawingCacheBackgroundColor = color;
22249 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
22250 }
22251 }
22252
22253 /**
22254 * @see #setDrawingCacheBackgroundColor(int)
22255 *
22256 * @return The background color to used for the drawing cache's bitmap
22257 *
22258 * @deprecated The view drawing cache was largely made obsolete with the introduction of
22259 * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
22260 * layers are largely unnecessary and can easily result in a net loss in performance due to the
22261 * cost of creating and updating the layer. In the rare cases where caching layers are useful,
22262 * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
22263 * rendering. For software-rendered snapshots of a small part of the View hierarchy or
22264 * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
22265 * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
22266 * software-rendered usages are discouraged and have compatibility issues with hardware-only
22267 * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
22268 * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
22269 * reports or unit testing the {@link PixelCopy} API is recommended.
22270 */
22271 @Deprecated
22272 @ColorInt
22273 public int getDrawingCacheBackgroundColor() {
22274 return mDrawingCacheBackgroundColor;
22275 }
22276
22277 /**
22278 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
22279 *
22280 * @see #buildDrawingCache(boolean)
22281 *
22282 * @deprecated The view drawing cache was largely made obsolete with the introduction of
22283 * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
22284 * layers are largely unnecessary and can easily result in a net loss in performance due to the
22285 * cost of creating and updating the layer. In the rare cases where caching layers are useful,
22286 * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
22287 * rendering. For software-rendered snapshots of a small part of the View hierarchy or
22288 * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
22289 * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
22290 * software-rendered usages are discouraged and have compatibility issues with hardware-only
22291 * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
22292 * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
22293 * reports or unit testing the {@link PixelCopy} API is recommended.
22294 */
22295 @Deprecated
22296 public void buildDrawingCache() {
22297 buildDrawingCache(false);
22298 }
22299
22300 /**
22301 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
22302 *
22303 * <p>If you call {@link #buildDrawingCache()} manually without calling
22304 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
22305 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
22306 *
22307 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
22308 * this method will create a bitmap of the same size as this view. Because this bitmap
22309 * will be drawn scaled by the parent ViewGroup, the result on screen might show
22310 * scaling artifacts. To avoid such artifacts, you should call this method by setting
22311 * the auto scaling to true. Doing so, however, will generate a bitmap of a different
22312 * size than the view. This implies that your application must be able to handle this
22313 * size.</p>
22314 *
22315 * <p>You should avoid calling this method when hardware acceleration is enabled. If
22316 * you do not need the drawing cache bitmap, calling this method will increase memory
22317 * usage and cause the view to be rendered in software once, thus negatively impacting
22318 * performance.</p>
22319 *
22320 * @see #getDrawingCache()
22321 * @see #destroyDrawingCache()
22322 *
22323 * @deprecated The view drawing cache was largely made obsolete with the introduction of
22324 * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
22325 * layers are largely unnecessary and can easily result in a net loss in performance due to the
22326 * cost of creating and updating the layer. In the rare cases where caching layers are useful,
22327 * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
22328 * rendering. For software-rendered snapshots of a small part of the View hierarchy or
22329 * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
22330 * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
22331 * software-rendered usages are discouraged and have compatibility issues with hardware-only
22332 * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
22333 * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
22334 * reports or unit testing the {@link PixelCopy} API is recommended.
22335 */
22336 @Deprecated
22337 public void buildDrawingCache(boolean autoScale) {
22338 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
22339 mDrawingCache == null : mUnscaledDrawingCache == null)) {
22340 if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) {
22341 Trace.traceBegin(Trace.TRACE_TAG_VIEW,
22342 "buildDrawingCache/SW Layer for " + getClass().getSimpleName());
22343 }
22344 try {
22345 buildDrawingCacheImpl(autoScale);
22346 } finally {
22347 Trace.traceEnd(Trace.TRACE_TAG_VIEW);
22348 }
22349 }
22350 }
22351
22352 /**
22353 * private, internal implementation of buildDrawingCache, used to enable tracing
22354 */
22355 private void buildDrawingCacheImpl(boolean autoScale) {
22356 mCachingFailed = false;
22357
22358 int width = mRight - mLeft;
22359 int height = mBottom - mTop;
22360
22361 final AttachInfo attachInfo = mAttachInfo;
22362 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
22363
22364 if (autoScale && scalingRequired) {
22365 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
22366 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
22367 }
22368
22369 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
22370 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
22371 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
22372
22373 final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
22374 final long drawingCacheSize =
22375 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
22376 if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
22377 if (width > 0 && height > 0) {
22378 Log.w(VIEW_LOG_TAG, getClass().getSimpleName() + " not displayed because it is"
22379 + " too large to fit into a software layer (or drawing cache), needs "
22380 + projectedBitmapSize + " bytes, only "
22381 + drawingCacheSize + " available");
22382 }
22383 destroyDrawingCache();
22384 mCachingFailed = true;
22385 return;
22386 }
22387
22388 boolean clear = true;
22389 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
22390
22391 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
22392 Bitmap.Config quality;
22393 if (!opaque) {
22394 // Never pick ARGB_4444 because it looks awful
22395 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
22396 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
22397 case DRAWING_CACHE_QUALITY_AUTO:
22398 case DRAWING_CACHE_QUALITY_LOW:
22399 case DRAWING_CACHE_QUALITY_HIGH:
22400 default:
22401 quality = Bitmap.Config.ARGB_8888;
22402 break;
22403 }
22404 } else {
22405 // Optimization for translucent windows
22406 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
22407 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
22408 }
22409
22410 // Try to cleanup memory
22411 if (bitmap != null) bitmap.recycle();
22412
22413 try {
22414 bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
22415 width, height, quality);
22416 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
22417 if (autoScale) {
22418 mDrawingCache = bitmap;
22419 } else {
22420 mUnscaledDrawingCache = bitmap;
22421 }
22422 if (opaque && use32BitCache) bitmap.setHasAlpha(false);
22423 } catch (OutOfMemoryError e) {
22424 // If there is not enough memory to create the bitmap cache, just
22425 // ignore the issue as bitmap caches are not required to draw the
22426 // view hierarchy
22427 if (autoScale) {
22428 mDrawingCache = null;
22429 } else {
22430 mUnscaledDrawingCache = null;
22431 }
22432 mCachingFailed = true;
22433 return;
22434 }
22435
22436 clear = drawingCacheBackgroundColor != 0;
22437 }
22438
22439 Canvas canvas;
22440 if (attachInfo != null) {
22441 canvas = attachInfo.mCanvas;
22442 if (canvas == null) {
22443 canvas = new Canvas();
22444 }
22445 canvas.setBitmap(bitmap);
22446 // Temporarily clobber the cached Canvas in case one of our children
22447 // is also using a drawing cache. Without this, the children would
22448 // steal the canvas by attaching their own bitmap to it and bad, bad
22449 // thing would happen (invisible views, corrupted drawings, etc.)
22450 attachInfo.mCanvas = null;
22451 } else {
22452 // This case should hopefully never or seldom happen
22453 canvas = new Canvas(bitmap);
22454 }
22455
22456 if (clear) {
22457 bitmap.eraseColor(drawingCacheBackgroundColor);
22458 }
22459
22460 computeScroll();
22461 final int restoreCount = canvas.save();
22462
22463 if (autoScale && scalingRequired) {
22464 final float scale = attachInfo.mApplicationScale;
22465 canvas.scale(scale, scale);
22466 }
22467
22468 canvas.translate(-mScrollX, -mScrollY);
22469
22470 mPrivateFlags |= PFLAG_DRAWN;
22471 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
22472 mLayerType != LAYER_TYPE_NONE) {
22473 mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
22474 }
22475
22476 // Fast path for layouts with no backgrounds
22477 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
22478 mPrivateFlags &= ~PFLAG_DIRTY_MASK;
22479 dispatchDraw(canvas);
22480 drawAutofilledHighlight(canvas);
22481 if (mOverlay != null && !mOverlay.isEmpty()) {
22482 mOverlay.getOverlayView().draw(canvas);
22483 }
22484 } else {
22485 draw(canvas);
22486 }
22487
22488 canvas.restoreToCount(restoreCount);
22489 canvas.setBitmap(null);
22490
22491 if (attachInfo != null) {
22492 // Restore the cached Canvas for our siblings
22493 attachInfo.mCanvas = canvas;
22494 }
22495 }
22496
22497 /**
22498 * Create a snapshot of the view into a bitmap. We should probably make
22499 * some form of this public, but should think about the API.
22500 *
22501 * @hide
22502 */
22503 @UnsupportedAppUsage
22504 public Bitmap createSnapshot(ViewDebug.CanvasProvider canvasProvider, boolean skipChildren) {
22505 int width = mRight - mLeft;
22506 int height = mBottom - mTop;
22507
22508 final AttachInfo attachInfo = mAttachInfo;
22509 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
22510 width = (int) ((width * scale) + 0.5f);
22511 height = (int) ((height * scale) + 0.5f);
22512
22513 Canvas oldCanvas = null;
22514 try {
22515 Canvas canvas = canvasProvider.getCanvas(this,
22516 width > 0 ? width : 1, height > 0 ? height : 1);
22517
22518 if (attachInfo != null) {
22519 oldCanvas = attachInfo.mCanvas;
22520 // Temporarily clobber the cached Canvas in case one of our children
22521 // is also using a drawing cache. Without this, the children would
22522 // steal the canvas by attaching their own bitmap to it and bad, bad
22523 // things would happen (invisible views, corrupted drawings, etc.)
22524 attachInfo.mCanvas = null;
22525 }
22526
22527 computeScroll();
22528 final int restoreCount = canvas.save();
22529 canvas.scale(scale, scale);
22530 canvas.translate(-mScrollX, -mScrollY);
22531
22532 // Temporarily remove the dirty mask
22533 int flags = mPrivateFlags;
22534 mPrivateFlags &= ~PFLAG_DIRTY_MASK;
22535
22536 // Fast path for layouts with no backgrounds
22537 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
22538 dispatchDraw(canvas);
22539 drawAutofilledHighlight(canvas);
22540 if (mOverlay != null && !mOverlay.isEmpty()) {
22541 mOverlay.getOverlayView().draw(canvas);
22542 }
22543 } else {
22544 draw(canvas);
22545 }
22546
22547 mPrivateFlags = flags;
22548 canvas.restoreToCount(restoreCount);
22549 return canvasProvider.createBitmap();
22550 } finally {
22551 if (oldCanvas != null) {
22552 attachInfo.mCanvas = oldCanvas;
22553 }
22554 }
22555 }
22556
22557 /**
22558 * Indicates whether this View is currently in edit mode. A View is usually
22559 * in edit mode when displayed within a developer tool. For instance, if
22560 * this View is being drawn by a visual user interface builder, this method
22561 * should return true.
22562 *
22563 * Subclasses should check the return value of this method to provide
22564 * different behaviors if their normal behavior might interfere with the
22565 * host environment. For instance: the class spawns a thread in its
22566 * constructor, the drawing code relies on device-specific features, etc.
22567 *
22568 * This method is usually checked in the drawing code of custom widgets.
22569 *
22570 * @return True if this View is in edit mode, false otherwise.
22571 */
22572 public boolean isInEditMode() {
22573 return false;
22574 }
22575
22576 /**
22577 * If the View draws content inside its padding and enables fading edges,
22578 * it needs to support padding offsets. Padding offsets are added to the
22579 * fading edges to extend the length of the fade so that it covers pixels
22580 * drawn inside the padding.
22581 *
22582 * Subclasses of this class should override this method if they need
22583 * to draw content inside the padding.
22584 *
22585 * @return True if padding offset must be applied, false otherwise.
22586 *
22587 * @see #getLeftPaddingOffset()
22588 * @see #getRightPaddingOffset()
22589 * @see #getTopPaddingOffset()
22590 * @see #getBottomPaddingOffset()
22591 *
22592 * @since CURRENT
22593 */
22594 protected boolean isPaddingOffsetRequired() {
22595 return false;
22596 }
22597
22598 /**
22599 * Amount by which to extend the left fading region. Called only when
22600 * {@link #isPaddingOffsetRequired()} returns true.
22601 *
22602 * @return The left padding offset in pixels.
22603 *
22604 * @see #isPaddingOffsetRequired()
22605 *
22606 * @since CURRENT
22607 */
22608 protected int getLeftPaddingOffset() {
22609 return 0;
22610 }
22611
22612 /**
22613 * Amount by which to extend the right fading region. Called only when
22614 * {@link #isPaddingOffsetRequired()} returns true.
22615 *
22616 * @return The right padding offset in pixels.
22617 *
22618 * @see #isPaddingOffsetRequired()
22619 *
22620 * @since CURRENT
22621 */
22622 protected int getRightPaddingOffset() {
22623 return 0;
22624 }
22625
22626 /**
22627 * Amount by which to extend the top fading region. Called only when
22628 * {@link #isPaddingOffsetRequired()} returns true.
22629 *
22630 * @return The top padding offset in pixels.
22631 *
22632 * @see #isPaddingOffsetRequired()
22633 *
22634 * @since CURRENT
22635 */
22636 protected int getTopPaddingOffset() {
22637 return 0;
22638 }
22639
22640 /**
22641 * Amount by which to extend the bottom fading region. Called only when
22642 * {@link #isPaddingOffsetRequired()} returns true.
22643 *
22644 * @return The bottom padding offset in pixels.
22645 *
22646 * @see #isPaddingOffsetRequired()
22647 *
22648 * @since CURRENT
22649 */
22650 protected int getBottomPaddingOffset() {
22651 return 0;
22652 }
22653
22654 /**
22655 * @hide
22656 * @param offsetRequired
22657 */
22658 protected int getFadeTop(boolean offsetRequired) {
22659 int top = mPaddingTop;
22660 if (offsetRequired) top += getTopPaddingOffset();
22661 return top;
22662 }
22663
22664 /**
22665 * @hide
22666 * @param offsetRequired
22667 */
22668 protected int getFadeHeight(boolean offsetRequired) {
22669 int padding = mPaddingTop;
22670 if (offsetRequired) padding += getTopPaddingOffset();
22671 return mBottom - mTop - mPaddingBottom - padding;
22672 }
22673
22674 /**
22675 * <p>Indicates whether this view is attached to a hardware accelerated
22676 * window or not.</p>
22677 *
22678 * <p>Even if this method returns true, it does not mean that every call
22679 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
22680 * accelerated {@link android.graphics.Canvas}. For instance, if this view
22681 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
22682 * window is hardware accelerated,
22683 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
22684 * return false, and this method will return true.</p>
22685 *
22686 * @return True if the view is attached to a window and the window is
22687 * hardware accelerated; false in any other case.
22688 */
22689 @ViewDebug.ExportedProperty(category = "drawing")
22690 public boolean isHardwareAccelerated() {
22691 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
22692 }
22693
22694 /**
22695 * Sets a rectangular area on this view to which the view will be clipped
22696 * when it is drawn. Setting the value to null will remove the clip bounds
22697 * and the view will draw normally, using its full bounds.
22698 *
22699 * @param clipBounds The rectangular area, in the local coordinates of
22700 * this view, to which future drawing operations will be clipped.
22701 */
22702 public void setClipBounds(Rect clipBounds) {
22703 if (clipBounds == mClipBounds
22704 || (clipBounds != null && clipBounds.equals(mClipBounds))) {
22705 return;
22706 }
22707 if (clipBounds != null) {
22708 if (mClipBounds == null) {
22709 mClipBounds = new Rect(clipBounds);
22710 } else {
22711 mClipBounds.set(clipBounds);
22712 }
22713 } else {
22714 mClipBounds = null;
22715 }
22716 mRenderNode.setClipRect(mClipBounds);
22717 invalidateViewProperty(false, false);
22718 }
22719
22720 /**
22721 * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
22722 *
22723 * @return A copy of the current clip bounds if clip bounds are set,
22724 * otherwise null.
22725 */
22726 public Rect getClipBounds() {
22727 return (mClipBounds != null) ? new Rect(mClipBounds) : null;
22728 }
22729
22730
22731 /**
22732 * Populates an output rectangle with the clip bounds of the view,
22733 * returning {@code true} if successful or {@code false} if the view's
22734 * clip bounds are {@code null}.
22735 *
22736 * @param outRect rectangle in which to place the clip bounds of the view
22737 * @return {@code true} if successful or {@code false} if the view's
22738 * clip bounds are {@code null}
22739 */
22740 public boolean getClipBounds(Rect outRect) {
22741 if (mClipBounds != null) {
22742 outRect.set(mClipBounds);
22743 return true;
22744 }
22745 return false;
22746 }
22747
22748 /**
22749 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
22750 * case of an active Animation being run on the view.
22751 */
22752 private boolean applyLegacyAnimation(ViewGroup parent, long drawingTime,
22753 Animation a, boolean scalingRequired) {
22754 Transformation invalidationTransform;
22755 final int flags = parent.mGroupFlags;
22756 final boolean initialized = a.isInitialized();
22757 if (!initialized) {
22758 a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
22759 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
22760 if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
22761 onAnimationStart();
22762 }
22763
22764 final Transformation t = parent.getChildTransformation();
22765 boolean more = a.getTransformation(drawingTime, t, 1f);
22766 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
22767 if (parent.mInvalidationTransformation == null) {
22768 parent.mInvalidationTransformation = new Transformation();
22769 }
22770 invalidationTransform = parent.mInvalidationTransformation;
22771 a.getTransformation(drawingTime, invalidationTransform, 1f);
22772 } else {
22773 invalidationTransform = t;
22774 }
22775
22776 if (more) {
22777 if (!a.willChangeBounds()) {
22778 if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
22779 ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
22780 parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
22781 } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
22782 // The child need to draw an animation, potentially offscreen, so
22783 // make sure we do not cancel invalidate requests
22784 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
22785 parent.invalidate(mLeft, mTop, mRight, mBottom);
22786 }
22787 } else {
22788 if (parent.mInvalidateRegion == null) {
22789 parent.mInvalidateRegion = new RectF();
22790 }
22791 final RectF region = parent.mInvalidateRegion;
22792 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
22793 invalidationTransform);
22794
22795 // The child need to draw an animation, potentially offscreen, so
22796 // make sure we do not cancel invalidate requests
22797 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
22798
22799 final int left = mLeft + (int) region.left;
22800 final int top = mTop + (int) region.top;
22801 parent.invalidate(left, top, left + (int) (region.width() + .5f),
22802 top + (int) (region.height() + .5f));
22803 }
22804 }
22805 return more;
22806 }
22807
22808 /**
22809 * This method is called by getDisplayList() when a display list is recorded for a View.
22810 * It pushes any properties to the RenderNode that aren't managed by the RenderNode.
22811 */
22812 void setDisplayListProperties(RenderNode renderNode) {
22813 if (renderNode != null) {
22814 renderNode.setHasOverlappingRendering(getHasOverlappingRendering());
22815 renderNode.setClipToBounds(mParent instanceof ViewGroup
22816 && ((ViewGroup) mParent).getClipChildren());
22817
22818 float alpha = 1;
22819 if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
22820 ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
22821 ViewGroup parentVG = (ViewGroup) mParent;
22822 final Transformation t = parentVG.getChildTransformation();
22823 if (parentVG.getChildStaticTransformation(this, t)) {
22824 final int transformType = t.getTransformationType();
22825 if (transformType != Transformation.TYPE_IDENTITY) {
22826 if ((transformType & Transformation.TYPE_ALPHA) != 0) {
22827 alpha = t.getAlpha();
22828 }
22829 if ((transformType & Transformation.TYPE_MATRIX) != 0) {
22830 renderNode.setStaticMatrix(t.getMatrix());
22831 }
22832 }
22833 }
22834 }
22835 if (mTransformationInfo != null) {
22836 alpha *= getFinalAlpha();
22837 if (alpha < 1) {
22838 final int multipliedAlpha = (int) (255 * alpha);
22839 if (onSetAlpha(multipliedAlpha)) {
22840 alpha = 1;
22841 }
22842 }
22843 renderNode.setAlpha(alpha);
22844 } else if (alpha < 1) {
22845 renderNode.setAlpha(alpha);
22846 }
22847 }
22848 }
22849
22850 /**
22851 * If an attached view draws to a HW canvas, it may use its RenderNode + DisplayList.
22852 *
22853 * If a view is dettached, its DisplayList shouldn't exist. If the canvas isn't
22854 * HW accelerated, it can't handle drawing RenderNodes.
22855 *
22856 * @hide
22857 */
22858 protected final boolean drawsWithRenderNode(Canvas canvas) {
22859 return mAttachInfo != null
22860 && mAttachInfo.mHardwareAccelerated
22861 && canvas.isHardwareAccelerated();
22862 }
22863
22864 /**
22865 * This method is called by ViewGroup.drawChild() to have each child view draw itself.
22866 *
22867 * This is where the View specializes rendering behavior based on layer type,
22868 * and hardware acceleration.
22869 */
22870 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
22871
22872 final boolean hardwareAcceleratedCanvas = canvas.isHardwareAccelerated();
22873
22874 boolean drawingWithRenderNode = drawsWithRenderNode(canvas);
22875
22876 boolean more = false;
22877 final boolean childHasIdentityMatrix = hasIdentityMatrix();
22878 final int parentFlags = parent.mGroupFlags;
22879
22880 if ((parentFlags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) != 0) {
22881 parent.getChildTransformation().clear();
22882 parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
22883 }
22884
22885 Transformation transformToApply = null;
22886 boolean concatMatrix = false;
22887 final boolean scalingRequired = mAttachInfo != null && mAttachInfo.mScalingRequired;
22888 final Animation a = getAnimation();
22889 if (a != null) {
22890 more = applyLegacyAnimation(parent, drawingTime, a, scalingRequired);
22891 concatMatrix = a.willChangeTransformationMatrix();
22892 if (concatMatrix) {
22893 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
22894 }
22895 transformToApply = parent.getChildTransformation();
22896 } else {
22897 if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) {
22898 // No longer animating: clear out old animation matrix
22899 mRenderNode.setAnimationMatrix(null);
22900 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
22901 }
22902 if (!drawingWithRenderNode
22903 && (parentFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
22904 final Transformation t = parent.getChildTransformation();
22905 final boolean hasTransform = parent.getChildStaticTransformation(this, t);
22906 if (hasTransform) {
22907 final int transformType = t.getTransformationType();
22908 transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
22909 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
22910 }
22911 }
22912 }
22913
22914 concatMatrix |= !childHasIdentityMatrix;
22915
22916 // Sets the flag as early as possible to allow draw() implementations
22917 // to call invalidate() successfully when doing animations
22918 mPrivateFlags |= PFLAG_DRAWN;
22919
22920 if (!concatMatrix &&
22921 (parentFlags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
22922 ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
22923 canvas.quickReject(mLeft, mTop, mRight, mBottom) &&
22924 (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
22925 mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
22926 return more;
22927 }
22928 mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
22929
22930 if (hardwareAcceleratedCanvas) {
22931 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
22932 // retain the flag's value temporarily in the mRecreateDisplayList flag
22933 mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) != 0;
22934 mPrivateFlags &= ~PFLAG_INVALIDATED;
22935 }
22936
22937 RenderNode renderNode = null;
22938 Bitmap cache = null;
22939 int layerType = getLayerType(); // TODO: signify cache state with just 'cache' local
22940 if (layerType == LAYER_TYPE_SOFTWARE || !drawingWithRenderNode) {
22941 if (layerType != LAYER_TYPE_NONE) {
22942 // If not drawing with RenderNode, treat HW layers as SW
22943 layerType = LAYER_TYPE_SOFTWARE;
22944 buildDrawingCache(true);
22945 }
22946 cache = getDrawingCache(true);
22947 }
22948
22949 if (drawingWithRenderNode) {
22950 // Delay getting the display list until animation-driven alpha values are
22951 // set up and possibly passed on to the view
22952 renderNode = updateDisplayListIfDirty();
22953 if (!renderNode.hasDisplayList()) {
22954 // Uncommon, but possible. If a view is removed from the hierarchy during the call
22955 // to getDisplayList(), the display list will be marked invalid and we should not
22956 // try to use it again.
22957 renderNode = null;
22958 drawingWithRenderNode = false;
22959 }
22960 }
22961
22962 int sx = 0;
22963 int sy = 0;
22964 if (!drawingWithRenderNode) {
22965 computeScroll();
22966 sx = mScrollX;
22967 sy = mScrollY;
22968 }
22969
22970 final boolean drawingWithDrawingCache = cache != null && !drawingWithRenderNode;
22971 final boolean offsetForScroll = cache == null && !drawingWithRenderNode;
22972
22973 int restoreTo = -1;
22974 if (!drawingWithRenderNode || transformToApply != null) {
22975 restoreTo = canvas.save();
22976 }
22977 if (offsetForScroll) {
22978 canvas.translate(mLeft - sx, mTop - sy);
22979 } else {
22980 if (!drawingWithRenderNode) {
22981 canvas.translate(mLeft, mTop);
22982 }
22983 if (scalingRequired) {
22984 if (drawingWithRenderNode) {
22985 // TODO: Might not need this if we put everything inside the DL
22986 restoreTo = canvas.save();
22987 }
22988 // mAttachInfo cannot be null, otherwise scalingRequired == false
22989 final float scale = 1.0f / mAttachInfo.mApplicationScale;
22990 canvas.scale(scale, scale);
22991 }
22992 }
22993
22994 float alpha = drawingWithRenderNode ? 1 : (getAlpha() * getTransitionAlpha());
22995 if (transformToApply != null
22996 || alpha < 1
22997 || !hasIdentityMatrix()
22998 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
22999 if (transformToApply != null || !childHasIdentityMatrix) {
23000 int transX = 0;
23001 int transY = 0;
23002
23003 if (offsetForScroll) {
23004 transX = -sx;
23005 transY = -sy;
23006 }
23007
23008 if (transformToApply != null) {
23009 if (concatMatrix) {
23010 if (drawingWithRenderNode) {
23011 renderNode.setAnimationMatrix(transformToApply.getMatrix());
23012 } else {
23013 // Undo the scroll translation, apply the transformation matrix,
23014 // then redo the scroll translate to get the correct result.
23015 canvas.translate(-transX, -transY);
23016 canvas.concat(transformToApply.getMatrix());
23017 canvas.translate(transX, transY);
23018 }
23019 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
23020 }
23021
23022 float transformAlpha = transformToApply.getAlpha();
23023 if (transformAlpha < 1) {
23024 alpha *= transformAlpha;
23025 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
23026 }
23027 }
23028
23029 if (!childHasIdentityMatrix && !drawingWithRenderNode) {
23030 canvas.translate(-transX, -transY);
23031 canvas.concat(getMatrix());
23032 canvas.translate(transX, transY);
23033 }
23034 }
23035
23036 // Deal with alpha if it is or used to be <1
23037 if (alpha < 1 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
23038 if (alpha < 1) {
23039 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
23040 } else {
23041 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
23042 }
23043 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
23044 if (!drawingWithDrawingCache) {
23045 final int multipliedAlpha = (int) (255 * alpha);
23046 if (!onSetAlpha(multipliedAlpha)) {
23047 if (drawingWithRenderNode) {
23048 renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha());
23049 } else if (layerType == LAYER_TYPE_NONE) {
23050 canvas.saveLayerAlpha(sx, sy, sx + getWidth(), sy + getHeight(),
23051 multipliedAlpha);
23052 }
23053 } else {
23054 // Alpha is handled by the child directly, clobber the layer's alpha
23055 mPrivateFlags |= PFLAG_ALPHA_SET;
23056 }
23057 }
23058 }
23059 } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
23060 onSetAlpha(255);
23061 mPrivateFlags &= ~PFLAG_ALPHA_SET;
23062 }
23063
23064 if (!drawingWithRenderNode) {
23065 // apply clips directly, since RenderNode won't do it for this draw
23066 if ((parentFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 && cache == null) {
23067 if (offsetForScroll) {
23068 canvas.clipRect(sx, sy, sx + getWidth(), sy + getHeight());
23069 } else {
23070 if (!scalingRequired || cache == null) {
23071 canvas.clipRect(0, 0, getWidth(), getHeight());
23072 } else {
23073 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
23074 }
23075 }
23076 }
23077
23078 if (mClipBounds != null) {
23079 // clip bounds ignore scroll
23080 canvas.clipRect(mClipBounds);
23081 }
23082 }
23083
23084 if (!drawingWithDrawingCache) {
23085 if (drawingWithRenderNode) {
23086 mPrivateFlags &= ~PFLAG_DIRTY_MASK;
23087 ((RecordingCanvas) canvas).drawRenderNode(renderNode);
23088 } else {
23089 // Fast path for layouts with no backgrounds
23090 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
23091 mPrivateFlags &= ~PFLAG_DIRTY_MASK;
23092 dispatchDraw(canvas);
23093 } else {
23094 draw(canvas);
23095 }
23096 }
23097 } else if (cache != null) {
23098 mPrivateFlags &= ~PFLAG_DIRTY_MASK;
23099 if (layerType == LAYER_TYPE_NONE || mLayerPaint == null) {
23100 // no layer paint, use temporary paint to draw bitmap
23101 Paint cachePaint = parent.mCachePaint;
23102 if (cachePaint == null) {
23103 cachePaint = new Paint();
23104 cachePaint.setDither(false);
23105 parent.mCachePaint = cachePaint;
23106 }
23107 cachePaint.setAlpha((int) (alpha * 255));
23108 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
23109 } else {
23110 // use layer paint to draw the bitmap, merging the two alphas, but also restore
23111 int layerPaintAlpha = mLayerPaint.getAlpha();
23112 if (alpha < 1) {
23113 mLayerPaint.setAlpha((int) (alpha * layerPaintAlpha));
23114 }
23115 canvas.drawBitmap(cache, 0.0f, 0.0f, mLayerPaint);
23116 if (alpha < 1) {
23117 mLayerPaint.setAlpha(layerPaintAlpha);
23118 }
23119 }
23120 }
23121
23122 if (restoreTo >= 0) {
23123 canvas.restoreToCount(restoreTo);
23124 }
23125
23126 if (a != null && !more) {
23127 if (!hardwareAcceleratedCanvas && !a.getFillAfter()) {
23128 onSetAlpha(255);
23129 }
23130 parent.finishAnimatingView(this, a);
23131 }
23132
23133 if (more && hardwareAcceleratedCanvas) {
23134 if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
23135 // alpha animations should cause the child to recreate its display list
23136 invalidate(true);
23137 }
23138 }
23139
23140 mRecreateDisplayList = false;
23141
23142 return more;
23143 }
23144
23145 static Paint getDebugPaint() {
23146 if (sDebugPaint == null) {
23147 sDebugPaint = new Paint();
23148 sDebugPaint.setAntiAlias(false);
23149 }
23150 return sDebugPaint;
23151 }
23152
23153 final int dipsToPixels(int dips) {
23154 float scale = getContext().getResources().getDisplayMetrics().density;
23155 return (int) (dips * scale + 0.5f);
23156 }
23157
23158 final private void debugDrawFocus(Canvas canvas) {
23159 if (isFocused()) {
23160 final int cornerSquareSize = dipsToPixels(DEBUG_CORNERS_SIZE_DIP);
23161 final int l = mScrollX;
23162 final int r = l + mRight - mLeft;
23163 final int t = mScrollY;
23164 final int b = t + mBottom - mTop;
23165
23166 final Paint paint = getDebugPaint();
23167 paint.setColor(DEBUG_CORNERS_COLOR);
23168
23169 // Draw squares in corners.
23170 paint.setStyle(Paint.Style.FILL);
23171 canvas.drawRect(l, t, l + cornerSquareSize, t + cornerSquareSize, paint);
23172 canvas.drawRect(r - cornerSquareSize, t, r, t + cornerSquareSize, paint);
23173 canvas.drawRect(l, b - cornerSquareSize, l + cornerSquareSize, b, paint);
23174 canvas.drawRect(r - cornerSquareSize, b - cornerSquareSize, r, b, paint);
23175
23176 // Draw big X across the view.
23177 paint.setStyle(Paint.Style.STROKE);
23178 canvas.drawLine(l, t, r, b, paint);
23179 canvas.drawLine(l, b, r, t, paint);
23180 }
23181 }
23182
23183 /**
23184 * Manually render this view (and all of its children) to the given Canvas.
23185 * The view must have already done a full layout before this function is
23186 * called. When implementing a view, implement
23187 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
23188 * If you do need to override this method, call the superclass version.
23189 *
23190 * @param canvas The Canvas to which the View is rendered.
23191 */
23192 @CallSuper
23193 public void draw(Canvas canvas) {
23194 final int privateFlags = mPrivateFlags;
23195 mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
23196
23197 /*
23198 * Draw traversal performs several drawing steps which must be executed
23199 * in the appropriate order:
23200 *
23201 * 1. Draw the background
23202 * 2. If necessary, save the canvas' layers to prepare for fading
23203 * 3. Draw view's content
23204 * 4. Draw children
23205 * 5. If necessary, draw the fading edges and restore layers
23206 * 6. Draw decorations (scrollbars for instance)
23207 * 7. If necessary, draw the default focus highlight
23208 */
23209
23210 // Step 1, draw the background, if needed
23211 int saveCount;
23212
23213 drawBackground(canvas);
23214
23215 // skip step 2 & 5 if possible (common case)
23216 final int viewFlags = mViewFlags;
23217 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
23218 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
23219 if (!verticalEdges && !horizontalEdges) {
23220 // Step 3, draw the content
23221 onDraw(canvas);
23222
23223 // Step 4, draw the children
23224 dispatchDraw(canvas);
23225
23226 drawAutofilledHighlight(canvas);
23227
23228 // Overlay is part of the content and draws beneath Foreground
23229 if (mOverlay != null && !mOverlay.isEmpty()) {
23230 mOverlay.getOverlayView().dispatchDraw(canvas);
23231 }
23232
23233 // Step 6, draw decorations (foreground, scrollbars)
23234 onDrawForeground(canvas);
23235
23236 // Step 7, draw the default focus highlight
23237 drawDefaultFocusHighlight(canvas);
23238
23239 if (isShowingLayoutBounds()) {
23240 debugDrawFocus(canvas);
23241 }
23242
23243 // we're done...
23244 return;
23245 }
23246
23247 /*
23248 * Here we do the full fledged routine...
23249 * (this is an uncommon case where speed matters less,
23250 * this is why we repeat some of the tests that have been
23251 * done above)
23252 */
23253
23254 boolean drawTop = false;
23255 boolean drawBottom = false;
23256 boolean drawLeft = false;
23257 boolean drawRight = false;
23258
23259 float topFadeStrength = 0.0f;
23260 float bottomFadeStrength = 0.0f;
23261 float leftFadeStrength = 0.0f;
23262 float rightFadeStrength = 0.0f;
23263
23264 // Step 2, save the canvas' layers
23265 int paddingLeft = mPaddingLeft;
23266
23267 final boolean offsetRequired = isPaddingOffsetRequired();
23268 if (offsetRequired) {
23269 paddingLeft += getLeftPaddingOffset();
23270 }
23271
23272 int left = mScrollX + paddingLeft;
23273 int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
23274 int top = mScrollY + getFadeTop(offsetRequired);
23275 int bottom = top + getFadeHeight(offsetRequired);
23276
23277 if (offsetRequired) {
23278 right += getRightPaddingOffset();
23279 bottom += getBottomPaddingOffset();
23280 }
23281
23282 final ScrollabilityCache scrollabilityCache = mScrollCache;
23283 final float fadeHeight = scrollabilityCache.fadingEdgeLength;
23284 int length = (int) fadeHeight;
23285
23286 // clip the fade length if top and bottom fades overlap
23287 // overlapping fades produce odd-looking artifacts
23288 if (verticalEdges && (top + length > bottom - length)) {
23289 length = (bottom - top) / 2;
23290 }
23291
23292 // also clip horizontal fades if necessary
23293 if (horizontalEdges && (left + length > right - length)) {
23294 length = (right - left) / 2;
23295 }
23296
23297 if (verticalEdges) {
23298 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
23299 drawTop = topFadeStrength * fadeHeight > 1.0f;
23300 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
23301 drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
23302 }
23303
23304 if (horizontalEdges) {
23305 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
23306 drawLeft = leftFadeStrength * fadeHeight > 1.0f;
23307 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
23308 drawRight = rightFadeStrength * fadeHeight > 1.0f;
23309 }
23310
23311 saveCount = canvas.getSaveCount();
23312 int topSaveCount = -1;
23313 int bottomSaveCount = -1;
23314 int leftSaveCount = -1;
23315 int rightSaveCount = -1;
23316
23317 int solidColor = getSolidColor();
23318 if (solidColor == 0) {
23319 if (drawTop) {
23320 topSaveCount = canvas.saveUnclippedLayer(left, top, right, top + length);
23321 }
23322
23323 if (drawBottom) {
23324 bottomSaveCount = canvas.saveUnclippedLayer(left, bottom - length, right, bottom);
23325 }
23326
23327 if (drawLeft) {
23328 leftSaveCount = canvas.saveUnclippedLayer(left, top, left + length, bottom);
23329 }
23330
23331 if (drawRight) {
23332 rightSaveCount = canvas.saveUnclippedLayer(right - length, top, right, bottom);
23333 }
23334 } else {
23335 scrollabilityCache.setFadeColor(solidColor);
23336 }
23337
23338 // Step 3, draw the content
23339 onDraw(canvas);
23340
23341 // Step 4, draw the children
23342 dispatchDraw(canvas);
23343
23344 // Step 5, draw the fade effect and restore layers
23345 final Paint p = scrollabilityCache.paint;
23346 final Matrix matrix = scrollabilityCache.matrix;
23347 final Shader fade = scrollabilityCache.shader;
23348
23349 // must be restored in the reverse order that they were saved
23350 if (drawRight) {
23351 matrix.setScale(1, fadeHeight * rightFadeStrength);
23352 matrix.postRotate(90);
23353 matrix.postTranslate(right, top);
23354 fade.setLocalMatrix(matrix);
23355 p.setShader(fade);
23356 if (solidColor == 0) {
23357 canvas.restoreUnclippedLayer(rightSaveCount, p);
23358
23359 } else {
23360 canvas.drawRect(right - length, top, right, bottom, p);
23361 }
23362 }
23363
23364 if (drawLeft) {
23365 matrix.setScale(1, fadeHeight * leftFadeStrength);
23366 matrix.postRotate(-90);
23367 matrix.postTranslate(left, top);
23368 fade.setLocalMatrix(matrix);
23369 p.setShader(fade);
23370 if (solidColor == 0) {
23371 canvas.restoreUnclippedLayer(leftSaveCount, p);
23372 } else {
23373 canvas.drawRect(left, top, left + length, bottom, p);
23374 }
23375 }
23376
23377 if (drawBottom) {
23378 matrix.setScale(1, fadeHeight * bottomFadeStrength);
23379 matrix.postRotate(180);
23380 matrix.postTranslate(left, bottom);
23381 fade.setLocalMatrix(matrix);
23382 p.setShader(fade);
23383 if (solidColor == 0) {
23384 canvas.restoreUnclippedLayer(bottomSaveCount, p);
23385 } else {
23386 canvas.drawRect(left, bottom - length, right, bottom, p);
23387 }
23388 }
23389
23390 if (drawTop) {
23391 matrix.setScale(1, fadeHeight * topFadeStrength);
23392 matrix.postTranslate(left, top);
23393 fade.setLocalMatrix(matrix);
23394 p.setShader(fade);
23395 if (solidColor == 0) {
23396 canvas.restoreUnclippedLayer(topSaveCount, p);
23397 } else {
23398 canvas.drawRect(left, top, right, top + length, p);
23399 }
23400 }
23401
23402 canvas.restoreToCount(saveCount);
23403
23404 drawAutofilledHighlight(canvas);
23405
23406 // Overlay is part of the content and draws beneath Foreground
23407 if (mOverlay != null && !mOverlay.isEmpty()) {
23408 mOverlay.getOverlayView().dispatchDraw(canvas);
23409 }
23410
23411 // Step 6, draw decorations (foreground, scrollbars)
23412 onDrawForeground(canvas);
23413
23414 // Step 7, draw the default focus highlight
23415 drawDefaultFocusHighlight(canvas);
23416
23417 if (isShowingLayoutBounds()) {
23418 debugDrawFocus(canvas);
23419 }
23420 }
23421
23422 /**
23423 * Draws the background onto the specified canvas.
23424 *
23425 * @param canvas Canvas on which to draw the background
23426 */
23427 @UnsupportedAppUsage
23428 private void drawBackground(Canvas canvas) {
23429 final Drawable background = mBackground;
23430 if (background == null) {
23431 return;
23432 }
23433
23434 setBackgroundBounds();
23435
23436 // Attempt to use a display list if requested.
23437 if (canvas.isHardwareAccelerated() && mAttachInfo != null
23438 && mAttachInfo.mThreadedRenderer != null) {
23439 mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode);
23440
23441 final RenderNode renderNode = mBackgroundRenderNode;
23442 if (renderNode != null && renderNode.hasDisplayList()) {
23443 setBackgroundRenderNodeProperties(renderNode);
23444 ((RecordingCanvas) canvas).drawRenderNode(renderNode);
23445 return;
23446 }
23447 }
23448
23449 final int scrollX = mScrollX;
23450 final int scrollY = mScrollY;
23451 if ((scrollX | scrollY) == 0) {
23452 background.draw(canvas);
23453 } else {
23454 canvas.translate(scrollX, scrollY);
23455 background.draw(canvas);
23456 canvas.translate(-scrollX, -scrollY);
23457 }
23458 }
23459
23460 /**
23461 * Sets the correct background bounds and rebuilds the outline, if needed.
23462 * <p/>
23463 * This is called by LayoutLib.
23464 */
23465 void setBackgroundBounds() {
23466 if (mBackgroundSizeChanged && mBackground != null) {
23467 mBackground.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
23468 mBackgroundSizeChanged = false;
23469 rebuildOutline();
23470 }
23471 }
23472
23473 private void setBackgroundRenderNodeProperties(RenderNode renderNode) {
23474 renderNode.setTranslationX(mScrollX);
23475 renderNode.setTranslationY(mScrollY);
23476 }
23477
23478 /**
23479 * Creates a new display list or updates the existing display list for the
23480 * specified Drawable.
23481 *
23482 * @param drawable Drawable for which to create a display list
23483 * @param renderNode Existing RenderNode, or {@code null}
23484 * @return A valid display list for the specified drawable
23485 */
23486 private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) {
23487 if (renderNode == null) {
23488 renderNode = RenderNode.create(drawable.getClass().getName(),
23489 new ViewAnimationHostBridge(this));
23490 renderNode.setUsageHint(RenderNode.USAGE_BACKGROUND);
23491 }
23492
23493 final Rect bounds = drawable.getBounds();
23494 final int width = bounds.width();
23495 final int height = bounds.height();
23496
23497 // Hacky hack: Reset any stretch effects as those are applied during the draw pass
23498 // instead of being "stateful" like other RenderNode properties
23499 renderNode.clearStretch();
23500
23501 final RecordingCanvas canvas = renderNode.beginRecording(width, height);
23502
23503 // Reverse left/top translation done by drawable canvas, which will
23504 // instead be applied by rendernode's LTRB bounds below. This way, the
23505 // drawable's bounds match with its rendernode bounds and its content
23506 // will lie within those bounds in the rendernode tree.
23507 canvas.translate(-bounds.left, -bounds.top);
23508
23509 try {
23510 drawable.draw(canvas);
23511 } finally {
23512 renderNode.endRecording();
23513 }
23514
23515 // Set up drawable properties that are view-independent.
23516 renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
23517 renderNode.setProjectBackwards(drawable.isProjected());
23518 renderNode.setProjectionReceiver(true);
23519 renderNode.setClipToBounds(false);
23520 return renderNode;
23521 }
23522
23523 /**
23524 * Returns the overlay for this view, creating it if it does not yet exist.
23525 * Adding drawables to the overlay will cause them to be displayed whenever
23526 * the view itself is redrawn. Objects in the overlay should be actively
23527 * managed: remove them when they should not be displayed anymore. The
23528 * overlay will always have the same size as its host view.
23529 *
23530 * <p>Note: Overlays do not currently work correctly with {@link
23531 * SurfaceView} or {@link TextureView}; contents in overlays for these
23532 * types of views may not display correctly.</p>
23533 *
23534 * @return The ViewOverlay object for this view.
23535 * @see ViewOverlay
23536 */
23537 public ViewOverlay getOverlay() {
23538 if (mOverlay == null) {
23539 mOverlay = new ViewOverlay(mContext, this);
23540 }
23541 return mOverlay;
23542 }
23543
23544 /**
23545 * Override this if your view is known to always be drawn on top of a solid color background,
23546 * and needs to draw fading edges. Returning a non-zero color enables the view system to
23547 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
23548 * should be set to 0xFF.
23549 *
23550 * @see #setVerticalFadingEdgeEnabled(boolean)
23551 * @see #setHorizontalFadingEdgeEnabled(boolean)
23552 *
23553 * @return The known solid color background for this view, or 0 if the color may vary
23554 */
23555 @ViewDebug.ExportedProperty(category = "drawing")
23556 @InspectableProperty
23557 @ColorInt
23558 public int getSolidColor() {
23559 return 0;
23560 }
23561
23562 /**
23563 * Build a human readable string representation of the specified view flags.
23564 *
23565 * @param flags the view flags to convert to a string
23566 * @return a String representing the supplied flags
23567 */
23568 private static String printFlags(int flags) {
23569 String output = "";
23570 int numFlags = 0;
23571 if ((flags & FOCUSABLE) == FOCUSABLE) {
23572 output += "TAKES_FOCUS";
23573 numFlags++;
23574 }
23575
23576 switch (flags & VISIBILITY_MASK) {
23577 case INVISIBLE:
23578 if (numFlags > 0) {
23579 output += " ";
23580 }
23581 output += "INVISIBLE";
23582 // USELESS HERE numFlags++;
23583 break;
23584 case GONE:
23585 if (numFlags > 0) {
23586 output += " ";
23587 }
23588 output += "GONE";
23589 // USELESS HERE numFlags++;
23590 break;
23591 default:
23592 break;
23593 }
23594 return output;
23595 }
23596
23597 /**
23598 * Build a human readable string representation of the specified private
23599 * view flags.
23600 *
23601 * @param privateFlags the private view flags to convert to a string
23602 * @return a String representing the supplied flags
23603 */
23604 private static String printPrivateFlags(int privateFlags) {
23605 String output = "";
23606 int numFlags = 0;
23607
23608 if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
23609 output += "WANTS_FOCUS";
23610 numFlags++;
23611 }
23612
23613 if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
23614 if (numFlags > 0) {
23615 output += " ";
23616 }
23617 output += "FOCUSED";
23618 numFlags++;
23619 }
23620
23621 if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
23622 if (numFlags > 0) {
23623 output += " ";
23624 }
23625 output += "SELECTED";
23626 numFlags++;
23627 }
23628
23629 if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
23630 if (numFlags > 0) {
23631 output += " ";
23632 }
23633 output += "IS_ROOT_NAMESPACE";
23634 numFlags++;
23635 }
23636
23637 if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
23638 if (numFlags > 0) {
23639 output += " ";
23640 }
23641 output += "HAS_BOUNDS";
23642 numFlags++;
23643 }
23644
23645 if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
23646 if (numFlags > 0) {
23647 output += " ";
23648 }
23649 output += "DRAWN";
23650 // USELESS HERE numFlags++;
23651 }
23652 return output;
23653 }
23654
23655 /**
23656 * <p>Indicates whether or not this view's layout will be requested during
23657 * the next hierarchy layout pass.</p>
23658 *
23659 * @return true if the layout will be forced during next layout pass
23660 */
23661 public boolean isLayoutRequested() {
23662 return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
23663 }
23664
23665 /**
23666 * Return true if o is a ViewGroup that is laying out using optical bounds.
23667 * @hide
23668 */
23669 public static boolean isLayoutModeOptical(Object o) {
23670 return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
23671 }
23672
23673 private boolean setOpticalFrame(int left, int top, int right, int bottom) {
23674 Insets parentInsets = mParent instanceof View ?
23675 ((View) mParent).getOpticalInsets() : Insets.NONE;
23676 Insets childInsets = getOpticalInsets();
23677 return setFrame(
23678 left + parentInsets.left - childInsets.left,
23679 top + parentInsets.top - childInsets.top,
23680 right + parentInsets.left + childInsets.right,
23681 bottom + parentInsets.top + childInsets.bottom);
23682 }
23683
23684 /**
23685 * Assign a size and position to a view and all of its
23686 * descendants
23687 *
23688 * <p>This is the second phase of the layout mechanism.
23689 * (The first is measuring). In this phase, each parent calls
23690 * layout on all of its children to position them.
23691 * This is typically done using the child measurements
23692 * that were stored in the measure pass().</p>
23693 *
23694 * <p>Derived classes should not override this method.
23695 * Derived classes with children should override
23696 * onLayout. In that method, they should
23697 * call layout on each of their children.</p>
23698 *
23699 * @param l Left position, relative to parent
23700 * @param t Top position, relative to parent
23701 * @param r Right position, relative to parent
23702 * @param b Bottom position, relative to parent
23703 */
23704 @SuppressWarnings({"unchecked"})
23705 public void layout(int l, int t, int r, int b) {
23706 if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
23707 onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
23708 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
23709 }
23710
23711 int oldL = mLeft;
23712 int oldT = mTop;
23713 int oldB = mBottom;
23714 int oldR = mRight;
23715
23716 boolean changed = isLayoutModeOptical(mParent) ?
23717 setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
23718
23719 if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
23720 onLayout(changed, l, t, r, b);
23721
23722 if (shouldDrawRoundScrollbar()) {
23723 if(mRoundScrollbarRenderer == null) {
23724 mRoundScrollbarRenderer = new RoundScrollbarRenderer(this);
23725 }
23726 } else {
23727 mRoundScrollbarRenderer = null;
23728 }
23729
23730 mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
23731
23732 ListenerInfo li = mListenerInfo;
23733 if (li != null && li.mOnLayoutChangeListeners != null) {
23734 ArrayList<OnLayoutChangeListener> listenersCopy =
23735 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
23736 int numListeners = listenersCopy.size();
23737 for (int i = 0; i < numListeners; ++i) {
23738 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
23739 }
23740 }
23741 }
23742
23743 final boolean wasLayoutValid = isLayoutValid();
23744
23745 mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
23746 mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
23747
23748 if (!wasLayoutValid && isFocused()) {
23749 mPrivateFlags &= ~PFLAG_WANTS_FOCUS;
23750 if (canTakeFocus()) {
23751 // We have a robust focus, so parents should no longer be wanting focus.
23752 clearParentsWantFocus();
23753 } else if (getViewRootImpl() == null || !getViewRootImpl().isInLayout()) {
23754 // This is a weird case. Most-likely the user, rather than ViewRootImpl, called
23755 // layout. In this case, there's no guarantee that parent layouts will be evaluated
23756 // and thus the safest action is to clear focus here.
23757 clearFocusInternal(null, /* propagate */ true, /* refocus */ false);
23758 clearParentsWantFocus();
23759 } else if (!hasParentWantsFocus()) {
23760 // original requestFocus was likely on this view directly, so just clear focus
23761 clearFocusInternal(null, /* propagate */ true, /* refocus */ false);
23762 }
23763 // otherwise, we let parents handle re-assigning focus during their layout passes.
23764 } else if ((mPrivateFlags & PFLAG_WANTS_FOCUS) != 0) {
23765 mPrivateFlags &= ~PFLAG_WANTS_FOCUS;
23766 View focused = findFocus();
23767 if (focused != null) {
23768 // Try to restore focus as close as possible to our starting focus.
23769 if (!restoreDefaultFocus() && !hasParentWantsFocus()) {
23770 // Give up and clear focus once we've reached the top-most parent which wants
23771 // focus.
23772 focused.clearFocusInternal(null, /* propagate */ true, /* refocus */ false);
23773 }
23774 }
23775 }
23776
23777 if ((mPrivateFlags3 & PFLAG3_NOTIFY_AUTOFILL_ENTER_ON_LAYOUT) != 0) {
23778 mPrivateFlags3 &= ~PFLAG3_NOTIFY_AUTOFILL_ENTER_ON_LAYOUT;
23779 notifyEnterOrExitForAutoFillIfNeeded(true);
23780 }
23781
23782 notifyAppearedOrDisappearedForContentCaptureIfNeeded(true);
23783 }
23784
23785 private boolean hasParentWantsFocus() {
23786 ViewParent parent = mParent;
23787 while (parent instanceof ViewGroup) {
23788 ViewGroup pv = (ViewGroup) parent;
23789 if ((pv.mPrivateFlags & PFLAG_WANTS_FOCUS) != 0) {
23790 return true;
23791 }
23792 parent = pv.mParent;
23793 }
23794 return false;
23795 }
23796
23797 /**
23798 * Called from layout when this view should
23799 * assign a size and position to each of its children.
23800 *
23801 * Derived classes with children should override
23802 * this method and call layout on each of
23803 * their children.
23804 * @param changed This is a new size or position for this view
23805 * @param left Left position, relative to parent
23806 * @param top Top position, relative to parent
23807 * @param right Right position, relative to parent
23808 * @param bottom Bottom position, relative to parent
23809 */
23810 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
23811 }
23812
23813 /**
23814 * Assign a size and position to this view.
23815 *
23816 * This is called from layout.
23817 *
23818 * @param left Left position, relative to parent
23819 * @param top Top position, relative to parent
23820 * @param right Right position, relative to parent
23821 * @param bottom Bottom position, relative to parent
23822 * @return true if the new size and position are different than the
23823 * previous ones
23824 * {@hide}
23825 */
23826 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
23827 protected boolean setFrame(int left, int top, int right, int bottom) {
23828 boolean changed = false;
23829
23830 if (DBG) {
23831 Log.d(VIEW_LOG_TAG, this + " View.setFrame(" + left + "," + top + ","
23832 + right + "," + bottom + ")");
23833 }
23834
23835 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
23836 changed = true;
23837
23838 // Remember our drawn bit
23839 int drawn = mPrivateFlags & PFLAG_DRAWN;
23840
23841 int oldWidth = mRight - mLeft;
23842 int oldHeight = mBottom - mTop;
23843 int newWidth = right - left;
23844 int newHeight = bottom - top;
23845 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
23846
23847 // Invalidate our old position
23848 invalidate(sizeChanged);
23849
23850 mLeft = left;
23851 mTop = top;
23852 mRight = right;
23853 mBottom = bottom;
23854 mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
23855
23856 mPrivateFlags |= PFLAG_HAS_BOUNDS;
23857
23858
23859 if (sizeChanged) {
23860 sizeChange(newWidth, newHeight, oldWidth, oldHeight);
23861 }
23862
23863 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) {
23864 // If we are visible, force the DRAWN bit to on so that
23865 // this invalidate will go through (at least to our parent).
23866 // This is because someone may have invalidated this view
23867 // before this call to setFrame came in, thereby clearing
23868 // the DRAWN bit.
23869 mPrivateFlags |= PFLAG_DRAWN;
23870 invalidate(sizeChanged);
23871 // parent display list may need to be recreated based on a change in the bounds
23872 // of any child
23873 invalidateParentCaches();
23874 }
23875
23876 // Reset drawn bit to original value (invalidate turns it off)
23877 mPrivateFlags |= drawn;
23878
23879 mBackgroundSizeChanged = true;
23880 mDefaultFocusHighlightSizeChanged = true;
23881 if (mForegroundInfo != null) {
23882 mForegroundInfo.mBoundsChanged = true;
23883 }
23884
23885 notifySubtreeAccessibilityStateChangedIfNeeded();
23886 }
23887 return changed;
23888 }
23889
23890 /**
23891 * Assign a size and position to this view.
23892 *
23893 * This method is meant to be used in animations only as it applies this position and size
23894 * for the view only temporary and it can be changed back at any time by the layout.
23895 *
23896 * @param left Left position, relative to parent
23897 * @param top Top position, relative to parent
23898 * @param right Right position, relative to parent
23899 * @param bottom Bottom position, relative to parent
23900 *
23901 * @see #setLeft(int), #setRight(int), #setTop(int), #setBottom(int)
23902 */
23903 public final void setLeftTopRightBottom(int left, int top, int right, int bottom) {
23904 setFrame(left, top, right, bottom);
23905 }
23906
23907 private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
23908 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
23909 if (mOverlay != null) {
23910 mOverlay.getOverlayView().setRight(newWidth);
23911 mOverlay.getOverlayView().setBottom(newHeight);
23912 }
23913 // If this isn't laid out yet, focus assignment will be handled during the "deferment/
23914 // backtracking" of requestFocus during layout, so don't touch focus here.
23915 if (!sCanFocusZeroSized && isLayoutValid()
23916 // Don't touch focus if animating
23917 && !(mParent instanceof ViewGroup && ((ViewGroup) mParent).isLayoutSuppressed())) {
23918 if (newWidth <= 0 || newHeight <= 0) {
23919 if (hasFocus()) {
23920 clearFocus();
23921 if (mParent instanceof ViewGroup) {
23922 ((ViewGroup) mParent).clearFocusedInCluster();
23923 }
23924 }
23925 clearAccessibilityFocus();
23926 } else if (oldWidth <= 0 || oldHeight <= 0) {
23927 if (mParent != null && canTakeFocus()) {
23928 mParent.focusableViewAvailable(this);
23929 }
23930 }
23931 }
23932 rebuildOutline();
23933 }
23934
23935 /**
23936 * Finalize inflating a view from XML. This is called as the last phase
23937 * of inflation, after all child views have been added.
23938 *
23939 * <p>Even if the subclass overrides onFinishInflate, they should always be
23940 * sure to call the super method, so that we get called.
23941 */
23942 @CallSuper
23943 protected void onFinishInflate() {
23944 }
23945
23946 /**
23947 * Returns the resources associated with this view.
23948 *
23949 * @return Resources object.
23950 */
23951 public Resources getResources() {
23952 return mResources;
23953 }
23954
23955 /**
23956 * Invalidates the specified Drawable.
23957 *
23958 * @param drawable the drawable to invalidate
23959 */
23960 @Override
23961 public void invalidateDrawable(@NonNull Drawable drawable) {
23962 if (verifyDrawable(drawable)) {
23963 final Rect dirty = drawable.getDirtyBounds();
23964 final int scrollX = mScrollX;
23965 final int scrollY = mScrollY;
23966
23967 invalidate(dirty.left + scrollX, dirty.top + scrollY,
23968 dirty.right + scrollX, dirty.bottom + scrollY);
23969 rebuildOutline();
23970 }
23971 }
23972
23973 /**
23974 * Schedules an action on a drawable to occur at a specified time.
23975 *
23976 * @param who the recipient of the action
23977 * @param what the action to run on the drawable
23978 * @param when the time at which the action must occur. Uses the
23979 * {@link SystemClock#uptimeMillis} timebase.
23980 */
23981 @Override
23982 public void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when) {
23983 if (verifyDrawable(who) && what != null) {
23984 final long delay = when - SystemClock.uptimeMillis();
23985 if (mAttachInfo != null) {
23986 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
23987 Choreographer.CALLBACK_ANIMATION, what, who,
23988 Choreographer.subtractFrameDelay(delay));
23989 } else {
23990 // Postpone the runnable until we know
23991 // on which thread it needs to run.
23992 getRunQueue().postDelayed(what, delay);
23993 }
23994 }
23995 }
23996
23997 /**
23998 * Cancels a scheduled action on a drawable.
23999 *
24000 * @param who the recipient of the action
24001 * @param what the action to cancel
24002 */
24003 @Override
24004 public void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what) {
24005 if (verifyDrawable(who) && what != null) {
24006 if (mAttachInfo != null) {
24007 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
24008 Choreographer.CALLBACK_ANIMATION, what, who);
24009 }
24010 getRunQueue().removeCallbacks(what);
24011 }
24012 }
24013
24014 /**
24015 * Unschedule any events associated with the given Drawable. This can be
24016 * used when selecting a new Drawable into a view, so that the previous
24017 * one is completely unscheduled.
24018 *
24019 * @param who The Drawable to unschedule.
24020 *
24021 * @see #drawableStateChanged
24022 */
24023 public void unscheduleDrawable(Drawable who) {
24024 if (mAttachInfo != null && who != null) {
24025 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
24026 Choreographer.CALLBACK_ANIMATION, null, who);
24027 }
24028 }
24029
24030 /**
24031 * Resolve the Drawables depending on the layout direction. This is implicitly supposing
24032 * that the View directionality can and will be resolved before its Drawables.
24033 *
24034 * Will call {@link View#onResolveDrawables} when resolution is done.
24035 *
24036 * @hide
24037 */
24038 protected void resolveDrawables() {
24039 // Drawables resolution may need to happen before resolving the layout direction (which is
24040 // done only during the measure() call).
24041 // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
24042 // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
24043 // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
24044 // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
24045 // direction to be resolved as its resolved value will be the same as its raw value.
24046 if (!isLayoutDirectionResolved() &&
24047 getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
24048 return;
24049 }
24050
24051 final int layoutDirection = isLayoutDirectionResolved() ?
24052 getLayoutDirection() : getRawLayoutDirection();
24053
24054 if (mBackground != null) {
24055 mBackground.setLayoutDirection(layoutDirection);
24056 }
24057 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
24058 mForegroundInfo.mDrawable.setLayoutDirection(layoutDirection);
24059 }
24060 if (mDefaultFocusHighlight != null) {
24061 mDefaultFocusHighlight.setLayoutDirection(layoutDirection);
24062 }
24063 mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
24064 onResolveDrawables(layoutDirection);
24065 }
24066
24067 boolean areDrawablesResolved() {
24068 return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
24069 }
24070
24071 /**
24072 * Called when layout direction has been resolved.
24073 *
24074 * The default implementation does nothing.
24075 *
24076 * @param layoutDirection The resolved layout direction.
24077 *
24078 * @see #LAYOUT_DIRECTION_LTR
24079 * @see #LAYOUT_DIRECTION_RTL
24080 *
24081 * @hide
24082 */
24083 public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
24084 }
24085
24086 /**
24087 * @hide
24088 */
24089 @TestApi
24090 protected void resetResolvedDrawables() {
24091 resetResolvedDrawablesInternal();
24092 }
24093
24094 void resetResolvedDrawablesInternal() {
24095 mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
24096 }
24097
24098 /**
24099 * If your view subclass is displaying its own Drawable objects, it should
24100 * override this function and return true for any Drawable it is
24101 * displaying. This allows animations for those drawables to be
24102 * scheduled.
24103 *
24104 * <p>Be sure to call through to the super class when overriding this
24105 * function.
24106 *
24107 * @param who The Drawable to verify. Return true if it is one you are
24108 * displaying, else return the result of calling through to the
24109 * super class.
24110 *
24111 * @return boolean If true then the Drawable is being displayed in the
24112 * view; else false and it is not allowed to animate.
24113 *
24114 * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
24115 * @see #drawableStateChanged()
24116 */
24117 @CallSuper
24118 protected boolean verifyDrawable(@NonNull Drawable who) {
24119 // Avoid verifying the scroll bar drawable so that we don't end up in
24120 // an invalidation loop. This effectively prevents the scroll bar
24121 // drawable from triggering invalidations and scheduling runnables.
24122 return who == mBackground || (mForegroundInfo != null && mForegroundInfo.mDrawable == who)
24123 || (mDefaultFocusHighlight == who);
24124 }
24125
24126 /**
24127 * This function is called whenever the state of the view changes in such
24128 * a way that it impacts the state of drawables being shown.
24129 * <p>
24130 * If the View has a StateListAnimator, it will also be called to run necessary state
24131 * change animations.
24132 * <p>
24133 * Be sure to call through to the superclass when overriding this function.
24134 *
24135 * @see Drawable#setState(int[])
24136 */
24137 @CallSuper
24138 protected void drawableStateChanged() {
24139 final int[] state = getDrawableState();
24140 boolean changed = false;
24141
24142 final Drawable bg = mBackground;
24143 if (bg != null && bg.isStateful()) {
24144 changed |= bg.setState(state);
24145 }
24146
24147 final Drawable hl = mDefaultFocusHighlight;
24148 if (hl != null && hl.isStateful()) {
24149 changed |= hl.setState(state);
24150 }
24151
24152 final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
24153 if (fg != null && fg.isStateful()) {
24154 changed |= fg.setState(state);
24155 }
24156
24157 if (mScrollCache != null) {
24158 final Drawable scrollBar = mScrollCache.scrollBar;
24159 if (scrollBar != null && scrollBar.isStateful()) {
24160 changed |= scrollBar.setState(state)
24161 && mScrollCache.state != ScrollabilityCache.OFF;
24162 }
24163 }
24164
24165 if (mStateListAnimator != null) {
24166 mStateListAnimator.setState(state);
24167 }
24168
24169 if (!isAggregatedVisible()) {
24170 // If we're not visible, skip any animated changes
24171 jumpDrawablesToCurrentState();
24172 }
24173
24174 if (changed) {
24175 invalidate();
24176 }
24177 }
24178
24179 /**
24180 * This function is called whenever the view hotspot changes and needs to
24181 * be propagated to drawables or child views managed by the view.
24182 * <p>
24183 * Dispatching to child views is handled by
24184 * {@link #dispatchDrawableHotspotChanged(float, float)}.
24185 * <p>
24186 * Be sure to call through to the superclass when overriding this function.
24187 *
24188 * @param x hotspot x coordinate
24189 * @param y hotspot y coordinate
24190 */
24191 @CallSuper
24192 public void drawableHotspotChanged(float x, float y) {
24193 if (mBackground != null) {
24194 mBackground.setHotspot(x, y);
24195 }
24196 if (mDefaultFocusHighlight != null) {
24197 mDefaultFocusHighlight.setHotspot(x, y);
24198 }
24199 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
24200 mForegroundInfo.mDrawable.setHotspot(x, y);
24201 }
24202
24203 dispatchDrawableHotspotChanged(x, y);
24204 }
24205
24206 /**
24207 * Dispatches drawableHotspotChanged to all of this View's children.
24208 *
24209 * @param x hotspot x coordinate
24210 * @param y hotspot y coordinate
24211 * @see #drawableHotspotChanged(float, float)
24212 */
24213 public void dispatchDrawableHotspotChanged(float x, float y) {
24214 }
24215
24216 /**
24217 * Call this to force a view to update its drawable state. This will cause
24218 * drawableStateChanged to be called on this view. Views that are interested
24219 * in the new state should call getDrawableState.
24220 *
24221 * @see #drawableStateChanged
24222 * @see #getDrawableState
24223 */
24224 public void refreshDrawableState() {
24225 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
24226 drawableStateChanged();
24227
24228 ViewParent parent = mParent;
24229 if (parent != null) {
24230 parent.childDrawableStateChanged(this);
24231 }
24232 }
24233
24234 /**
24235 * Create a default focus highlight if it doesn't exist.
24236 * @return a default focus highlight.
24237 */
24238 private Drawable getDefaultFocusHighlightDrawable() {
24239 if (mDefaultFocusHighlightCache == null) {
24240 if (mContext != null) {
24241 final int[] attrs = new int[] { android.R.attr.selectableItemBackground };
24242 final TypedArray ta = mContext.obtainStyledAttributes(attrs);
24243 mDefaultFocusHighlightCache = ta.getDrawable(0);
24244 ta.recycle();
24245 }
24246 }
24247 return mDefaultFocusHighlightCache;
24248 }
24249
24250 /**
24251 * Set the current default focus highlight.
24252 * @param highlight the highlight drawable, or {@code null} if it's no longer needed.
24253 */
24254 private void setDefaultFocusHighlight(Drawable highlight) {
24255 mDefaultFocusHighlight = highlight;
24256 mDefaultFocusHighlightSizeChanged = true;
24257 if (highlight != null) {
24258 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
24259 mPrivateFlags &= ~PFLAG_SKIP_DRAW;
24260 }
24261 highlight.setLayoutDirection(getLayoutDirection());
24262 if (highlight.isStateful()) {
24263 highlight.setState(getDrawableState());
24264 }
24265 if (isAttachedToWindow()) {
24266 highlight.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
24267 }
24268 // Set callback last, since the view may still be initializing.
24269 highlight.setCallback(this);
24270 } else if ((mViewFlags & WILL_NOT_DRAW) != 0 && mBackground == null
24271 && (mForegroundInfo == null || mForegroundInfo.mDrawable == null)) {
24272 mPrivateFlags |= PFLAG_SKIP_DRAW;
24273 }
24274 invalidate();
24275 }
24276
24277 /**
24278 * Check whether we need to draw a default focus highlight when this view gets focused,
24279 * which requires:
24280 * <ul>
24281 * <li>In both background and foreground, {@link android.R.attr#state_focused}
24282 * is not defined.</li>
24283 * <li>This view is not in touch mode.</li>
24284 * <li>This view doesn't opt out for a default focus highlight, via
24285 * {@link #setDefaultFocusHighlightEnabled(boolean)}.</li>
24286 * <li>This view is attached to window.</li>
24287 * </ul>
24288 * @return {@code true} if a default focus highlight is needed.
24289 * @hide
24290 */
24291 @TestApi
24292 public boolean isDefaultFocusHighlightNeeded(Drawable background, Drawable foreground) {
24293 final boolean lackFocusState = (background == null || !background.isStateful()
24294 || !background.hasFocusStateSpecified())
24295 && (foreground == null || !foreground.isStateful()
24296 || !foreground.hasFocusStateSpecified());
24297 return !isInTouchMode() && getDefaultFocusHighlightEnabled() && lackFocusState
24298 && isAttachedToWindow() && sUseDefaultFocusHighlight;
24299 }
24300
24301 /**
24302 * When this view is focused, switches on/off the default focused highlight.
24303 * <p>
24304 * This always happens when this view is focused, and only at this moment the default focus
24305 * highlight can be visible.
24306 */
24307 private void switchDefaultFocusHighlight() {
24308 if (isFocused()) {
24309 final boolean needed = isDefaultFocusHighlightNeeded(mBackground,
24310 mForegroundInfo == null ? null : mForegroundInfo.mDrawable);
24311 final boolean active = mDefaultFocusHighlight != null;
24312 if (needed && !active) {
24313 setDefaultFocusHighlight(getDefaultFocusHighlightDrawable());
24314 } else if (!needed && active) {
24315 // The highlight is no longer needed, so tear it down.
24316 setDefaultFocusHighlight(null);
24317 }
24318 }
24319 }
24320
24321 /**
24322 * Draw the default focus highlight onto the canvas if there is one and this view is focused.
24323 * @param canvas the canvas where we're drawing the highlight.
24324 */
24325 private void drawDefaultFocusHighlight(Canvas canvas) {
24326 if (mDefaultFocusHighlight != null && isFocused()) {
24327 if (mDefaultFocusHighlightSizeChanged) {
24328 mDefaultFocusHighlightSizeChanged = false;
24329 final int l = mScrollX;
24330 final int r = l + mRight - mLeft;
24331 final int t = mScrollY;
24332 final int b = t + mBottom - mTop;
24333 mDefaultFocusHighlight.setBounds(l, t, r, b);
24334 }
24335 mDefaultFocusHighlight.draw(canvas);
24336 }
24337 }
24338
24339 /**
24340 * Return an array of resource IDs of the drawable states representing the
24341 * current state of the view.
24342 *
24343 * @return The current drawable state
24344 *
24345 * @see Drawable#setState(int[])
24346 * @see #drawableStateChanged()
24347 * @see #onCreateDrawableState(int)
24348 */
24349 public final int[] getDrawableState() {
24350 if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
24351 return mDrawableState;
24352 } else {
24353 mDrawableState = onCreateDrawableState(0);
24354 mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
24355 return mDrawableState;
24356 }
24357 }
24358
24359 /**
24360 * Generate the new {@link android.graphics.drawable.Drawable} state for
24361 * this view. This is called by the view
24362 * system when the cached Drawable state is determined to be invalid. To
24363 * retrieve the current state, you should use {@link #getDrawableState}.
24364 *
24365 * @param extraSpace if non-zero, this is the number of extra entries you
24366 * would like in the returned array in which you can place your own
24367 * states.
24368 *
24369 * @return Returns an array holding the current {@link Drawable} state of
24370 * the view.
24371 *
24372 * @see #mergeDrawableStates(int[], int[])
24373 */
24374 protected int[] onCreateDrawableState(int extraSpace) {
24375 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
24376 mParent instanceof View) {
24377 return ((View) mParent).onCreateDrawableState(extraSpace);
24378 }
24379
24380 int[] drawableState;
24381
24382 int privateFlags = mPrivateFlags;
24383
24384 int viewStateIndex = 0;
24385 if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= StateSet.VIEW_STATE_PRESSED;
24386 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= StateSet.VIEW_STATE_ENABLED;
24387 if (isFocused()) viewStateIndex |= StateSet.VIEW_STATE_FOCUSED;
24388 if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= StateSet.VIEW_STATE_SELECTED;
24389 if (hasWindowFocus()) viewStateIndex |= StateSet.VIEW_STATE_WINDOW_FOCUSED;
24390 if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= StateSet.VIEW_STATE_ACTIVATED;
24391 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested) {
24392 // This is set if HW acceleration is requested, even if the current
24393 // process doesn't allow it. This is just to allow app preview
24394 // windows to better match their app.
24395 viewStateIndex |= StateSet.VIEW_STATE_ACCELERATED;
24396 }
24397 if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= StateSet.VIEW_STATE_HOVERED;
24398
24399 final int privateFlags2 = mPrivateFlags2;
24400 if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) {
24401 viewStateIndex |= StateSet.VIEW_STATE_DRAG_CAN_ACCEPT;
24402 }
24403 if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) {
24404 viewStateIndex |= StateSet.VIEW_STATE_DRAG_HOVERED;
24405 }
24406
24407 drawableState = StateSet.get(viewStateIndex);
24408
24409 //noinspection ConstantIfStatement
24410 if (false) {
24411 Log.i("View", "drawableStateIndex=" + viewStateIndex);
24412 Log.i("View", toString()
24413 + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
24414 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
24415 + " fo=" + hasFocus()
24416 + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
24417 + " wf=" + hasWindowFocus()
24418 + ": " + Arrays.toString(drawableState));
24419 }
24420
24421 if (extraSpace == 0) {
24422 return drawableState;
24423 }
24424
24425 final int[] fullState;
24426 if (drawableState != null) {
24427 fullState = new int[drawableState.length + extraSpace];
24428 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
24429 } else {
24430 fullState = new int[extraSpace];
24431 }
24432
24433 return fullState;
24434 }
24435
24436 /**
24437 * Merge your own state values in <var>additionalState</var> into the base
24438 * state values <var>baseState</var> that were returned by
24439 * {@link #onCreateDrawableState(int)}.
24440 *
24441 * @param baseState The base state values returned by
24442 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
24443 * own additional state values.
24444 *
24445 * @param additionalState The additional state values you would like
24446 * added to <var>baseState</var>; this array is not modified.
24447 *
24448 * @return As a convenience, the <var>baseState</var> array you originally
24449 * passed into the function is returned.
24450 *
24451 * @see #onCreateDrawableState(int)
24452 */
24453 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
24454 final int N = baseState.length;
24455 int i = N - 1;
24456 while (i >= 0 && baseState[i] == 0) {
24457 i--;
24458 }
24459 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
24460 return baseState;
24461 }
24462
24463 /**
24464 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
24465 * on all Drawable objects associated with this view.
24466 * <p>
24467 * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator
24468 * attached to this view.
24469 */
24470 @CallSuper
24471 public void jumpDrawablesToCurrentState() {
24472 if (mBackground != null) {
24473 mBackground.jumpToCurrentState();
24474 }
24475 if (mStateListAnimator != null) {
24476 mStateListAnimator.jumpToCurrentState();
24477 }
24478 if (mDefaultFocusHighlight != null) {
24479 mDefaultFocusHighlight.jumpToCurrentState();
24480 }
24481 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
24482 mForegroundInfo.mDrawable.jumpToCurrentState();
24483 }
24484 }
24485
24486 /**
24487 * Sets the background color for this view.
24488 * @param color the color of the background
24489 */
24490 @RemotableViewMethod
24491 public void setBackgroundColor(@ColorInt int color) {
24492 if (mBackground instanceof ColorDrawable) {
24493 ((ColorDrawable) mBackground.mutate()).setColor(color);
24494 computeOpaqueFlags();
24495 mBackgroundResource = 0;
24496 } else {
24497 setBackground(new ColorDrawable(color));
24498 }
24499 }
24500
24501 /**
24502 * Set the background to a given resource. The resource should refer to
24503 * a Drawable object or 0 to remove the background.
24504 * @param resid The identifier of the resource.
24505 *
24506 * @attr ref android.R.styleable#View_background
24507 */
24508 @RemotableViewMethod
24509 public void setBackgroundResource(@DrawableRes int resid) {
24510 if (resid != 0 && resid == mBackgroundResource) {
24511 return;
24512 }
24513
24514 Drawable d = null;
24515 if (resid != 0) {
24516 d = mContext.getDrawable(resid);
24517 }
24518 setBackground(d);
24519
24520 mBackgroundResource = resid;
24521 }
24522
24523 /**
24524 * Set the background to a given Drawable, or remove the background. If the
24525 * background has padding, this View's padding is set to the background's
24526 * padding. However, when a background is removed, this View's padding isn't
24527 * touched. If setting the padding is desired, please use
24528 * {@link #setPadding(int, int, int, int)}.
24529 *
24530 * @param background The Drawable to use as the background, or null to remove the
24531 * background
24532 */
24533 public void setBackground(Drawable background) {
24534 //noinspection deprecation
24535 setBackgroundDrawable(background);
24536 }
24537
24538 /**
24539 * @deprecated use {@link #setBackground(Drawable)} instead
24540 */
24541 @Deprecated
24542 public void setBackgroundDrawable(Drawable background) {
24543 computeOpaqueFlags();
24544
24545 if (background == mBackground) {
24546 return;
24547 }
24548
24549 boolean requestLayout = false;
24550
24551 mBackgroundResource = 0;
24552
24553 /*
24554 * Regardless of whether we're setting a new background or not, we want
24555 * to clear the previous drawable. setVisible first while we still have the callback set.
24556 */
24557 if (mBackground != null) {
24558 if (isAttachedToWindow()) {
24559 mBackground.setVisible(false, false);
24560 }
24561 mBackground.setCallback(null);
24562 unscheduleDrawable(mBackground);
24563 }
24564
24565 if (background != null) {
24566 Rect padding = sThreadLocal.get();
24567 if (padding == null) {
24568 padding = new Rect();
24569 sThreadLocal.set(padding);
24570 }
24571 resetResolvedDrawablesInternal();
24572 background.setLayoutDirection(getLayoutDirection());
24573 if (background.getPadding(padding)) {
24574 resetResolvedPaddingInternal();
24575 switch (background.getLayoutDirection()) {
24576 case LAYOUT_DIRECTION_RTL:
24577 mUserPaddingLeftInitial = padding.right;
24578 mUserPaddingRightInitial = padding.left;
24579 internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
24580 break;
24581 case LAYOUT_DIRECTION_LTR:
24582 default:
24583 mUserPaddingLeftInitial = padding.left;
24584 mUserPaddingRightInitial = padding.right;
24585 internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
24586 }
24587 mLeftPaddingDefined = false;
24588 mRightPaddingDefined = false;
24589 }
24590
24591 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or
24592 // if it has a different minimum size, we should layout again
24593 if (mBackground == null
24594 || mBackground.getMinimumHeight() != background.getMinimumHeight()
24595 || mBackground.getMinimumWidth() != background.getMinimumWidth()) {
24596 requestLayout = true;
24597 }
24598
24599 // Set mBackground before we set this as the callback and start making other
24600 // background drawable state change calls. In particular, the setVisible call below
24601 // can result in drawables attempting to start animations or otherwise invalidate,
24602 // which requires the view set as the callback (us) to recognize the drawable as
24603 // belonging to it as per verifyDrawable.
24604 mBackground = background;
24605 if (background.isStateful()) {
24606 background.setState(getDrawableState());
24607 }
24608 if (isAttachedToWindow()) {
24609 background.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
24610 }
24611
24612 applyBackgroundTint();
24613
24614 // Set callback last, since the view may still be initializing.
24615 background.setCallback(this);
24616
24617 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
24618 mPrivateFlags &= ~PFLAG_SKIP_DRAW;
24619 requestLayout = true;
24620 }
24621 } else {
24622 /* Remove the background */
24623 mBackground = null;
24624 if ((mViewFlags & WILL_NOT_DRAW) != 0
24625 && (mDefaultFocusHighlight == null)
24626 && (mForegroundInfo == null || mForegroundInfo.mDrawable == null)) {
24627 mPrivateFlags |= PFLAG_SKIP_DRAW;
24628 }
24629
24630 /*
24631 * When the background is set, we try to apply its padding to this
24632 * View. When the background is removed, we don't touch this View's
24633 * padding. This is noted in the Javadocs. Hence, we don't need to
24634 * requestLayout(), the invalidate() below is sufficient.
24635 */
24636
24637 // The old background's minimum size could have affected this
24638 // View's layout, so let's requestLayout
24639 requestLayout = true;
24640 }
24641
24642 computeOpaqueFlags();
24643
24644 if (requestLayout) {
24645 requestLayout();
24646 }
24647
24648 mBackgroundSizeChanged = true;
24649 invalidate(true);
24650 invalidateOutline();
24651 }
24652
24653 /**
24654 * Gets the background drawable
24655 *
24656 * @return The drawable used as the background for this view, if any.
24657 *
24658 * @see #setBackground(Drawable)
24659 *
24660 * @attr ref android.R.styleable#View_background
24661 */
24662 @InspectableProperty
24663 public Drawable getBackground() {
24664 return mBackground;
24665 }
24666
24667 /**
24668 * Applies a tint to the background drawable. Does not modify the current tint
24669 * mode, which is {@link BlendMode#SRC_IN} by default.
24670 * <p>
24671 * Subsequent calls to {@link #setBackground(Drawable)} will automatically
24672 * mutate the drawable and apply the specified tint and tint mode using
24673 * {@link Drawable#setTintList(ColorStateList)}.
24674 *
24675 * @param tint the tint to apply, may be {@code null} to clear tint
24676 *
24677 * @attr ref android.R.styleable#View_backgroundTint
24678 * @see #getBackgroundTintList()
24679 * @see Drawable#setTintList(ColorStateList)
24680 */
24681 @RemotableViewMethod
24682 public void setBackgroundTintList(@Nullable ColorStateList tint) {
24683 if (mBackgroundTint == null) {
24684 mBackgroundTint = new TintInfo();
24685 }
24686 mBackgroundTint.mTintList = tint;
24687 mBackgroundTint.mHasTintList = true;
24688
24689 applyBackgroundTint();
24690 }
24691
24692 /**
24693 * Return the tint applied to the background drawable, if specified.
24694 *
24695 * @return the tint applied to the background drawable
24696 * @attr ref android.R.styleable#View_backgroundTint
24697 * @see #setBackgroundTintList(ColorStateList)
24698 */
24699 @InspectableProperty(name = "backgroundTint")
24700 @Nullable
24701 public ColorStateList getBackgroundTintList() {
24702 return mBackgroundTint != null ? mBackgroundTint.mTintList : null;
24703 }
24704
24705 /**
24706 * Specifies the blending mode used to apply the tint specified by
24707 * {@link #setBackgroundTintList(ColorStateList)}} to the background
24708 * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
24709 *
24710 * @param tintMode the blending mode used to apply the tint, may be
24711 * {@code null} to clear tint
24712 * @attr ref android.R.styleable#View_backgroundTintMode
24713 * @see #getBackgroundTintMode()
24714 * @see Drawable#setTintMode(PorterDuff.Mode)
24715 */
24716 public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) {
24717 BlendMode mode = null;
24718 if (tintMode != null) {
24719 mode = BlendMode.fromValue(tintMode.nativeInt);
24720 }
24721
24722 setBackgroundTintBlendMode(mode);
24723 }
24724
24725 /**
24726 * Specifies the blending mode used to apply the tint specified by
24727 * {@link #setBackgroundTintList(ColorStateList)}} to the background
24728 * drawable. The default mode is {@link BlendMode#SRC_IN}.
24729 *
24730 * @param blendMode the blending mode used to apply the tint, may be
24731 * {@code null} to clear tint
24732 * @attr ref android.R.styleable#View_backgroundTintMode
24733 * @see #getBackgroundTintMode()
24734 * @see Drawable#setTintBlendMode(BlendMode)
24735 */
24736 @RemotableViewMethod
24737 public void setBackgroundTintBlendMode(@Nullable BlendMode blendMode) {
24738 if (mBackgroundTint == null) {
24739 mBackgroundTint = new TintInfo();
24740 }
24741
24742 mBackgroundTint.mBlendMode = blendMode;
24743 mBackgroundTint.mHasTintMode = true;
24744
24745 applyBackgroundTint();
24746 }
24747
24748 /**
24749 * Return the blending mode used to apply the tint to the background
24750 * drawable, if specified.
24751 *
24752 * @return the blending mode used to apply the tint to the background
24753 * drawable
24754 * @attr ref android.R.styleable#View_backgroundTintMode
24755 * @see #setBackgroundTintBlendMode(BlendMode)
24756 *
24757 */
24758 @Nullable
24759 @InspectableProperty
24760 public PorterDuff.Mode getBackgroundTintMode() {
24761 PorterDuff.Mode porterDuffMode;
24762 if (mBackgroundTint != null && mBackgroundTint.mBlendMode != null) {
24763 porterDuffMode = BlendMode.blendModeToPorterDuffMode(mBackgroundTint.mBlendMode);
24764 } else {
24765 porterDuffMode = null;
24766 }
24767 return porterDuffMode;
24768 }
24769
24770 /**
24771 * Return the blending mode used to apply the tint to the background
24772 * drawable, if specified.
24773 *
24774 * @return the blending mode used to apply the tint to the background
24775 * drawable, null if no blend has previously been configured
24776 * @attr ref android.R.styleable#View_backgroundTintMode
24777 * @see #setBackgroundTintBlendMode(BlendMode)
24778 */
24779 public @Nullable BlendMode getBackgroundTintBlendMode() {
24780 return mBackgroundTint != null ? mBackgroundTint.mBlendMode : null;
24781 }
24782
24783 private void applyBackgroundTint() {
24784 if (mBackground != null && mBackgroundTint != null) {
24785 final TintInfo tintInfo = mBackgroundTint;
24786 if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
24787 mBackground = mBackground.mutate();
24788
24789 if (tintInfo.mHasTintList) {
24790 mBackground.setTintList(tintInfo.mTintList);
24791 }
24792
24793 if (tintInfo.mHasTintMode) {
24794 mBackground.setTintBlendMode(tintInfo.mBlendMode);
24795 }
24796
24797 // The drawable (or one of its children) may not have been
24798 // stateful before applying the tint, so let's try again.
24799 if (mBackground.isStateful()) {
24800 mBackground.setState(getDrawableState());
24801 }
24802 }
24803 }
24804 }
24805
24806 /**
24807 * Returns the drawable used as the foreground of this View. The
24808 * foreground drawable, if non-null, is always drawn on top of the view's content.
24809 *
24810 * @return a Drawable or null if no foreground was set
24811 *
24812 * @see #onDrawForeground(Canvas)
24813 */
24814 @InspectableProperty
24815 public Drawable getForeground() {
24816 return mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
24817 }
24818
24819 /**
24820 * Supply a Drawable that is to be rendered on top of all of the content in the view.
24821 *
24822 * @param foreground the Drawable to be drawn on top of the children
24823 *
24824 * @attr ref android.R.styleable#View_foreground
24825 */
24826 public void setForeground(Drawable foreground) {
24827 if (mForegroundInfo == null) {
24828 if (foreground == null) {
24829 // Nothing to do.
24830 return;
24831 }
24832 mForegroundInfo = new ForegroundInfo();
24833 }
24834
24835 if (foreground == mForegroundInfo.mDrawable) {
24836 // Nothing to do
24837 return;
24838 }
24839
24840 if (mForegroundInfo.mDrawable != null) {
24841 if (isAttachedToWindow()) {
24842 mForegroundInfo.mDrawable.setVisible(false, false);
24843 }
24844 mForegroundInfo.mDrawable.setCallback(null);
24845 unscheduleDrawable(mForegroundInfo.mDrawable);
24846 }
24847
24848 mForegroundInfo.mDrawable = foreground;
24849 mForegroundInfo.mBoundsChanged = true;
24850 if (foreground != null) {
24851 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
24852 mPrivateFlags &= ~PFLAG_SKIP_DRAW;
24853 }
24854 foreground.setLayoutDirection(getLayoutDirection());
24855 if (foreground.isStateful()) {
24856 foreground.setState(getDrawableState());
24857 }
24858 applyForegroundTint();
24859 if (isAttachedToWindow()) {
24860 foreground.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
24861 }
24862 // Set callback last, since the view may still be initializing.
24863 foreground.setCallback(this);
24864 } else if ((mViewFlags & WILL_NOT_DRAW) != 0 && mBackground == null
24865 && (mDefaultFocusHighlight == null)) {
24866 mPrivateFlags |= PFLAG_SKIP_DRAW;
24867 }
24868 requestLayout();
24869 invalidate();
24870 }
24871
24872 /**
24873 * Magic bit used to support features of framework-internal window decor implementation details.
24874 * This used to live exclusively in FrameLayout.
24875 *
24876 * @return true if the foreground should draw inside the padding region or false
24877 * if it should draw inset by the view's padding
24878 * @hide internal use only; only used by FrameLayout and internal screen layouts.
24879 */
24880 public boolean isForegroundInsidePadding() {
24881 return mForegroundInfo != null ? mForegroundInfo.mInsidePadding : true;
24882 }
24883
24884 /**
24885 * Describes how the foreground is positioned.
24886 *
24887 * @return foreground gravity.
24888 *
24889 * @see #setForegroundGravity(int)
24890 *
24891 * @attr ref android.R.styleable#View_foregroundGravity
24892 */
24893 @InspectableProperty(valueType = InspectableProperty.ValueType.GRAVITY)
24894 public int getForegroundGravity() {
24895 return mForegroundInfo != null ? mForegroundInfo.mGravity
24896 : Gravity.START | Gravity.TOP;
24897 }
24898
24899 /**
24900 * Describes how the foreground is positioned. Defaults to START and TOP.
24901 *
24902 * @param gravity see {@link android.view.Gravity}
24903 *
24904 * @see #getForegroundGravity()
24905 *
24906 * @attr ref android.R.styleable#View_foregroundGravity
24907 */
24908 public void setForegroundGravity(int gravity) {
24909 if (mForegroundInfo == null) {
24910 mForegroundInfo = new ForegroundInfo();
24911 }
24912
24913 if (mForegroundInfo.mGravity != gravity) {
24914 if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) {
24915 gravity |= Gravity.START;
24916 }
24917
24918 if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) {
24919 gravity |= Gravity.TOP;
24920 }
24921
24922 mForegroundInfo.mGravity = gravity;
24923 requestLayout();
24924 }
24925 }
24926
24927 /**
24928 * Applies a tint to the foreground drawable. Does not modify the current tint
24929 * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
24930 * <p>
24931 * Subsequent calls to {@link #setForeground(Drawable)} will automatically
24932 * mutate the drawable and apply the specified tint and tint mode using
24933 * {@link Drawable#setTintList(ColorStateList)}.
24934 *
24935 * @param tint the tint to apply, may be {@code null} to clear tint
24936 *
24937 * @attr ref android.R.styleable#View_foregroundTint
24938 * @see #getForegroundTintList()
24939 * @see Drawable#setTintList(ColorStateList)
24940 */
24941 @RemotableViewMethod
24942 public void setForegroundTintList(@Nullable ColorStateList tint) {
24943 if (mForegroundInfo == null) {
24944 mForegroundInfo = new ForegroundInfo();
24945 }
24946 if (mForegroundInfo.mTintInfo == null) {
24947 mForegroundInfo.mTintInfo = new TintInfo();
24948 }
24949 mForegroundInfo.mTintInfo.mTintList = tint;
24950 mForegroundInfo.mTintInfo.mHasTintList = true;
24951
24952 applyForegroundTint();
24953 }
24954
24955 /**
24956 * Return the tint applied to the foreground drawable, if specified.
24957 *
24958 * @return the tint applied to the foreground drawable
24959 * @attr ref android.R.styleable#View_foregroundTint
24960 * @see #setForegroundTintList(ColorStateList)
24961 */
24962 @InspectableProperty(name = "foregroundTint")
24963 @Nullable
24964 public ColorStateList getForegroundTintList() {
24965 return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
24966 ? mForegroundInfo.mTintInfo.mTintList : null;
24967 }
24968
24969 /**
24970 * Specifies the blending mode used to apply the tint specified by
24971 * {@link #setForegroundTintList(ColorStateList)}} to the background
24972 * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
24973 *
24974 * @param tintMode the blending mode used to apply the tint, may be
24975 * {@code null} to clear tint
24976 * @attr ref android.R.styleable#View_foregroundTintMode
24977 * @see #getForegroundTintMode()
24978 * @see Drawable#setTintMode(PorterDuff.Mode)
24979 *
24980 */
24981 public void setForegroundTintMode(@Nullable PorterDuff.Mode tintMode) {
24982 BlendMode mode = null;
24983 if (tintMode != null) {
24984 mode = BlendMode.fromValue(tintMode.nativeInt);
24985 }
24986 setForegroundTintBlendMode(mode);
24987 }
24988
24989 /**
24990 * Specifies the blending mode used to apply the tint specified by
24991 * {@link #setForegroundTintList(ColorStateList)}} to the background
24992 * drawable. The default mode is {@link BlendMode#SRC_IN}.
24993 *
24994 * @param blendMode the blending mode used to apply the tint, may be
24995 * {@code null} to clear tint
24996 * @attr ref android.R.styleable#View_foregroundTintMode
24997 * @see #getForegroundTintMode()
24998 * @see Drawable#setTintBlendMode(BlendMode)
24999 */
25000 @RemotableViewMethod
25001 public void setForegroundTintBlendMode(@Nullable BlendMode blendMode) {
25002 if (mForegroundInfo == null) {
25003 mForegroundInfo = new ForegroundInfo();
25004 }
25005 if (mForegroundInfo.mTintInfo == null) {
25006 mForegroundInfo.mTintInfo = new TintInfo();
25007 }
25008 mForegroundInfo.mTintInfo.mBlendMode = blendMode;
25009 mForegroundInfo.mTintInfo.mHasTintMode = true;
25010
25011 applyForegroundTint();
25012 }
25013
25014 /**
25015 * Return the blending mode used to apply the tint to the foreground
25016 * drawable, if specified.
25017 *
25018 * @return the blending mode used to apply the tint to the foreground
25019 * drawable
25020 * @attr ref android.R.styleable#View_foregroundTintMode
25021 * @see #setForegroundTintMode(PorterDuff.Mode)
25022 */
25023 @InspectableProperty
25024 @Nullable
25025 public PorterDuff.Mode getForegroundTintMode() {
25026 BlendMode blendMode = mForegroundInfo != null && mForegroundInfo.mTintInfo != null
25027 ? mForegroundInfo.mTintInfo.mBlendMode : null;
25028 if (blendMode != null) {
25029 return BlendMode.blendModeToPorterDuffMode(blendMode);
25030 } else {
25031 return null;
25032 }
25033 }
25034
25035 /**
25036 * Return the blending mode used to apply the tint to the foreground
25037 * drawable, if specified.
25038 *
25039 * @return the blending mode used to apply the tint to the foreground
25040 * drawable
25041 * @attr ref android.R.styleable#View_foregroundTintMode
25042 * @see #setForegroundTintBlendMode(BlendMode)
25043 *
25044 */
25045 public @Nullable BlendMode getForegroundTintBlendMode() {
25046 return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
25047 ? mForegroundInfo.mTintInfo.mBlendMode : null;
25048 }
25049
25050 private void applyForegroundTint() {
25051 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
25052 && mForegroundInfo.mTintInfo != null) {
25053 final TintInfo tintInfo = mForegroundInfo.mTintInfo;
25054 if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
25055 mForegroundInfo.mDrawable = mForegroundInfo.mDrawable.mutate();
25056
25057 if (tintInfo.mHasTintList) {
25058 mForegroundInfo.mDrawable.setTintList(tintInfo.mTintList);
25059 }
25060
25061 if (tintInfo.mHasTintMode) {
25062 mForegroundInfo.mDrawable.setTintBlendMode(tintInfo.mBlendMode);
25063 }
25064
25065 // The drawable (or one of its children) may not have been
25066 // stateful before applying the tint, so let's try again.
25067 if (mForegroundInfo.mDrawable.isStateful()) {
25068 mForegroundInfo.mDrawable.setState(getDrawableState());
25069 }
25070 }
25071 }
25072 }
25073
25074 /**
25075 * Get the drawable to be overlayed when a view is autofilled
25076 *
25077 * @return The drawable
25078 *
25079 * @throws IllegalStateException if the drawable could not be found.
25080 */
25081 @Nullable private Drawable getAutofilledDrawable() {
25082 if (mAttachInfo == null) {
25083 return null;
25084 }
25085 // Lazily load the isAutofilled drawable.
25086 if (mAttachInfo.mAutofilledDrawable == null) {
25087 Context rootContext = getRootView().getContext();
25088 TypedArray a = rootContext.getTheme().obtainStyledAttributes(AUTOFILL_HIGHLIGHT_ATTR);
25089 int attributeResourceId = a.getResourceId(0, 0);
25090 mAttachInfo.mAutofilledDrawable = rootContext.getDrawable(attributeResourceId);
25091 a.recycle();
25092 }
25093
25094 return mAttachInfo.mAutofilledDrawable;
25095 }
25096
25097 /**
25098 * Draw {@link View#isAutofilled()} highlight over view if the view is autofilled, unless
25099 * {@link #PFLAG4_AUTOFILL_HIDE_HIGHLIGHT} is enabled.
25100 *
25101 * @param canvas The canvas to draw on
25102 */
25103 private void drawAutofilledHighlight(@NonNull Canvas canvas) {
25104 if (isAutofilled() && !hideAutofillHighlight()) {
25105 Drawable autofilledHighlight = getAutofilledDrawable();
25106
25107 if (autofilledHighlight != null) {
25108 autofilledHighlight.setBounds(0, 0, getWidth(), getHeight());
25109 autofilledHighlight.draw(canvas);
25110 }
25111 }
25112 }
25113
25114 /**
25115 * Draw any foreground content for this view.
25116 *
25117 * <p>Foreground content may consist of scroll bars, a {@link #setForeground foreground}
25118 * drawable or other view-specific decorations. The foreground is drawn on top of the
25119 * primary view content.</p>
25120 *
25121 * @param canvas canvas to draw into
25122 */
25123 public void onDrawForeground(Canvas canvas) {
25124 onDrawScrollIndicators(canvas);
25125 onDrawScrollBars(canvas);
25126
25127 final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
25128 if (foreground != null) {
25129 if (mForegroundInfo.mBoundsChanged) {
25130 mForegroundInfo.mBoundsChanged = false;
25131 final Rect selfBounds = mForegroundInfo.mSelfBounds;
25132 final Rect overlayBounds = mForegroundInfo.mOverlayBounds;
25133
25134 if (mForegroundInfo.mInsidePadding) {
25135 selfBounds.set(0, 0, getWidth(), getHeight());
25136 } else {
25137 selfBounds.set(getPaddingLeft(), getPaddingTop(),
25138 getWidth() - getPaddingRight(), getHeight() - getPaddingBottom());
25139 }
25140
25141 final int ld = getLayoutDirection();
25142 Gravity.apply(mForegroundInfo.mGravity, foreground.getIntrinsicWidth(),
25143 foreground.getIntrinsicHeight(), selfBounds, overlayBounds, ld);
25144 foreground.setBounds(overlayBounds);
25145 }
25146
25147 foreground.draw(canvas);
25148 }
25149 }
25150
25151 /**
25152 * Sets the padding. The view may add on the space required to display
25153 * the scrollbars, depending on the style and visibility of the scrollbars.
25154 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
25155 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
25156 * from the values set in this call.
25157 *
25158 * @attr ref android.R.styleable#View_padding
25159 * @attr ref android.R.styleable#View_paddingBottom
25160 * @attr ref android.R.styleable#View_paddingLeft
25161 * @attr ref android.R.styleable#View_paddingRight
25162 * @attr ref android.R.styleable#View_paddingTop
25163 * @param left the left padding in pixels
25164 * @param top the top padding in pixels
25165 * @param right the right padding in pixels
25166 * @param bottom the bottom padding in pixels
25167 */
25168 public void setPadding(int left, int top, int right, int bottom) {
25169 resetResolvedPaddingInternal();
25170
25171 mUserPaddingStart = UNDEFINED_PADDING;
25172 mUserPaddingEnd = UNDEFINED_PADDING;
25173
25174 mUserPaddingLeftInitial = left;
25175 mUserPaddingRightInitial = right;
25176
25177 mLeftPaddingDefined = true;
25178 mRightPaddingDefined = true;
25179
25180 internalSetPadding(left, top, right, bottom);
25181 }
25182
25183 /**
25184 * @hide
25185 */
25186 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 123768420)
25187 protected void internalSetPadding(int left, int top, int right, int bottom) {
25188 mUserPaddingLeft = left;
25189 mUserPaddingRight = right;
25190 mUserPaddingBottom = bottom;
25191
25192 final int viewFlags = mViewFlags;
25193 boolean changed = false;
25194
25195 // Common case is there are no scroll bars.
25196 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
25197 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
25198 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
25199 ? 0 : getVerticalScrollbarWidth();
25200 switch (mVerticalScrollbarPosition) {
25201 case SCROLLBAR_POSITION_DEFAULT:
25202 if (isLayoutRtl()) {
25203 left += offset;
25204 } else {
25205 right += offset;
25206 }
25207 break;
25208 case SCROLLBAR_POSITION_RIGHT:
25209 right += offset;
25210 break;
25211 case SCROLLBAR_POSITION_LEFT:
25212 left += offset;
25213 break;
25214 }
25215 }
25216 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
25217 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
25218 ? 0 : getHorizontalScrollbarHeight();
25219 }
25220 }
25221
25222 if (mPaddingLeft != left) {
25223 changed = true;
25224 mPaddingLeft = left;
25225 }
25226 if (mPaddingTop != top) {
25227 changed = true;
25228 mPaddingTop = top;
25229 }
25230 if (mPaddingRight != right) {
25231 changed = true;
25232 mPaddingRight = right;
25233 }
25234 if (mPaddingBottom != bottom) {
25235 changed = true;
25236 mPaddingBottom = bottom;
25237 }
25238
25239 if (changed) {
25240 requestLayout();
25241 invalidateOutline();
25242 }
25243 }
25244
25245 /**
25246 * Sets the relative padding. The view may add on the space required to display
25247 * the scrollbars, depending on the style and visibility of the scrollbars.
25248 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
25249 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
25250 * from the values set in this call.
25251 *
25252 * @attr ref android.R.styleable#View_padding
25253 * @attr ref android.R.styleable#View_paddingBottom
25254 * @attr ref android.R.styleable#View_paddingStart
25255 * @attr ref android.R.styleable#View_paddingEnd
25256 * @attr ref android.R.styleable#View_paddingTop
25257 * @param start the start padding in pixels
25258 * @param top the top padding in pixels
25259 * @param end the end padding in pixels
25260 * @param bottom the bottom padding in pixels
25261 */
25262 public void setPaddingRelative(int start, int top, int end, int bottom) {
25263 resetResolvedPaddingInternal();
25264
25265 mUserPaddingStart = start;
25266 mUserPaddingEnd = end;
25267 mLeftPaddingDefined = true;
25268 mRightPaddingDefined = true;
25269
25270 switch(getLayoutDirection()) {
25271 case LAYOUT_DIRECTION_RTL:
25272 mUserPaddingLeftInitial = end;
25273 mUserPaddingRightInitial = start;
25274 internalSetPadding(end, top, start, bottom);
25275 break;
25276 case LAYOUT_DIRECTION_LTR:
25277 default:
25278 mUserPaddingLeftInitial = start;
25279 mUserPaddingRightInitial = end;
25280 internalSetPadding(start, top, end, bottom);
25281 }
25282 }
25283
25284 /**
25285 * A {@link View} can be inflated from an XML layout. For such Views this method returns the
25286 * resource ID of the source layout.
25287 *
25288 * @return The layout resource id if this view was inflated from XML, otherwise
25289 * {@link Resources#ID_NULL}.
25290 */
25291 @LayoutRes
25292 public int getSourceLayoutResId() {
25293 return mSourceLayoutId;
25294 }
25295
25296 /**
25297 * Returns the top padding of this view.
25298 *
25299 * @return the top padding in pixels
25300 */
25301 @InspectableProperty
25302 public int getPaddingTop() {
25303 return mPaddingTop;
25304 }
25305
25306 /**
25307 * Returns the bottom padding of this view. If there are inset and enabled
25308 * scrollbars, this value may include the space required to display the
25309 * scrollbars as well.
25310 *
25311 * @return the bottom padding in pixels
25312 */
25313 @InspectableProperty
25314 public int getPaddingBottom() {
25315 return mPaddingBottom;
25316 }
25317
25318 /**
25319 * Returns the left padding of this view. If there are inset and enabled
25320 * scrollbars, this value may include the space required to display the
25321 * scrollbars as well.
25322 *
25323 * @return the left padding in pixels
25324 */
25325 @InspectableProperty
25326 public int getPaddingLeft() {
25327 if (!isPaddingResolved()) {
25328 resolvePadding();
25329 }
25330 return mPaddingLeft;
25331 }
25332
25333 /**
25334 * Returns the start padding of this view depending on its resolved layout direction.
25335 * If there are inset and enabled scrollbars, this value may include the space
25336 * required to display the scrollbars as well.
25337 *
25338 * @return the start padding in pixels
25339 */
25340 public int getPaddingStart() {
25341 if (!isPaddingResolved()) {
25342 resolvePadding();
25343 }
25344 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
25345 mPaddingRight : mPaddingLeft;
25346 }
25347
25348 /**
25349 * Returns the right padding of this view. If there are inset and enabled
25350 * scrollbars, this value may include the space required to display the
25351 * scrollbars as well.
25352 *
25353 * @return the right padding in pixels
25354 */
25355 @InspectableProperty
25356 public int getPaddingRight() {
25357 if (!isPaddingResolved()) {
25358 resolvePadding();
25359 }
25360 return mPaddingRight;
25361 }
25362
25363 /**
25364 * Returns the end padding of this view depending on its resolved layout direction.
25365 * If there are inset and enabled scrollbars, this value may include the space
25366 * required to display the scrollbars as well.
25367 *
25368 * @return the end padding in pixels
25369 */
25370 public int getPaddingEnd() {
25371 if (!isPaddingResolved()) {
25372 resolvePadding();
25373 }
25374 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
25375 mPaddingLeft : mPaddingRight;
25376 }
25377
25378 /**
25379 * Return if the padding has been set through relative values
25380 * {@link #setPaddingRelative(int, int, int, int)} or through
25381 * @attr ref android.R.styleable#View_paddingStart or
25382 * @attr ref android.R.styleable#View_paddingEnd
25383 *
25384 * @return true if the padding is relative or false if it is not.
25385 */
25386 public boolean isPaddingRelative() {
25387 return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
25388 }
25389
25390 Insets computeOpticalInsets() {
25391 return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
25392 }
25393
25394 /**
25395 * @hide
25396 */
25397 @UnsupportedAppUsage
25398 public void resetPaddingToInitialValues() {
25399 if (isRtlCompatibilityMode()) {
25400 mPaddingLeft = mUserPaddingLeftInitial;
25401 mPaddingRight = mUserPaddingRightInitial;
25402 return;
25403 }
25404 if (isLayoutRtl()) {
25405 mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
25406 mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
25407 } else {
25408 mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
25409 mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
25410 }
25411 }
25412
25413 /**
25414 * @hide
25415 */
25416 public Insets getOpticalInsets() {
25417 if (mLayoutInsets == null) {
25418 mLayoutInsets = computeOpticalInsets();
25419 }
25420 return mLayoutInsets;
25421 }
25422
25423 /**
25424 * Set this view's optical insets.
25425 *
25426 * <p>This method should be treated similarly to setMeasuredDimension and not as a general
25427 * property. Views that compute their own optical insets should call it as part of measurement.
25428 * This method does not request layout. If you are setting optical insets outside of
25429 * measure/layout itself you will want to call requestLayout() yourself.
25430 * </p>
25431 * @hide
25432 */
25433 public void setOpticalInsets(Insets insets) {
25434 mLayoutInsets = insets;
25435 }
25436
25437 /**
25438 * Changes the selection state of this view. A view can be selected or not.
25439 * Note that selection is not the same as focus. Views are typically
25440 * selected in the context of an AdapterView like ListView or GridView;
25441 * the selected view is the view that is highlighted.
25442 *
25443 * @param selected true if the view must be selected, false otherwise
25444 */
25445 public void setSelected(boolean selected) {
25446 //noinspection DoubleNegation
25447 if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
25448 mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
25449 if (!selected) resetPressedState();
25450 invalidate(true);
25451 refreshDrawableState();
25452 dispatchSetSelected(selected);
25453 if (selected) {
25454 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
25455 } else {
25456 notifyViewAccessibilityStateChangedIfNeeded(
25457 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
25458 }
25459 }
25460 }
25461
25462 /**
25463 * Dispatch setSelected to all of this View's children.
25464 *
25465 * @see #setSelected(boolean)
25466 *
25467 * @param selected The new selected state
25468 */
25469 protected void dispatchSetSelected(boolean selected) {
25470 }
25471
25472 /**
25473 * Indicates the selection state of this view.
25474 *
25475 * @return true if the view is selected, false otherwise
25476 */
25477 @ViewDebug.ExportedProperty
25478 @InspectableProperty(hasAttributeId = false)
25479 public boolean isSelected() {
25480 return (mPrivateFlags & PFLAG_SELECTED) != 0;
25481 }
25482
25483 /**
25484 * Changes the activated state of this view. A view can be activated or not.
25485 * Note that activation is not the same as selection. Selection is
25486 * a transient property, representing the view (hierarchy) the user is
25487 * currently interacting with. Activation is a longer-term state that the
25488 * user can move views in and out of. For example, in a list view with
25489 * single or multiple selection enabled, the views in the current selection
25490 * set are activated. (Um, yeah, we are deeply sorry about the terminology
25491 * here.) The activated state is propagated down to children of the view it
25492 * is set on.
25493 *
25494 * @param activated true if the view must be activated, false otherwise
25495 */
25496 public void setActivated(boolean activated) {
25497 //noinspection DoubleNegation
25498 if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
25499 mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
25500 invalidate(true);
25501 refreshDrawableState();
25502 dispatchSetActivated(activated);
25503 }
25504 }
25505
25506 /**
25507 * Dispatch setActivated to all of this View's children.
25508 *
25509 * @see #setActivated(boolean)
25510 *
25511 * @param activated The new activated state
25512 */
25513 protected void dispatchSetActivated(boolean activated) {
25514 }
25515
25516 /**
25517 * Indicates the activation state of this view.
25518 *
25519 * @return true if the view is activated, false otherwise
25520 */
25521 @ViewDebug.ExportedProperty
25522 @InspectableProperty(hasAttributeId = false)
25523 public boolean isActivated() {
25524 return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
25525 }
25526
25527 /**
25528 * Returns the ViewTreeObserver for this view's hierarchy. The view tree
25529 * observer can be used to get notifications when global events, like
25530 * layout, happen.
25531 *
25532 * The returned ViewTreeObserver observer is not guaranteed to remain
25533 * valid for the lifetime of this View. If the caller of this method keeps
25534 * a long-lived reference to ViewTreeObserver, it should always check for
25535 * the return value of {@link ViewTreeObserver#isAlive()}.
25536 *
25537 * @return The ViewTreeObserver for this view's hierarchy.
25538 */
25539 public ViewTreeObserver getViewTreeObserver() {
25540 if (mAttachInfo != null) {
25541 return mAttachInfo.mTreeObserver;
25542 }
25543 if (mFloatingTreeObserver == null) {
25544 mFloatingTreeObserver = new ViewTreeObserver(mContext);
25545 }
25546 return mFloatingTreeObserver;
25547 }
25548
25549 /**
25550 * <p>Finds the topmost view in the current view hierarchy.</p>
25551 *
25552 * @return the topmost view containing this view
25553 */
25554 public View getRootView() {
25555 if (mAttachInfo != null) {
25556 final View v = mAttachInfo.mRootView;
25557 if (v != null) {
25558 return v;
25559 }
25560 }
25561
25562 View parent = this;
25563
25564 while (parent.mParent instanceof View) {
25565 parent = (View) parent.mParent;
25566 }
25567
25568 return parent;
25569 }
25570
25571 /**
25572 * Transforms a motion event from view-local coordinates to on-screen
25573 * coordinates.
25574 *
25575 * @param ev the view-local motion event
25576 * @return false if the transformation could not be applied
25577 * @hide
25578 */
25579 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
25580 public boolean toGlobalMotionEvent(MotionEvent ev) {
25581 final AttachInfo info = mAttachInfo;
25582 if (info == null) {
25583 return false;
25584 }
25585
25586 final Matrix m = info.mTmpMatrix;
25587 m.set(Matrix.IDENTITY_MATRIX);
25588 transformMatrixToGlobal(m);
25589 ev.transform(m);
25590 return true;
25591 }
25592
25593 /**
25594 * Transforms a motion event from on-screen coordinates to view-local
25595 * coordinates.
25596 *
25597 * @param ev the on-screen motion event
25598 * @return false if the transformation could not be applied
25599 * @hide
25600 */
25601 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
25602 public boolean toLocalMotionEvent(MotionEvent ev) {
25603 final AttachInfo info = mAttachInfo;
25604 if (info == null) {
25605 return false;
25606 }
25607
25608 final Matrix m = info.mTmpMatrix;
25609 m.set(Matrix.IDENTITY_MATRIX);
25610 transformMatrixToLocal(m);
25611 ev.transform(m);
25612 return true;
25613 }
25614
25615 /**
25616 * Modifies the input matrix such that it maps view-local coordinates to
25617 * on-screen coordinates.
25618 *
25619 * @param matrix input matrix to modify
25620 */
25621 public void transformMatrixToGlobal(@NonNull Matrix matrix) {
25622 final ViewParent parent = mParent;
25623 if (parent instanceof View) {
25624 final View vp = (View) parent;
25625 vp.transformMatrixToGlobal(matrix);
25626 matrix.preTranslate(-vp.mScrollX, -vp.mScrollY);
25627 } else if (parent instanceof ViewRootImpl) {
25628 final ViewRootImpl vr = (ViewRootImpl) parent;
25629 vr.transformMatrixToGlobal(matrix);
25630 matrix.preTranslate(0, -vr.mCurScrollY);
25631 }
25632
25633 matrix.preTranslate(mLeft, mTop);
25634
25635 if (!hasIdentityMatrix()) {
25636 matrix.preConcat(getMatrix());
25637 }
25638 }
25639
25640 /**
25641 * Modifies the input matrix such that it maps on-screen coordinates to
25642 * view-local coordinates.
25643 *
25644 * @param matrix input matrix to modify
25645 */
25646 public void transformMatrixToLocal(@NonNull Matrix matrix) {
25647 final ViewParent parent = mParent;
25648 if (parent instanceof View) {
25649 final View vp = (View) parent;
25650 vp.transformMatrixToLocal(matrix);
25651 matrix.postTranslate(vp.mScrollX, vp.mScrollY);
25652 } else if (parent instanceof ViewRootImpl) {
25653 final ViewRootImpl vr = (ViewRootImpl) parent;
25654 vr.transformMatrixToLocal(matrix);
25655 matrix.postTranslate(0, vr.mCurScrollY);
25656 }
25657
25658 matrix.postTranslate(-mLeft, -mTop);
25659
25660 if (!hasIdentityMatrix()) {
25661 matrix.postConcat(getInverseMatrix());
25662 }
25663 }
25664
25665 /**
25666 * @hide
25667 */
25668 @ViewDebug.ExportedProperty(category = "layout", indexMapping = {
25669 @ViewDebug.IntToString(from = 0, to = "x"),
25670 @ViewDebug.IntToString(from = 1, to = "y")
25671 })
25672 @UnsupportedAppUsage
25673 public int[] getLocationOnScreen() {
25674 int[] location = new int[2];
25675 getLocationOnScreen(location);
25676 return location;
25677 }
25678
25679 /**
25680 * Gets the coordinates of this view in the coordinate space of the device
25681 * screen, irrespective of system decorations and whether the system is in
25682 * multi-window mode.
25683 *
25684 * <p>In multi-window mode, the coordinate space encompasses the entire
25685 * device screen, ignoring the bounds of the app window. For example, if the
25686 * view is in the bottom portion of a horizontal split screen, the top edge
25687 * of the screen&mdash;not the top edge of the window&mdash;is the origin
25688 * from which the y-coordinate is calculated.
25689 *
25690 * <p>In multiple-screen scenarios, the coordinate space can span screens.
25691 * For example, if the app is spanning both screens of a dual-screen device
25692 * and the view is located on the right-hand screen, the x-coordinate is
25693 * calculated from the left edge of the left-hand screen to the left edge of
25694 * the view. When the app is restricted to a single screen in a
25695 * multiple-screen environment, the coordinate space includes only the
25696 * screen on which the app is running.
25697 *
25698 * <p>After the method returns, the argument array contains the x and y
25699 * coordinates of the view relative to the view's left and top edges,
25700 * respectively.
25701 *
25702 * @param outLocation A two-element integer array in which the view
25703 * coordinates are stored. The x-coordinate is at index 0; the
25704 * y-coordinate, at index 1.
25705 */
25706 public void getLocationOnScreen(@Size(2) int[] outLocation) {
25707 getLocationInWindow(outLocation);
25708
25709 final AttachInfo info = mAttachInfo;
25710 if (info != null) {
25711 outLocation[0] += info.mWindowLeft;
25712 outLocation[1] += info.mWindowTop;
25713 }
25714 }
25715
25716 /**
25717 * Gets the coordinates of this view in the coordinate space of the window
25718 * that contains the view, irrespective of system decorations.
25719 *
25720 * <p>In multi-window mode, the origin of the coordinate space is the
25721 * top left corner of the window that contains the view. In full screen
25722 * mode, the origin is the top left corner of the device screen.
25723 *
25724 * <p>In multiple-screen scenarios, if the app spans multiple screens, the
25725 * coordinate space also spans multiple screens. But if the app is
25726 * restricted to a single screen, the coordinate space includes only the
25727 * screen on which the app is running.
25728 *
25729 * <p>After the method returns, the argument array contains the x and y
25730 * coordinates of the view relative to the view's left and top edges,
25731 * respectively.
25732 *
25733 * @param outLocation A two-element integer array in which the view
25734 * coordinates are stored. The x-coordinate is at index 0; the
25735 * y-coordinate, at index 1.
25736 */
25737 public void getLocationInWindow(@Size(2) int[] outLocation) {
25738 if (outLocation == null || outLocation.length < 2) {
25739 throw new IllegalArgumentException("outLocation must be an array of two integers");
25740 }
25741
25742 outLocation[0] = 0;
25743 outLocation[1] = 0;
25744
25745 transformFromViewToWindowSpace(outLocation);
25746 }
25747
25748 /** @hide */
25749 public void transformFromViewToWindowSpace(@Size(2) int[] inOutLocation) {
25750 if (inOutLocation == null || inOutLocation.length < 2) {
25751 throw new IllegalArgumentException("inOutLocation must be an array of two integers");
25752 }
25753
25754 if (mAttachInfo == null) {
25755 // When the view is not attached to a window, this method does not make sense
25756 inOutLocation[0] = inOutLocation[1] = 0;
25757 return;
25758 }
25759
25760 float position[] = mAttachInfo.mTmpTransformLocation;
25761 position[0] = inOutLocation[0];
25762 position[1] = inOutLocation[1];
25763
25764 if (!hasIdentityMatrix()) {
25765 getMatrix().mapPoints(position);
25766 }
25767
25768 position[0] += mLeft;
25769 position[1] += mTop;
25770
25771 ViewParent viewParent = mParent;
25772 while (viewParent instanceof View) {
25773 final View view = (View) viewParent;
25774
25775 position[0] -= view.mScrollX;
25776 position[1] -= view.mScrollY;
25777
25778 if (!view.hasIdentityMatrix()) {
25779 view.getMatrix().mapPoints(position);
25780 }
25781
25782 position[0] += view.mLeft;
25783 position[1] += view.mTop;
25784
25785 viewParent = view.mParent;
25786 }
25787
25788 if (viewParent instanceof ViewRootImpl) {
25789 // *cough*
25790 final ViewRootImpl vr = (ViewRootImpl) viewParent;
25791 position[1] -= vr.mCurScrollY;
25792 }
25793
25794 inOutLocation[0] = Math.round(position[0]);
25795 inOutLocation[1] = Math.round(position[1]);
25796 }
25797
25798 /**
25799 * @param id the id of the view to be found
25800 * @return the view of the specified id, null if cannot be found
25801 * @hide
25802 */
25803 protected <T extends View> T findViewTraversal(@IdRes int id) {
25804 if (id == mID) {
25805 return (T) this;
25806 }
25807 return null;
25808 }
25809
25810 /**
25811 * @param tag the tag of the view to be found
25812 * @return the view of specified tag, null if cannot be found
25813 * @hide
25814 */
25815 protected <T extends View> T findViewWithTagTraversal(Object tag) {
25816 if (tag != null && tag.equals(mTag)) {
25817 return (T) this;
25818 }
25819 return null;
25820 }
25821
25822 /**
25823 * @param predicate The predicate to evaluate.
25824 * @param childToSkip If not null, ignores this child during the recursive traversal.
25825 * @return The first view that matches the predicate or null.
25826 * @hide
25827 */
25828 protected <T extends View> T findViewByPredicateTraversal(Predicate<View> predicate,
25829 View childToSkip) {
25830 if (predicate.test(this)) {
25831 return (T) this;
25832 }
25833 return null;
25834 }
25835
25836 /**
25837 * Finds the first descendant view with the given ID, the view itself if
25838 * the ID matches {@link #getId()}, or {@code null} if the ID is invalid
25839 * (< 0) or there is no matching view in the hierarchy.
25840 * <p>
25841 * <strong>Note:</strong> In most cases -- depending on compiler support --
25842 * the resulting view is automatically cast to the target class type. If
25843 * the target class type is unconstrained, an explicit cast may be
25844 * necessary.
25845 *
25846 * @param id the ID to search for
25847 * @return a view with given ID if found, or {@code null} otherwise
25848 * @see View#requireViewById(int)
25849 */
25850 @Nullable
25851 public final <T extends View> T findViewById(@IdRes int id) {
25852 if (id == NO_ID) {
25853 return null;
25854 }
25855 return findViewTraversal(id);
25856 }
25857
25858 /**
25859 * Finds the first descendant view with the given ID, the view itself if the ID matches
25860 * {@link #getId()}, or throws an IllegalArgumentException if the ID is invalid or there is no
25861 * matching view in the hierarchy.
25862 * <p>
25863 * <strong>Note:</strong> In most cases -- depending on compiler support --
25864 * the resulting view is automatically cast to the target class type. If
25865 * the target class type is unconstrained, an explicit cast may be
25866 * necessary.
25867 *
25868 * @param id the ID to search for
25869 * @return a view with given ID
25870 * @see View#findViewById(int)
25871 */
25872 @NonNull
25873 public final <T extends View> T requireViewById(@IdRes int id) {
25874 T view = findViewById(id);
25875 if (view == null) {
25876 throw new IllegalArgumentException("ID does not reference a View inside this View");
25877 }
25878 return view;
25879 }
25880
25881 /**
25882 * Performs the traversal to find a view by its unique and stable accessibility id.
25883 *
25884 * <strong>Note:</strong>This method does not stop at the root namespace
25885 * boundary since the user can touch the screen at an arbitrary location
25886 * potentially crossing the root namespace boundary which will send an
25887 * accessibility event to accessibility services and they should be able
25888 * to obtain the event source. Also accessibility ids are guaranteed to be
25889 * unique in the window.
25890 *
25891 * @param accessibilityId The accessibility id.
25892 * @return The found view.
25893 * @hide
25894 */
25895 public <T extends View> T findViewByAccessibilityIdTraversal(int accessibilityId) {
25896 if (getAccessibilityViewId() == accessibilityId) {
25897 return (T) this;
25898 }
25899 return null;
25900 }
25901
25902 /**
25903 * Performs the traversal to find a view by its autofill id.
25904 *
25905 * <strong>Note:</strong>This method does not stop at the root namespace
25906 * boundary.
25907 *
25908 * @param autofillId The autofill id.
25909 * @return The found view.
25910 * @hide
25911 */
25912 public <T extends View> T findViewByAutofillIdTraversal(int autofillId) {
25913 if (getAutofillViewId() == autofillId) {
25914 return (T) this;
25915 }
25916 return null;
25917 }
25918
25919 /**
25920 * Look for a child view with the given tag. If this view has the given
25921 * tag, return this view.
25922 *
25923 * @param tag The tag to search for, using "tag.equals(getTag())".
25924 * @return The View that has the given tag in the hierarchy or null
25925 */
25926 public final <T extends View> T findViewWithTag(Object tag) {
25927 if (tag == null) {
25928 return null;
25929 }
25930 return findViewWithTagTraversal(tag);
25931 }
25932
25933 /**
25934 * Look for a child view that matches the specified predicate.
25935 * If this view matches the predicate, return this view.
25936 *
25937 * @param predicate The predicate to evaluate.
25938 * @return The first view that matches the predicate or null.
25939 * @hide
25940 */
25941 public final <T extends View> T findViewByPredicate(Predicate<View> predicate) {
25942 return findViewByPredicateTraversal(predicate, null);
25943 }
25944
25945 /**
25946 * Look for a child view that matches the specified predicate,
25947 * starting with the specified view and its descendents and then
25948 * recusively searching the ancestors and siblings of that view
25949 * until this view is reached.
25950 *
25951 * This method is useful in cases where the predicate does not match
25952 * a single unique view (perhaps multiple views use the same id)
25953 * and we are trying to find the view that is "closest" in scope to the
25954 * starting view.
25955 *
25956 * @param start The view to start from.
25957 * @param predicate The predicate to evaluate.
25958 * @return The first view that matches the predicate or null.
25959 * @hide
25960 */
25961 public final <T extends View> T findViewByPredicateInsideOut(
25962 View start, Predicate<View> predicate) {
25963 View childToSkip = null;
25964 for (;;) {
25965 T view = start.findViewByPredicateTraversal(predicate, childToSkip);
25966 if (view != null || start == this) {
25967 return view;
25968 }
25969
25970 ViewParent parent = start.getParent();
25971 if (parent == null || !(parent instanceof View)) {
25972 return null;
25973 }
25974
25975 childToSkip = start;
25976 start = (View) parent;
25977 }
25978 }
25979
25980 /**
25981 * Sets the identifier for this view. The identifier does not have to be
25982 * unique in this view's hierarchy. The identifier should be a positive
25983 * number.
25984 *
25985 * @see #NO_ID
25986 * @see #getId()
25987 * @see #findViewById(int)
25988 *
25989 * @param id a number used to identify the view
25990 *
25991 * @attr ref android.R.styleable#View_id
25992 */
25993 public void setId(@IdRes int id) {
25994 mID = id;
25995 if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
25996 mID = generateViewId();
25997 }
25998 }
25999
26000 /**
26001 * {@hide}
26002 *
26003 * @param isRoot true if the view belongs to the root namespace, false
26004 * otherwise
26005 */
26006 @UnsupportedAppUsage
26007 @TestApi
26008 public void setIsRootNamespace(boolean isRoot) {
26009 if (isRoot) {
26010 mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
26011 } else {
26012 mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
26013 }
26014 }
26015
26016 /**
26017 * {@hide}
26018 *
26019 * @return true if the view belongs to the root namespace, false otherwise
26020 */
26021 @UnsupportedAppUsage
26022 public boolean isRootNamespace() {
26023 return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
26024 }
26025
26026 /**
26027 * Returns this view's identifier.
26028 *
26029 * @return a positive integer used to identify the view or {@link #NO_ID}
26030 * if the view has no ID
26031 *
26032 * @see #setId(int)
26033 * @see #findViewById(int)
26034 * @attr ref android.R.styleable#View_id
26035 */
26036 @IdRes
26037 @ViewDebug.CapturedViewProperty
26038 @InspectableProperty
26039 public int getId() {
26040 return mID;
26041 }
26042
26043 /**
26044 * Get the identifier used for this view by the drawing system.
26045 *
26046 * @see RenderNode#getUniqueId()
26047 * @return A long that uniquely identifies this view's drawing component
26048 */
26049 public long getUniqueDrawingId() {
26050 return mRenderNode.getUniqueId();
26051 }
26052
26053 /**
26054 * Returns this view's tag.
26055 *
26056 * @return the Object stored in this view as a tag, or {@code null} if not
26057 * set
26058 *
26059 * @see #setTag(Object)
26060 * @see #getTag(int)
26061 */
26062 @ViewDebug.ExportedProperty
26063 @InspectableProperty
26064 public Object getTag() {
26065 return mTag;
26066 }
26067
26068 /**
26069 * Sets the tag associated with this view. A tag can be used to mark
26070 * a view in its hierarchy and does not have to be unique within the
26071 * hierarchy. Tags can also be used to store data within a view without
26072 * resorting to another data structure.
26073 *
26074 * @param tag an Object to tag the view with
26075 *
26076 * @see #getTag()
26077 * @see #setTag(int, Object)
26078 */
26079 public void setTag(final Object tag) {
26080 mTag = tag;
26081 }
26082
26083 /**
26084 * Returns the tag associated with this view and the specified key.
26085 *
26086 * @param key The key identifying the tag
26087 *
26088 * @return the Object stored in this view as a tag, or {@code null} if not
26089 * set
26090 *
26091 * @see #setTag(int, Object)
26092 * @see #getTag()
26093 */
26094 public Object getTag(int key) {
26095 if (mKeyedTags != null) return mKeyedTags.get(key);
26096 return null;
26097 }
26098
26099 /**
26100 * Sets a tag associated with this view and a key. A tag can be used
26101 * to mark a view in its hierarchy and does not have to be unique within
26102 * the hierarchy. Tags can also be used to store data within a view
26103 * without resorting to another data structure.
26104 *
26105 * The specified key should be an id declared in the resources of the
26106 * application to ensure it is unique (see the <a
26107 * href="{@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
26108 * Keys identified as belonging to
26109 * the Android framework or not associated with any package will cause
26110 * an {@link IllegalArgumentException} to be thrown.
26111 *
26112 * @param key The key identifying the tag
26113 * @param tag An Object to tag the view with
26114 *
26115 * @throws IllegalArgumentException If they specified key is not valid
26116 *
26117 * @see #setTag(Object)
26118 * @see #getTag(int)
26119 */
26120 public void setTag(int key, final Object tag) {
26121 // If the package id is 0x00 or 0x01, it's either an undefined package
26122 // or a framework id
26123 if ((key >>> 24) < 2) {
26124 throw new IllegalArgumentException("The key must be an application-specific "
26125 + "resource id.");
26126 }
26127
26128 setKeyedTag(key, tag);
26129 }
26130
26131 /**
26132 * Variation of {@link #setTag(int, Object)} that enforces the key to be a
26133 * framework id.
26134 *
26135 * @hide
26136 */
26137 @UnsupportedAppUsage
26138 public void setTagInternal(int key, Object tag) {
26139 if ((key >>> 24) != 0x1) {
26140 throw new IllegalArgumentException("The key must be a framework-specific "
26141 + "resource id.");
26142 }
26143
26144 setKeyedTag(key, tag);
26145 }
26146
26147 private void setKeyedTag(int key, Object tag) {
26148 if (mKeyedTags == null) {
26149 mKeyedTags = new SparseArray<Object>(2);
26150 }
26151
26152 mKeyedTags.put(key, tag);
26153 }
26154
26155 /**
26156 * Prints information about this view in the log output, with the tag
26157 * {@link #VIEW_LOG_TAG}.
26158 *
26159 * @hide
26160 */
26161 @UnsupportedAppUsage
26162 public void debug() {
26163 debug(0);
26164 }
26165
26166 /**
26167 * Prints information about this view in the log output, with the tag
26168 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
26169 * indentation defined by the <code>depth</code>.
26170 *
26171 * @param depth the indentation level
26172 *
26173 * @hide
26174 */
26175 @UnsupportedAppUsage
26176 protected void debug(int depth) {
26177 String output = debugIndent(depth - 1);
26178
26179 output += "+ " + this;
26180 int id = getId();
26181 if (id != -1) {
26182 output += " (id=" + id + ")";
26183 }
26184 Object tag = getTag();
26185 if (tag != null) {
26186 output += " (tag=" + tag + ")";
26187 }
26188 Log.d(VIEW_LOG_TAG, output);
26189
26190 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
26191 output = debugIndent(depth) + " FOCUSED";
26192 Log.d(VIEW_LOG_TAG, output);
26193 }
26194
26195 output = debugIndent(depth);
26196 output += "frame={" + mLeft + ", " + mTop + ", " + mRight
26197 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
26198 + "} ";
26199 Log.d(VIEW_LOG_TAG, output);
26200
26201 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
26202 || mPaddingBottom != 0) {
26203 output = debugIndent(depth);
26204 output += "padding={" + mPaddingLeft + ", " + mPaddingTop
26205 + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
26206 Log.d(VIEW_LOG_TAG, output);
26207 }
26208
26209 output = debugIndent(depth);
26210 output += "mMeasureWidth=" + mMeasuredWidth +
26211 " mMeasureHeight=" + mMeasuredHeight;
26212 Log.d(VIEW_LOG_TAG, output);
26213
26214 output = debugIndent(depth);
26215 if (mLayoutParams == null) {
26216 output += "BAD! no layout params";
26217 } else {
26218 output = mLayoutParams.debug(output);
26219 }
26220 Log.d(VIEW_LOG_TAG, output);
26221
26222 output = debugIndent(depth);
26223 output += "flags={";
26224 output += View.printFlags(mViewFlags);
26225 output += "}";
26226 Log.d(VIEW_LOG_TAG, output);
26227
26228 output = debugIndent(depth);
26229 output += "privateFlags={";
26230 output += View.printPrivateFlags(mPrivateFlags);
26231 output += "}";
26232 Log.d(VIEW_LOG_TAG, output);
26233 }
26234
26235 /**
26236 * Creates a string of whitespaces used for indentation.
26237 *
26238 * @param depth the indentation level
26239 * @return a String containing (depth * 2 + 3) * 2 white spaces
26240 *
26241 * @hide
26242 */
26243 protected static String debugIndent(int depth) {
26244 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
26245 for (int i = 0; i < (depth * 2) + 3; i++) {
26246 spaces.append(' ').append(' ');
26247 }
26248 return spaces.toString();
26249 }
26250
26251 /**
26252 * <p>Return the offset of the widget's text baseline from the widget's top
26253 * boundary. If this widget does not support baseline alignment, this
26254 * method returns -1. </p>
26255 *
26256 * @return the offset of the baseline within the widget's bounds or -1
26257 * if baseline alignment is not supported
26258 */
26259 @ViewDebug.ExportedProperty(category = "layout")
26260 @InspectableProperty
26261 public int getBaseline() {
26262 return -1;
26263 }
26264
26265 /**
26266 * Returns whether the view hierarchy is currently undergoing a layout pass. This
26267 * information is useful to avoid situations such as calling {@link #requestLayout()} during
26268 * a layout pass.
26269 *
26270 * @return whether the view hierarchy is currently undergoing a layout pass
26271 */
26272 public boolean isInLayout() {
26273 ViewRootImpl viewRoot = getViewRootImpl();
26274 return (viewRoot != null && viewRoot.isInLayout());
26275 }
26276
26277 /**
26278 * Call this when something has changed which has invalidated the
26279 * layout of this view. This will schedule a layout pass of the view
26280 * tree. This should not be called while the view hierarchy is currently in a layout
26281 * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
26282 * end of the current layout pass (and then layout will run again) or after the current
26283 * frame is drawn and the next layout occurs.
26284 *
26285 * <p>Subclasses which override this method should call the superclass method to
26286 * handle possible request-during-layout errors correctly.</p>
26287 */
26288 @CallSuper
26289 public void requestLayout() {
26290 if (mMeasureCache != null) mMeasureCache.clear();
26291
26292 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
26293 // Only trigger request-during-layout logic if this is the view requesting it,
26294 // not the views in its parent hierarchy
26295 ViewRootImpl viewRoot = getViewRootImpl();
26296 if (viewRoot != null && viewRoot.isInLayout()) {
26297 if (!viewRoot.requestLayoutDuringLayout(this)) {
26298 return;
26299 }
26300 }
26301 mAttachInfo.mViewRequestingLayout = this;
26302 }
26303
26304 mPrivateFlags |= PFLAG_FORCE_LAYOUT;
26305 mPrivateFlags |= PFLAG_INVALIDATED;
26306
26307 if (mParent != null && !mParent.isLayoutRequested()) {
26308 mParent.requestLayout();
26309 }
26310 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
26311 mAttachInfo.mViewRequestingLayout = null;
26312 }
26313 }
26314
26315 /**
26316 * Forces this view to be laid out during the next layout pass.
26317 * This method does not call requestLayout() or forceLayout()
26318 * on the parent.
26319 */
26320 public void forceLayout() {
26321 if (mMeasureCache != null) mMeasureCache.clear();
26322
26323 mPrivateFlags |= PFLAG_FORCE_LAYOUT;
26324 mPrivateFlags |= PFLAG_INVALIDATED;
26325 }
26326
26327 /**
26328 * <p>
26329 * This is called to find out how big a view should be. The parent
26330 * supplies constraint information in the width and height parameters.
26331 * </p>
26332 *
26333 * <p>
26334 * The actual measurement work of a view is performed in
26335 * {@link #onMeasure(int, int)}, called by this method. Therefore, only
26336 * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
26337 * </p>
26338 *
26339 *
26340 * @param widthMeasureSpec Horizontal space requirements as imposed by the
26341 * parent
26342 * @param heightMeasureSpec Vertical space requirements as imposed by the
26343 * parent
26344 *
26345 * @see #onMeasure(int, int)
26346 */
26347 public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
26348 boolean optical = isLayoutModeOptical(this);
26349 if (optical != isLayoutModeOptical(mParent)) {
26350 Insets insets = getOpticalInsets();
26351 int oWidth = insets.left + insets.right;
26352 int oHeight = insets.top + insets.bottom;
26353 widthMeasureSpec = MeasureSpec.adjust(widthMeasureSpec, optical ? -oWidth : oWidth);
26354 heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
26355 }
26356
26357 // Suppress sign extension for the low bytes
26358 long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
26359 if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
26360
26361 final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
26362
26363 // Optimize layout by avoiding an extra EXACTLY pass when the view is
26364 // already measured as the correct size. In API 23 and below, this
26365 // extra pass is required to make LinearLayout re-distribute weight.
26366 final boolean specChanged = widthMeasureSpec != mOldWidthMeasureSpec
26367 || heightMeasureSpec != mOldHeightMeasureSpec;
26368 final boolean isSpecExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY
26369 && MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY;
26370 final boolean matchesSpecSize = getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec)
26371 && getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec);
26372 final boolean needsLayout = specChanged
26373 && (sAlwaysRemeasureExactly || !isSpecExactly || !matchesSpecSize);
26374
26375 if (forceLayout || needsLayout) {
26376 // first clears the measured dimension flag
26377 mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
26378
26379 resolveRtlPropertiesIfNeeded();
26380
26381 int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key);
26382 if (cacheIndex < 0 || sIgnoreMeasureCache) {
26383 // measure ourselves, this should set the measured dimension flag back
26384 onMeasure(widthMeasureSpec, heightMeasureSpec);
26385 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
26386 } else {
26387 long value = mMeasureCache.valueAt(cacheIndex);
26388 // Casting a long to int drops the high 32 bits, no mask needed
26389 setMeasuredDimensionRaw((int) (value >> 32), (int) value);
26390 mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
26391 }
26392
26393 // flag not set, setMeasuredDimension() was not invoked, we raise
26394 // an exception to warn the developer
26395 if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
26396 throw new IllegalStateException("View with id " + getId() + ": "
26397 + getClass().getName() + "#onMeasure() did not set the"
26398 + " measured dimension by calling"
26399 + " setMeasuredDimension()");
26400 }
26401
26402 mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
26403 }
26404
26405 mOldWidthMeasureSpec = widthMeasureSpec;
26406 mOldHeightMeasureSpec = heightMeasureSpec;
26407
26408 mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
26409 (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
26410 }
26411
26412 /**
26413 * <p>
26414 * Measure the view and its content to determine the measured width and the
26415 * measured height. This method is invoked by {@link #measure(int, int)} and
26416 * should be overridden by subclasses to provide accurate and efficient
26417 * measurement of their contents.
26418 * </p>
26419 *
26420 * <p>
26421 * <strong>CONTRACT:</strong> When overriding this method, you
26422 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
26423 * measured width and height of this view. Failure to do so will trigger an
26424 * <code>IllegalStateException</code>, thrown by
26425 * {@link #measure(int, int)}. Calling the superclass'
26426 * {@link #onMeasure(int, int)} is a valid use.
26427 * </p>
26428 *
26429 * <p>
26430 * The base class implementation of measure defaults to the background size,
26431 * unless a larger size is allowed by the MeasureSpec. Subclasses should
26432 * override {@link #onMeasure(int, int)} to provide better measurements of
26433 * their content.
26434 * </p>
26435 *
26436 * <p>
26437 * If this method is overridden, it is the subclass's responsibility to make
26438 * sure the measured height and width are at least the view's minimum height
26439 * and width ({@link #getSuggestedMinimumHeight()} and
26440 * {@link #getSuggestedMinimumWidth()}).
26441 * </p>
26442 *
26443 * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
26444 * The requirements are encoded with
26445 * {@link android.view.View.MeasureSpec}.
26446 * @param heightMeasureSpec vertical space requirements as imposed by the parent.
26447 * The requirements are encoded with
26448 * {@link android.view.View.MeasureSpec}.
26449 *
26450 * @see #getMeasuredWidth()
26451 * @see #getMeasuredHeight()
26452 * @see #setMeasuredDimension(int, int)
26453 * @see #getSuggestedMinimumHeight()
26454 * @see #getSuggestedMinimumWidth()
26455 * @see android.view.View.MeasureSpec#getMode(int)
26456 * @see android.view.View.MeasureSpec#getSize(int)
26457 */
26458 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
26459 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
26460 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
26461 }
26462
26463 /**
26464 * <p>This method must be called by {@link #onMeasure(int, int)} to store the
26465 * measured width and measured height. Failing to do so will trigger an
26466 * exception at measurement time.</p>
26467 *
26468 * @param measuredWidth The measured width of this view. May be a complex
26469 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
26470 * {@link #MEASURED_STATE_TOO_SMALL}.
26471 * @param measuredHeight The measured height of this view. May be a complex
26472 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
26473 * {@link #MEASURED_STATE_TOO_SMALL}.
26474 */
26475 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
26476 boolean optical = isLayoutModeOptical(this);
26477 if (optical != isLayoutModeOptical(mParent)) {
26478 Insets insets = getOpticalInsets();
26479 int opticalWidth = insets.left + insets.right;
26480 int opticalHeight = insets.top + insets.bottom;
26481
26482 measuredWidth += optical ? opticalWidth : -opticalWidth;
26483 measuredHeight += optical ? opticalHeight : -opticalHeight;
26484 }
26485 setMeasuredDimensionRaw(measuredWidth, measuredHeight);
26486 }
26487
26488 /**
26489 * Sets the measured dimension without extra processing for things like optical bounds.
26490 * Useful for reapplying consistent values that have already been cooked with adjustments
26491 * for optical bounds, etc. such as those from the measurement cache.
26492 *
26493 * @param measuredWidth The measured width of this view. May be a complex
26494 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
26495 * {@link #MEASURED_STATE_TOO_SMALL}.
26496 * @param measuredHeight The measured height of this view. May be a complex
26497 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
26498 * {@link #MEASURED_STATE_TOO_SMALL}.
26499 */
26500 private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
26501 mMeasuredWidth = measuredWidth;
26502 mMeasuredHeight = measuredHeight;
26503
26504 mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
26505 }
26506
26507 /**
26508 * Merge two states as returned by {@link #getMeasuredState()}.
26509 * @param curState The current state as returned from a view or the result
26510 * of combining multiple views.
26511 * @param newState The new view state to combine.
26512 * @return Returns a new integer reflecting the combination of the two
26513 * states.
26514 */
26515 public static int combineMeasuredStates(int curState, int newState) {
26516 return curState | newState;
26517 }
26518
26519 /**
26520 * Version of {@link #resolveSizeAndState(int, int, int)}
26521 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
26522 */
26523 public static int resolveSize(int size, int measureSpec) {
26524 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
26525 }
26526
26527 /**
26528 * Utility to reconcile a desired size and state, with constraints imposed
26529 * by a MeasureSpec. Will take the desired size, unless a different size
26530 * is imposed by the constraints. The returned value is a compound integer,
26531 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
26532 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the
26533 * resulting size is smaller than the size the view wants to be.
26534 *
26535 * @param size How big the view wants to be.
26536 * @param measureSpec Constraints imposed by the parent.
26537 * @param childMeasuredState Size information bit mask for the view's
26538 * children.
26539 * @return Size information bit mask as defined by
26540 * {@link #MEASURED_SIZE_MASK} and
26541 * {@link #MEASURED_STATE_TOO_SMALL}.
26542 */
26543 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
26544 final int specMode = MeasureSpec.getMode(measureSpec);
26545 final int specSize = MeasureSpec.getSize(measureSpec);
26546 final int result;
26547 switch (specMode) {
26548 case MeasureSpec.AT_MOST:
26549 if (specSize < size) {
26550 result = specSize | MEASURED_STATE_TOO_SMALL;
26551 } else {
26552 result = size;
26553 }
26554 break;
26555 case MeasureSpec.EXACTLY:
26556 result = specSize;
26557 break;
26558 case MeasureSpec.UNSPECIFIED:
26559 default:
26560 result = size;
26561 }
26562 return result | (childMeasuredState & MEASURED_STATE_MASK);
26563 }
26564
26565 /**
26566 * Utility to return a default size. Uses the supplied size if the
26567 * MeasureSpec imposed no constraints. Will get larger if allowed
26568 * by the MeasureSpec.
26569 *
26570 * @param size Default size for this view
26571 * @param measureSpec Constraints imposed by the parent
26572 * @return The size this view should be.
26573 */
26574 public static int getDefaultSize(int size, int measureSpec) {
26575 int result = size;
26576 int specMode = MeasureSpec.getMode(measureSpec);
26577 int specSize = MeasureSpec.getSize(measureSpec);
26578
26579 switch (specMode) {
26580 case MeasureSpec.UNSPECIFIED:
26581 result = size;
26582 break;
26583 case MeasureSpec.AT_MOST:
26584 case MeasureSpec.EXACTLY:
26585 result = specSize;
26586 break;
26587 }
26588 return result;
26589 }
26590
26591 /**
26592 * Returns the suggested minimum height that the view should use. This
26593 * returns the maximum of the view's minimum height
26594 * and the background's minimum height
26595 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
26596 * <p>
26597 * When being used in {@link #onMeasure(int, int)}, the caller should still
26598 * ensure the returned height is within the requirements of the parent.
26599 *
26600 * @return The suggested minimum height of the view.
26601 */
26602 protected int getSuggestedMinimumHeight() {
26603 return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
26604
26605 }
26606
26607 /**
26608 * Returns the suggested minimum width that the view should use. This
26609 * returns the maximum of the view's minimum width
26610 * and the background's minimum width
26611 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
26612 * <p>
26613 * When being used in {@link #onMeasure(int, int)}, the caller should still
26614 * ensure the returned width is within the requirements of the parent.
26615 *
26616 * @return The suggested minimum width of the view.
26617 */
26618 protected int getSuggestedMinimumWidth() {
26619 return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
26620 }
26621
26622 /**
26623 * Returns the minimum height of the view.
26624 *
26625 * @return the minimum height the view will try to be, in pixels
26626 *
26627 * @see #setMinimumHeight(int)
26628 *
26629 * @attr ref android.R.styleable#View_minHeight
26630 */
26631 @InspectableProperty(name = "minHeight")
26632 public int getMinimumHeight() {
26633 return mMinHeight;
26634 }
26635
26636 /**
26637 * Sets the minimum height of the view. It is not guaranteed the view will
26638 * be able to achieve this minimum height (for example, if its parent layout
26639 * constrains it with less available height).
26640 *
26641 * @param minHeight The minimum height the view will try to be, in pixels
26642 *
26643 * @see #getMinimumHeight()
26644 *
26645 * @attr ref android.R.styleable#View_minHeight
26646 */
26647 @RemotableViewMethod
26648 public void setMinimumHeight(int minHeight) {
26649 mMinHeight = minHeight;
26650 requestLayout();
26651 }
26652
26653 /**
26654 * Returns the minimum width of the view.
26655 *
26656 * @return the minimum width the view will try to be, in pixels
26657 *
26658 * @see #setMinimumWidth(int)
26659 *
26660 * @attr ref android.R.styleable#View_minWidth
26661 */
26662 @InspectableProperty(name = "minWidth")
26663 public int getMinimumWidth() {
26664 return mMinWidth;
26665 }
26666
26667 /**
26668 * Sets the minimum width of the view. It is not guaranteed the view will
26669 * be able to achieve this minimum width (for example, if its parent layout
26670 * constrains it with less available width).
26671 *
26672 * @param minWidth The minimum width the view will try to be, in pixels
26673 *
26674 * @see #getMinimumWidth()
26675 *
26676 * @attr ref android.R.styleable#View_minWidth
26677 */
26678 @RemotableViewMethod
26679 public void setMinimumWidth(int minWidth) {
26680 mMinWidth = minWidth;
26681 requestLayout();
26682
26683 }
26684
26685 /**
26686 * Get the animation currently associated with this view.
26687 *
26688 * @return The animation that is currently playing or
26689 * scheduled to play for this view.
26690 */
26691 public Animation getAnimation() {
26692 return mCurrentAnimation;
26693 }
26694
26695 /**
26696 * Start the specified animation now.
26697 *
26698 * @param animation the animation to start now
26699 */
26700 public void startAnimation(Animation animation) {
26701 animation.setStartTime(Animation.START_ON_FIRST_FRAME);
26702 setAnimation(animation);
26703 invalidateParentCaches();
26704 invalidate(true);
26705 }
26706
26707 /**
26708 * Cancels any animations for this view.
26709 */
26710 public void clearAnimation() {
26711 if (mCurrentAnimation != null) {
26712 mCurrentAnimation.detach();
26713 }
26714 mCurrentAnimation = null;
26715 invalidateParentIfNeeded();
26716 }
26717
26718 /**
26719 * Sets the next animation to play for this view.
26720 * If you want the animation to play immediately, use
26721 * {@link #startAnimation(android.view.animation.Animation)} instead.
26722 * This method provides allows fine-grained
26723 * control over the start time and invalidation, but you
26724 * must make sure that 1) the animation has a start time set, and
26725 * 2) the view's parent (which controls animations on its children)
26726 * will be invalidated when the animation is supposed to
26727 * start.
26728 *
26729 * @param animation The next animation, or null.
26730 */
26731 public void setAnimation(Animation animation) {
26732 mCurrentAnimation = animation;
26733
26734 if (animation != null) {
26735 // If the screen is off assume the animation start time is now instead of
26736 // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
26737 // would cause the animation to start when the screen turns back on
26738 if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF
26739 && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
26740 animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
26741 }
26742 animation.reset();
26743 }
26744 }
26745
26746 /**
26747 * Invoked by a parent ViewGroup to notify the start of the animation
26748 * currently associated with this view. If you override this method,
26749 * always call super.onAnimationStart();
26750 *
26751 * @see #setAnimation(android.view.animation.Animation)
26752 * @see #getAnimation()
26753 */
26754 @CallSuper
26755 protected void onAnimationStart() {
26756 mPrivateFlags |= PFLAG_ANIMATION_STARTED;
26757 }
26758
26759 /**
26760 * Invoked by a parent ViewGroup to notify the end of the animation
26761 * currently associated with this view. If you override this method,
26762 * always call super.onAnimationEnd();
26763 *
26764 * @see #setAnimation(android.view.animation.Animation)
26765 * @see #getAnimation()
26766 */
26767 @CallSuper
26768 protected void onAnimationEnd() {
26769 mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
26770 }
26771
26772 /**
26773 * Invoked if there is a Transform that involves alpha. Subclass that can
26774 * draw themselves with the specified alpha should return true, and then
26775 * respect that alpha when their onDraw() is called. If this returns false
26776 * then the view may be redirected to draw into an offscreen buffer to
26777 * fulfill the request, which will look fine, but may be slower than if the
26778 * subclass handles it internally. The default implementation returns false.
26779 *
26780 * @param alpha The alpha (0..255) to apply to the view's drawing
26781 * @return true if the view can draw with the specified alpha.
26782 */
26783 protected boolean onSetAlpha(int alpha) {
26784 return false;
26785 }
26786
26787 /**
26788 * This is used by the ViewRoot to perform an optimization when
26789 * the view hierarchy contains one or several SurfaceView.
26790 * SurfaceView is always considered transparent, but its children are not,
26791 * therefore all View objects remove themselves from the global transparent
26792 * region (passed as a parameter to this function).
26793 *
26794 * @param region The transparent region for this ViewAncestor (window).
26795 *
26796 * @return Returns true if the effective visibility of the view at this
26797 * point is opaque, regardless of the transparent region; returns false
26798 * if it is possible for underlying windows to be seen behind the view.
26799 *
26800 */
26801 public boolean gatherTransparentRegion(@Nullable Region region) {
26802 final AttachInfo attachInfo = mAttachInfo;
26803 if (region != null && attachInfo != null) {
26804 final int pflags = mPrivateFlags;
26805 if ((pflags & PFLAG_SKIP_DRAW) == 0) {
26806 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
26807 // remove it from the transparent region.
26808 final int[] location = attachInfo.mTransparentLocation;
26809 getLocationInWindow(location);
26810 // When a view has Z value, then it will be better to leave some area below the view
26811 // for drawing shadow. The shadow outset is proportional to the Z value. Note that
26812 // the bottom part needs more offset than the left, top and right parts due to the
26813 // spot light effects.
26814 int shadowOffset = getZ() > 0 ? (int) getZ() : 0;
26815 region.op(location[0] - shadowOffset, location[1] - shadowOffset,
26816 location[0] + mRight - mLeft + shadowOffset,
26817 location[1] + mBottom - mTop + (shadowOffset * 3), Region.Op.DIFFERENCE);
26818 } else {
26819 if (mBackground != null && mBackground.getOpacity() != PixelFormat.TRANSPARENT) {
26820 // The SKIP_DRAW flag IS set and the background drawable exists, we remove
26821 // the background drawable's non-transparent parts from this transparent region.
26822 applyDrawableToTransparentRegion(mBackground, region);
26823 }
26824 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
26825 && mForegroundInfo.mDrawable.getOpacity() != PixelFormat.TRANSPARENT) {
26826 // Similarly, we remove the foreground drawable's non-transparent parts.
26827 applyDrawableToTransparentRegion(mForegroundInfo.mDrawable, region);
26828 }
26829 if (mDefaultFocusHighlight != null
26830 && mDefaultFocusHighlight.getOpacity() != PixelFormat.TRANSPARENT) {
26831 // Similarly, we remove the default focus highlight's non-transparent parts.
26832 applyDrawableToTransparentRegion(mDefaultFocusHighlight, region);
26833 }
26834 }
26835 }
26836 return true;
26837 }
26838
26839 /**
26840 * Play a sound effect for this view.
26841 *
26842 * <p>The framework will play sound effects for some built in actions, such as
26843 * clicking, but you may wish to play these effects in your widget,
26844 * for instance, for internal navigation.
26845 *
26846 * <p>The sound effect will only be played if sound effects are enabled by the user, and
26847 * {@link #isSoundEffectsEnabled()} is true.
26848 *
26849 * @param soundConstant One of the constants defined in {@link SoundEffectConstants}.
26850 */
26851 public void playSoundEffect(@SoundEffectConstants.SoundEffect int soundConstant) {
26852 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
26853 return;
26854 }
26855 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
26856 }
26857
26858 /**
26859 * BZZZTT!!1!
26860 *
26861 * <p>Provide haptic feedback to the user for this view.
26862 *
26863 * <p>The framework will provide haptic feedback for some built in actions,
26864 * such as long presses, but you may wish to provide feedback for your
26865 * own widget.
26866 *
26867 * <p>The feedback will only be performed if
26868 * {@link #isHapticFeedbackEnabled()} is true.
26869 *
26870 * @param feedbackConstant One of the constants defined in
26871 * {@link HapticFeedbackConstants}
26872 */
26873 public boolean performHapticFeedback(int feedbackConstant) {
26874 return performHapticFeedback(feedbackConstant, 0);
26875 }
26876
26877 /**
26878 * BZZZTT!!1!
26879 *
26880 * <p>Like {@link #performHapticFeedback(int)}, with additional options.
26881 *
26882 * @param feedbackConstant One of the constants defined in
26883 * {@link HapticFeedbackConstants}
26884 * @param flags Additional flags as per {@link HapticFeedbackConstants}.
26885 */
26886 public boolean performHapticFeedback(int feedbackConstant, int flags) {
26887 if (mAttachInfo == null) {
26888 return false;
26889 }
26890 //noinspection SimplifiableIfStatement
26891 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
26892 && !isHapticFeedbackEnabled()) {
26893 return false;
26894 }
26895 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
26896 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
26897 }
26898
26899 /**
26900 * Request that the visibility of the status bar or other screen/window
26901 * decorations be changed.
26902 *
26903 * <p>This method is used to put the over device UI into temporary modes
26904 * where the user's attention is focused more on the application content,
26905 * by dimming or hiding surrounding system affordances. This is typically
26906 * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
26907 * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
26908 * to be placed behind the action bar (and with these flags other system
26909 * affordances) so that smooth transitions between hiding and showing them
26910 * can be done.
26911 *
26912 * <p>Two representative examples of the use of system UI visibility is
26913 * implementing a content browsing application (like a magazine reader)
26914 * and a video playing application.
26915 *
26916 * <p>The first code shows a typical implementation of a View in a content
26917 * browsing application. In this implementation, the application goes
26918 * into a content-oriented mode by hiding the status bar and action bar,
26919 * and putting the navigation elements into lights out mode. The user can
26920 * then interact with content while in this mode. Such an application should
26921 * provide an easy way for the user to toggle out of the mode (such as to
26922 * check information in the status bar or access notifications). In the
26923 * implementation here, this is done simply by tapping on the content.
26924 *
26925 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
26926 * content}
26927 *
26928 * <p>This second code sample shows a typical implementation of a View
26929 * in a video playing application. In this situation, while the video is
26930 * playing the application would like to go into a complete full-screen mode,
26931 * to use as much of the display as possible for the video. When in this state
26932 * the user can not interact with the application; the system intercepts
26933 * touching on the screen to pop the UI out of full screen mode. See
26934 * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
26935 *
26936 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
26937 * content}
26938 *
26939 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
26940 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
26941 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
26942 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
26943 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
26944 *
26945 * @deprecated SystemUiVisibility flags are deprecated. Use {@link WindowInsetsController}
26946 * instead.
26947 */
26948 @Deprecated
26949 public void setSystemUiVisibility(int visibility) {
26950 if (visibility != mSystemUiVisibility) {
26951 mSystemUiVisibility = visibility;
26952 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
26953 mParent.recomputeViewAttributes(this);
26954 }
26955 }
26956 }
26957
26958 /**
26959 * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
26960 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
26961 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
26962 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
26963 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
26964 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
26965 *
26966 * @deprecated SystemUiVisibility flags are deprecated. Use {@link WindowInsetsController}
26967 * instead.
26968 */
26969 @Deprecated
26970 public int getSystemUiVisibility() {
26971 return mSystemUiVisibility;
26972 }
26973
26974 /**
26975 * Returns the current system UI visibility that is currently set for
26976 * the entire window. This is the combination of the
26977 * {@link #setSystemUiVisibility(int)} values supplied by all of the
26978 * views in the window.
26979 *
26980 * @deprecated SystemUiVisibility flags are deprecated. Use {@link WindowInsetsController}
26981 * instead.
26982 */
26983 @Deprecated
26984 public int getWindowSystemUiVisibility() {
26985 return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
26986 }
26987
26988 /**
26989 * Override to find out when the window's requested system UI visibility
26990 * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
26991 * This is different from the callbacks received through
26992 * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
26993 * in that this is only telling you about the local request of the window,
26994 * not the actual values applied by the system.
26995 *
26996 * @deprecated SystemUiVisibility flags are deprecated. Use {@link WindowInsetsController}
26997 * instead.
26998 */
26999 @Deprecated
27000 public void onWindowSystemUiVisibilityChanged(int visible) {
27001 }
27002
27003 /**
27004 * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
27005 * the view hierarchy.
27006 *
27007 * @deprecated SystemUiVisibility flags are deprecated. Use {@link WindowInsetsController}
27008 * instead.
27009 */
27010 @Deprecated
27011 public void dispatchWindowSystemUiVisiblityChanged(int visible) {
27012 onWindowSystemUiVisibilityChanged(visible);
27013 }
27014
27015 /**
27016 * Set a listener to receive callbacks when the visibility of the system bar changes.
27017 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
27018 *
27019 * @deprecated Use {@link WindowInsets#isVisible(int)} to find out about system bar visibilities
27020 * by setting a {@link OnApplyWindowInsetsListener} on this view.
27021 */
27022 @Deprecated
27023 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
27024 getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
27025 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
27026 mParent.recomputeViewAttributes(this);
27027 }
27028 }
27029
27030 /**
27031 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
27032 * the view hierarchy.
27033 *
27034 * @deprecated Use {@link WindowInsets#isVisible(int)} to find out about system bar visibilities
27035 * by setting a {@link OnApplyWindowInsetsListener} on this view.
27036 */
27037 @Deprecated
27038 public void dispatchSystemUiVisibilityChanged(int visibility) {
27039 ListenerInfo li = mListenerInfo;
27040 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
27041 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
27042 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
27043 }
27044 }
27045
27046 boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
27047 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
27048 if (val != mSystemUiVisibility) {
27049 setSystemUiVisibility(val);
27050 return true;
27051 }
27052 return false;
27053 }
27054
27055 /** @hide */
27056 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
27057 public void setDisabledSystemUiVisibility(int flags) {
27058 if (mAttachInfo != null) {
27059 if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
27060 mAttachInfo.mDisabledSystemUiVisibility = flags;
27061 if (mParent != null) {
27062 mParent.recomputeViewAttributes(this);
27063 }
27064 }
27065 }
27066 }
27067
27068 /**
27069 * This needs to be a better API before it is exposed. For now, only the root view will get
27070 * notified.
27071 * @hide
27072 */
27073 public void onSystemBarAppearanceChanged(@WindowInsetsController.Appearance int appearance) {
27074 }
27075
27076 /**
27077 * Creates an image that the system displays during the drag and drop
27078 * operation. This is called a &quot;drag shadow&quot;. The default implementation
27079 * for a DragShadowBuilder based on a View returns an image that has exactly the same
27080 * appearance as the given View. The default also positions the center of the drag shadow
27081 * directly under the touch point. If no View is provided (the constructor with no parameters
27082 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
27083 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overridden, then the
27084 * default is an invisible drag shadow.
27085 * <p>
27086 * You are not required to use the View you provide to the constructor as the basis of the
27087 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
27088 * anything you want as the drag shadow.
27089 * </p>
27090 * <p>
27091 * You pass a DragShadowBuilder object to the system when you start the drag. The system
27092 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
27093 * size and position of the drag shadow. It uses this data to construct a
27094 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
27095 * so that your application can draw the shadow image in the Canvas.
27096 * </p>
27097 *
27098 * <div class="special reference">
27099 * <h3>Developer Guides</h3>
27100 * <p>For a guide to implementing drag and drop features, read the
27101 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
27102 * </div>
27103 */
27104 public static class DragShadowBuilder {
27105 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
27106 private final WeakReference<View> mView;
27107
27108 /**
27109 * Constructs a shadow image builder based on a View. By default, the resulting drag
27110 * shadow will have the same appearance and dimensions as the View, with the touch point
27111 * over the center of the View.
27112 * @param view A View. Any View in scope can be used.
27113 */
27114 public DragShadowBuilder(View view) {
27115 mView = new WeakReference<View>(view);
27116 }
27117
27118 /**
27119 * Construct a shadow builder object with no associated View. This
27120 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
27121 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
27122 * to supply the drag shadow's dimensions and appearance without
27123 * reference to any View object.
27124 */
27125 public DragShadowBuilder() {
27126 mView = new WeakReference<View>(null);
27127 }
27128
27129 /**
27130 * Returns the View object that had been passed to the
27131 * {@link #DragShadowBuilder(View)}
27132 * constructor. If that View parameter was {@code null} or if the
27133 * {@link #DragShadowBuilder()}
27134 * constructor was used to instantiate the builder object, this method will return
27135 * null.
27136 *
27137 * @return The View object associate with this builder object.
27138 */
27139 @SuppressWarnings({"JavadocReference"})
27140 final public View getView() {
27141 return mView.get();
27142 }
27143
27144 /**
27145 * Provides the metrics for the shadow image. These include the dimensions of
27146 * the shadow image, and the point within that shadow that should
27147 * be centered under the touch location while dragging.
27148 * <p>
27149 * The default implementation sets the dimensions of the shadow to be the
27150 * same as the dimensions of the View itself and centers the shadow under
27151 * the touch point.
27152 * </p>
27153 *
27154 * @param outShadowSize A {@link android.graphics.Point} containing the width and height
27155 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
27156 * desired width and must set {@link android.graphics.Point#y} to the desired height of the
27157 * image. Since Android P, the width and height must be positive values.
27158 *
27159 * @param outShadowTouchPoint A {@link android.graphics.Point} for the position within the
27160 * shadow image that should be underneath the touch point during the drag and drop
27161 * operation. Your application must set {@link android.graphics.Point#x} to the
27162 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
27163 */
27164 public void onProvideShadowMetrics(Point outShadowSize, Point outShadowTouchPoint) {
27165 final View view = mView.get();
27166 if (view != null) {
27167 outShadowSize.set(view.getWidth(), view.getHeight());
27168 outShadowTouchPoint.set(outShadowSize.x / 2, outShadowSize.y / 2);
27169 } else {
27170 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
27171 }
27172 }
27173
27174 /**
27175 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
27176 * based on the dimensions it received from the
27177 * {@link #onProvideShadowMetrics(Point, Point)} callback.
27178 *
27179 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
27180 */
27181 public void onDrawShadow(Canvas canvas) {
27182 final View view = mView.get();
27183 if (view != null) {
27184 view.draw(canvas);
27185 } else {
27186 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
27187 }
27188 }
27189 }
27190
27191 /**
27192 * @deprecated Use {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)
27193 * startDragAndDrop()} for newer platform versions.
27194 */
27195 @Deprecated
27196 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
27197 Object myLocalState, int flags) {
27198 return startDragAndDrop(data, shadowBuilder, myLocalState, flags);
27199 }
27200
27201 /**
27202 * Starts a drag and drop operation. When your application calls this method, it passes a
27203 * {@link android.view.View.DragShadowBuilder} object to the system. The
27204 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
27205 * to get metrics for the drag shadow, and then calls the object's
27206 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
27207 * <p>
27208 * Once the system has the drag shadow, it begins the drag and drop operation by sending
27209 * drag events to all the View objects in your application that are currently visible. It does
27210 * this either by calling the View object's drag listener (an implementation of
27211 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
27212 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
27213 * Both are passed a {@link android.view.DragEvent} object that has a
27214 * {@link android.view.DragEvent#getAction()} value of
27215 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
27216 * </p>
27217 * <p>
27218 * Your application can invoke {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object,
27219 * int) startDragAndDrop()} on any attached View object. The View object does not need to be
27220 * the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to be related
27221 * to the View the user selected for dragging.
27222 * </p>
27223 * @param data A {@link android.content.ClipData} object pointing to the data to be
27224 * transferred by the drag and drop operation.
27225 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
27226 * drag shadow.
27227 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
27228 * drop operation. When dispatching drag events to views in the same activity this object
27229 * will be available through {@link android.view.DragEvent#getLocalState()}. Views in other
27230 * activities will not have access to this data ({@link android.view.DragEvent#getLocalState()}
27231 * will return null).
27232 * <p>
27233 * myLocalState is a lightweight mechanism for the sending information from the dragged View
27234 * to the target Views. For example, it can contain flags that differentiate between a
27235 * a copy operation and a move operation.
27236 * </p>
27237 * @param flags Flags that control the drag and drop operation. This can be set to 0 for no
27238 * flags, or any combination of the following:
27239 * <ul>
27240 * <li>{@link #DRAG_FLAG_GLOBAL}</li>
27241 * <li>{@link #DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION}</li>
27242 * <li>{@link #DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION}</li>
27243 * <li>{@link #DRAG_FLAG_GLOBAL_URI_READ}</li>
27244 * <li>{@link #DRAG_FLAG_GLOBAL_URI_WRITE}</li>
27245 * <li>{@link #DRAG_FLAG_OPAQUE}</li>
27246 * <li>{@link #DRAG_FLAG_ACCESSIBILITY_ACTION}</li>
27247 * </ul>
27248 * @return {@code true} if the method completes successfully, or
27249 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
27250 * do a drag because of another ongoing operation or some other reasons.
27251 */
27252 public final boolean startDragAndDrop(ClipData data, DragShadowBuilder shadowBuilder,
27253 Object myLocalState, int flags) {
27254 if (ViewDebug.DEBUG_DRAG) {
27255 Log.d(VIEW_LOG_TAG, "startDragAndDrop: data=" + data + " flags=" + flags);
27256 }
27257 if (mAttachInfo == null) {
27258 Log.w(VIEW_LOG_TAG, "startDragAndDrop called on a detached view.");
27259 return false;
27260 }
27261 if (!mAttachInfo.mViewRootImpl.mSurface.isValid()) {
27262 Log.w(VIEW_LOG_TAG, "startDragAndDrop called with an invalid surface.");
27263 return false;
27264 }
27265
27266 if (data != null) {
27267 data.prepareToLeaveProcess((flags & View.DRAG_FLAG_GLOBAL) != 0);
27268 }
27269
27270 Rect bounds = new Rect();
27271 getBoundsOnScreen(bounds, true);
27272
27273 Point lastTouchPoint = new Point();
27274 mAttachInfo.mViewRootImpl.getLastTouchPoint(lastTouchPoint);
27275 final ViewRootImpl root = mAttachInfo.mViewRootImpl;
27276
27277 // Skip surface logic since shadows and animation are not required during the a11y drag
27278 final boolean a11yEnabled = AccessibilityManager.getInstance(mContext).isEnabled();
27279 if (a11yEnabled && (flags & View.DRAG_FLAG_ACCESSIBILITY_ACTION) != 0) {
27280 try {
27281 IBinder token = mAttachInfo.mSession.performDrag(
27282 mAttachInfo.mWindow, flags, null,
27283 mAttachInfo.mViewRootImpl.getLastTouchSource(),
27284 0f, 0f, 0f, 0f, data);
27285 if (ViewDebug.DEBUG_DRAG) {
27286 Log.d(VIEW_LOG_TAG, "startDragAndDrop via a11y action returned " + token);
27287 }
27288 if (token != null) {
27289 root.setLocalDragState(myLocalState);
27290 mAttachInfo.mDragToken = token;
27291 mAttachInfo.mViewRootImpl.setDragStartedViewForAccessibility(this);
27292 setAccessibilityDragStarted(true);
27293 }
27294 return token != null;
27295 } catch (Exception e) {
27296 Log.e(VIEW_LOG_TAG, "Unable to initiate a11y drag", e);
27297 return false;
27298 }
27299 }
27300
27301 Point shadowSize = new Point();
27302 Point shadowTouchPoint = new Point();
27303 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
27304
27305 if ((shadowSize.x < 0) || (shadowSize.y < 0)
27306 || (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
27307 throw new IllegalStateException("Drag shadow dimensions must not be negative");
27308 }
27309
27310 // Create 1x1 surface when zero surface size is specified because SurfaceControl.Builder
27311 // does not accept zero size surface.
27312 if (shadowSize.x == 0 || shadowSize.y == 0) {
27313 if (!sAcceptZeroSizeDragShadow) {
27314 throw new IllegalStateException("Drag shadow dimensions must be positive");
27315 }
27316 shadowSize.x = 1;
27317 shadowSize.y = 1;
27318 }
27319
27320 if (ViewDebug.DEBUG_DRAG) {
27321 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
27322 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
27323 }
27324
27325 final SurfaceSession session = new SurfaceSession();
27326 final SurfaceControl surfaceControl = new SurfaceControl.Builder(session)
27327 .setName("drag surface")
27328 .setParent(root.getSurfaceControl())
27329 .setBufferSize(shadowSize.x, shadowSize.y)
27330 .setFormat(PixelFormat.TRANSLUCENT)
27331 .setCallsite("View.startDragAndDrop")
27332 .build();
27333 final Surface surface = new Surface();
27334 surface.copyFrom(surfaceControl);
27335 IBinder token = null;
27336 try {
27337 final Canvas canvas = isHardwareAccelerated()
27338 ? surface.lockHardwareCanvas()
27339 : surface.lockCanvas(null);
27340 try {
27341 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
27342 shadowBuilder.onDrawShadow(canvas);
27343 } finally {
27344 surface.unlockCanvasAndPost(canvas);
27345 }
27346
27347 token = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, flags, surfaceControl,
27348 root.getLastTouchSource(), lastTouchPoint.x, lastTouchPoint.y,
27349 shadowTouchPoint.x, shadowTouchPoint.y, data);
27350 if (ViewDebug.DEBUG_DRAG) {
27351 Log.d(VIEW_LOG_TAG, "performDrag returned " + token);
27352 }
27353 if (token != null) {
27354 if (mAttachInfo.mDragSurface != null) {
27355 mAttachInfo.mDragSurface.release();
27356 }
27357 mAttachInfo.mDragSurface = surface;
27358 mAttachInfo.mDragToken = token;
27359 // Cache the local state object for delivery with DragEvents
27360 root.setLocalDragState(myLocalState);
27361 if (a11yEnabled) {
27362 // Set for AccessibilityEvents
27363 mAttachInfo.mViewRootImpl.setDragStartedViewForAccessibility(this);
27364 }
27365 }
27366 return token != null;
27367 } catch (Exception e) {
27368 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
27369 return false;
27370 } finally {
27371 if (token == null) {
27372 surface.destroy();
27373 }
27374 session.kill();
27375 }
27376 }
27377
27378 void setAccessibilityDragStarted(boolean started) {
27379 int pflags4 = mPrivateFlags4;
27380 if (started) {
27381 pflags4 |= PFLAG4_DRAG_A11Y_STARTED;
27382 } else {
27383 pflags4 &= ~PFLAG4_DRAG_A11Y_STARTED;
27384 }
27385
27386 if (pflags4 != mPrivateFlags4) {
27387 mPrivateFlags4 = pflags4;
27388 sendWindowContentChangedAccessibilityEvent(CONTENT_CHANGE_TYPE_UNDEFINED);
27389 }
27390 }
27391
27392 private boolean startedSystemDragForAccessibility() {
27393 return (mPrivateFlags4 & PFLAG4_DRAG_A11Y_STARTED) != 0;
27394 }
27395
27396 /**
27397 * Cancels an ongoing drag and drop operation.
27398 * <p>
27399 * A {@link android.view.DragEvent} object with
27400 * {@link android.view.DragEvent#getAction()} value of
27401 * {@link android.view.DragEvent#ACTION_DRAG_ENDED} and
27402 * {@link android.view.DragEvent#getResult()} value of {@code false}
27403 * will be sent to every
27404 * View that received {@link android.view.DragEvent#ACTION_DRAG_STARTED}
27405 * even if they are not currently visible.
27406 * </p>
27407 * <p>
27408 * This method can be called on any View in the same window as the View on which
27409 * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int) startDragAndDrop}
27410 * was called.
27411 * </p>
27412 */
27413 public final void cancelDragAndDrop() {
27414 if (ViewDebug.DEBUG_DRAG) {
27415 Log.d(VIEW_LOG_TAG, "cancelDragAndDrop");
27416 }
27417 if (mAttachInfo == null) {
27418 Log.w(VIEW_LOG_TAG, "cancelDragAndDrop called on a detached view.");
27419 return;
27420 }
27421 if (mAttachInfo.mDragToken != null) {
27422 try {
27423 mAttachInfo.mSession.cancelDragAndDrop(mAttachInfo.mDragToken, false);
27424 } catch (Exception e) {
27425 Log.e(VIEW_LOG_TAG, "Unable to cancel drag", e);
27426 }
27427 mAttachInfo.mDragToken = null;
27428 } else {
27429 Log.e(VIEW_LOG_TAG, "No active drag to cancel");
27430 }
27431 }
27432
27433 /**
27434 * Updates the drag shadow for the ongoing drag and drop operation.
27435 *
27436 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
27437 * new drag shadow.
27438 */
27439 public final void updateDragShadow(DragShadowBuilder shadowBuilder) {
27440 if (ViewDebug.DEBUG_DRAG) {
27441 Log.d(VIEW_LOG_TAG, "updateDragShadow");
27442 }
27443 if (mAttachInfo == null) {
27444 Log.w(VIEW_LOG_TAG, "updateDragShadow called on a detached view.");
27445 return;
27446 }
27447 if (mAttachInfo.mDragToken != null) {
27448 try {
27449 Canvas canvas = isHardwareAccelerated()
27450 ? mAttachInfo.mDragSurface.lockHardwareCanvas()
27451 : mAttachInfo.mDragSurface.lockCanvas(null);
27452 try {
27453 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
27454 shadowBuilder.onDrawShadow(canvas);
27455 } finally {
27456 mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas);
27457 }
27458 } catch (Exception e) {
27459 Log.e(VIEW_LOG_TAG, "Unable to update drag shadow", e);
27460 }
27461 } else {
27462 Log.e(VIEW_LOG_TAG, "No active drag");
27463 }
27464 }
27465
27466 /**
27467 * Starts a move from {startX, startY}, the amount of the movement will be the offset
27468 * between {startX, startY} and the new cursor positon.
27469 * @param startX horizontal coordinate where the move started.
27470 * @param startY vertical coordinate where the move started.
27471 * @return whether moving was started successfully.
27472 * @hide
27473 */
27474 public final boolean startMovingTask(float startX, float startY) {
27475 if (ViewDebug.DEBUG_POSITIONING) {
27476 Log.d(VIEW_LOG_TAG, "startMovingTask: {" + startX + "," + startY + "}");
27477 }
27478 try {
27479 return mAttachInfo.mSession.startMovingTask(mAttachInfo.mWindow, startX, startY);
27480 } catch (RemoteException e) {
27481 Log.e(VIEW_LOG_TAG, "Unable to start moving", e);
27482 }
27483 return false;
27484 }
27485
27486 /**
27487 * Finish a window move task.
27488 * @hide
27489 */
27490 public void finishMovingTask() {
27491 if (ViewDebug.DEBUG_POSITIONING) {
27492 Log.d(VIEW_LOG_TAG, "finishMovingTask");
27493 }
27494 try {
27495 mAttachInfo.mSession.finishMovingTask(mAttachInfo.mWindow);
27496 } catch (RemoteException e) {
27497 Log.e(VIEW_LOG_TAG, "Unable to finish moving", e);
27498 }
27499 }
27500
27501 /**
27502 * Handles drag events sent by the system following a call to
27503 * {@link android.view.View#startDragAndDrop(ClipData,DragShadowBuilder,Object,int)
27504 * startDragAndDrop()}.
27505 * <p>
27506 * The system calls this method and passes a {@link DragEvent} object in response to drag and
27507 * drop events. This method can then call {@link DragEvent#getAction()} to determine the state
27508 * of the drag and drop operation.
27509 * <p>
27510 * The default implementation returns {@code false} unless an {@link OnReceiveContentListener}
27511 * has been set for this view (see {@link #setOnReceiveContentListener}), in which case
27512 * the default implementation does the following:
27513 * <ul>
27514 * <li>Returns {@code true} for an
27515 * {@link DragEvent#ACTION_DRAG_STARTED ACTION_DRAG_STARTED} event
27516 * <li>Calls {@link #performReceiveContent} for an
27517 * {@link DragEvent#ACTION_DROP ACTION_DROP} event
27518 * <li>Returns {@code true} for an {@link DragEvent#ACTION_DROP ACTION_DROP} event if the
27519 * {@code OnReceiveContentListener} consumed some or all of the content
27520 * </ul>
27521 *
27522 * @param event The {@link DragEvent} object sent by the system. The
27523 * {@link DragEvent#getAction()} method returns an action type constant that indicates the
27524 * type of drag event represented by this object.
27525 * @return {@code true} if the method successfully handled the drag event, otherwise
27526 * {@code false}.
27527 * <p>
27528 * The method must return {@code true} in response to an
27529 * {@link DragEvent#ACTION_DRAG_STARTED ACTION_DRAG_STARTED} action type to continue to
27530 * receive drag events for the current drag and drop operation.
27531 * <p>
27532 * The method should return {@code true} in response to an
27533 * {@link DragEvent#ACTION_DROP ACTION_DROP} action type if the dropped data was consumed
27534 * (at least partially); {@code false}, if none of the data was consumed.
27535 * <p>
27536 * For all other events, the return value is {@code false}.
27537 */
27538 public boolean onDragEvent(DragEvent event) {
27539 if (mListenerInfo == null || mListenerInfo.mOnReceiveContentListener == null) {
27540 return false;
27541 }
27542 // Accept drag events by default if there's an OnReceiveContentListener set.
27543 if (event.getAction() == DragEvent.ACTION_DRAG_STARTED) {
27544 return true;
27545 }
27546 if (event.getAction() == DragEvent.ACTION_DROP) {
27547 final DragAndDropPermissions permissions = DragAndDropPermissions.obtain(event);
27548 if (permissions != null) {
27549 permissions.takeTransient();
27550 }
27551 final ContentInfo payload =
27552 new ContentInfo.Builder(event.getClipData(), SOURCE_DRAG_AND_DROP)
27553 .setDragAndDropPermissions(permissions)
27554 .build();
27555 ContentInfo remainingPayload = performReceiveContent(payload);
27556 // Return true unless none of the payload was consumed.
27557 return remainingPayload != payload;
27558 }
27559 return false;
27560 }
27561
27562 // Dispatches ACTION_DRAG_ENTERED and ACTION_DRAG_EXITED events for pre-Nougat apps.
27563 boolean dispatchDragEnterExitInPreN(DragEvent event) {
27564 return callDragEventHandler(event);
27565 }
27566
27567 /**
27568 * Detects if this View is enabled and has a drag event listener.
27569 * If both are true, then it calls the drag event listener with the
27570 * {@link android.view.DragEvent} it received. If the drag event listener returns
27571 * {@code true}, then dispatchDragEvent() returns {@code true}.
27572 * <p>
27573 * For all other cases, the method calls the
27574 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
27575 * method and returns its result.
27576 * </p>
27577 * <p>
27578 * This ensures that a drag event is always consumed, even if the View does not have a drag
27579 * event listener. However, if the View has a listener and the listener returns true, then
27580 * onDragEvent() is not called.
27581 * </p>
27582 */
27583 public boolean dispatchDragEvent(DragEvent event) {
27584 event.mEventHandlerWasCalled = true;
27585 if (event.mAction == DragEvent.ACTION_DRAG_LOCATION ||
27586 event.mAction == DragEvent.ACTION_DROP) {
27587 // About to deliver an event with coordinates to this view. Notify that now this view
27588 // has drag focus. This will send exit/enter events as needed.
27589 getViewRootImpl().setDragFocus(this, event);
27590 }
27591 return callDragEventHandler(event);
27592 }
27593
27594 final boolean callDragEventHandler(DragEvent event) {
27595 final boolean result;
27596
27597 ListenerInfo li = mListenerInfo;
27598 //noinspection SimplifiableIfStatement
27599 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
27600 && li.mOnDragListener.onDrag(this, event)) {
27601 result = true;
27602 } else {
27603 result = onDragEvent(event);
27604 }
27605
27606 switch (event.mAction) {
27607 case DragEvent.ACTION_DRAG_STARTED: {
27608 if (result && li != null && li.mOnDragListener != null) {
27609 sendWindowContentChangedAccessibilityEvent(
27610 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
27611 }
27612 } break;
27613 case DragEvent.ACTION_DRAG_ENTERED: {
27614 mPrivateFlags2 |= View.PFLAG2_DRAG_HOVERED;
27615 refreshDrawableState();
27616 } break;
27617 case DragEvent.ACTION_DRAG_EXITED: {
27618 mPrivateFlags2 &= ~View.PFLAG2_DRAG_HOVERED;
27619 refreshDrawableState();
27620 } break;
27621 case DragEvent.ACTION_DROP: {
27622 if (result && li != null && (li.mOnDragListener != null
27623 || li.mOnReceiveContentListener != null)) {
27624 sendWindowContentChangedAccessibilityEvent(
27625 AccessibilityEvent.CONTENT_CHANGE_TYPE_DRAG_DROPPED);
27626 }
27627 } break;
27628 case DragEvent.ACTION_DRAG_ENDED: {
27629 sendWindowContentChangedAccessibilityEvent(
27630 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
27631 mPrivateFlags2 &= ~View.DRAG_MASK;
27632 refreshDrawableState();
27633 } break;
27634 }
27635
27636 return result;
27637 }
27638
27639 boolean canAcceptDrag() {
27640 return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
27641 }
27642
27643 void sendWindowContentChangedAccessibilityEvent(int changeType) {
27644 if (AccessibilityManager.getInstance(mContext).isEnabled()) {
27645 AccessibilityEvent event = AccessibilityEvent.obtain();
27646 event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
27647 event.setContentChangeTypes(changeType);
27648 sendAccessibilityEventUnchecked(event);
27649 }
27650 }
27651
27652 /**
27653 * This needs to be a better API (NOT ON VIEW) before it is exposed. If
27654 * it is ever exposed at all.
27655 * @hide
27656 */
27657 @UnsupportedAppUsage
27658 public void onCloseSystemDialogs(String reason) {
27659 }
27660
27661 /**
27662 * Given a Drawable whose bounds have been set to draw into this view,
27663 * update a Region being computed for
27664 * {@link #gatherTransparentRegion(android.graphics.Region)} so
27665 * that any non-transparent parts of the Drawable are removed from the
27666 * given transparent region.
27667 *
27668 * @param dr The Drawable whose transparency is to be applied to the region.
27669 * @param region A Region holding the current transparency information,
27670 * where any parts of the region that are set are considered to be
27671 * transparent. On return, this region will be modified to have the
27672 * transparency information reduced by the corresponding parts of the
27673 * Drawable that are not transparent.
27674 * {@hide}
27675 */
27676 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
27677 public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
27678 if (DBG) {
27679 Log.i("View", "Getting transparent region for: " + this);
27680 }
27681 final Region r = dr.getTransparentRegion();
27682 final Rect db = dr.getBounds();
27683 final AttachInfo attachInfo = mAttachInfo;
27684 if (r != null && attachInfo != null) {
27685 final int w = getRight()-getLeft();
27686 final int h = getBottom()-getTop();
27687 if (db.left > 0) {
27688 //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
27689 r.op(0, 0, db.left, h, Region.Op.UNION);
27690 }
27691 if (db.right < w) {
27692 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
27693 r.op(db.right, 0, w, h, Region.Op.UNION);
27694 }
27695 if (db.top > 0) {
27696 //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
27697 r.op(0, 0, w, db.top, Region.Op.UNION);
27698 }
27699 if (db.bottom < h) {
27700 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
27701 r.op(0, db.bottom, w, h, Region.Op.UNION);
27702 }
27703 final int[] location = attachInfo.mTransparentLocation;
27704 getLocationInWindow(location);
27705 r.translate(location[0], location[1]);
27706 region.op(r, Region.Op.INTERSECT);
27707 } else {
27708 region.op(db, Region.Op.DIFFERENCE);
27709 }
27710 }
27711
27712 private void checkForLongClick(long delay, float x, float y, int classification) {
27713 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE || (mViewFlags & TOOLTIP) == TOOLTIP) {
27714 mHasPerformedLongPress = false;
27715
27716 if (mPendingCheckForLongPress == null) {
27717 mPendingCheckForLongPress = new CheckForLongPress();
27718 }
27719 mPendingCheckForLongPress.setAnchor(x, y);
27720 mPendingCheckForLongPress.rememberWindowAttachCount();
27721 mPendingCheckForLongPress.rememberPressedState();
27722 mPendingCheckForLongPress.setClassification(classification);
27723 postDelayed(mPendingCheckForLongPress, delay);
27724 }
27725 }
27726
27727 /**
27728 * Inflate a view from an XML resource. This convenience method wraps the {@link
27729 * LayoutInflater} class, which provides a full range of options for view inflation.
27730 *
27731 * @param context The Context object for your activity or application.
27732 * @param resource The resource ID to inflate
27733 * @param root A view group that will be the parent. Used to properly inflate the
27734 * layout_* parameters.
27735 * @see LayoutInflater
27736 */
27737 public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
27738 LayoutInflater factory = LayoutInflater.from(context);
27739 return factory.inflate(resource, root);
27740 }
27741
27742 /**
27743 * Scroll the view with standard behavior for scrolling beyond the normal
27744 * content boundaries. Views that call this method should override
27745 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
27746 * results of an over-scroll operation.
27747 *
27748 * Views can use this method to handle any touch or fling-based scrolling.
27749 *
27750 * @param deltaX Change in X in pixels
27751 * @param deltaY Change in Y in pixels
27752 * @param scrollX Current X scroll value in pixels before applying deltaX
27753 * @param scrollY Current Y scroll value in pixels before applying deltaY
27754 * @param scrollRangeX Maximum content scroll range along the X axis
27755 * @param scrollRangeY Maximum content scroll range along the Y axis
27756 * @param maxOverScrollX Number of pixels to overscroll by in either direction
27757 * along the X axis.
27758 * @param maxOverScrollY Number of pixels to overscroll by in either direction
27759 * along the Y axis.
27760 * @param isTouchEvent true if this scroll operation is the result of a touch event.
27761 * @return true if scrolling was clamped to an over-scroll boundary along either
27762 * axis, false otherwise.
27763 */
27764 @SuppressWarnings({"UnusedParameters"})
27765 protected boolean overScrollBy(int deltaX, int deltaY,
27766 int scrollX, int scrollY,
27767 int scrollRangeX, int scrollRangeY,
27768 int maxOverScrollX, int maxOverScrollY,
27769 boolean isTouchEvent) {
27770 final int overScrollMode = mOverScrollMode;
27771 final boolean canScrollHorizontal =
27772 computeHorizontalScrollRange() > computeHorizontalScrollExtent();
27773 final boolean canScrollVertical =
27774 computeVerticalScrollRange() > computeVerticalScrollExtent();
27775 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
27776 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
27777 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
27778 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
27779
27780 int newScrollX = scrollX + deltaX;
27781 if (!overScrollHorizontal) {
27782 maxOverScrollX = 0;
27783 }
27784
27785 int newScrollY = scrollY + deltaY;
27786 if (!overScrollVertical) {
27787 maxOverScrollY = 0;
27788 }
27789
27790 // Clamp values if at the limits and record
27791 final int left = -maxOverScrollX;
27792 final int right = maxOverScrollX + scrollRangeX;
27793 final int top = -maxOverScrollY;
27794 final int bottom = maxOverScrollY + scrollRangeY;
27795
27796 boolean clampedX = false;
27797 if (newScrollX > right) {
27798 newScrollX = right;
27799 clampedX = true;
27800 } else if (newScrollX < left) {
27801 newScrollX = left;
27802 clampedX = true;
27803 }
27804
27805 boolean clampedY = false;
27806 if (newScrollY > bottom) {
27807 newScrollY = bottom;
27808 clampedY = true;
27809 } else if (newScrollY < top) {
27810 newScrollY = top;
27811 clampedY = true;
27812 }
27813
27814 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
27815
27816 return clampedX || clampedY;
27817 }
27818
27819 /**
27820 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
27821 * respond to the results of an over-scroll operation.
27822 *
27823 * @param scrollX New X scroll value in pixels
27824 * @param scrollY New Y scroll value in pixels
27825 * @param clampedX True if scrollX was clamped to an over-scroll boundary
27826 * @param clampedY True if scrollY was clamped to an over-scroll boundary
27827 */
27828 protected void onOverScrolled(int scrollX, int scrollY,
27829 boolean clampedX, boolean clampedY) {
27830 // Intentionally empty.
27831 }
27832
27833 /**
27834 * Returns the over-scroll mode for this view. The result will be
27835 * one of {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
27836 * (allow over-scrolling only if the view content is larger than the container),
27837 * or {@link #OVER_SCROLL_NEVER}.
27838 *
27839 * @return This view's over-scroll mode.
27840 */
27841 @InspectableProperty(enumMapping = {
27842 @EnumEntry(value = OVER_SCROLL_ALWAYS, name = "always"),
27843 @EnumEntry(value = OVER_SCROLL_IF_CONTENT_SCROLLS, name = "ifContentScrolls"),
27844 @EnumEntry(value = OVER_SCROLL_NEVER, name = "never")
27845 })
27846 public int getOverScrollMode() {
27847 return mOverScrollMode;
27848 }
27849
27850 /**
27851 * Set the over-scroll mode for this view. Valid over-scroll modes are
27852 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
27853 * (allow over-scrolling only if the view content is larger than the container),
27854 * or {@link #OVER_SCROLL_NEVER}.
27855 *
27856 * Setting the over-scroll mode of a view will have an effect only if the
27857 * view is capable of scrolling.
27858 *
27859 * @param overScrollMode The new over-scroll mode for this view.
27860 */
27861 public void setOverScrollMode(int overScrollMode) {
27862 if (overScrollMode != OVER_SCROLL_ALWAYS &&
27863 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
27864 overScrollMode != OVER_SCROLL_NEVER) {
27865 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
27866 }
27867 mOverScrollMode = overScrollMode;
27868 }
27869
27870 /**
27871 * Enable or disable nested scrolling for this view.
27872 *
27873 * <p>If this property is set to true the view will be permitted to initiate nested
27874 * scrolling operations with a compatible parent view in the current hierarchy. If this
27875 * view does not implement nested scrolling this will have no effect. Disabling nested scrolling
27876 * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping}
27877 * the nested scroll.</p>
27878 *
27879 * @param enabled true to enable nested scrolling, false to disable
27880 *
27881 * @see #isNestedScrollingEnabled()
27882 */
27883 public void setNestedScrollingEnabled(boolean enabled) {
27884 if (enabled) {
27885 mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED;
27886 } else {
27887 stopNestedScroll();
27888 mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED;
27889 }
27890 }
27891
27892 /**
27893 * Returns true if nested scrolling is enabled for this view.
27894 *
27895 * <p>If nested scrolling is enabled and this View class implementation supports it,
27896 * this view will act as a nested scrolling child view when applicable, forwarding data
27897 * about the scroll operation in progress to a compatible and cooperating nested scrolling
27898 * parent.</p>
27899 *
27900 * @return true if nested scrolling is enabled
27901 *
27902 * @see #setNestedScrollingEnabled(boolean)
27903 */
27904 @InspectableProperty
27905 public boolean isNestedScrollingEnabled() {
27906 return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) ==
27907 PFLAG3_NESTED_SCROLLING_ENABLED;
27908 }
27909
27910 /**
27911 * Begin a nestable scroll operation along the given axes.
27912 *
27913 * <p>A view starting a nested scroll promises to abide by the following contract:</p>
27914 *
27915 * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case
27916 * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}.
27917 * In the case of touch scrolling the nested scroll will be terminated automatically in
27918 * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}.
27919 * In the event of programmatic scrolling the caller must explicitly call
27920 * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p>
27921 *
27922 * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found.
27923 * If it returns false the caller may ignore the rest of this contract until the next scroll.
27924 * Calling startNestedScroll while a nested scroll is already in progress will return true.</p>
27925 *
27926 * <p>At each incremental step of the scroll the caller should invoke
27927 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll}
27928 * once it has calculated the requested scrolling delta. If it returns true the nested scrolling
27929 * parent at least partially consumed the scroll and the caller should adjust the amount it
27930 * scrolls by.</p>
27931 *
27932 * <p>After applying the remainder of the scroll delta the caller should invoke
27933 * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing
27934 * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat
27935 * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}.
27936 * </p>
27937 *
27938 * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or
27939 * {@link #SCROLL_AXIS_VERTICAL}.
27940 * @return true if a cooperative parent was found and nested scrolling has been enabled for
27941 * the current gesture.
27942 *
27943 * @see #stopNestedScroll()
27944 * @see #dispatchNestedPreScroll(int, int, int[], int[])
27945 * @see #dispatchNestedScroll(int, int, int, int, int[])
27946 */
27947 public boolean startNestedScroll(int axes) {
27948 if (hasNestedScrollingParent()) {
27949 // Already in progress
27950 return true;
27951 }
27952 if (isNestedScrollingEnabled()) {
27953 ViewParent p = getParent();
27954 View child = this;
27955 while (p != null) {
27956 try {
27957 if (p.onStartNestedScroll(child, this, axes)) {
27958 mNestedScrollingParent = p;
27959 p.onNestedScrollAccepted(child, this, axes);
27960 return true;
27961 }
27962 } catch (AbstractMethodError e) {
27963 Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " +
27964 "method onStartNestedScroll", e);
27965 // Allow the search upward to continue
27966 }
27967 if (p instanceof View) {
27968 child = (View) p;
27969 }
27970 p = p.getParent();
27971 }
27972 }
27973 return false;
27974 }
27975
27976 /**
27977 * Stop a nested scroll in progress.
27978 *
27979 * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p>
27980 *
27981 * @see #startNestedScroll(int)
27982 */
27983 public void stopNestedScroll() {
27984 if (mNestedScrollingParent != null) {
27985 mNestedScrollingParent.onStopNestedScroll(this);
27986 mNestedScrollingParent = null;
27987 }
27988 }
27989
27990 /**
27991 * Returns true if this view has a nested scrolling parent.
27992 *
27993 * <p>The presence of a nested scrolling parent indicates that this view has initiated
27994 * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p>
27995 *
27996 * @return whether this view has a nested scrolling parent
27997 */
27998 public boolean hasNestedScrollingParent() {
27999 return mNestedScrollingParent != null;
28000 }
28001
28002 /**
28003 * Dispatch one step of a nested scroll in progress.
28004 *
28005 * <p>Implementations of views that support nested scrolling should call this to report
28006 * info about a scroll in progress to the current nested scrolling parent. If a nested scroll
28007 * is not currently in progress or nested scrolling is not
28008 * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p>
28009 *
28010 * <p>Compatible View implementations should also call
28011 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before
28012 * consuming a component of the scroll event themselves.</p>
28013 *
28014 * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step
28015 * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step
28016 * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view
28017 * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view
28018 * @param offsetInWindow Optional. If not null, on return this will contain the offset
28019 * in local view coordinates of this view from before this operation
28020 * to after it completes. View implementations may use this to adjust
28021 * expected input coordinate tracking.
28022 * @return true if the event was dispatched, false if it could not be dispatched.
28023 * @see #dispatchNestedPreScroll(int, int, int[], int[])
28024 */
28025 public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed,
28026 int dxUnconsumed, int dyUnconsumed, @Nullable @Size(2) int[] offsetInWindow) {
28027 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
28028 if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) {
28029 int startX = 0;
28030 int startY = 0;
28031 if (offsetInWindow != null) {
28032 getLocationInWindow(offsetInWindow);
28033 startX = offsetInWindow[0];
28034 startY = offsetInWindow[1];
28035 }
28036
28037 mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed,
28038 dxUnconsumed, dyUnconsumed);
28039
28040 if (offsetInWindow != null) {
28041 getLocationInWindow(offsetInWindow);
28042 offsetInWindow[0] -= startX;
28043 offsetInWindow[1] -= startY;
28044 }
28045 return true;
28046 } else if (offsetInWindow != null) {
28047 // No motion, no dispatch. Keep offsetInWindow up to date.
28048 offsetInWindow[0] = 0;
28049 offsetInWindow[1] = 0;
28050 }
28051 }
28052 return false;
28053 }
28054
28055 /**
28056 * Dispatch one step of a nested scroll in progress before this view consumes any portion of it.
28057 *
28058 * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch.
28059 * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested
28060 * scrolling operation to consume some or all of the scroll operation before the child view
28061 * consumes it.</p>
28062 *
28063 * @param dx Horizontal scroll distance in pixels
28064 * @param dy Vertical scroll distance in pixels
28065 * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx
28066 * and consumed[1] the consumed dy.
28067 * @param offsetInWindow Optional. If not null, on return this will contain the offset
28068 * in local view coordinates of this view from before this operation
28069 * to after it completes. View implementations may use this to adjust
28070 * expected input coordinate tracking.
28071 * @return true if the parent consumed some or all of the scroll delta
28072 * @see #dispatchNestedScroll(int, int, int, int, int[])
28073 */
28074 public boolean dispatchNestedPreScroll(int dx, int dy,
28075 @Nullable @Size(2) int[] consumed, @Nullable @Size(2) int[] offsetInWindow) {
28076 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
28077 if (dx != 0 || dy != 0) {
28078 int startX = 0;
28079 int startY = 0;
28080 if (offsetInWindow != null) {
28081 getLocationInWindow(offsetInWindow);
28082 startX = offsetInWindow[0];
28083 startY = offsetInWindow[1];
28084 }
28085
28086 if (consumed == null) {
28087 if (mTempNestedScrollConsumed == null) {
28088 mTempNestedScrollConsumed = new int[2];
28089 }
28090 consumed = mTempNestedScrollConsumed;
28091 }
28092 consumed[0] = 0;
28093 consumed[1] = 0;
28094 mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed);
28095
28096 if (offsetInWindow != null) {
28097 getLocationInWindow(offsetInWindow);
28098 offsetInWindow[0] -= startX;
28099 offsetInWindow[1] -= startY;
28100 }
28101 return consumed[0] != 0 || consumed[1] != 0;
28102 } else if (offsetInWindow != null) {
28103 offsetInWindow[0] = 0;
28104 offsetInWindow[1] = 0;
28105 }
28106 }
28107 return false;
28108 }
28109
28110 /**
28111 * Dispatch a fling to a nested scrolling parent.
28112 *
28113 * <p>This method should be used to indicate that a nested scrolling child has detected
28114 * suitable conditions for a fling. Generally this means that a touch scroll has ended with a
28115 * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds
28116 * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity}
28117 * along a scrollable axis.</p>
28118 *
28119 * <p>If a nested scrolling child view would normally fling but it is at the edge of
28120 * its own content, it can use this method to delegate the fling to its nested scrolling
28121 * parent instead. The parent may optionally consume the fling or observe a child fling.</p>
28122 *
28123 * @param velocityX Horizontal fling velocity in pixels per second
28124 * @param velocityY Vertical fling velocity in pixels per second
28125 * @param consumed true if the child consumed the fling, false otherwise
28126 * @return true if the nested scrolling parent consumed or otherwise reacted to the fling
28127 */
28128 public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
28129 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
28130 return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed);
28131 }
28132 return false;
28133 }
28134
28135 /**
28136 * Dispatch a fling to a nested scrolling parent before it is processed by this view.
28137 *
28138 * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch
28139 * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code>
28140 * offsets an opportunity for the parent view in a nested fling to fully consume the fling
28141 * before the child view consumes it. If this method returns <code>true</code>, a nested
28142 * parent view consumed the fling and this view should not scroll as a result.</p>
28143 *
28144 * <p>For a better user experience, only one view in a nested scrolling chain should consume
28145 * the fling at a time. If a parent view consumed the fling this method will return false.
28146 * Custom view implementations should account for this in two ways:</p>
28147 *
28148 * <ul>
28149 * <li>If a custom view is paged and needs to settle to a fixed page-point, do not
28150 * call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid
28151 * position regardless.</li>
28152 * <li>If a nested parent does consume the fling, this view should not scroll at all,
28153 * even to settle back to a valid idle position.</li>
28154 * </ul>
28155 *
28156 * <p>Views should also not offer fling velocities to nested parent views along an axis
28157 * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView}
28158 * should not offer a horizontal fling velocity to its parents since scrolling along that
28159 * axis is not permitted and carrying velocity along that motion does not make sense.</p>
28160 *
28161 * @param velocityX Horizontal fling velocity in pixels per second
28162 * @param velocityY Vertical fling velocity in pixels per second
28163 * @return true if a nested scrolling parent consumed the fling
28164 */
28165 public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
28166 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
28167 return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY);
28168 }
28169 return false;
28170 }
28171
28172 /**
28173 * Gets a scale factor that determines the distance the view should scroll
28174 * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
28175 * @return The vertical scroll scale factor.
28176 * @hide
28177 */
28178 @UnsupportedAppUsage
28179 protected float getVerticalScrollFactor() {
28180 if (mVerticalScrollFactor == 0) {
28181 TypedValue outValue = new TypedValue();
28182 if (!mContext.getTheme().resolveAttribute(
28183 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
28184 throw new IllegalStateException(
28185 "Expected theme to define listPreferredItemHeight.");
28186 }
28187 mVerticalScrollFactor = outValue.getDimension(
28188 mContext.getResources().getDisplayMetrics());
28189 }
28190 return mVerticalScrollFactor;
28191 }
28192
28193 /**
28194 * Gets a scale factor that determines the distance the view should scroll
28195 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
28196 * @return The horizontal scroll scale factor.
28197 * @hide
28198 */
28199 @UnsupportedAppUsage
28200 protected float getHorizontalScrollFactor() {
28201 // TODO: Should use something else.
28202 return getVerticalScrollFactor();
28203 }
28204
28205 /**
28206 * Return the value specifying the text direction or policy that was set with
28207 * {@link #setTextDirection(int)}.
28208 *
28209 * @return the defined text direction. It can be one of:
28210 *
28211 * {@link #TEXT_DIRECTION_INHERIT},
28212 * {@link #TEXT_DIRECTION_FIRST_STRONG},
28213 * {@link #TEXT_DIRECTION_ANY_RTL},
28214 * {@link #TEXT_DIRECTION_LTR},
28215 * {@link #TEXT_DIRECTION_RTL},
28216 * {@link #TEXT_DIRECTION_LOCALE},
28217 * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
28218 * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
28219 *
28220 * @attr ref android.R.styleable#View_textDirection
28221 *
28222 * @hide
28223 */
28224 @ViewDebug.ExportedProperty(category = "text", mapping = {
28225 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
28226 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
28227 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
28228 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
28229 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
28230 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
28231 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
28232 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
28233 })
28234 @InspectableProperty(hasAttributeId = false, enumMapping = {
28235 @EnumEntry(value = TEXT_DIRECTION_INHERIT, name = "inherit"),
28236 @EnumEntry(value = TEXT_DIRECTION_LOCALE, name = "locale"),
28237 @EnumEntry(value = TEXT_DIRECTION_ANY_RTL, name = "anyRtl"),
28238 @EnumEntry(value = TEXT_DIRECTION_LTR, name = "ltr"),
28239 @EnumEntry(value = TEXT_DIRECTION_RTL, name = "rtl"),
28240 @EnumEntry(value = TEXT_DIRECTION_FIRST_STRONG, name = "firstStrong"),
28241 @EnumEntry(value = TEXT_DIRECTION_FIRST_STRONG_LTR, name = "firstStrongLtr"),
28242 @EnumEntry(value = TEXT_DIRECTION_FIRST_STRONG_RTL, name = "firstStrongRtl"),
28243 })
28244 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
28245 public int getRawTextDirection() {
28246 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
28247 }
28248
28249 /**
28250 * Set the text direction.
28251 *
28252 * @param textDirection the direction to set. Should be one of:
28253 *
28254 * {@link #TEXT_DIRECTION_INHERIT},
28255 * {@link #TEXT_DIRECTION_FIRST_STRONG},
28256 * {@link #TEXT_DIRECTION_ANY_RTL},
28257 * {@link #TEXT_DIRECTION_LTR},
28258 * {@link #TEXT_DIRECTION_RTL},
28259 * {@link #TEXT_DIRECTION_LOCALE}
28260 * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
28261 * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL},
28262 *
28263 * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
28264 * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
28265 * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
28266 *
28267 * @attr ref android.R.styleable#View_textDirection
28268 */
28269 public void setTextDirection(int textDirection) {
28270 if (getRawTextDirection() != textDirection) {
28271 // Reset the current text direction and the resolved one
28272 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
28273 resetResolvedTextDirection();
28274 // Set the new text direction
28275 mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
28276 // Do resolution
28277 resolveTextDirection();
28278 // Notify change
28279 onRtlPropertiesChanged(getLayoutDirection());
28280 // Refresh
28281 requestLayout();
28282 invalidate(true);
28283 }
28284 }
28285
28286 /**
28287 * Return the resolved text direction.
28288 *
28289 * @return the resolved text direction. Returns one of:
28290 *
28291 * {@link #TEXT_DIRECTION_FIRST_STRONG},
28292 * {@link #TEXT_DIRECTION_ANY_RTL},
28293 * {@link #TEXT_DIRECTION_LTR},
28294 * {@link #TEXT_DIRECTION_RTL},
28295 * {@link #TEXT_DIRECTION_LOCALE},
28296 * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
28297 * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
28298 *
28299 * @attr ref android.R.styleable#View_textDirection
28300 */
28301 @ViewDebug.ExportedProperty(category = "text", mapping = {
28302 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
28303 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
28304 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
28305 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
28306 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
28307 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
28308 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
28309 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
28310 })
28311 @InspectableProperty(hasAttributeId = false, enumMapping = {
28312 @EnumEntry(value = TEXT_DIRECTION_LOCALE, name = "locale"),
28313 @EnumEntry(value = TEXT_DIRECTION_ANY_RTL, name = "anyRtl"),
28314 @EnumEntry(value = TEXT_DIRECTION_LTR, name = "ltr"),
28315 @EnumEntry(value = TEXT_DIRECTION_RTL, name = "rtl"),
28316 @EnumEntry(value = TEXT_DIRECTION_FIRST_STRONG, name = "firstStrong"),
28317 @EnumEntry(value = TEXT_DIRECTION_FIRST_STRONG_LTR, name = "firstStrongLtr"),
28318 @EnumEntry(value = TEXT_DIRECTION_FIRST_STRONG_RTL, name = "firstStrongRtl"),
28319 })
28320 public int getTextDirection() {
28321 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
28322 }
28323
28324 /**
28325 * Resolve the text direction.
28326 *
28327 * @return true if resolution has been done, false otherwise.
28328 *
28329 * @hide
28330 */
28331 public boolean resolveTextDirection() {
28332 // Reset any previous text direction resolution
28333 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
28334
28335 if (hasRtlSupport()) {
28336 // Set resolved text direction flag depending on text direction flag
28337 final int textDirection = getRawTextDirection();
28338 switch(textDirection) {
28339 case TEXT_DIRECTION_INHERIT:
28340 if (!canResolveTextDirection()) {
28341 // We cannot do the resolution if there is no parent, so use the default one
28342 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
28343 // Resolution will need to happen again later
28344 return false;
28345 }
28346
28347 // Parent has not yet resolved, so we still return the default
28348 try {
28349 if (!mParent.isTextDirectionResolved()) {
28350 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
28351 // Resolution will need to happen again later
28352 return false;
28353 }
28354 } catch (AbstractMethodError e) {
28355 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
28356 " does not fully implement ViewParent", e);
28357 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
28358 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
28359 return true;
28360 }
28361
28362 // Set current resolved direction to the same value as the parent's one
28363 int parentResolvedDirection;
28364 try {
28365 parentResolvedDirection = mParent.getTextDirection();
28366 } catch (AbstractMethodError e) {
28367 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
28368 " does not fully implement ViewParent", e);
28369 parentResolvedDirection = TEXT_DIRECTION_LTR;
28370 }
28371 switch (parentResolvedDirection) {
28372 case TEXT_DIRECTION_FIRST_STRONG:
28373 case TEXT_DIRECTION_ANY_RTL:
28374 case TEXT_DIRECTION_LTR:
28375 case TEXT_DIRECTION_RTL:
28376 case TEXT_DIRECTION_LOCALE:
28377 case TEXT_DIRECTION_FIRST_STRONG_LTR:
28378 case TEXT_DIRECTION_FIRST_STRONG_RTL:
28379 mPrivateFlags2 |=
28380 (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
28381 break;
28382 default:
28383 // Default resolved direction is "first strong" heuristic
28384 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
28385 }
28386 break;
28387 case TEXT_DIRECTION_FIRST_STRONG:
28388 case TEXT_DIRECTION_ANY_RTL:
28389 case TEXT_DIRECTION_LTR:
28390 case TEXT_DIRECTION_RTL:
28391 case TEXT_DIRECTION_LOCALE:
28392 case TEXT_DIRECTION_FIRST_STRONG_LTR:
28393 case TEXT_DIRECTION_FIRST_STRONG_RTL:
28394 // Resolved direction is the same as text direction
28395 mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
28396 break;
28397 default:
28398 // Default resolved direction is "first strong" heuristic
28399 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
28400 }
28401 } else {
28402 // Default resolved direction is "first strong" heuristic
28403 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
28404 }
28405
28406 // Set to resolved
28407 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
28408 return true;
28409 }
28410
28411 /**
28412 * Check if text direction resolution can be done.
28413 *
28414 * @return true if text direction resolution can be done otherwise return false.
28415 */
28416 public boolean canResolveTextDirection() {
28417 switch (getRawTextDirection()) {
28418 case TEXT_DIRECTION_INHERIT:
28419 if (mParent != null) {
28420 try {
28421 return mParent.canResolveTextDirection();
28422 } catch (AbstractMethodError e) {
28423 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
28424 " does not fully implement ViewParent", e);
28425 }
28426 }
28427 return false;
28428
28429 default:
28430 return true;
28431 }
28432 }
28433
28434 /**
28435 * Reset resolved text direction. Text direction will be resolved during a call to
28436 * {@link #onMeasure(int, int)}.
28437 *
28438 * @hide
28439 */
28440 @TestApi
28441 public void resetResolvedTextDirection() {
28442 // Reset any previous text direction resolution
28443 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
28444 // Set to default value
28445 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
28446 }
28447
28448 /**
28449 * @return true if text direction is inherited.
28450 *
28451 * @hide
28452 */
28453 public boolean isTextDirectionInherited() {
28454 return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
28455 }
28456
28457 /**
28458 * @return true if text direction is resolved.
28459 */
28460 public boolean isTextDirectionResolved() {
28461 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
28462 }
28463
28464 /**
28465 * Return the value specifying the text alignment or policy that was set with
28466 * {@link #setTextAlignment(int)}.
28467 *
28468 * @return the defined text alignment. It can be one of:
28469 *
28470 * {@link #TEXT_ALIGNMENT_INHERIT},
28471 * {@link #TEXT_ALIGNMENT_GRAVITY},
28472 * {@link #TEXT_ALIGNMENT_CENTER},
28473 * {@link #TEXT_ALIGNMENT_TEXT_START},
28474 * {@link #TEXT_ALIGNMENT_TEXT_END},
28475 * {@link #TEXT_ALIGNMENT_VIEW_START},
28476 * {@link #TEXT_ALIGNMENT_VIEW_END}
28477 *
28478 * @attr ref android.R.styleable#View_textAlignment
28479 *
28480 * @hide
28481 */
28482 @ViewDebug.ExportedProperty(category = "text", mapping = {
28483 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
28484 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
28485 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
28486 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
28487 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
28488 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
28489 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
28490 })
28491 @InspectableProperty(hasAttributeId = false, enumMapping = {
28492 @EnumEntry(value = TEXT_ALIGNMENT_INHERIT, name = "inherit"),
28493 @EnumEntry(value = TEXT_ALIGNMENT_GRAVITY, name = "gravity"),
28494 @EnumEntry(value = TEXT_ALIGNMENT_TEXT_START, name = "textStart"),
28495 @EnumEntry(value = TEXT_ALIGNMENT_TEXT_END, name = "textEnd"),
28496 @EnumEntry(value = TEXT_ALIGNMENT_CENTER, name = "center"),
28497 @EnumEntry(value = TEXT_ALIGNMENT_VIEW_START, name = "viewStart"),
28498 @EnumEntry(value = TEXT_ALIGNMENT_VIEW_END, name = "viewEnd")
28499 })
28500 @TextAlignment
28501 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
28502 public int getRawTextAlignment() {
28503 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
28504 }
28505
28506 /**
28507 * Set the text alignment.
28508 *
28509 * @param textAlignment The text alignment to set. Should be one of
28510 *
28511 * {@link #TEXT_ALIGNMENT_INHERIT},
28512 * {@link #TEXT_ALIGNMENT_GRAVITY},
28513 * {@link #TEXT_ALIGNMENT_CENTER},
28514 * {@link #TEXT_ALIGNMENT_TEXT_START},
28515 * {@link #TEXT_ALIGNMENT_TEXT_END},
28516 * {@link #TEXT_ALIGNMENT_VIEW_START},
28517 * {@link #TEXT_ALIGNMENT_VIEW_END}
28518 *
28519 * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
28520 * proceeds up the parent chain of the view to get the value. If there is no parent, then it
28521 * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
28522 *
28523 * @attr ref android.R.styleable#View_textAlignment
28524 */
28525 public void setTextAlignment(@TextAlignment int textAlignment) {
28526 if (textAlignment != getRawTextAlignment()) {
28527 // Reset the current and resolved text alignment
28528 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
28529 resetResolvedTextAlignment();
28530 // Set the new text alignment
28531 mPrivateFlags2 |=
28532 ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
28533 // Do resolution
28534 resolveTextAlignment();
28535 // Notify change
28536 onRtlPropertiesChanged(getLayoutDirection());
28537 // Refresh
28538 requestLayout();
28539 invalidate(true);
28540 }
28541 }
28542
28543 /**
28544 * Return the resolved text alignment.
28545 *
28546 * @return the resolved text alignment. Returns one of:
28547 *
28548 * {@link #TEXT_ALIGNMENT_GRAVITY},
28549 * {@link #TEXT_ALIGNMENT_CENTER},
28550 * {@link #TEXT_ALIGNMENT_TEXT_START},
28551 * {@link #TEXT_ALIGNMENT_TEXT_END},
28552 * {@link #TEXT_ALIGNMENT_VIEW_START},
28553 * {@link #TEXT_ALIGNMENT_VIEW_END}
28554 *
28555 * @attr ref android.R.styleable#View_textAlignment
28556 */
28557 @ViewDebug.ExportedProperty(category = "text", mapping = {
28558 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
28559 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
28560 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
28561 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
28562 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
28563 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
28564 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
28565 })
28566 @InspectableProperty(enumMapping = {
28567 @EnumEntry(value = TEXT_ALIGNMENT_GRAVITY, name = "gravity"),
28568 @EnumEntry(value = TEXT_ALIGNMENT_TEXT_START, name = "textStart"),
28569 @EnumEntry(value = TEXT_ALIGNMENT_TEXT_END, name = "textEnd"),
28570 @EnumEntry(value = TEXT_ALIGNMENT_CENTER, name = "center"),
28571 @EnumEntry(value = TEXT_ALIGNMENT_VIEW_START, name = "viewStart"),
28572 @EnumEntry(value = TEXT_ALIGNMENT_VIEW_END, name = "viewEnd")
28573 })
28574 @TextAlignment
28575 public int getTextAlignment() {
28576 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
28577 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
28578 }
28579
28580 /**
28581 * Resolve the text alignment.
28582 *
28583 * @return true if resolution has been done, false otherwise.
28584 *
28585 * @hide
28586 */
28587 public boolean resolveTextAlignment() {
28588 // Reset any previous text alignment resolution
28589 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
28590
28591 if (hasRtlSupport()) {
28592 // Set resolved text alignment flag depending on text alignment flag
28593 final int textAlignment = getRawTextAlignment();
28594 switch (textAlignment) {
28595 case TEXT_ALIGNMENT_INHERIT:
28596 // Check if we can resolve the text alignment
28597 if (!canResolveTextAlignment()) {
28598 // We cannot do the resolution if there is no parent so use the default
28599 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
28600 // Resolution will need to happen again later
28601 return false;
28602 }
28603
28604 // Parent has not yet resolved, so we still return the default
28605 try {
28606 if (!mParent.isTextAlignmentResolved()) {
28607 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
28608 // Resolution will need to happen again later
28609 return false;
28610 }
28611 } catch (AbstractMethodError e) {
28612 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
28613 " does not fully implement ViewParent", e);
28614 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
28615 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
28616 return true;
28617 }
28618
28619 int parentResolvedTextAlignment;
28620 try {
28621 parentResolvedTextAlignment = mParent.getTextAlignment();
28622 } catch (AbstractMethodError e) {
28623 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
28624 " does not fully implement ViewParent", e);
28625 parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
28626 }
28627 switch (parentResolvedTextAlignment) {
28628 case TEXT_ALIGNMENT_GRAVITY:
28629 case TEXT_ALIGNMENT_TEXT_START:
28630 case TEXT_ALIGNMENT_TEXT_END:
28631 case TEXT_ALIGNMENT_CENTER:
28632 case TEXT_ALIGNMENT_VIEW_START:
28633 case TEXT_ALIGNMENT_VIEW_END:
28634 // Resolved text alignment is the same as the parent resolved
28635 // text alignment
28636 mPrivateFlags2 |=
28637 (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
28638 break;
28639 default:
28640 // Use default resolved text alignment
28641 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
28642 }
28643 break;
28644 case TEXT_ALIGNMENT_GRAVITY:
28645 case TEXT_ALIGNMENT_TEXT_START:
28646 case TEXT_ALIGNMENT_TEXT_END:
28647 case TEXT_ALIGNMENT_CENTER:
28648 case TEXT_ALIGNMENT_VIEW_START:
28649 case TEXT_ALIGNMENT_VIEW_END:
28650 // Resolved text alignment is the same as text alignment
28651 mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
28652 break;
28653 default:
28654 // Use default resolved text alignment
28655 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
28656 }
28657 } else {
28658 // Use default resolved text alignment
28659 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
28660 }
28661
28662 // Set the resolved
28663 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
28664 return true;
28665 }
28666
28667 /**
28668 * Check if text alignment resolution can be done.
28669 *
28670 * @return true if text alignment resolution can be done otherwise return false.
28671 */
28672 public boolean canResolveTextAlignment() {
28673 switch (getRawTextAlignment()) {
28674 case TEXT_DIRECTION_INHERIT:
28675 if (mParent != null) {
28676 try {
28677 return mParent.canResolveTextAlignment();
28678 } catch (AbstractMethodError e) {
28679 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
28680 " does not fully implement ViewParent", e);
28681 }
28682 }
28683 return false;
28684
28685 default:
28686 return true;
28687 }
28688 }
28689
28690 /**
28691 * Reset resolved text alignment. Text alignment will be resolved during a call to
28692 * {@link #onMeasure(int, int)}.
28693 *
28694 * @hide
28695 */
28696 @TestApi
28697 public void resetResolvedTextAlignment() {
28698 // Reset any previous text alignment resolution
28699 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
28700 // Set to default
28701 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
28702 }
28703
28704 /**
28705 * @return true if text alignment is inherited.
28706 *
28707 * @hide
28708 */
28709 public boolean isTextAlignmentInherited() {
28710 return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
28711 }
28712
28713 /**
28714 * @return true if text alignment is resolved.
28715 */
28716 public boolean isTextAlignmentResolved() {
28717 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
28718 }
28719
28720 /**
28721 * Generate a value suitable for use in {@link #setId(int)}.
28722 * This value will not collide with ID values generated at build time by aapt for R.id.
28723 *
28724 * @return a generated ID value
28725 */
28726 public static int generateViewId() {
28727 for (;;) {
28728 final int result = sNextGeneratedId.get();
28729 // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
28730 int newValue = result + 1;
28731 if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
28732 if (sNextGeneratedId.compareAndSet(result, newValue)) {
28733 return result;
28734 }
28735 }
28736 }
28737
28738 private static boolean isViewIdGenerated(int id) {
28739 return (id & 0xFF000000) == 0 && (id & 0x00FFFFFF) != 0;
28740 }
28741
28742 /**
28743 * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions.
28744 * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and
28745 * a normal View or a ViewGroup with
28746 * {@link android.view.ViewGroup#isTransitionGroup()} true.
28747 * @hide
28748 */
28749 public void captureTransitioningViews(List<View> transitioningViews) {
28750 if (getVisibility() == View.VISIBLE) {
28751 transitioningViews.add(this);
28752 }
28753 }
28754
28755 /**
28756 * Adds all Views that have {@link #getTransitionName()} non-null to namedElements.
28757 * @param namedElements Will contain all Views in the hierarchy having a transitionName.
28758 * @hide
28759 */
28760 public void findNamedViews(Map<String, View> namedElements) {
28761 if (getVisibility() == VISIBLE || mGhostView != null) {
28762 String transitionName = getTransitionName();
28763 if (transitionName != null) {
28764 namedElements.put(transitionName, this);
28765 }
28766 }
28767 }
28768
28769 /**
28770 * Returns the pointer icon for the motion event, or null if it doesn't specify the icon.
28771 * The default implementation does not care the location or event types, but some subclasses
28772 * may use it (such as WebViews).
28773 * @param event The MotionEvent from a mouse
28774 * @param pointerIndex The index of the pointer for which to retrieve the {@link PointerIcon}.
28775 * This will be between 0 and {@link MotionEvent#getPointerCount()}.
28776 * @see PointerIcon
28777 */
28778 public PointerIcon onResolvePointerIcon(MotionEvent event, int pointerIndex) {
28779 final float x = event.getX(pointerIndex);
28780 final float y = event.getY(pointerIndex);
28781 if (isDraggingScrollBar() || isOnScrollbarThumb(x, y)) {
28782 return PointerIcon.getSystemIcon(mContext, PointerIcon.TYPE_ARROW);
28783 }
28784 return mPointerIcon;
28785 }
28786
28787 /**
28788 * Set the pointer icon for the current view.
28789 * Passing {@code null} will restore the pointer icon to its default value.
28790 * @param pointerIcon A PointerIcon instance which will be shown when the mouse hovers.
28791 */
28792 public void setPointerIcon(PointerIcon pointerIcon) {
28793 mPointerIcon = pointerIcon;
28794 if (mAttachInfo == null || mAttachInfo.mHandlingPointerEvent) {
28795 return;
28796 }
28797 try {
28798 mAttachInfo.mSession.updatePointerIcon(mAttachInfo.mWindow);
28799 } catch (RemoteException e) {
28800 }
28801 }
28802
28803 /**
28804 * Gets the pointer icon for the current view.
28805 */
28806 @InspectableProperty
28807 public PointerIcon getPointerIcon() {
28808 return mPointerIcon;
28809 }
28810
28811 /**
28812 * Checks pointer capture status.
28813 *
28814 * @return true if the view has pointer capture.
28815 * @see #requestPointerCapture()
28816 * @see #hasPointerCapture()
28817 */
28818 public boolean hasPointerCapture() {
28819 final ViewRootImpl viewRootImpl = getViewRootImpl();
28820 if (viewRootImpl == null) {
28821 return false;
28822 }
28823 return viewRootImpl.hasPointerCapture();
28824 }
28825
28826 /**
28827 * Requests pointer capture mode.
28828 * <p>
28829 * When the window has pointer capture, the mouse pointer icon will disappear and will not
28830 * change its position. Enabling pointer capture will change the behavior of input devices in
28831 * the following ways:
28832 * <ul>
28833 * <li>Events from a mouse will be delivered with the source
28834 * {@link InputDevice#SOURCE_MOUSE_RELATIVE}, and relative position changes will be
28835 * available through {@link MotionEvent#getX} and {@link MotionEvent#getY}.</li>
28836 *
28837 * <li>Events from a touchpad or trackpad will be delivered with the source
28838 * {@link InputDevice#SOURCE_TOUCHPAD}, where the absolute position of each of the pointers
28839 * on the touchpad will be available through {@link MotionEvent#getX(int)} and
28840 * {@link MotionEvent#getY(int)}, and their relative movements are stored in
28841 * {@link MotionEvent#AXIS_RELATIVE_X} and {@link MotionEvent#AXIS_RELATIVE_Y}.</li>
28842 *
28843 * <li>Events from other types of devices, such as touchscreens, will not be affected.</li>
28844 * </ul>
28845 * <p>
28846 * When pointer capture changes, connected mouse and trackpad devices may be reconfigured,
28847 * and their properties (such as their sources or motion ranges) may change. Use an
28848 * {@link android.hardware.input.InputManager.InputDeviceListener} to be notified when a device
28849 * changes (which may happen after enabling or disabling pointer capture), and use
28850 * {@link InputDevice#getDevice(int)} to get the updated {@link InputDevice}.
28851 * <p>
28852 * Events captured through pointer capture will be dispatched to
28853 * {@link OnCapturedPointerListener#onCapturedPointer(View, MotionEvent)} if an
28854 * {@link OnCapturedPointerListener} is set, and otherwise to
28855 * {@link #onCapturedPointerEvent(MotionEvent)}.
28856 * <p>
28857 * If the window already has pointer capture, this call does nothing.
28858 * <p>
28859 * The capture may be released through {@link #releasePointerCapture()}, or will be lost
28860 * automatically when the window loses focus.
28861 *
28862 * @see #releasePointerCapture()
28863 * @see #hasPointerCapture()
28864 * @see #onPointerCaptureChange(boolean)
28865 */
28866 public void requestPointerCapture() {
28867 final ViewRootImpl viewRootImpl = getViewRootImpl();
28868 if (viewRootImpl != null) {
28869 viewRootImpl.requestPointerCapture(true);
28870 }
28871 }
28872
28873
28874 /**
28875 * Releases the pointer capture.
28876 * <p>
28877 * If the window does not have pointer capture, this call will do nothing.
28878 * @see #requestPointerCapture()
28879 * @see #hasPointerCapture()
28880 * @see #onPointerCaptureChange(boolean)
28881 */
28882 public void releasePointerCapture() {
28883 final ViewRootImpl viewRootImpl = getViewRootImpl();
28884 if (viewRootImpl != null) {
28885 viewRootImpl.requestPointerCapture(false);
28886 }
28887 }
28888
28889 /**
28890 * Called when the window has just acquired or lost pointer capture.
28891 *
28892 * @param hasCapture True if the view now has pointerCapture, false otherwise.
28893 */
28894 @CallSuper
28895 public void onPointerCaptureChange(boolean hasCapture) {
28896 }
28897
28898 /**
28899 * @see #onPointerCaptureChange
28900 */
28901 public void dispatchPointerCaptureChanged(boolean hasCapture) {
28902 onPointerCaptureChange(hasCapture);
28903 }
28904
28905 /**
28906 * Implement this method to handle captured pointer events
28907 *
28908 * @param event The captured pointer event.
28909 * @return True if the event was handled, false otherwise.
28910 * @see #requestPointerCapture()
28911 */
28912 public boolean onCapturedPointerEvent(MotionEvent event) {
28913 return false;
28914 }
28915
28916 /**
28917 * Interface definition for a callback to be invoked when a captured pointer event
28918 * is being dispatched this view. The callback will be invoked before the event is
28919 * given to the view.
28920 */
28921 public interface OnCapturedPointerListener {
28922 /**
28923 * Called when a captured pointer event is dispatched to a view.
28924 * @param view The view this event has been dispatched to.
28925 * @param event The captured event.
28926 * @return True if the listener has consumed the event, false otherwise.
28927 */
28928 boolean onCapturedPointer(View view, MotionEvent event);
28929 }
28930
28931 /**
28932 * Set a listener to receive callbacks when the pointer capture state of a view changes.
28933 * @param l The {@link OnCapturedPointerListener} to receive callbacks.
28934 */
28935 public void setOnCapturedPointerListener(OnCapturedPointerListener l) {
28936 getListenerInfo().mOnCapturedPointerListener = l;
28937 }
28938
28939 // Properties
28940 //
28941 /**
28942 * A Property wrapper around the <code>alpha</code> functionality handled by the
28943 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
28944 */
28945 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
28946 @Override
28947 public void setValue(View object, float value) {
28948 object.setAlpha(value);
28949 }
28950
28951 @Override
28952 public Float get(View object) {
28953 return object.getAlpha();
28954 }
28955 };
28956
28957 /**
28958 * A Property wrapper around the <code>translationX</code> functionality handled by the
28959 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
28960 */
28961 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
28962 @Override
28963 public void setValue(View object, float value) {
28964 object.setTranslationX(value);
28965 }
28966
28967 @Override
28968 public Float get(View object) {
28969 return object.getTranslationX();
28970 }
28971 };
28972
28973 /**
28974 * A Property wrapper around the <code>translationY</code> functionality handled by the
28975 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
28976 */
28977 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
28978 @Override
28979 public void setValue(View object, float value) {
28980 object.setTranslationY(value);
28981 }
28982
28983 @Override
28984 public Float get(View object) {
28985 return object.getTranslationY();
28986 }
28987 };
28988
28989 /**
28990 * A Property wrapper around the <code>translationZ</code> functionality handled by the
28991 * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
28992 */
28993 public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
28994 @Override
28995 public void setValue(View object, float value) {
28996 object.setTranslationZ(value);
28997 }
28998
28999 @Override
29000 public Float get(View object) {
29001 return object.getTranslationZ();
29002 }
29003 };
29004
29005 /**
29006 * A Property wrapper around the <code>x</code> functionality handled by the
29007 * {@link View#setX(float)} and {@link View#getX()} methods.
29008 */
29009 public static final Property<View, Float> X = new FloatProperty<View>("x") {
29010 @Override
29011 public void setValue(View object, float value) {
29012 object.setX(value);
29013 }
29014
29015 @Override
29016 public Float get(View object) {
29017 return object.getX();
29018 }
29019 };
29020
29021 /**
29022 * A Property wrapper around the <code>y</code> functionality handled by the
29023 * {@link View#setY(float)} and {@link View#getY()} methods.
29024 */
29025 public static final Property<View, Float> Y = new FloatProperty<View>("y") {
29026 @Override
29027 public void setValue(View object, float value) {
29028 object.setY(value);
29029 }
29030
29031 @Override
29032 public Float get(View object) {
29033 return object.getY();
29034 }
29035 };
29036
29037 /**
29038 * A Property wrapper around the <code>z</code> functionality handled by the
29039 * {@link View#setZ(float)} and {@link View#getZ()} methods.
29040 */
29041 public static final Property<View, Float> Z = new FloatProperty<View>("z") {
29042 @Override
29043 public void setValue(View object, float value) {
29044 object.setZ(value);
29045 }
29046
29047 @Override
29048 public Float get(View object) {
29049 return object.getZ();
29050 }
29051 };
29052
29053 /**
29054 * A Property wrapper around the <code>rotation</code> functionality handled by the
29055 * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
29056 */
29057 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
29058 @Override
29059 public void setValue(View object, float value) {
29060 object.setRotation(value);
29061 }
29062
29063 @Override
29064 public Float get(View object) {
29065 return object.getRotation();
29066 }
29067 };
29068
29069 /**
29070 * A Property wrapper around the <code>rotationX</code> functionality handled by the
29071 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
29072 */
29073 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
29074 @Override
29075 public void setValue(View object, float value) {
29076 object.setRotationX(value);
29077 }
29078
29079 @Override
29080 public Float get(View object) {
29081 return object.getRotationX();
29082 }
29083 };
29084
29085 /**
29086 * A Property wrapper around the <code>rotationY</code> functionality handled by the
29087 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
29088 */
29089 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
29090 @Override
29091 public void setValue(View object, float value) {
29092 object.setRotationY(value);
29093 }
29094
29095 @Override
29096 public Float get(View object) {
29097 return object.getRotationY();
29098 }
29099 };
29100
29101 /**
29102 * A Property wrapper around the <code>scaleX</code> functionality handled by the
29103 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
29104 */
29105 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
29106 @Override
29107 public void setValue(View object, float value) {
29108 object.setScaleX(value);
29109 }
29110
29111 @Override
29112 public Float get(View object) {
29113 return object.getScaleX();
29114 }
29115 };
29116
29117 /**
29118 * A Property wrapper around the <code>scaleY</code> functionality handled by the
29119 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
29120 */
29121 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
29122 @Override
29123 public void setValue(View object, float value) {
29124 object.setScaleY(value);
29125 }
29126
29127 @Override
29128 public Float get(View object) {
29129 return object.getScaleY();
29130 }
29131 };
29132
29133 /**
29134 * A MeasureSpec encapsulates the layout requirements passed from parent to child.
29135 * Each MeasureSpec represents a requirement for either the width or the height.
29136 * A MeasureSpec is comprised of a size and a mode. There are three possible
29137 * modes:
29138 * <dl>
29139 * <dt>UNSPECIFIED</dt>
29140 * <dd>
29141 * The parent has not imposed any constraint on the child. It can be whatever size
29142 * it wants.
29143 * </dd>
29144 *
29145 * <dt>EXACTLY</dt>
29146 * <dd>
29147 * The parent has determined an exact size for the child. The child is going to be
29148 * given those bounds regardless of how big it wants to be.
29149 * </dd>
29150 *
29151 * <dt>AT_MOST</dt>
29152 * <dd>
29153 * The child can be as large as it wants up to the specified size.
29154 * </dd>
29155 * </dl>
29156 *
29157 * MeasureSpecs are implemented as ints to reduce object allocation. This class
29158 * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
29159 */
29160 public static class MeasureSpec {
29161 private static final int MODE_SHIFT = 30;
29162 private static final int MODE_MASK = 0x3 << MODE_SHIFT;
29163
29164 /** @hide */
29165 @IntDef({UNSPECIFIED, EXACTLY, AT_MOST})
29166 @Retention(RetentionPolicy.SOURCE)
29167 public @interface MeasureSpecMode {}
29168
29169 /**
29170 * Measure specification mode: The parent has not imposed any constraint
29171 * on the child. It can be whatever size it wants.
29172 */
29173 public static final int UNSPECIFIED = 0 << MODE_SHIFT;
29174
29175 /**
29176 * Measure specification mode: The parent has determined an exact size
29177 * for the child. The child is going to be given those bounds regardless
29178 * of how big it wants to be.
29179 */
29180 public static final int EXACTLY = 1 << MODE_SHIFT;
29181
29182 /**
29183 * Measure specification mode: The child can be as large as it wants up
29184 * to the specified size.
29185 */
29186 public static final int AT_MOST = 2 << MODE_SHIFT;
29187
29188 /**
29189 * Creates a measure specification based on the supplied size and mode.
29190 *
29191 * The mode must always be one of the following:
29192 * <ul>
29193 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
29194 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
29195 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
29196 * </ul>
29197 *
29198 * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
29199 * implementation was such that the order of arguments did not matter
29200 * and overflow in either value could impact the resulting MeasureSpec.
29201 * {@link android.widget.RelativeLayout} was affected by this bug.
29202 * Apps targeting API levels greater than 17 will get the fixed, more strict
29203 * behavior.</p>
29204 *
29205 * @param size the size of the measure specification
29206 * @param mode the mode of the measure specification
29207 * @return the measure specification based on size and mode
29208 */
29209 public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size,
29210 @MeasureSpecMode int mode) {
29211 if (sUseBrokenMakeMeasureSpec) {
29212 return size + mode;
29213 } else {
29214 return (size & ~MODE_MASK) | (mode & MODE_MASK);
29215 }
29216 }
29217
29218 /**
29219 * Like {@link #makeMeasureSpec(int, int)}, but any spec with a mode of UNSPECIFIED
29220 * will automatically get a size of 0. Older apps expect this.
29221 *
29222 * @hide internal use only for compatibility with system widgets and older apps
29223 */
29224 @UnsupportedAppUsage
29225 public static int makeSafeMeasureSpec(int size, int mode) {
29226 if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) {
29227 return 0;
29228 }
29229 return makeMeasureSpec(size, mode);
29230 }
29231
29232 /**
29233 * Extracts the mode from the supplied measure specification.
29234 *
29235 * @param measureSpec the measure specification to extract the mode from
29236 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
29237 * {@link android.view.View.MeasureSpec#AT_MOST} or
29238 * {@link android.view.View.MeasureSpec#EXACTLY}
29239 */
29240 @MeasureSpecMode
29241 public static int getMode(int measureSpec) {
29242 //noinspection ResourceType
29243 return (measureSpec & MODE_MASK);
29244 }
29245
29246 /**
29247 * Extracts the size from the supplied measure specification.
29248 *
29249 * @param measureSpec the measure specification to extract the size from
29250 * @return the size in pixels defined in the supplied measure specification
29251 */
29252 public static int getSize(int measureSpec) {
29253 return (measureSpec & ~MODE_MASK);
29254 }
29255
29256 static int adjust(int measureSpec, int delta) {
29257 final int mode = getMode(measureSpec);
29258 int size = getSize(measureSpec);
29259 if (mode == UNSPECIFIED) {
29260 // No need to adjust size for UNSPECIFIED mode.
29261 return makeMeasureSpec(size, UNSPECIFIED);
29262 }
29263 size += delta;
29264 if (size < 0) {
29265 Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
29266 ") spec: " + toString(measureSpec) + " delta: " + delta);
29267 size = 0;
29268 }
29269 return makeMeasureSpec(size, mode);
29270 }
29271
29272 /**
29273 * Returns a String representation of the specified measure
29274 * specification.
29275 *
29276 * @param measureSpec the measure specification to convert to a String
29277 * @return a String with the following format: "MeasureSpec: MODE SIZE"
29278 */
29279 public static String toString(int measureSpec) {
29280 int mode = getMode(measureSpec);
29281 int size = getSize(measureSpec);
29282
29283 StringBuilder sb = new StringBuilder("MeasureSpec: ");
29284
29285 if (mode == UNSPECIFIED)
29286 sb.append("UNSPECIFIED ");
29287 else if (mode == EXACTLY)
29288 sb.append("EXACTLY ");
29289 else if (mode == AT_MOST)
29290 sb.append("AT_MOST ");
29291 else
29292 sb.append(mode).append(" ");
29293
29294 sb.append(size);
29295 return sb.toString();
29296 }
29297 }
29298
29299 private final class CheckForLongPress implements Runnable {
29300 private int mOriginalWindowAttachCount;
29301 private float mX;
29302 private float mY;
29303 private boolean mOriginalPressedState;
29304 /**
29305 * The classification of the long click being checked: one of the
29306 * FrameworkStatsLog.TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__* constants.
29307 */
29308 private int mClassification;
29309
29310 @UnsupportedAppUsage
29311 private CheckForLongPress() {
29312 }
29313
29314 @Override
29315 public void run() {
29316 if ((mOriginalPressedState == isPressed()) && (mParent != null)
29317 && mOriginalWindowAttachCount == mWindowAttachCount) {
29318 recordGestureClassification(mClassification);
29319 if (performLongClick(mX, mY)) {
29320 mHasPerformedLongPress = true;
29321 }
29322 }
29323 }
29324
29325 public void setAnchor(float x, float y) {
29326 mX = x;
29327 mY = y;
29328 }
29329
29330 public void rememberWindowAttachCount() {
29331 mOriginalWindowAttachCount = mWindowAttachCount;
29332 }
29333
29334 public void rememberPressedState() {
29335 mOriginalPressedState = isPressed();
29336 }
29337
29338 public void setClassification(int classification) {
29339 mClassification = classification;
29340 }
29341 }
29342
29343 private final class CheckForTap implements Runnable {
29344 public float x;
29345 public float y;
29346
29347 @Override
29348 public void run() {
29349 mPrivateFlags &= ~PFLAG_PREPRESSED;
29350 setPressed(true, x, y);
29351 final long delay =
29352 ViewConfiguration.getLongPressTimeout() - ViewConfiguration.getTapTimeout();
29353 checkForLongClick(delay, x, y, TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__LONG_PRESS);
29354 }
29355 }
29356
29357 private final class PerformClick implements Runnable {
29358 @Override
29359 public void run() {
29360 recordGestureClassification(TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__SINGLE_TAP);
29361 performClickInternal();
29362 }
29363 }
29364
29365 /** Records a classification for the current event stream. */
29366 private void recordGestureClassification(int classification) {
29367 if (classification == TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__UNKNOWN_CLASSIFICATION) {
29368 return;
29369 }
29370 // To avoid negatively impacting View performance, the latency and displacement metrics
29371 // are omitted.
29372 FrameworkStatsLog.write(FrameworkStatsLog.TOUCH_GESTURE_CLASSIFIED, getClass().getName(),
29373 classification);
29374 }
29375
29376 /**
29377 * This method returns a ViewPropertyAnimator object, which can be used to animate
29378 * specific properties on this View.
29379 *
29380 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
29381 */
29382 public ViewPropertyAnimator animate() {
29383 if (mAnimator == null) {
29384 mAnimator = new ViewPropertyAnimator(this);
29385 }
29386 return mAnimator;
29387 }
29388
29389 /**
29390 * Sets the name of the View to be used to identify Views in Transitions.
29391 * Names should be unique in the View hierarchy.
29392 *
29393 * @param transitionName The name of the View to uniquely identify it for Transitions.
29394 */
29395 public final void setTransitionName(String transitionName) {
29396 mTransitionName = transitionName;
29397 }
29398
29399 /**
29400 * Returns the name of the View to be used to identify Views in Transitions.
29401 * Names should be unique in the View hierarchy.
29402 *
29403 * <p>This returns null if the View has not been given a name.</p>
29404 *
29405 * @return The name used of the View to be used to identify Views in Transitions or null
29406 * if no name has been given.
29407 */
29408 @ViewDebug.ExportedProperty
29409 @InspectableProperty
29410 public String getTransitionName() {
29411 return mTransitionName;
29412 }
29413
29414 /**
29415 * @hide
29416 */
29417 public void requestKeyboardShortcuts(List<KeyboardShortcutGroup> data, int deviceId) {
29418 // Do nothing.
29419 }
29420
29421 /**
29422 * Interface definition for a callback to be invoked when a hardware key event is
29423 * dispatched to this view. The callback will be invoked before the key event is
29424 * given to the view. This is only useful for hardware keyboards; a software input
29425 * method has no obligation to trigger this listener.
29426 */
29427 public interface OnKeyListener {
29428 /**
29429 * Called when a hardware key is dispatched to a view. This allows listeners to
29430 * get a chance to respond before the target view.
29431 * <p>Key presses in software keyboards will generally NOT trigger this method,
29432 * although some may elect to do so in some situations. Do not assume a
29433 * software input method has to be key-based; even if it is, it may use key presses
29434 * in a different way than you expect, so there is no way to reliably catch soft
29435 * input key presses.
29436 *
29437 * @param v The view the key has been dispatched to.
29438 * @param keyCode The code for the physical key that was pressed
29439 * @param event The KeyEvent object containing full information about
29440 * the event.
29441 * @return True if the listener has consumed the event, false otherwise.
29442 */
29443 boolean onKey(View v, int keyCode, KeyEvent event);
29444 }
29445
29446 /**
29447 * Interface definition for a callback to be invoked when a hardware key event hasn't
29448 * been handled by the view hierarchy.
29449 */
29450 public interface OnUnhandledKeyEventListener {
29451 /**
29452 * Called when a hardware key is dispatched to a view after being unhandled during normal
29453 * {@link KeyEvent} dispatch.
29454 *
29455 * @param v The view the key has been dispatched to.
29456 * @param event The KeyEvent object containing information about the event.
29457 * @return {@code true} if the listener has consumed the event, {@code false} otherwise.
29458 */
29459 boolean onUnhandledKeyEvent(View v, KeyEvent event);
29460 }
29461
29462 /**
29463 * Interface definition for a callback to be invoked when a touch event is
29464 * dispatched to this view. The callback will be invoked before the touch
29465 * event is given to the view.
29466 */
29467 public interface OnTouchListener {
29468 /**
29469 * Called when a touch event is dispatched to a view. This allows listeners to
29470 * get a chance to respond before the target view.
29471 *
29472 * @param v The view the touch event has been dispatched to.
29473 * @param event The MotionEvent object containing full information about
29474 * the event.
29475 * @return True if the listener has consumed the event, false otherwise.
29476 */
29477 boolean onTouch(View v, MotionEvent event);
29478 }
29479
29480 /**
29481 * Interface definition for a callback to be invoked when a hover event is
29482 * dispatched to this view. The callback will be invoked before the hover
29483 * event is given to the view.
29484 */
29485 public interface OnHoverListener {
29486 /**
29487 * Called when a hover event is dispatched to a view. This allows listeners to
29488 * get a chance to respond before the target view.
29489 *
29490 * @param v The view the hover event has been dispatched to.
29491 * @param event The MotionEvent object containing full information about
29492 * the event.
29493 * @return True if the listener has consumed the event, false otherwise.
29494 */
29495 boolean onHover(View v, MotionEvent event);
29496 }
29497
29498 /**
29499 * Interface definition for a callback to be invoked when a generic motion event is
29500 * dispatched to this view. The callback will be invoked before the generic motion
29501 * event is given to the view.
29502 */
29503 public interface OnGenericMotionListener {
29504 /**
29505 * Called when a generic motion event is dispatched to a view. This allows listeners to
29506 * get a chance to respond before the target view.
29507 *
29508 * @param v The view the generic motion event has been dispatched to.
29509 * @param event The MotionEvent object containing full information about
29510 * the event.
29511 * @return True if the listener has consumed the event, false otherwise.
29512 */
29513 boolean onGenericMotion(View v, MotionEvent event);
29514 }
29515
29516 /**
29517 * Interface definition for a callback to be invoked when a view has been clicked and held.
29518 */
29519 public interface OnLongClickListener {
29520 /**
29521 * Called when a view has been clicked and held.
29522 *
29523 * @param v The view that was clicked and held.
29524 *
29525 * @return true if the callback consumed the long click, false otherwise.
29526 */
29527 boolean onLongClick(View v);
29528 }
29529
29530 /**
29531 * Interface definition for a listener that's invoked when a drag event is dispatched to this
29532 * view. The listener is invoked before the view's own
29533 * {@link #onDragEvent(DragEvent)} method. To fall back to the view's
29534 * {@code onDragEvent(DragEvent)} behavior, return {@code false} from the listener method.
29535 *
29536 * <div class="special reference">
29537 * <h3>Developer Guides</h3>
29538 * <p>For a guide to implementing drag and drop features, see the
29539 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and drop</a> developer guide.</p>
29540 * </div>
29541 */
29542 public interface OnDragListener {
29543 /**
29544 * Called when a drag event is dispatched to a view. Enables listeners to override the
29545 * base behavior provided by {@link #onDragEvent(DragEvent)}.
29546 *
29547 * @param v The {@code View} that received the drag event.
29548 * @param event The event object for the drag event.
29549 * @return {@code true} if the drag event was handled successfully; {@code false}, if the
29550 * drag event was not handled. <b>Note:</b> A {@code false} return value triggers the
29551 * view's {@link #onDragEvent(DragEvent)} handler.
29552 */
29553 boolean onDrag(View v, DragEvent event);
29554 }
29555
29556 /**
29557 * Interface definition for a callback to be invoked when the focus state of
29558 * a view changed.
29559 */
29560 public interface OnFocusChangeListener {
29561 /**
29562 * Called when the focus state of a view has changed.
29563 *
29564 * @param v The view whose state has changed.
29565 * @param hasFocus The new focus state of v.
29566 */
29567 void onFocusChange(View v, boolean hasFocus);
29568 }
29569
29570 /**
29571 * Interface definition for a callback to be invoked when a view is clicked.
29572 */
29573 public interface OnClickListener {
29574 /**
29575 * Called when a view has been clicked.
29576 *
29577 * @param v The view that was clicked.
29578 */
29579 void onClick(View v);
29580 }
29581
29582 /**
29583 * Interface definition for a callback to be invoked when a view is context clicked.
29584 */
29585 public interface OnContextClickListener {
29586 /**
29587 * Called when a view is context clicked.
29588 *
29589 * @param v The view that has been context clicked.
29590 * @return true if the callback consumed the context click, false otherwise.
29591 */
29592 boolean onContextClick(View v);
29593 }
29594
29595 /**
29596 * Interface definition for a callback to be invoked when the context menu
29597 * for this view is being built.
29598 */
29599 public interface OnCreateContextMenuListener {
29600 /**
29601 * Called when the context menu for this view is being built. It is not
29602 * safe to hold onto the menu after this method returns.
29603 *
29604 * @param menu The context menu that is being built
29605 * @param v The view for which the context menu is being built
29606 * @param menuInfo Extra information about the item for which the
29607 * context menu should be shown. This information will vary
29608 * depending on the class of v.
29609 */
29610 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
29611 }
29612
29613 /**
29614 * Interface definition for a callback to be invoked when the status bar changes
29615 * visibility. This reports <strong>global</strong> changes to the system UI
29616 * state, not what the application is requesting.
29617 *
29618 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
29619 *
29620 * @deprecated Use {@link WindowInsets#isVisible(int)} to find out about system bar visibilities
29621 * by setting a {@link OnApplyWindowInsetsListener} on this view.
29622 */
29623 @Deprecated
29624 public interface OnSystemUiVisibilityChangeListener {
29625 /**
29626 * Called when the status bar changes visibility because of a call to
29627 * {@link View#setSystemUiVisibility(int)}.
29628 *
29629 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
29630 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
29631 * This tells you the <strong>global</strong> state of these UI visibility
29632 * flags, not what your app is currently applying.
29633 */
29634 public void onSystemUiVisibilityChange(int visibility);
29635 }
29636
29637 /**
29638 * Interface definition for a callback to be invoked when this view is attached
29639 * or detached from its window.
29640 */
29641 public interface OnAttachStateChangeListener {
29642 /**
29643 * Called when the view is attached to a window.
29644 * @param v The view that was attached
29645 */
29646 public void onViewAttachedToWindow(@NonNull View v);
29647 /**
29648 * Called when the view is detached from a window.
29649 * @param v The view that was detached
29650 */
29651 public void onViewDetachedFromWindow(@NonNull View v);
29652 }
29653
29654 /**
29655 * Listener for applying window insets on a view in a custom way.
29656 *
29657 * <p>Apps may choose to implement this interface if they want to apply custom policy
29658 * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
29659 * is set, its
29660 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
29661 * method will be called instead of the View's own
29662 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
29663 * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
29664 * the View's normal behavior as part of its own.</p>
29665 */
29666 public interface OnApplyWindowInsetsListener {
29667 /**
29668 * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
29669 * on a View, this listener method will be called instead of the view's own
29670 * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
29671 *
29672 * @param v The view applying window insets
29673 * @param insets The insets to apply
29674 * @return The insets supplied, minus any insets that were consumed
29675 */
29676 public @NonNull WindowInsets onApplyWindowInsets(@NonNull View v,
29677 @NonNull WindowInsets insets);
29678 }
29679
29680 private final class UnsetPressedState implements Runnable {
29681 @Override
29682 public void run() {
29683 setPressed(false);
29684 }
29685 }
29686
29687 /**
29688 * When a view becomes invisible checks if autofill considers the view invisible too. This
29689 * happens after the regular removal operation to make sure the operation is finished by the
29690 * time this is called.
29691 */
29692 private static class VisibilityChangeForAutofillHandler extends Handler {
29693 private final AutofillManager mAfm;
29694 private final View mView;
29695
29696 private VisibilityChangeForAutofillHandler(@NonNull AutofillManager afm,
29697 @NonNull View view) {
29698 mAfm = afm;
29699 mView = view;
29700 }
29701
29702 @Override
29703 public void handleMessage(Message msg) {
29704 mAfm.notifyViewVisibilityChanged(mView, mView.isShown());
29705 }
29706 }
29707
29708 /**
29709 * Base class for derived classes that want to save and restore their own
29710 * state in {@link android.view.View#onSaveInstanceState()}.
29711 */
29712 public static class BaseSavedState extends AbsSavedState {
29713 static final int START_ACTIVITY_REQUESTED_WHO_SAVED = 0b1;
29714 static final int IS_AUTOFILLED = 0b10;
29715 static final int AUTOFILL_ID = 0b100;
29716
29717 // Flags that describe what data in this state is valid
29718 int mSavedData;
29719 String mStartActivityRequestWhoSaved;
29720 boolean mIsAutofilled;
29721 boolean mHideHighlight;
29722 int mAutofillViewId;
29723
29724 /**
29725 * Constructor used when reading from a parcel. Reads the state of the superclass.
29726 *
29727 * @param source parcel to read from
29728 */
29729 public BaseSavedState(Parcel source) {
29730 this(source, null);
29731 }
29732
29733 /**
29734 * Constructor used when reading from a parcel using a given class loader.
29735 * Reads the state of the superclass.
29736 *
29737 * @param source parcel to read from
29738 * @param loader ClassLoader to use for reading
29739 */
29740 public BaseSavedState(Parcel source, ClassLoader loader) {
29741 super(source, loader);
29742 mSavedData = source.readInt();
29743 mStartActivityRequestWhoSaved = source.readString();
29744 mIsAutofilled = source.readBoolean();
29745 mHideHighlight = source.readBoolean();
29746 mAutofillViewId = source.readInt();
29747 }
29748
29749 /**
29750 * Constructor called by derived classes when creating their SavedState objects
29751 *
29752 * @param superState The state of the superclass of this view
29753 */
29754 public BaseSavedState(Parcelable superState) {
29755 super(superState);
29756 }
29757
29758 @Override
29759 public void writeToParcel(Parcel out, int flags) {
29760 super.writeToParcel(out, flags);
29761
29762 out.writeInt(mSavedData);
29763 out.writeString(mStartActivityRequestWhoSaved);
29764 out.writeBoolean(mIsAutofilled);
29765 out.writeBoolean(mHideHighlight);
29766 out.writeInt(mAutofillViewId);
29767 }
29768
29769 public static final @android.annotation.NonNull Parcelable.Creator<BaseSavedState> CREATOR
29770 = new Parcelable.ClassLoaderCreator<BaseSavedState>() {
29771 @Override
29772 public BaseSavedState createFromParcel(Parcel in) {
29773 return new BaseSavedState(in);
29774 }
29775
29776 @Override
29777 public BaseSavedState createFromParcel(Parcel in, ClassLoader loader) {
29778 return new BaseSavedState(in, loader);
29779 }
29780
29781 @Override
29782 public BaseSavedState[] newArray(int size) {
29783 return new BaseSavedState[size];
29784 }
29785 };
29786 }
29787
29788 /**
29789 * A set of information given to a view when it is attached to its parent
29790 * window.
29791 */
29792 final static class AttachInfo {
29793
29794 interface Callbacks {
29795 void playSoundEffect(int effectId);
29796 boolean performHapticFeedback(int effectId, boolean always);
29797 }
29798
29799 /**
29800 * InvalidateInfo is used to post invalidate(int, int, int, int) messages
29801 * to a Handler. This class contains the target (View) to invalidate and
29802 * the coordinates of the dirty rectangle.
29803 *
29804 * For performance purposes, this class also implements a pool of up to
29805 * POOL_LIMIT objects that get reused. This reduces memory allocations
29806 * whenever possible.
29807 */
29808 static class InvalidateInfo {
29809
29810 @UnsupportedAppUsage
29811 InvalidateInfo() {
29812 }
29813
29814 private static final int POOL_LIMIT = 10;
29815
29816 private static final SynchronizedPool<InvalidateInfo> sPool =
29817 new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
29818
29819 @UnsupportedAppUsage
29820 View target;
29821
29822 @UnsupportedAppUsage
29823 int left;
29824 @UnsupportedAppUsage
29825 int top;
29826 @UnsupportedAppUsage
29827 int right;
29828 @UnsupportedAppUsage
29829 int bottom;
29830
29831 public static InvalidateInfo obtain() {
29832 InvalidateInfo instance = sPool.acquire();
29833 return (instance != null) ? instance : new InvalidateInfo();
29834 }
29835
29836 public void recycle() {
29837 target = null;
29838 sPool.release(this);
29839 }
29840 }
29841
29842 @UnsupportedAppUsage
29843 final IWindowSession mSession;
29844
29845 @UnsupportedAppUsage
29846 final IWindow mWindow;
29847
29848 final IBinder mWindowToken;
29849
29850 Display mDisplay;
29851
29852 final Callbacks mRootCallbacks;
29853
29854 IWindowId mIWindowId;
29855 WindowId mWindowId;
29856
29857 /**
29858 * The top view of the hierarchy.
29859 */
29860 View mRootView;
29861
29862 IBinder mPanelParentWindowToken;
29863
29864 boolean mHardwareAccelerated;
29865 boolean mHardwareAccelerationRequested;
29866 ThreadedRenderer mThreadedRenderer;
29867 List<RenderNode> mPendingAnimatingRenderNodes;
29868
29869 /**
29870 * The state of the display to which the window is attached, as reported
29871 * by {@link Display#getState()}. Note that the display state constants
29872 * declared by {@link Display} do not exactly line up with the screen state
29873 * constants declared by {@link View} (there are more display states than
29874 * screen states).
29875 */
29876 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
29877 int mDisplayState = Display.STATE_UNKNOWN;
29878
29879 /**
29880 * Scale factor used by the compatibility mode
29881 */
29882 @UnsupportedAppUsage
29883 float mApplicationScale;
29884
29885 /**
29886 * Indicates whether the application is in compatibility mode
29887 */
29888 @UnsupportedAppUsage
29889 boolean mScalingRequired;
29890
29891 /**
29892 * Left position of this view's window
29893 */
29894 int mWindowLeft;
29895
29896 /**
29897 * Top position of this view's window
29898 */
29899 int mWindowTop;
29900
29901 /**
29902 * Indicates whether views need to use 32-bit drawing caches
29903 */
29904 boolean mUse32BitDrawingCache;
29905
29906 /**
29907 * For windows that are full-screen but using insets to layout inside
29908 * of the screen decorations, these are the current insets for the
29909 * content of the window.
29910 */
29911 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.Q,
29912 publicAlternatives = "Use {@link WindowInsets#getInsets(int)}")
29913 final Rect mContentInsets = new Rect();
29914
29915 /**
29916 * For windows that are full-screen but using insets to layout inside
29917 * of the screen decorations, these are the current insets for the
29918 * actual visible parts of the window.
29919 */
29920 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.Q,
29921 publicAlternatives = "Use {@link WindowInsets#getInsets(int)}")
29922 final Rect mVisibleInsets = new Rect();
29923
29924 /**
29925 * For windows that are full-screen but using insets to layout inside
29926 * of the screen decorations, these are the current insets for the
29927 * stable system windows.
29928 */
29929 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.Q,
29930 publicAlternatives = "Use {@link WindowInsets#getInsets(int)}")
29931 final Rect mStableInsets = new Rect();
29932
29933 /**
29934 * Current caption insets to the display coordinate.
29935 */
29936 final Rect mCaptionInsets = new Rect();
29937
29938 /**
29939 * In multi-window we force show the system bars. Because we don't want that the surface
29940 * size changes in this mode, we instead have a flag whether the system bars sizes should
29941 * always be consumed, so the app is treated like there are no virtual system bars at all.
29942 */
29943 boolean mAlwaysConsumeSystemBars;
29944
29945 /**
29946 * The internal insets given by this window. This value is
29947 * supplied by the client (through
29948 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
29949 * be given to the window manager when changed to be used in laying
29950 * out windows behind it.
29951 */
29952 @UnsupportedAppUsage
29953 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
29954 = new ViewTreeObserver.InternalInsetsInfo();
29955
29956 /**
29957 * Set to true when mGivenInternalInsets is non-empty.
29958 */
29959 boolean mHasNonEmptyGivenInternalInsets;
29960
29961 /**
29962 * All views in the window's hierarchy that serve as scroll containers,
29963 * used to determine if the window can be resized or must be panned
29964 * to adjust for a soft input area.
29965 */
29966 @UnsupportedAppUsage
29967 final ArrayList<View> mScrollContainers = new ArrayList<View>();
29968
29969 @UnsupportedAppUsage
29970 final KeyEvent.DispatcherState mKeyDispatchState
29971 = new KeyEvent.DispatcherState();
29972
29973 /**
29974 * Indicates whether the view's window currently has the focus.
29975 */
29976 @UnsupportedAppUsage
29977 boolean mHasWindowFocus;
29978
29979 /**
29980 * The current visibility of the window.
29981 */
29982 int mWindowVisibility;
29983
29984 /**
29985 * Indicates the time at which drawing started to occur.
29986 */
29987 @UnsupportedAppUsage
29988 long mDrawingTime;
29989
29990 /**
29991 * Indicates whether the view's window is currently in touch mode.
29992 */
29993 @UnsupportedAppUsage
29994 boolean mInTouchMode;
29995
29996 /**
29997 * Indicates whether the view has requested unbuffered input dispatching for the current
29998 * event stream.
29999 */
30000 boolean mUnbufferedDispatchRequested;
30001
30002 /**
30003 * Indicates that ViewAncestor should trigger a global layout change
30004 * the next time it performs a traversal
30005 */
30006 @UnsupportedAppUsage
30007 boolean mRecomputeGlobalAttributes;
30008
30009 /**
30010 * Always report new attributes at next traversal.
30011 */
30012 boolean mForceReportNewAttributes;
30013
30014 /**
30015 * Set during a traveral if any views want to keep the screen on.
30016 */
30017 @UnsupportedAppUsage
30018 boolean mKeepScreenOn;
30019
30020 /**
30021 * Set during a traveral if the light center needs to be updated.
30022 */
30023 boolean mNeedsUpdateLightCenter;
30024
30025 /**
30026 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
30027 */
30028 int mSystemUiVisibility;
30029
30030 /**
30031 * Hack to force certain system UI visibility flags to be cleared.
30032 */
30033 int mDisabledSystemUiVisibility;
30034
30035 /**
30036 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
30037 * attached.
30038 */
30039 boolean mHasSystemUiListeners;
30040
30041 /**
30042 * Set if the visibility of any views has changed.
30043 */
30044 @UnsupportedAppUsage
30045 boolean mViewVisibilityChanged;
30046
30047 /**
30048 * Set to true if a view has been scrolled.
30049 */
30050 @UnsupportedAppUsage
30051 boolean mViewScrollChanged;
30052
30053 /**
30054 * Set to true if a pointer event is currently being handled.
30055 */
30056 boolean mHandlingPointerEvent;
30057
30058 /**
30059 * The window matrix of this view when it's on a {@link SurfaceControlViewHost} that is
30060 * embedded within a SurfaceView.
30061 */
30062 Matrix mWindowMatrixInEmbeddedHierarchy;
30063
30064 /**
30065 * Global to the view hierarchy used as a temporary for dealing with
30066 * x/y points in the transparent region computations.
30067 */
30068 final int[] mTransparentLocation = new int[2];
30069
30070 /**
30071 * Global to the view hierarchy used as a temporary for dealing with
30072 * x/y points in the ViewGroup.invalidateChild implementation.
30073 */
30074 final int[] mInvalidateChildLocation = new int[2];
30075
30076 /**
30077 * Global to the view hierarchy used as a temporary for dealing with
30078 * computing absolute on-screen location.
30079 */
30080 final int[] mTmpLocation = new int[2];
30081
30082 /**
30083 * Global to the view hierarchy used as a temporary for dealing with
30084 * x/y location when view is transformed.
30085 */
30086 final float[] mTmpTransformLocation = new float[2];
30087
30088 /**
30089 * The view tree observer used to dispatch global events like
30090 * layout, pre-draw, touch mode change, etc.
30091 */
30092 @UnsupportedAppUsage
30093 final ViewTreeObserver mTreeObserver;
30094
30095 /**
30096 * A Canvas used by the view hierarchy to perform bitmap caching.
30097 */
30098 Canvas mCanvas;
30099
30100 /**
30101 * The view root impl.
30102 */
30103 final ViewRootImpl mViewRootImpl;
30104
30105 /**
30106 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
30107 * handler can be used to pump events in the UI events queue.
30108 */
30109 @UnsupportedAppUsage
30110 final Handler mHandler;
30111
30112 /**
30113 * Temporary for use in computing invalidate rectangles while
30114 * calling up the hierarchy.
30115 */
30116 final Rect mTmpInvalRect = new Rect();
30117
30118 /**
30119 * Temporary for use in computing hit areas with transformed views
30120 */
30121 final RectF mTmpTransformRect = new RectF();
30122
30123 /**
30124 * Temporary for use in computing hit areas with transformed views
30125 */
30126 final RectF mTmpTransformRect1 = new RectF();
30127
30128 /**
30129 * Temporary list of rectanges.
30130 */
30131 final List<RectF> mTmpRectList = new ArrayList<>();
30132
30133 /**
30134 * Temporary for use in transforming invalidation rect
30135 */
30136 final Matrix mTmpMatrix = new Matrix();
30137
30138 /**
30139 * Temporary for use in transforming invalidation rect
30140 */
30141 final Transformation mTmpTransformation = new Transformation();
30142
30143 /**
30144 * Temporary for use in querying outlines from OutlineProviders
30145 */
30146 final Outline mTmpOutline = new Outline();
30147
30148 /**
30149 * Temporary list for use in collecting focusable descendents of a view.
30150 */
30151 final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
30152
30153 /**
30154 * The id of the window for accessibility purposes.
30155 */
30156 int mAccessibilityWindowId = AccessibilityWindowInfo.UNDEFINED_WINDOW_ID;
30157
30158 /**
30159 * Flags related to accessibility processing.
30160 *
30161 * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
30162 * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
30163 */
30164 int mAccessibilityFetchFlags;
30165
30166 /**
30167 * The drawable for highlighting accessibility focus.
30168 */
30169 Drawable mAccessibilityFocusDrawable;
30170
30171 /**
30172 * The drawable for highlighting autofilled views.
30173 *
30174 * @see #isAutofilled()
30175 */
30176 Drawable mAutofilledDrawable;
30177
30178 /**
30179 * Show where the margins, bounds and layout bounds are for each view.
30180 */
30181 boolean mDebugLayout = DisplayProperties.debug_layout().orElse(false);
30182
30183 /**
30184 * Point used to compute visible regions.
30185 */
30186 final Point mPoint = new Point();
30187
30188 /**
30189 * Used to track which View originated a requestLayout() call, used when
30190 * requestLayout() is called during layout.
30191 */
30192 View mViewRequestingLayout;
30193
30194 /**
30195 * Used to track the identity of the current drag operation.
30196 */
30197 IBinder mDragToken;
30198
30199 /**
30200 * The drag shadow surface for the current drag operation.
30201 */
30202 public Surface mDragSurface;
30203
30204
30205 /**
30206 * The view that currently has a tooltip displayed.
30207 */
30208 View mTooltipHost;
30209
30210 /**
30211 * The initial structure has been reported so the view is ready to report updates.
30212 */
30213 boolean mReadyForContentCaptureUpdates;
30214
30215 /**
30216 * Map(keyed by session) of content capture events that need to be notified after the view
30217 * hierarchy is traversed: value is either the view itself for appearead events, or its
30218 * autofill id for disappeared.
30219 */
30220 SparseArray<ArrayList<Object>> mContentCaptureEvents;
30221
30222 /**
30223 * Cached reference to the {@link ContentCaptureManager}.
30224 */
30225 ContentCaptureManager mContentCaptureManager;
30226
30227 /**
30228 * Listener used to fit content on window level.
30229 */
30230 OnContentApplyWindowInsetsListener mContentOnApplyWindowInsetsListener;
30231
30232 /**
30233 * The leash token of this view's parent when it's in an embedded hierarchy that is
30234 * re-parented to another window.
30235 */
30236 IBinder mLeashedParentToken;
30237
30238 /**
30239 * The accessibility view id of this view's parent when it's in an embedded
30240 * hierarchy that is re-parented to another window.
30241 */
30242 int mLeashedParentAccessibilityViewId;
30243
30244 /**
30245 *
30246 */
30247 ScrollCaptureInternal mScrollCaptureInternal;
30248
30249 /**
30250 * Creates a new set of attachment information with the specified
30251 * events handler and thread.
30252 *
30253 * @param handler the events handler the view must use
30254 */
30255 AttachInfo(IWindowSession session, IWindow window, Display display,
30256 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer,
30257 Context context) {
30258 mSession = session;
30259 mWindow = window;
30260 mWindowToken = window.asBinder();
30261 mDisplay = display;
30262 mViewRootImpl = viewRootImpl;
30263 mHandler = handler;
30264 mRootCallbacks = effectPlayer;
30265 mTreeObserver = new ViewTreeObserver(context);
30266 }
30267
30268 @Nullable
30269 ContentCaptureManager getContentCaptureManager(@NonNull Context context) {
30270 if (mContentCaptureManager != null) {
30271 return mContentCaptureManager;
30272 }
30273 mContentCaptureManager = context.getSystemService(ContentCaptureManager.class);
30274 return mContentCaptureManager;
30275 }
30276
30277 void delayNotifyContentCaptureInsetsEvent(@NonNull Insets insets) {
30278 if (mContentCaptureManager == null) {
30279 return;
30280 }
30281
30282 ArrayList<Object> events = ensureEvents(
30283 mContentCaptureManager.getMainContentCaptureSession());
30284 events.add(insets);
30285 }
30286
30287 private void delayNotifyContentCaptureEvent(@NonNull ContentCaptureSession session,
30288 @NonNull View view, boolean appeared) {
30289 ArrayList<Object> events = ensureEvents(session);
30290 events.add(appeared ? view : view.getAutofillId());
30291 }
30292
30293 @NonNull
30294 private ArrayList<Object> ensureEvents(@NonNull ContentCaptureSession session) {
30295 if (mContentCaptureEvents == null) {
30296 // Most of the time there will be just one session, so intial capacity is 1
30297 mContentCaptureEvents = new SparseArray<>(1);
30298 }
30299 int sessionId = session.getId();
30300 // TODO: life would be much easier if we provided a MultiMap implementation somwhere...
30301 ArrayList<Object> events = mContentCaptureEvents.get(sessionId);
30302 if (events == null) {
30303 events = new ArrayList<>();
30304 mContentCaptureEvents.put(sessionId, events);
30305 }
30306
30307 return events;
30308 }
30309
30310 @Nullable
30311 ScrollCaptureInternal getScrollCaptureInternal() {
30312 if (mScrollCaptureInternal != null) {
30313 mScrollCaptureInternal = new ScrollCaptureInternal();
30314 }
30315 return mScrollCaptureInternal;
30316 }
30317
30318 AttachedSurfaceControl getRootSurfaceControl() {
30319 return mViewRootImpl;
30320 }
30321
30322 public void dump(String prefix, PrintWriter writer) {
30323 String innerPrefix = prefix + " ";
30324 writer.println(prefix + "AttachInfo:");
30325 writer.println(innerPrefix + "mHasWindowFocus=" + mHasWindowFocus);
30326 writer.println(innerPrefix + "mWindowVisibility=" + mWindowVisibility);
30327 writer.println(innerPrefix + "mInTouchMode=" + mInTouchMode);
30328 writer.println(innerPrefix + "mUnbufferedDispatchRequested="
30329 + mUnbufferedDispatchRequested);
30330 }
30331 }
30332
30333 /**
30334 * <p>ScrollabilityCache holds various fields used by a View when scrolling
30335 * is supported. This avoids keeping too many unused fields in most
30336 * instances of View.</p>
30337 */
30338 private static class ScrollabilityCache implements Runnable {
30339
30340 /**
30341 * Scrollbars are not visible
30342 */
30343 public static final int OFF = 0;
30344
30345 /**
30346 * Scrollbars are visible
30347 */
30348 public static final int ON = 1;
30349
30350 /**
30351 * Scrollbars are fading away
30352 */
30353 public static final int FADING = 2;
30354
30355 public boolean fadeScrollBars;
30356
30357 public int fadingEdgeLength;
30358 public int scrollBarDefaultDelayBeforeFade;
30359 public int scrollBarFadeDuration;
30360
30361 public int scrollBarSize;
30362 public int scrollBarMinTouchTarget;
30363 @UnsupportedAppUsage
30364 public ScrollBarDrawable scrollBar;
30365 public float[] interpolatorValues;
30366 @UnsupportedAppUsage
30367 public View host;
30368
30369 public final Paint paint;
30370 public final Matrix matrix;
30371 public Shader shader;
30372
30373 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
30374
30375 private static final float[] OPAQUE = { 255 };
30376 private static final float[] TRANSPARENT = { 0.0f };
30377
30378 /**
30379 * When fading should start. This time moves into the future every time
30380 * a new scroll happens. Measured based on SystemClock.uptimeMillis()
30381 */
30382 public long fadeStartTime;
30383
30384
30385 /**
30386 * The current state of the scrollbars: ON, OFF, or FADING
30387 */
30388 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
30389 public int state = OFF;
30390
30391 private int mLastColor;
30392
30393 public final Rect mScrollBarBounds = new Rect();
30394 public final Rect mScrollBarTouchBounds = new Rect();
30395
30396 public static final int NOT_DRAGGING = 0;
30397 public static final int DRAGGING_VERTICAL_SCROLL_BAR = 1;
30398 public static final int DRAGGING_HORIZONTAL_SCROLL_BAR = 2;
30399 public int mScrollBarDraggingState = NOT_DRAGGING;
30400
30401 public float mScrollBarDraggingPos = 0;
30402
30403 public ScrollabilityCache(ViewConfiguration configuration, View host) {
30404 fadingEdgeLength = configuration.getScaledFadingEdgeLength();
30405 scrollBarSize = configuration.getScaledScrollBarSize();
30406 scrollBarMinTouchTarget = configuration.getScaledMinScrollbarTouchTarget();
30407 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
30408 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
30409
30410 paint = new Paint();
30411 matrix = new Matrix();
30412 // use use a height of 1, and then wack the matrix each time we
30413 // actually use it.
30414 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
30415 paint.setShader(shader);
30416 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
30417
30418 this.host = host;
30419 }
30420
30421 public void setFadeColor(int color) {
30422 if (color != mLastColor) {
30423 mLastColor = color;
30424
30425 if (color != 0) {
30426 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
30427 color & 0x00FFFFFF, Shader.TileMode.CLAMP);
30428 paint.setShader(shader);
30429 // Restore the default transfer mode (src_over)
30430 paint.setXfermode(null);
30431 } else {
30432 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
30433 paint.setShader(shader);
30434 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
30435 }
30436 }
30437 }
30438
30439 public void run() {
30440 long now = AnimationUtils.currentAnimationTimeMillis();
30441 if (now >= fadeStartTime) {
30442
30443 // the animation fades the scrollbars out by changing
30444 // the opacity (alpha) from fully opaque to fully
30445 // transparent
30446 int nextFrame = (int) now;
30447 int framesCount = 0;
30448
30449 Interpolator interpolator = scrollBarInterpolator;
30450
30451 // Start opaque
30452 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
30453
30454 // End transparent
30455 nextFrame += scrollBarFadeDuration;
30456 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
30457
30458 state = FADING;
30459
30460 // Kick off the fade animation
30461 host.invalidate(true);
30462 }
30463 }
30464 }
30465
30466 private class SendAccessibilityEventThrottle implements Runnable {
30467 public volatile boolean mIsPending;
30468 private AccessibilityEvent mAccessibilityEvent;
30469
30470 public void post(AccessibilityEvent accessibilityEvent) {
30471 updateWithAccessibilityEvent(accessibilityEvent);
30472 if (!mIsPending) {
30473 mIsPending = true;
30474 postDelayed(this,
30475 ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
30476 }
30477 }
30478
30479 @Override
30480 public void run() {
30481 if (AccessibilityManager.getInstance(mContext).isEnabled() && isShown()) {
30482 requestParentSendAccessibilityEvent(mAccessibilityEvent);
30483 }
30484 reset();
30485 }
30486
30487 public void updateWithAccessibilityEvent(AccessibilityEvent accessibilityEvent) {
30488 mAccessibilityEvent = accessibilityEvent;
30489 }
30490
30491 public void reset() {
30492 mIsPending = false;
30493 mAccessibilityEvent = null;
30494 }
30495
30496 }
30497
30498 /**
30499 * Resuable callback for sending
30500 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
30501 */
30502 private class SendViewScrolledAccessibilityEvent extends SendAccessibilityEventThrottle {
30503 public int mDeltaX;
30504 public int mDeltaY;
30505
30506 @Override
30507 public void updateWithAccessibilityEvent(AccessibilityEvent accessibilityEvent) {
30508 super.updateWithAccessibilityEvent(accessibilityEvent);
30509 mDeltaX += accessibilityEvent.getScrollDeltaX();
30510 mDeltaY += accessibilityEvent.getScrollDeltaY();
30511 accessibilityEvent.setScrollDeltaX(mDeltaX);
30512 accessibilityEvent.setScrollDeltaY(mDeltaY);
30513 }
30514
30515 @Override
30516 public void reset() {
30517 super.reset();
30518 mDeltaX = 0;
30519 mDeltaY = 0;
30520 }
30521 }
30522 /**
30523 * Remove the pending callback for sending a throttled accessibility event.
30524 */
30525 @UnsupportedAppUsage
30526 private void cancel(@Nullable SendAccessibilityEventThrottle callback) {
30527 if (callback == null || !callback.mIsPending) return;
30528 removeCallbacks(callback);
30529 callback.reset();
30530 }
30531
30532 /**
30533 * <p>
30534 * This class represents a delegate that can be registered in a {@link View}
30535 * to enhance accessibility support via composition rather via inheritance.
30536 * It is specifically targeted to widget developers that extend basic View
30537 * classes i.e. classes in package android.view, that would like their
30538 * applications to be backwards compatible.
30539 * </p>
30540 * <div class="special reference">
30541 * <h3>Developer Guides</h3>
30542 * <p>For more information about making applications accessible, read the
30543 * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
30544 * developer guide.</p>
30545 * </div>
30546 * <p>
30547 * A scenario in which a developer would like to use an accessibility delegate
30548 * is overriding a method introduced in a later API version than the minimal API
30549 * version supported by the application. For example, the method
30550 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
30551 * in API version 4 when the accessibility APIs were first introduced. If a
30552 * developer would like their application to run on API version 4 devices (assuming
30553 * all other APIs used by the application are version 4 or lower) and take advantage
30554 * of this method, instead of overriding the method which would break the application's
30555 * backwards compatibility, they can override the corresponding method in this
30556 * delegate and register the delegate in the target View if the API version of
30557 * the system is high enough, i.e. the API version is the same as or higher than the API
30558 * version that introduced
30559 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
30560 * </p>
30561 * <p>
30562 * Here is an example implementation:
30563 * </p>
30564 * <code><pre><p>
30565 * if (Build.VERSION.SDK_INT >= 14) {
30566 * // If the API version is equal of higher than the version in
30567 * // which onInitializeAccessibilityNodeInfo was introduced we
30568 * // register a delegate with a customized implementation.
30569 * View view = findViewById(R.id.view_id);
30570 * view.setAccessibilityDelegate(new AccessibilityDelegate() {
30571 * public void onInitializeAccessibilityNodeInfo(View host,
30572 * AccessibilityNodeInfo info) {
30573 * // Let the default implementation populate the info.
30574 * super.onInitializeAccessibilityNodeInfo(host, info);
30575 * // Set some other information.
30576 * info.setEnabled(host.isEnabled());
30577 * }
30578 * });
30579 * }
30580 * </code></pre></p>
30581 * <p>
30582 * This delegate contains methods that correspond to the accessibility methods
30583 * in View. If a delegate has been specified the implementation in View hands
30584 * off handling to the corresponding method in this delegate. The default
30585 * implementation the delegate methods behaves exactly as the corresponding
30586 * method in View for the case of no accessibility delegate been set. Hence,
30587 * to customize the behavior of a View method, clients can override only the
30588 * corresponding delegate method without altering the behavior of the rest
30589 * accessibility related methods of the host view.
30590 * </p>
30591 * <p>
30592 * <strong>Note:</strong> On platform versions prior to
30593 * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on
30594 * views in the {@code android.widget.*} package are called <i>before</i>
30595 * host methods. This prevents certain properties such as class name from
30596 * being modified by overriding
30597 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)},
30598 * as any changes will be overwritten by the host class.
30599 * <p>
30600 * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate
30601 * methods are called <i>after</i> host methods, which all properties to be
30602 * modified without being overwritten by the host class.
30603 */
30604 public static class AccessibilityDelegate {
30605
30606 /**
30607 * Sends an accessibility event of the given type. If accessibility is not
30608 * enabled this method has no effect.
30609 * <p>
30610 * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
30611 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
30612 * been set.
30613 * </p>
30614 *
30615 * @param host The View hosting the delegate.
30616 * @param eventType The type of the event to send.
30617 *
30618 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
30619 */
30620 public void sendAccessibilityEvent(@NonNull View host, int eventType) {
30621 host.sendAccessibilityEventInternal(eventType);
30622 }
30623
30624 /**
30625 * Performs the specified accessibility action on the view. For
30626 * possible accessibility actions look at {@link AccessibilityNodeInfo}.
30627 * <p>
30628 * The default implementation behaves as
30629 * {@link View#performAccessibilityAction(int, Bundle)
30630 * View#performAccessibilityAction(int, Bundle)} for the case of
30631 * no accessibility delegate been set.
30632 * </p>
30633 *
30634 * @param action The action to perform.
30635 * @return Whether the action was performed.
30636 *
30637 * @see View#performAccessibilityAction(int, Bundle)
30638 * View#performAccessibilityAction(int, Bundle)
30639 */
30640 public boolean performAccessibilityAction(@NonNull View host, int action,
30641 @Nullable Bundle args) {
30642 return host.performAccessibilityActionInternal(action, args);
30643 }
30644
30645 /**
30646 * Sends an accessibility event. This method behaves exactly as
30647 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
30648 * empty {@link AccessibilityEvent} and does not perform a check whether
30649 * accessibility is enabled.
30650 * <p>
30651 * The default implementation behaves as
30652 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
30653 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
30654 * the case of no accessibility delegate been set.
30655 * </p>
30656 *
30657 * @param host The View hosting the delegate.
30658 * @param event The event to send.
30659 *
30660 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
30661 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)
30662 */
30663 public void sendAccessibilityEventUnchecked(@NonNull View host,
30664 @NonNull AccessibilityEvent event) {
30665 host.sendAccessibilityEventUncheckedInternal(event);
30666 }
30667
30668 /**
30669 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
30670 * to its children for adding their text content to the event.
30671 * <p>
30672 * The default implementation behaves as
30673 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
30674 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
30675 * the case of no accessibility delegate been set.
30676 * </p>
30677 *
30678 * @param host The View hosting the delegate.
30679 * @param event The event.
30680 * @return True if the event population was completed.
30681 *
30682 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
30683 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
30684 */
30685 public boolean dispatchPopulateAccessibilityEvent(@NonNull View host,
30686 @NonNull AccessibilityEvent event) {
30687 return host.dispatchPopulateAccessibilityEventInternal(event);
30688 }
30689
30690 /**
30691 * Gives a chance to the host View to populate the accessibility event with its
30692 * text content.
30693 * <p>
30694 * The default implementation behaves as
30695 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
30696 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
30697 * the case of no accessibility delegate been set.
30698 * </p>
30699 *
30700 * @param host The View hosting the delegate.
30701 * @param event The accessibility event which to populate.
30702 *
30703 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
30704 * View#onPopulateAccessibilityEvent(AccessibilityEvent)
30705 */
30706 public void onPopulateAccessibilityEvent(@NonNull View host,
30707 @NonNull AccessibilityEvent event) {
30708 host.onPopulateAccessibilityEventInternal(event);
30709 }
30710
30711 /**
30712 * Initializes an {@link AccessibilityEvent} with information about the
30713 * the host View which is the event source.
30714 * <p>
30715 * The default implementation behaves as
30716 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
30717 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
30718 * the case of no accessibility delegate been set.
30719 * </p>
30720 *
30721 * @param host The View hosting the delegate.
30722 * @param event The event to initialize.
30723 *
30724 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
30725 * View#onInitializeAccessibilityEvent(AccessibilityEvent)
30726 */
30727 public void onInitializeAccessibilityEvent(@NonNull View host,
30728 @NonNull AccessibilityEvent event) {
30729 host.onInitializeAccessibilityEventInternal(event);
30730 }
30731
30732 /**
30733 * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
30734 * <p>
30735 * The default implementation behaves as
30736 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
30737 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
30738 * the case of no accessibility delegate been set.
30739 * </p>
30740 *
30741 * @param host The View hosting the delegate.
30742 * @param info The instance to initialize.
30743 *
30744 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
30745 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
30746 */
30747 public void onInitializeAccessibilityNodeInfo(@NonNull View host,
30748 @NonNull AccessibilityNodeInfo info) {
30749 host.onInitializeAccessibilityNodeInfoInternal(info);
30750 }
30751
30752 /**
30753 * Adds extra data to an {@link AccessibilityNodeInfo} based on an explicit request for the
30754 * additional data.
30755 * <p>
30756 * This method only needs to be implemented if the View offers to provide additional data.
30757 * </p>
30758 * <p>
30759 * The default implementation behaves as
30760 * {@link View#addExtraDataToAccessibilityNodeInfo(AccessibilityNodeInfo, String, Bundle)
30761 * for the case where no accessibility delegate is set.
30762 * </p>
30763 *
30764 * @param host The View hosting the delegate. Never {@code null}.
30765 * @param info The info to which to add the extra data. Never {@code null}.
30766 * @param extraDataKey A key specifying the type of extra data to add to the info. The
30767 * extra data should be added to the {@link Bundle} returned by
30768 * the info's {@link AccessibilityNodeInfo#getExtras} method. Never
30769 * {@code null}.
30770 * @param arguments A {@link Bundle} holding any arguments relevant for this request.
30771 * May be {@code null} if the if the service provided no arguments.
30772 *
30773 * @see AccessibilityNodeInfo#setAvailableExtraData(List)
30774 */
30775 public void addExtraDataToAccessibilityNodeInfo(@NonNull View host,
30776 @NonNull AccessibilityNodeInfo info, @NonNull String extraDataKey,
30777 @Nullable Bundle arguments) {
30778 host.addExtraDataToAccessibilityNodeInfo(info, extraDataKey, arguments);
30779 }
30780
30781 /**
30782 * Called when a child of the host View has requested sending an
30783 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
30784 * to augment the event.
30785 * <p>
30786 * The default implementation behaves as
30787 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
30788 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
30789 * the case of no accessibility delegate been set.
30790 * </p>
30791 *
30792 * @param host The View hosting the delegate.
30793 * @param child The child which requests sending the event.
30794 * @param event The event to be sent.
30795 * @return True if the event should be sent
30796 *
30797 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
30798 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
30799 */
30800 public boolean onRequestSendAccessibilityEvent(@NonNull ViewGroup host, @NonNull View child,
30801 @NonNull AccessibilityEvent event) {
30802 return host.onRequestSendAccessibilityEventInternal(child, event);
30803 }
30804
30805 /**
30806 * Gets the provider for managing a virtual view hierarchy rooted at this View
30807 * and reported to {@link android.accessibilityservice.AccessibilityService}s
30808 * that explore the window content.
30809 * <p>
30810 * The default implementation behaves as
30811 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
30812 * the case of no accessibility delegate been set.
30813 * </p>
30814 *
30815 * @return The provider.
30816 *
30817 * @see AccessibilityNodeProvider
30818 */
30819 public @Nullable AccessibilityNodeProvider getAccessibilityNodeProvider(
30820 @NonNull View host) {
30821 return null;
30822 }
30823
30824 /**
30825 * Returns an {@link AccessibilityNodeInfo} representing the host view from the
30826 * point of view of an {@link android.accessibilityservice.AccessibilityService}.
30827 * This method is responsible for obtaining an accessibility node info from a
30828 * pool of reusable instances and calling
30829 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
30830 * view to initialize the former.
30831 * <p>
30832 * <strong>Note:</strong> The client is responsible for recycling the obtained
30833 * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
30834 * creation.
30835 * </p>
30836 * <p>
30837 * The default implementation behaves as
30838 * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
30839 * the case of no accessibility delegate been set.
30840 * </p>
30841 * @return A populated {@link AccessibilityNodeInfo}.
30842 *
30843 * @see AccessibilityNodeInfo
30844 *
30845 * @hide
30846 */
30847 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
30848 public AccessibilityNodeInfo createAccessibilityNodeInfo(@NonNull View host) {
30849 return host.createAccessibilityNodeInfoInternal();
30850 }
30851 }
30852
30853 private static class MatchIdPredicate implements Predicate<View> {
30854 public int mId;
30855
30856 @Override
30857 public boolean test(View view) {
30858 return (view.mID == mId);
30859 }
30860 }
30861
30862 private static class MatchLabelForPredicate implements Predicate<View> {
30863 private int mLabeledId;
30864
30865 @Override
30866 public boolean test(View view) {
30867 return (view.mLabelForId == mLabeledId);
30868 }
30869 }
30870
30871
30872 /**
30873 * Returns the current scroll capture hint for this view.
30874 *
30875 * @return the current scroll capture hint
30876 */
30877 @ScrollCaptureHint
30878 public int getScrollCaptureHint() {
30879 return (mPrivateFlags4 & PFLAG4_SCROLL_CAPTURE_HINT_MASK)
30880 >> PFLAG4_SCROLL_CAPTURE_HINT_SHIFT;
30881 }
30882
30883 /**
30884 * Sets the scroll capture hint for this View. These flags affect the search for a potential
30885 * scroll capture targets.
30886 *
30887 * @param hint the scrollCaptureHint flags value to set
30888 */
30889 public void setScrollCaptureHint(@ScrollCaptureHint int hint) {
30890 mPrivateFlags4 &= ~PFLAG4_SCROLL_CAPTURE_HINT_MASK;
30891 // Since include/exclude are mutually exclusive, exclude takes precedence.
30892 if ((hint & SCROLL_CAPTURE_HINT_EXCLUDE) != 0) {
30893 hint &= ~SCROLL_CAPTURE_HINT_INCLUDE;
30894 }
30895 mPrivateFlags4 |= ((hint << PFLAG4_SCROLL_CAPTURE_HINT_SHIFT)
30896 & PFLAG4_SCROLL_CAPTURE_HINT_MASK);
30897 }
30898
30899 /**
30900 * Sets the callback to receive scroll capture requests. This component is the adapter between
30901 * the scroll capture API and application UI code. If no callback is set, the system may provide
30902 * an implementation. Any value provided here will take precedence over a system version.
30903 * <p>
30904 * This view will be ignored when {@link #SCROLL_CAPTURE_HINT_EXCLUDE} is set in its {@link
30905 * #setScrollCaptureHint(int) scrollCaptureHint}, regardless whether a callback has been set.
30906 * <p>
30907 * It is recommended to set the scroll capture hint {@link #SCROLL_CAPTURE_HINT_INCLUDE} when
30908 * setting a custom callback to help ensure it is selected as the target.
30909 *
30910 * @param callback the new callback to assign
30911 */
30912 public final void setScrollCaptureCallback(@Nullable ScrollCaptureCallback callback) {
30913 getListenerInfo().mScrollCaptureCallback = callback;
30914 }
30915
30916 /** {@hide} */
30917 @Nullable
30918 public ScrollCaptureCallback createScrollCaptureCallbackInternal(@NonNull Rect localVisibleRect,
30919 @NonNull Point windowOffset) {
30920 if (mAttachInfo == null) {
30921 return null;
30922 }
30923 if (mAttachInfo.mScrollCaptureInternal == null) {
30924 mAttachInfo.mScrollCaptureInternal = new ScrollCaptureInternal();
30925 }
30926 return mAttachInfo.mScrollCaptureInternal.requestCallback(this, localVisibleRect,
30927 windowOffset);
30928 }
30929
30930 /**
30931 * Dispatch a scroll capture search request down the view hierarchy.
30932 *
30933 * @param localVisibleRect the visible area of this ViewGroup in local coordinates, according to
30934 * the parent
30935 * @param windowOffset the offset of this view within the window
30936 * @param targets accepts potential scroll capture targets; {@link Consumer#accept
30937 * results.accept} may be called zero or more times on the calling
30938 * thread before onScrollCaptureSearch returns
30939 */
30940 public void dispatchScrollCaptureSearch(
30941 @NonNull Rect localVisibleRect, @NonNull Point windowOffset,
30942 @NonNull Consumer<ScrollCaptureTarget> targets) {
30943 onScrollCaptureSearch(localVisibleRect, windowOffset, targets);
30944 }
30945
30946 /**
30947 * Called when scroll capture is requested, to search for appropriate content to scroll. If
30948 * applicable, this view adds itself to the provided list for consideration, subject to the
30949 * flags set by {@link #setScrollCaptureHint}.
30950 *
30951 * @param localVisibleRect the local visible rect of this view
30952 * @param windowOffset the offset of localVisibleRect within the window
30953 * @param targets accepts potential scroll capture targets; {@link Consumer#accept
30954 * results.accept} may be called zero or more times on the calling
30955 * thread before onScrollCaptureSearch returns
30956 * @throws IllegalStateException if this view is not attached to a window
30957 */
30958 public void onScrollCaptureSearch(@NonNull Rect localVisibleRect,
30959 @NonNull Point windowOffset, @NonNull Consumer<ScrollCaptureTarget> targets) {
30960 int hint = getScrollCaptureHint();
30961 if ((hint & SCROLL_CAPTURE_HINT_EXCLUDE) != 0) {
30962 return;
30963 }
30964 boolean rectIsVisible = true;
30965
30966 // Apply clipBounds if present.
30967 if (mClipBounds != null) {
30968 rectIsVisible = localVisibleRect.intersect(mClipBounds);
30969 }
30970 if (!rectIsVisible) {
30971 return;
30972 }
30973
30974 // Get a callback provided by the framework, library or application.
30975 ScrollCaptureCallback callback =
30976 (mListenerInfo == null) ? null : mListenerInfo.mScrollCaptureCallback;
30977
30978 // Try framework support for standard scrolling containers.
30979 if (callback == null) {
30980 callback = createScrollCaptureCallbackInternal(localVisibleRect, windowOffset);
30981 }
30982
30983 // If found, then add it to the list.
30984 if (callback != null) {
30985 // Add to the list for consideration
30986 Point offset = new Point(windowOffset.x, windowOffset.y);
30987 Rect rect = new Rect(localVisibleRect);
30988 targets.accept(new ScrollCaptureTarget(this, rect, offset, callback));
30989 }
30990 }
30991
30992 /**
30993 * Dump all private flags in readable format, useful for documentation and
30994 * consistency checking.
30995 */
30996 private static void dumpFlags() {
30997 final HashMap<String, String> found = Maps.newHashMap();
30998 try {
30999 for (Field field : View.class.getDeclaredFields()) {
31000 final int modifiers = field.getModifiers();
31001 if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
31002 if (field.getType().equals(int.class)) {
31003 final int value = field.getInt(null);
31004 dumpFlag(found, field.getName(), value);
31005 } else if (field.getType().equals(int[].class)) {
31006 final int[] values = (int[]) field.get(null);
31007 for (int i = 0; i < values.length; i++) {
31008 dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
31009 }
31010 }
31011 }
31012 }
31013 } catch (IllegalAccessException e) {
31014 throw new RuntimeException(e);
31015 }
31016
31017 final ArrayList<String> keys = Lists.newArrayList();
31018 keys.addAll(found.keySet());
31019 Collections.sort(keys);
31020 for (String key : keys) {
31021 Log.d(VIEW_LOG_TAG, found.get(key));
31022 }
31023 }
31024
31025 private static void dumpFlag(HashMap<String, String> found, String name, int value) {
31026 // Sort flags by prefix, then by bits, always keeping unique keys
31027 final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
31028 final int prefix = name.indexOf('_');
31029 final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
31030 final String output = bits + " " + name;
31031 found.put(key, output);
31032 }
31033
31034 /** {@hide} */
31035 public void encode(@NonNull ViewHierarchyEncoder stream) {
31036 stream.beginObject(this);
31037 encodeProperties(stream);
31038 stream.endObject();
31039 }
31040
31041 /** {@hide} */
31042 @CallSuper
31043 protected void encodeProperties(@NonNull ViewHierarchyEncoder stream) {
31044 Object resolveId = ViewDebug.resolveId(getContext(), mID);
31045 if (resolveId instanceof String) {
31046 stream.addProperty("id", (String) resolveId);
31047 } else {
31048 stream.addProperty("id", mID);
31049 }
31050
31051 stream.addProperty("misc:transformation.alpha",
31052 mTransformationInfo != null ? mTransformationInfo.mAlpha : 0);
31053 stream.addProperty("misc:transitionName", getTransitionName());
31054
31055 // layout
31056 stream.addProperty("layout:left", mLeft);
31057 stream.addProperty("layout:right", mRight);
31058 stream.addProperty("layout:top", mTop);
31059 stream.addProperty("layout:bottom", mBottom);
31060 stream.addProperty("layout:width", getWidth());
31061 stream.addProperty("layout:height", getHeight());
31062 stream.addProperty("layout:layoutDirection", getLayoutDirection());
31063 stream.addProperty("layout:layoutRtl", isLayoutRtl());
31064 stream.addProperty("layout:hasTransientState", hasTransientState());
31065 stream.addProperty("layout:baseline", getBaseline());
31066
31067 // layout params
31068 ViewGroup.LayoutParams layoutParams = getLayoutParams();
31069 if (layoutParams != null) {
31070 stream.addPropertyKey("layoutParams");
31071 layoutParams.encode(stream);
31072 }
31073
31074 // scrolling
31075 stream.addProperty("scrolling:scrollX", mScrollX);
31076 stream.addProperty("scrolling:scrollY", mScrollY);
31077
31078 // padding
31079 stream.addProperty("padding:paddingLeft", mPaddingLeft);
31080 stream.addProperty("padding:paddingRight", mPaddingRight);
31081 stream.addProperty("padding:paddingTop", mPaddingTop);
31082 stream.addProperty("padding:paddingBottom", mPaddingBottom);
31083 stream.addProperty("padding:userPaddingRight", mUserPaddingRight);
31084 stream.addProperty("padding:userPaddingLeft", mUserPaddingLeft);
31085 stream.addProperty("padding:userPaddingBottom", mUserPaddingBottom);
31086 stream.addProperty("padding:userPaddingStart", mUserPaddingStart);
31087 stream.addProperty("padding:userPaddingEnd", mUserPaddingEnd);
31088
31089 // measurement
31090 stream.addProperty("measurement:minHeight", mMinHeight);
31091 stream.addProperty("measurement:minWidth", mMinWidth);
31092 stream.addProperty("measurement:measuredWidth", mMeasuredWidth);
31093 stream.addProperty("measurement:measuredHeight", mMeasuredHeight);
31094
31095 // drawing
31096 stream.addProperty("drawing:elevation", getElevation());
31097 stream.addProperty("drawing:translationX", getTranslationX());
31098 stream.addProperty("drawing:translationY", getTranslationY());
31099 stream.addProperty("drawing:translationZ", getTranslationZ());
31100 stream.addProperty("drawing:rotation", getRotation());
31101 stream.addProperty("drawing:rotationX", getRotationX());
31102 stream.addProperty("drawing:rotationY", getRotationY());
31103 stream.addProperty("drawing:scaleX", getScaleX());
31104 stream.addProperty("drawing:scaleY", getScaleY());
31105 stream.addProperty("drawing:pivotX", getPivotX());
31106 stream.addProperty("drawing:pivotY", getPivotY());
31107 stream.addProperty("drawing:clipBounds",
31108 mClipBounds == null ? null : mClipBounds.toString());
31109 stream.addProperty("drawing:opaque", isOpaque());
31110 stream.addProperty("drawing:alpha", getAlpha());
31111 stream.addProperty("drawing:transitionAlpha", getTransitionAlpha());
31112 stream.addProperty("drawing:shadow", hasShadow());
31113 stream.addProperty("drawing:solidColor", getSolidColor());
31114 stream.addProperty("drawing:layerType", mLayerType);
31115 stream.addProperty("drawing:willNotDraw", willNotDraw());
31116 stream.addProperty("drawing:hardwareAccelerated", isHardwareAccelerated());
31117 stream.addProperty("drawing:willNotCacheDrawing", willNotCacheDrawing());
31118 stream.addProperty("drawing:drawingCacheEnabled", isDrawingCacheEnabled());
31119 stream.addProperty("drawing:overlappingRendering", hasOverlappingRendering());
31120 stream.addProperty("drawing:outlineAmbientShadowColor", getOutlineAmbientShadowColor());
31121 stream.addProperty("drawing:outlineSpotShadowColor", getOutlineSpotShadowColor());
31122
31123 // focus
31124 stream.addProperty("focus:hasFocus", hasFocus());
31125 stream.addProperty("focus:isFocused", isFocused());
31126 stream.addProperty("focus:focusable", getFocusable());
31127 stream.addProperty("focus:isFocusable", isFocusable());
31128 stream.addProperty("focus:isFocusableInTouchMode", isFocusableInTouchMode());
31129
31130 stream.addProperty("misc:clickable", isClickable());
31131 stream.addProperty("misc:pressed", isPressed());
31132 stream.addProperty("misc:selected", isSelected());
31133 stream.addProperty("misc:touchMode", isInTouchMode());
31134 stream.addProperty("misc:hovered", isHovered());
31135 stream.addProperty("misc:activated", isActivated());
31136
31137 stream.addProperty("misc:visibility", getVisibility());
31138 stream.addProperty("misc:fitsSystemWindows", getFitsSystemWindows());
31139 stream.addProperty("misc:filterTouchesWhenObscured", getFilterTouchesWhenObscured());
31140
31141 stream.addProperty("misc:enabled", isEnabled());
31142 stream.addProperty("misc:soundEffectsEnabled", isSoundEffectsEnabled());
31143 stream.addProperty("misc:hapticFeedbackEnabled", isHapticFeedbackEnabled());
31144
31145 // theme attributes
31146 Resources.Theme theme = getContext().getTheme();
31147 if (theme != null) {
31148 stream.addPropertyKey("theme");
31149 theme.encode(stream);
31150 }
31151
31152 // view attribute information
31153 int n = mAttributes != null ? mAttributes.length : 0;
31154 stream.addProperty("meta:__attrCount__", n/2);
31155 for (int i = 0; i < n; i += 2) {
31156 stream.addProperty("meta:__attr__" + mAttributes[i], mAttributes[i+1]);
31157 }
31158
31159 stream.addProperty("misc:scrollBarStyle", getScrollBarStyle());
31160
31161 // text
31162 stream.addProperty("text:textDirection", getTextDirection());
31163 stream.addProperty("text:textAlignment", getTextAlignment());
31164
31165 // accessibility
31166 CharSequence contentDescription = getContentDescription();
31167 stream.addUserProperty("accessibility:contentDescription",
31168 contentDescription == null ? "" : contentDescription.toString());
31169 stream.addProperty("accessibility:labelFor", getLabelFor());
31170 stream.addProperty("accessibility:importantForAccessibility", getImportantForAccessibility());
31171 }
31172
31173 /**
31174 * Determine if this view is rendered on a round wearable device and is the main view
31175 * on the screen.
31176 */
31177 boolean shouldDrawRoundScrollbar() {
31178 if (!mResources.getConfiguration().isScreenRound() || mAttachInfo == null) {
31179 return false;
31180 }
31181
31182 final View rootView = getRootView();
31183 final WindowInsets insets = getRootWindowInsets();
31184
31185 int height = getHeight();
31186 int width = getWidth();
31187 int displayHeight = rootView.getHeight();
31188 int displayWidth = rootView.getWidth();
31189
31190 if (height != displayHeight || width != displayWidth) {
31191 return false;
31192 }
31193
31194 getLocationInWindow(mAttachInfo.mTmpLocation);
31195 return mAttachInfo.mTmpLocation[0] == insets.getStableInsetLeft()
31196 && mAttachInfo.mTmpLocation[1] == insets.getStableInsetTop();
31197 }
31198
31199 /**
31200 * Sets the tooltip text which will be displayed in a small popup next to the view.
31201 * <p>
31202 * The tooltip will be displayed:
31203 * <ul>
31204 * <li>On long click, unless it is handled otherwise (by OnLongClickListener or a context
31205 * menu). </li>
31206 * <li>On hover, after a brief delay since the pointer has stopped moving </li>
31207 * </ul>
31208 * <p>
31209 * <strong>Note:</strong> Do not override this method, as it will have no
31210 * effect on the text displayed in the tooltip.
31211 *
31212 * @param tooltipText the tooltip text, or null if no tooltip is required
31213 * @see #getTooltipText()
31214 * @attr ref android.R.styleable#View_tooltipText
31215 */
31216 public void setTooltipText(@Nullable CharSequence tooltipText) {
31217 if (TextUtils.isEmpty(tooltipText)) {
31218 setFlags(0, TOOLTIP);
31219 hideTooltip();
31220 mTooltipInfo = null;
31221 } else {
31222 setFlags(TOOLTIP, TOOLTIP);
31223 if (mTooltipInfo == null) {
31224 mTooltipInfo = new TooltipInfo();
31225 mTooltipInfo.mShowTooltipRunnable = this::showHoverTooltip;
31226 mTooltipInfo.mHideTooltipRunnable = this::hideTooltip;
31227 mTooltipInfo.mHoverSlop = ViewConfiguration.get(mContext).getScaledHoverSlop();
31228 mTooltipInfo.clearAnchorPos();
31229 }
31230 mTooltipInfo.mTooltipText = tooltipText;
31231 }
31232 }
31233
31234 /**
31235 * @hide Binary compatibility stub. To be removed when we finalize O APIs.
31236 */
31237 @UnsupportedAppUsage
31238 public void setTooltip(@Nullable CharSequence tooltipText) {
31239 setTooltipText(tooltipText);
31240 }
31241
31242 /**
31243 * Returns the view's tooltip text.
31244 *
31245 * <strong>Note:</strong> Do not override this method, as it will have no
31246 * effect on the text displayed in the tooltip. You must call
31247 * {@link #setTooltipText(CharSequence)} to modify the tooltip text.
31248 *
31249 * @return the tooltip text
31250 * @see #setTooltipText(CharSequence)
31251 * @attr ref android.R.styleable#View_tooltipText
31252 */
31253 @InspectableProperty
31254 @Nullable
31255 public CharSequence getTooltipText() {
31256 return mTooltipInfo != null ? mTooltipInfo.mTooltipText : null;
31257 }
31258
31259 /**
31260 * @hide Binary compatibility stub. To be removed when we finalize O APIs.
31261 */
31262 @Nullable
31263 public CharSequence getTooltip() {
31264 return getTooltipText();
31265 }
31266
31267 private boolean showTooltip(int x, int y, boolean fromLongClick) {
31268 if (mAttachInfo == null || mTooltipInfo == null) {
31269 return false;
31270 }
31271 if (fromLongClick && (mViewFlags & ENABLED_MASK) != ENABLED) {
31272 return false;
31273 }
31274 if (TextUtils.isEmpty(mTooltipInfo.mTooltipText)) {
31275 return false;
31276 }
31277 hideTooltip();
31278 mTooltipInfo.mTooltipFromLongClick = fromLongClick;
31279 mTooltipInfo.mTooltipPopup = new TooltipPopup(getContext());
31280 final boolean fromTouch = (mPrivateFlags3 & PFLAG3_FINGER_DOWN) == PFLAG3_FINGER_DOWN;
31281 mTooltipInfo.mTooltipPopup.show(this, x, y, fromTouch, mTooltipInfo.mTooltipText);
31282 mAttachInfo.mTooltipHost = this;
31283 // The available accessibility actions have changed
31284 notifyViewAccessibilityStateChangedIfNeeded(CONTENT_CHANGE_TYPE_UNDEFINED);
31285 return true;
31286 }
31287
31288 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
31289 void hideTooltip() {
31290 if (mTooltipInfo == null) {
31291 return;
31292 }
31293 removeCallbacks(mTooltipInfo.mShowTooltipRunnable);
31294 if (mTooltipInfo.mTooltipPopup == null) {
31295 return;
31296 }
31297 mTooltipInfo.mTooltipPopup.hide();
31298 mTooltipInfo.mTooltipPopup = null;
31299 mTooltipInfo.mTooltipFromLongClick = false;
31300 mTooltipInfo.clearAnchorPos();
31301 if (mAttachInfo != null) {
31302 mAttachInfo.mTooltipHost = null;
31303 }
31304 // The available accessibility actions have changed
31305 notifyViewAccessibilityStateChangedIfNeeded(CONTENT_CHANGE_TYPE_UNDEFINED);
31306 }
31307
31308 private boolean showLongClickTooltip(int x, int y) {
31309 removeCallbacks(mTooltipInfo.mShowTooltipRunnable);
31310 removeCallbacks(mTooltipInfo.mHideTooltipRunnable);
31311 return showTooltip(x, y, true);
31312 }
31313
31314 private boolean showHoverTooltip() {
31315 return showTooltip(mTooltipInfo.mAnchorX, mTooltipInfo.mAnchorY, false);
31316 }
31317
31318 boolean dispatchTooltipHoverEvent(MotionEvent event) {
31319 if (mTooltipInfo == null) {
31320 return false;
31321 }
31322 switch(event.getAction()) {
31323 case MotionEvent.ACTION_HOVER_MOVE:
31324 if ((mViewFlags & TOOLTIP) != TOOLTIP) {
31325 break;
31326 }
31327 if (!mTooltipInfo.mTooltipFromLongClick && mTooltipInfo.updateAnchorPos(event)) {
31328 if (mTooltipInfo.mTooltipPopup == null) {
31329 // Schedule showing the tooltip after a timeout.
31330 removeCallbacks(mTooltipInfo.mShowTooltipRunnable);
31331 postDelayed(mTooltipInfo.mShowTooltipRunnable,
31332 ViewConfiguration.getHoverTooltipShowTimeout());
31333 }
31334
31335 // Hide hover-triggered tooltip after a period of inactivity.
31336 // Match the timeout used by NativeInputManager to hide the mouse pointer
31337 // (depends on SYSTEM_UI_FLAG_LOW_PROFILE being set).
31338 final int timeout;
31339 if ((getWindowSystemUiVisibility() & SYSTEM_UI_FLAG_LOW_PROFILE)
31340 == SYSTEM_UI_FLAG_LOW_PROFILE) {
31341 timeout = ViewConfiguration.getHoverTooltipHideShortTimeout();
31342 } else {
31343 timeout = ViewConfiguration.getHoverTooltipHideTimeout();
31344 }
31345 removeCallbacks(mTooltipInfo.mHideTooltipRunnable);
31346 postDelayed(mTooltipInfo.mHideTooltipRunnable, timeout);
31347 }
31348 return true;
31349
31350 case MotionEvent.ACTION_HOVER_EXIT:
31351 mTooltipInfo.clearAnchorPos();
31352 if (!mTooltipInfo.mTooltipFromLongClick) {
31353 hideTooltip();
31354 }
31355 break;
31356 }
31357 return false;
31358 }
31359
31360 void handleTooltipKey(KeyEvent event) {
31361 switch (event.getAction()) {
31362 case KeyEvent.ACTION_DOWN:
31363 if (event.getRepeatCount() == 0) {
31364 hideTooltip();
31365 }
31366 break;
31367
31368 case KeyEvent.ACTION_UP:
31369 handleTooltipUp();
31370 break;
31371 }
31372 }
31373
31374 private void handleTooltipUp() {
31375 if (mTooltipInfo == null || mTooltipInfo.mTooltipPopup == null) {
31376 return;
31377 }
31378 removeCallbacks(mTooltipInfo.mHideTooltipRunnable);
31379 postDelayed(mTooltipInfo.mHideTooltipRunnable,
31380 ViewConfiguration.getLongPressTooltipHideTimeout());
31381 }
31382
31383 private int getFocusableAttribute(TypedArray attributes) {
31384 TypedValue val = new TypedValue();
31385 if (attributes.getValue(com.android.internal.R.styleable.View_focusable, val)) {
31386 if (val.type == TypedValue.TYPE_INT_BOOLEAN) {
31387 return (val.data == 0 ? NOT_FOCUSABLE : FOCUSABLE);
31388 } else {
31389 return val.data;
31390 }
31391 } else {
31392 return FOCUSABLE_AUTO;
31393 }
31394 }
31395
31396 /**
31397 * @return The content view of the tooltip popup currently being shown, or null if the tooltip
31398 * is not showing.
31399 * @hide
31400 */
31401 @TestApi
31402 public View getTooltipView() {
31403 if (mTooltipInfo == null || mTooltipInfo.mTooltipPopup == null) {
31404 return null;
31405 }
31406 return mTooltipInfo.mTooltipPopup.getContentView();
31407 }
31408
31409 /**
31410 * @return {@code true} if the default focus highlight is enabled, {@code false} otherwies.
31411 * @hide
31412 */
31413 @TestApi
31414 public static boolean isDefaultFocusHighlightEnabled() {
31415 return sUseDefaultFocusHighlight;
31416 }
31417
31418 /**
31419 * Dispatch a previously unhandled {@link KeyEvent} to this view. Unlike normal key dispatch,
31420 * this dispatches to ALL child views until it is consumed. The dispatch order is z-order
31421 * (visually on-top views first).
31422 *
31423 * @param evt the previously unhandled {@link KeyEvent}.
31424 * @return the {@link View} which consumed the event or {@code null} if not consumed.
31425 */
31426 View dispatchUnhandledKeyEvent(KeyEvent evt) {
31427 if (onUnhandledKeyEvent(evt)) {
31428 return this;
31429 }
31430 return null;
31431 }
31432
31433 /**
31434 * Allows this view to handle {@link KeyEvent}s which weren't handled by normal dispatch. This
31435 * occurs after the normal view hierarchy dispatch, but before the window callback. By default,
31436 * this will dispatch into all the listeners registered via
31437 * {@link #addOnUnhandledKeyEventListener(OnUnhandledKeyEventListener)} in last-in-first-out
31438 * order (most recently added will receive events first).
31439 *
31440 * @param event An unhandled event.
31441 * @return {@code true} if the event was handled, {@code false} otherwise.
31442 * @see #addOnUnhandledKeyEventListener
31443 */
31444 boolean onUnhandledKeyEvent(@NonNull KeyEvent event) {
31445 if (mListenerInfo != null && mListenerInfo.mUnhandledKeyListeners != null) {
31446 for (int i = mListenerInfo.mUnhandledKeyListeners.size() - 1; i >= 0; --i) {
31447 if (mListenerInfo.mUnhandledKeyListeners.get(i).onUnhandledKeyEvent(this, event)) {
31448 return true;
31449 }
31450 }
31451 }
31452 return false;
31453 }
31454
31455 boolean hasUnhandledKeyListener() {
31456 return (mListenerInfo != null && mListenerInfo.mUnhandledKeyListeners != null
31457 && !mListenerInfo.mUnhandledKeyListeners.isEmpty());
31458 }
31459
31460 /**
31461 * Adds a listener which will receive unhandled {@link KeyEvent}s. This must be called on the
31462 * UI thread.
31463 *
31464 * @param listener a receiver of unhandled {@link KeyEvent}s.
31465 * @see #removeOnUnhandledKeyEventListener
31466 */
31467 public void addOnUnhandledKeyEventListener(OnUnhandledKeyEventListener listener) {
31468 ArrayList<OnUnhandledKeyEventListener> listeners = getListenerInfo().mUnhandledKeyListeners;
31469 if (listeners == null) {
31470 listeners = new ArrayList<>();
31471 getListenerInfo().mUnhandledKeyListeners = listeners;
31472 }
31473 listeners.add(listener);
31474 if (listeners.size() == 1 && mParent instanceof ViewGroup) {
31475 ((ViewGroup) mParent).incrementChildUnhandledKeyListeners();
31476 }
31477 }
31478
31479 /**
31480 * Removes a listener which will receive unhandled {@link KeyEvent}s. This must be called on the
31481 * UI thread.
31482 *
31483 * @param listener a receiver of unhandled {@link KeyEvent}s.
31484 * @see #addOnUnhandledKeyEventListener
31485 */
31486 public void removeOnUnhandledKeyEventListener(OnUnhandledKeyEventListener listener) {
31487 if (mListenerInfo != null) {
31488 if (mListenerInfo.mUnhandledKeyListeners != null
31489 && !mListenerInfo.mUnhandledKeyListeners.isEmpty()) {
31490 mListenerInfo.mUnhandledKeyListeners.remove(listener);
31491 if (mListenerInfo.mUnhandledKeyListeners.isEmpty()) {
31492 mListenerInfo.mUnhandledKeyListeners = null;
31493 if (mParent instanceof ViewGroup) {
31494 ((ViewGroup) mParent).decrementChildUnhandledKeyListeners();
31495 }
31496 }
31497 }
31498 }
31499 }
31500
31501 /**
31502 * Set the view to be detached or not detached.
31503 *
31504 * @param detached Whether the view is detached.
31505 *
31506 * @hide
31507 */
31508 protected void setDetached(boolean detached) {
31509 if (detached) {
31510 mPrivateFlags4 |= PFLAG4_DETACHED;
31511 } else {
31512 mPrivateFlags4 &= ~PFLAG4_DETACHED;
31513 }
31514 }
31515
31516 /**
31517 * Set whether this view enables automatic handwriting initiation.
31518 *
31519 * For a view with an active {@link InputConnection}, if auto handwriting is enabled then
31520 * stylus movement within its view boundary will automatically trigger the handwriting mode.
31521 * Check {@link android.view.inputmethod.InputMethodManager#startStylusHandwriting(View)} for
31522 * more details about handwriting mode.
31523 *
31524 * If the View wants to initiate handwriting mode by itself, it can set this field to
31525 * {@code false} and call
31526 * {@link android.view.inputmethod.InputMethodManager#startStylusHandwriting(View)} when there
31527 * is stylus movement detected.
31528 *
31529 * @see #onCreateInputConnection(EditorInfo)
31530 * @see android.view.inputmethod.InputMethodManager#startStylusHandwriting(View)
31531 * @param enabled whether auto handwriting initiation is enabled for this view.
31532 * @attr ref android.R.styleable#View_autoHandwritingEnabled
31533 */
31534 public void setAutoHandwritingEnabled(boolean enabled) {
31535 if (enabled) {
31536 mPrivateFlags4 |= PFLAG4_AUTO_HANDWRITING_ENABLED;
31537 } else {
31538 mPrivateFlags4 &= ~PFLAG4_AUTO_HANDWRITING_ENABLED;
31539 }
31540 updatePositionUpdateListener();
31541 postUpdate(this::updateHandwritingArea);
31542 }
31543
31544 /**
31545 * Return whether the View allows automatic handwriting initiation. Returns true if automatic
31546 * handwriting initiation is enabled, and verse visa.
31547 * @see #setAutoHandwritingEnabled(boolean)
31548 */
31549 public boolean isAutoHandwritingEnabled() {
31550 return (mPrivateFlags4 & PFLAG4_AUTO_HANDWRITING_ENABLED)
31551 == PFLAG4_AUTO_HANDWRITING_ENABLED;
31552 }
31553
31554 /**
31555 * Collects a {@link ViewTranslationRequest} which represents the content to be translated in
31556 * the view.
31557 *
31558 * <p>The default implementation does nothing.</p>
31559 *
31560 * @param supportedFormats the supported translation formats. For now, the only possible value
31561 * is the {@link android.view.translation.TranslationSpec#DATA_FORMAT_TEXT}.
31562 * @param requestsCollector a {@link ViewTranslationRequest} collector that can be used to
31563 * collect the information to be translated in the view. The {@code requestsCollector} only
31564 * accepts one request; an IllegalStateException is thrown if more than one
31565 * {@link ViewTranslationRequest} is submitted to it. The {@link AutofillId} must be set on the
31566 * {@link ViewTranslationRequest}.
31567 */
31568 public void onCreateViewTranslationRequest(@NonNull @DataFormat int[] supportedFormats,
31569 @NonNull Consumer<ViewTranslationRequest> requestsCollector) {
31570 }
31571
31572 /**
31573 * Collects {@link ViewTranslationRequest}s which represents the content to be translated
31574 * for the virtual views in the host view. This is called if this view returned a virtual
31575 * view structure from {@link #onProvideContentCaptureStructure} and the system determined that
31576 * those virtual views were relevant for translation.
31577 *
31578 * <p>The default implementation does nothing.</p>
31579 *
31580 * @param virtualIds the virtual view ids which represents the virtual views in the host
31581 * view.
31582 * @param supportedFormats the supported translation formats. For now, the only possible value
31583 * is the {@link android.view.translation.TranslationSpec#DATA_FORMAT_TEXT}.
31584 * @param requestsCollector a {@link ViewTranslationRequest} collector that can be called
31585 * multiple times to collect the information to be translated in the host view. One
31586 * {@link ViewTranslationRequest} per virtual child. The {@link ViewTranslationRequest} must
31587 * contains the {@link AutofillId} corresponding to the virtualChildIds. Do not keep this
31588 * Consumer after the method returns.
31589 */
31590 @SuppressLint("NullableCollection")
31591 public void onCreateVirtualViewTranslationRequests(@NonNull long[] virtualIds,
31592 @NonNull @DataFormat int[] supportedFormats,
31593 @NonNull Consumer<ViewTranslationRequest> requestsCollector) {
31594 // no-op
31595 }
31596
31597 /**
31598 * Returns a {@link ViewTranslationCallback} that is used to display the translated information
31599 * or {@code null} if this View doesn't support translation.
31600 *
31601 * @hide
31602 */
31603 @Nullable
31604 public ViewTranslationCallback getViewTranslationCallback() {
31605 return mViewTranslationCallback;
31606 }
31607
31608 /**
31609 * Sets a {@link ViewTranslationCallback} that is used to display/hide the translated
31610 * information. Developers can provide the customized implementation for show/hide translated
31611 * information.
31612 *
31613 * @param callback a {@link ViewTranslationCallback} that is used to control how to display the
31614 * translated information
31615 */
31616 public void setViewTranslationCallback(@NonNull ViewTranslationCallback callback) {
31617 mViewTranslationCallback = callback;
31618 }
31619
31620 /**
31621 * Clear the {@link ViewTranslationCallback} from this view.
31622 */
31623 public void clearViewTranslationCallback() {
31624 mViewTranslationCallback = null;
31625 }
31626
31627 /**
31628 * Returns the {@link ViewTranslationResponse} associated with this view. The response will be
31629 * set when the translation is done then {@link #onViewTranslationResponse} is called. The
31630 * {@link ViewTranslationCallback} can use to get {@link ViewTranslationResponse} to display the
31631 * translated information.
31632 *
31633 * @return a {@link ViewTranslationResponse} that contains the translated information associated
31634 * with this view or {@code null} if this View doesn't have the translation.
31635 */
31636 @Nullable
31637 public ViewTranslationResponse getViewTranslationResponse() {
31638 return mViewTranslationResponse;
31639 }
31640
31641 /**
31642 * Called when the content from {@link View#onCreateViewTranslationRequest} had been translated
31643 * by the TranslationService. The {@link ViewTranslationResponse} should be saved here so that
31644 * the {@link ViewTranslationResponse} can be used to display the translation when the system
31645 * calls {@link ViewTranslationCallback#onShowTranslation}.
31646 *
31647 * <p> The default implementation will set the ViewTranslationResponse that can be get from
31648 * {@link View#getViewTranslationResponse}. </p>
31649 *
31650 * @param response a {@link ViewTranslationResponse} that contains the translated information
31651 * which can be shown in the view.
31652 */
31653 public void onViewTranslationResponse(@NonNull ViewTranslationResponse response) {
31654 mViewTranslationResponse = response;
31655 }
31656
31657 /**
31658 * Clears the ViewTranslationResponse stored by the default implementation of {@link
31659 * #onViewTranslationResponse}.
31660 *
31661 * @hide
31662 */
31663 public void clearViewTranslationResponse() {
31664 mViewTranslationResponse = null;
31665 }
31666
31667 /**
31668 * Called when the content from {@link View#onCreateVirtualViewTranslationRequests} had been
31669 * translated by the TranslationService.
31670 *
31671 * <p> The default implementation does nothing.</p>
31672 *
31673 * @param response a {@link ViewTranslationResponse} SparseArray for the request that send by
31674 * {@link View#onCreateVirtualViewTranslationRequests} that contains the translated information
31675 * which can be shown in the view. The key of SparseArray is the virtual child ids.
31676 */
31677 public void onVirtualViewTranslationResponses(
31678 @NonNull LongSparseArray<ViewTranslationResponse> response) {
31679 // no-op
31680 }
31681
31682 /**
31683 * Dispatch to collect the {@link ViewTranslationRequest}s for translation purpose by traversing
31684 * the hierarchy when the app requests ui translation. Typically, this method should only be
31685 * overridden by subclasses that provide a view hierarchy (such as {@link ViewGroup}). Other
31686 * classes should override {@link View#onCreateViewTranslationRequest} for normal view or
31687 * override {@link View#onVirtualViewTranslationResponses} for view contains virtual children.
31688 * When requested to start the ui translation, the system will call this method to traverse the
31689 * view hierarchy to collect {@link ViewTranslationRequest}s and create a
31690 * {@link android.view.translation.Translator} to translate the requests. All the
31691 * {@link ViewTranslationRequest}s must be added when the traversal is done.
31692 *
31693 * <p> The default implementation calls {@link View#onCreateViewTranslationRequest} for normal
31694 * view or calls {@link View#onVirtualViewTranslationResponses} for view contains virtual
31695 * children to build {@link ViewTranslationRequest} if the view should be translated.
31696 * The view is marked as having {@link #setHasTransientState(boolean) transient state} so that
31697 * recycling of views doesn't prevent the system from attaching the response to it. Therefore,
31698 * if overriding this method, you should set or reset the transient state. </p>
31699 *
31700 * @param viewIds a map for the view's {@link AutofillId} and its virtual child ids or
31701 * {@code null} if the view doesn't have virtual child that should be translated. The virtual
31702 * child ids are the same virtual ids provided by ContentCapture.
31703 * @param supportedFormats the supported translation formats. For now, the only possible value
31704 * is the {@link android.view.translation.TranslationSpec#DATA_FORMAT_TEXT}.
31705 * @param capability a {@link TranslationCapability} that holds translation capability.
31706 * information, e.g. source spec, target spec.
31707 * @param requests fill in with {@link ViewTranslationRequest}s for translation purpose.
31708 */
31709 public void dispatchCreateViewTranslationRequest(@NonNull Map<AutofillId, long[]> viewIds,
31710 @NonNull @DataFormat int[] supportedFormats,
31711 @NonNull TranslationCapability capability,
31712 @NonNull List<ViewTranslationRequest> requests) {
31713 AutofillId autofillId = getAutofillId();
31714 if (viewIds.containsKey(autofillId)) {
31715 if (viewIds.get(autofillId) == null) {
31716 // TODO: avoiding the allocation per view
31717 onCreateViewTranslationRequest(supportedFormats,
31718 new ViewTranslationRequestConsumer(requests));
31719 } else {
31720 onCreateVirtualViewTranslationRequests(viewIds.get(autofillId), supportedFormats,
31721 request -> {
31722 requests.add(request);
31723 });
31724 }
31725 }
31726 }
31727
31728 private class ViewTranslationRequestConsumer implements Consumer<ViewTranslationRequest> {
31729 private final List<ViewTranslationRequest> mRequests;
31730 private boolean mCalled;
31731
31732 ViewTranslationRequestConsumer(List<ViewTranslationRequest> requests) {
31733 mRequests = requests;
31734 }
31735
31736 @Override
31737 public void accept(ViewTranslationRequest request) {
31738 if (mCalled) {
31739 throw new IllegalStateException("The translation Consumer is not reusable.");
31740 }
31741 mCalled = true;
31742 if (request != null && request.getKeys().size() > 0) {
31743 mRequests.add(request);
31744 if (Log.isLoggable(CONTENT_CAPTURE_LOG_TAG, Log.VERBOSE)) {
31745 Log.v(CONTENT_CAPTURE_LOG_TAG, "Calling setHasTransientState(true) for "
31746 + getAutofillId());
31747 }
31748 setHasTransientState(true);
31749 setHasTranslationTransientState(true);
31750 }
31751 }
31752 }
31753
31754 /**
31755 * Called to generate a {@link DisplayHash} for this view.
31756 *
31757 * @param hashAlgorithm The hash algorithm to use when hashing the display. Must be one of
31758 * the values returned from
31759 * {@link DisplayHashManager#getSupportedHashAlgorithms()}
31760 * @param bounds The bounds for the content within the View to generate the hash for. If
31761 * bounds are null, the entire View's bounds will be used. If empty, it will
31762 * invoke the callback
31763 * {@link DisplayHashResultCallback#onDisplayHashError} with error
31764 * {@link DisplayHashResultCallback#DISPLAY_HASH_ERROR_INVALID_BOUNDS}
31765 * @param executor The executor that the callback should be invoked on.
31766 * @param callback The callback to handle the results of generating the display hash
31767 */
31768 public void generateDisplayHash(@NonNull String hashAlgorithm,
31769 @Nullable Rect bounds, @NonNull Executor executor,
31770 @NonNull DisplayHashResultCallback callback) {
31771 IWindowSession session = getWindowSession();
31772 if (session == null) {
31773 callback.onDisplayHashError(DISPLAY_HASH_ERROR_MISSING_WINDOW);
31774 return;
31775 }
31776 IWindow window = getWindow();
31777 if (window == null) {
31778 callback.onDisplayHashError(DISPLAY_HASH_ERROR_MISSING_WINDOW);
31779 return;
31780 }
31781
31782 Rect visibleBounds = new Rect();
31783 getGlobalVisibleRect(visibleBounds);
31784
31785 if (bounds != null && bounds.isEmpty()) {
31786 callback.onDisplayHashError(DISPLAY_HASH_ERROR_INVALID_BOUNDS);
31787 return;
31788 }
31789
31790 if (bounds != null) {
31791 bounds.offset(visibleBounds.left, visibleBounds.top);
31792 visibleBounds.intersectUnchecked(bounds);
31793 }
31794
31795 if (visibleBounds.isEmpty()) {
31796 callback.onDisplayHashError(DISPLAY_HASH_ERROR_NOT_VISIBLE_ON_SCREEN);
31797 return;
31798 }
31799
31800 RemoteCallback remoteCallback = new RemoteCallback(result ->
31801 executor.execute(() -> {
31802 DisplayHash displayHash = result.getParcelable(EXTRA_DISPLAY_HASH);
31803 int errorCode = result.getInt(EXTRA_DISPLAY_HASH_ERROR_CODE,
31804 DISPLAY_HASH_ERROR_UNKNOWN);
31805 if (displayHash != null) {
31806 callback.onDisplayHashResult(displayHash);
31807 } else {
31808 callback.onDisplayHashError(errorCode);
31809 }
31810 }));
31811
31812 try {
31813 session.generateDisplayHash(window, visibleBounds, hashAlgorithm, remoteCallback);
31814 } catch (RemoteException e) {
31815 Log.e(VIEW_LOG_TAG, "Failed to call generateDisplayHash");
31816 callback.onDisplayHashError(DISPLAY_HASH_ERROR_UNKNOWN);
31817 }
31818 }
31819
31820 /**
31821 * The AttachedSurfaceControl itself is not a View, it is just the interface to the
31822 * windowing-system object that contains the entire view hierarchy.
31823 * For the root View of a given hierarchy see {@link #getRootView}.
31824
31825 * @return The {@link android.view.AttachedSurfaceControl} interface for this View.
31826 * This will only return a non-null value when called between {@link #onAttachedToWindow}
31827 * and {@link #onDetachedFromWindow}.
31828 */
31829 public @Nullable AttachedSurfaceControl getRootSurfaceControl() {
31830 if (mAttachInfo != null) {
31831 return mAttachInfo.getRootSurfaceControl();
31832 }
31833 return null;
31834 }
31835 }