View.java revision c380e18e31cdc922d42b11c016482857ad47b9a9
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
17package android.view;
18
19import static android.view.accessibility.AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED;
20
21import static java.lang.Math.max;
22
23import android.animation.AnimatorInflater;
24import android.animation.StateListAnimator;
25import android.annotation.CallSuper;
26import android.annotation.ColorInt;
27import android.annotation.DrawableRes;
28import android.annotation.FloatRange;
29import android.annotation.IdRes;
30import android.annotation.IntDef;
31import android.annotation.IntRange;
32import android.annotation.LayoutRes;
33import android.annotation.NonNull;
34import android.annotation.Nullable;
35import android.annotation.Size;
36import android.annotation.TestApi;
37import android.annotation.UiThread;
38import android.content.ClipData;
39import android.content.Context;
40import android.content.ContextWrapper;
41import android.content.Intent;
42import android.content.res.ColorStateList;
43import android.content.res.Configuration;
44import android.content.res.Resources;
45import android.content.res.TypedArray;
46import android.graphics.Bitmap;
47import android.graphics.Canvas;
48import android.graphics.Color;
49import android.graphics.Insets;
50import android.graphics.Interpolator;
51import android.graphics.LinearGradient;
52import android.graphics.Matrix;
53import android.graphics.Outline;
54import android.graphics.Paint;
55import android.graphics.PixelFormat;
56import android.graphics.Point;
57import android.graphics.PorterDuff;
58import android.graphics.PorterDuffXfermode;
59import android.graphics.Rect;
60import android.graphics.RectF;
61import android.graphics.Region;
62import android.graphics.Shader;
63import android.graphics.drawable.ColorDrawable;
64import android.graphics.drawable.Drawable;
65import android.hardware.display.DisplayManagerGlobal;
66import android.net.Uri;
67import android.os.Build;
68import android.os.Bundle;
69import android.os.Handler;
70import android.os.IBinder;
71import android.os.Message;
72import android.os.Parcel;
73import android.os.Parcelable;
74import android.os.RemoteException;
75import android.os.SystemClock;
76import android.os.SystemProperties;
77import android.os.Trace;
78import android.text.InputType;
79import android.text.TextUtils;
80import android.util.AttributeSet;
81import android.util.FloatProperty;
82import android.util.LayoutDirection;
83import android.util.Log;
84import android.util.LongSparseLongArray;
85import android.util.Pools.SynchronizedPool;
86import android.util.Property;
87import android.util.SparseArray;
88import android.util.StateSet;
89import android.util.SuperNotCalledException;
90import android.util.TypedValue;
91import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
92import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
93import android.view.AccessibilityIterators.TextSegmentIterator;
94import android.view.AccessibilityIterators.WordTextSegmentIterator;
95import android.view.ContextMenu.ContextMenuInfo;
96import android.view.accessibility.AccessibilityEvent;
97import android.view.accessibility.AccessibilityEventSource;
98import android.view.accessibility.AccessibilityManager;
99import android.view.accessibility.AccessibilityNodeInfo;
100import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction;
101import android.view.accessibility.AccessibilityNodeProvider;
102import android.view.accessibility.AccessibilityWindowInfo;
103import android.view.animation.Animation;
104import android.view.animation.AnimationUtils;
105import android.view.animation.Transformation;
106import android.view.autofill.AutofillId;
107import android.view.autofill.AutofillManager;
108import android.view.autofill.AutofillValue;
109import android.view.inputmethod.EditorInfo;
110import android.view.inputmethod.InputConnection;
111import android.view.inputmethod.InputMethodManager;
112import android.widget.Checkable;
113import android.widget.FrameLayout;
114import android.widget.ScrollBarDrawable;
115
116import com.android.internal.R;
117import com.android.internal.view.TooltipPopup;
118import com.android.internal.view.menu.MenuBuilder;
119import com.android.internal.widget.ScrollBarUtils;
120
121import com.google.android.collect.Lists;
122import com.google.android.collect.Maps;
123
124import java.lang.annotation.Retention;
125import java.lang.annotation.RetentionPolicy;
126import java.lang.ref.WeakReference;
127import java.lang.reflect.Field;
128import java.lang.reflect.InvocationTargetException;
129import java.lang.reflect.Method;
130import java.lang.reflect.Modifier;
131import java.util.ArrayList;
132import java.util.Arrays;
133import java.util.Calendar;
134import java.util.Collection;
135import java.util.Collections;
136import java.util.HashMap;
137import java.util.List;
138import java.util.Locale;
139import java.util.Map;
140import java.util.concurrent.CopyOnWriteArrayList;
141import java.util.concurrent.atomic.AtomicInteger;
142import java.util.function.Predicate;
143
144/**
145 * <p>
146 * This class represents the basic building block for user interface components. A View
147 * occupies a rectangular area on the screen and is responsible for drawing and
148 * event handling. View is the base class for <em>widgets</em>, which are
149 * used to create interactive UI components (buttons, text fields, etc.). The
150 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
151 * are invisible containers that hold other Views (or other ViewGroups) and define
152 * their layout properties.
153 * </p>
154 *
155 * <div class="special reference">
156 * <h3>Developer Guides</h3>
157 * <p>For information about using this class to develop your application's user interface,
158 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
159 * </div>
160 *
161 * <a name="Using"></a>
162 * <h3>Using Views</h3>
163 * <p>
164 * All of the views in a window are arranged in a single tree. You can add views
165 * either from code or by specifying a tree of views in one or more XML layout
166 * files. There are many specialized subclasses of views that act as controls or
167 * are capable of displaying text, images, or other content.
168 * </p>
169 * <p>
170 * Once you have created a tree of views, there are typically a few types of
171 * common operations you may wish to perform:
172 * <ul>
173 * <li><strong>Set properties:</strong> for example setting the text of a
174 * {@link android.widget.TextView}. The available properties and the methods
175 * that set them will vary among the different subclasses of views. Note that
176 * properties that are known at build time can be set in the XML layout
177 * files.</li>
178 * <li><strong>Set focus:</strong> The framework will handle moving focus in
179 * response to user input. To force focus to a specific view, call
180 * {@link #requestFocus}.</li>
181 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
182 * that will be notified when something interesting happens to the view. For
183 * example, all views will let you set a listener to be notified when the view
184 * gains or loses focus. You can register such a listener using
185 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
186 * Other view subclasses offer more specialized listeners. For example, a Button
187 * exposes a listener to notify clients when the button is clicked.</li>
188 * <li><strong>Set visibility:</strong> You can hide or show views using
189 * {@link #setVisibility(int)}.</li>
190 * </ul>
191 * </p>
192 * <p><em>
193 * Note: The Android framework is responsible for measuring, laying out and
194 * drawing views. You should not call methods that perform these actions on
195 * views yourself unless you are actually implementing a
196 * {@link android.view.ViewGroup}.
197 * </em></p>
198 *
199 * <a name="Lifecycle"></a>
200 * <h3>Implementing a Custom View</h3>
201 *
202 * <p>
203 * To implement a custom view, you will usually begin by providing overrides for
204 * some of the standard methods that the framework calls on all views. You do
205 * not need to override all of these methods. In fact, you can start by just
206 * overriding {@link #onDraw(android.graphics.Canvas)}.
207 * <table border="2" width="85%" align="center" cellpadding="5">
208 *     <thead>
209 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
210 *     </thead>
211 *
212 *     <tbody>
213 *     <tr>
214 *         <td rowspan="2">Creation</td>
215 *         <td>Constructors</td>
216 *         <td>There is a form of the constructor that are called when the view
217 *         is created from code and a form that is called when the view is
218 *         inflated from a layout file. The second form should parse and apply
219 *         any attributes defined in the layout file.
220 *         </td>
221 *     </tr>
222 *     <tr>
223 *         <td><code>{@link #onFinishInflate()}</code></td>
224 *         <td>Called after a view and all of its children has been inflated
225 *         from XML.</td>
226 *     </tr>
227 *
228 *     <tr>
229 *         <td rowspan="3">Layout</td>
230 *         <td><code>{@link #onMeasure(int, int)}</code></td>
231 *         <td>Called to determine the size requirements for this view and all
232 *         of its children.
233 *         </td>
234 *     </tr>
235 *     <tr>
236 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
237 *         <td>Called when this view should assign a size and position to all
238 *         of its children.
239 *         </td>
240 *     </tr>
241 *     <tr>
242 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
243 *         <td>Called when the size of this view has changed.
244 *         </td>
245 *     </tr>
246 *
247 *     <tr>
248 *         <td>Drawing</td>
249 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
250 *         <td>Called when the view should render its content.
251 *         </td>
252 *     </tr>
253 *
254 *     <tr>
255 *         <td rowspan="4">Event processing</td>
256 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
257 *         <td>Called when a new hardware key event occurs.
258 *         </td>
259 *     </tr>
260 *     <tr>
261 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
262 *         <td>Called when a hardware key up event occurs.
263 *         </td>
264 *     </tr>
265 *     <tr>
266 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
267 *         <td>Called when a trackball motion event occurs.
268 *         </td>
269 *     </tr>
270 *     <tr>
271 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
272 *         <td>Called when a touch screen motion event occurs.
273 *         </td>
274 *     </tr>
275 *
276 *     <tr>
277 *         <td rowspan="2">Focus</td>
278 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
279 *         <td>Called when the view gains or loses focus.
280 *         </td>
281 *     </tr>
282 *
283 *     <tr>
284 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
285 *         <td>Called when the window containing the view gains or loses focus.
286 *         </td>
287 *     </tr>
288 *
289 *     <tr>
290 *         <td rowspan="3">Attaching</td>
291 *         <td><code>{@link #onAttachedToWindow()}</code></td>
292 *         <td>Called when the view is attached to a window.
293 *         </td>
294 *     </tr>
295 *
296 *     <tr>
297 *         <td><code>{@link #onDetachedFromWindow}</code></td>
298 *         <td>Called when the view is detached from its window.
299 *         </td>
300 *     </tr>
301 *
302 *     <tr>
303 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
304 *         <td>Called when the visibility of the window containing the view
305 *         has changed.
306 *         </td>
307 *     </tr>
308 *     </tbody>
309 *
310 * </table>
311 * </p>
312 *
313 * <a name="IDs"></a>
314 * <h3>IDs</h3>
315 * Views may have an integer id associated with them. These ids are typically
316 * assigned in the layout XML files, and are used to find specific views within
317 * the view tree. A common pattern is to:
318 * <ul>
319 * <li>Define a Button in the layout file and assign it a unique ID.
320 * <pre>
321 * &lt;Button
322 *     android:id="@+id/my_button"
323 *     android:layout_width="wrap_content"
324 *     android:layout_height="wrap_content"
325 *     android:text="@string/my_button_text"/&gt;
326 * </pre></li>
327 * <li>From the onCreate method of an Activity, find the Button
328 * <pre class="prettyprint">
329 *      Button myButton = findViewById(R.id.my_button);
330 * </pre></li>
331 * </ul>
332 * <p>
333 * View IDs need not be unique throughout the tree, but it is good practice to
334 * ensure that they are at least unique within the part of the tree you are
335 * searching.
336 * </p>
337 *
338 * <a name="Position"></a>
339 * <h3>Position</h3>
340 * <p>
341 * The geometry of a view is that of a rectangle. A view has a location,
342 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
343 * two dimensions, expressed as a width and a height. The unit for location
344 * and dimensions is the pixel.
345 * </p>
346 *
347 * <p>
348 * It is possible to retrieve the location of a view by invoking the methods
349 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
350 * coordinate of the rectangle representing the view. The latter returns the
351 * top, or Y, coordinate of the rectangle representing the view. These methods
352 * both return the location of the view relative to its parent. For instance,
353 * when getLeft() returns 20, that means the view is located 20 pixels to the
354 * right of the left edge of its direct parent.
355 * </p>
356 *
357 * <p>
358 * In addition, several convenience methods are offered to avoid unnecessary
359 * computations, namely {@link #getRight()} and {@link #getBottom()}.
360 * These methods return the coordinates of the right and bottom edges of the
361 * rectangle representing the view. For instance, calling {@link #getRight()}
362 * is similar to the following computation: <code>getLeft() + getWidth()</code>
363 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
364 * </p>
365 *
366 * <a name="SizePaddingMargins"></a>
367 * <h3>Size, padding and margins</h3>
368 * <p>
369 * The size of a view is expressed with a width and a height. A view actually
370 * possess two pairs of width and height values.
371 * </p>
372 *
373 * <p>
374 * The first pair is known as <em>measured width</em> and
375 * <em>measured height</em>. These dimensions define how big a view wants to be
376 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
377 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
378 * and {@link #getMeasuredHeight()}.
379 * </p>
380 *
381 * <p>
382 * The second pair is simply known as <em>width</em> and <em>height</em>, or
383 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
384 * dimensions define the actual size of the view on screen, at drawing time and
385 * after layout. These values may, but do not have to, be different from the
386 * measured width and height. The width and height can be obtained by calling
387 * {@link #getWidth()} and {@link #getHeight()}.
388 * </p>
389 *
390 * <p>
391 * To measure its dimensions, a view takes into account its padding. The padding
392 * is expressed in pixels for the left, top, right and bottom parts of the view.
393 * Padding can be used to offset the content of the view by a specific amount of
394 * pixels. For instance, a left padding of 2 will push the view's content by
395 * 2 pixels to the right of the left edge. Padding can be set using the
396 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
397 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
398 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
399 * {@link #getPaddingEnd()}.
400 * </p>
401 *
402 * <p>
403 * Even though a view can define a padding, it does not provide any support for
404 * margins. However, view groups provide such a support. Refer to
405 * {@link android.view.ViewGroup} and
406 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
407 * </p>
408 *
409 * <a name="Layout"></a>
410 * <h3>Layout</h3>
411 * <p>
412 * Layout is a two pass process: a measure pass and a layout pass. The measuring
413 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
414 * of the view tree. Each view pushes dimension specifications down the tree
415 * during the recursion. At the end of the measure pass, every view has stored
416 * its measurements. The second pass happens in
417 * {@link #layout(int,int,int,int)} and is also top-down. During
418 * this pass each parent is responsible for positioning all of its children
419 * using the sizes computed in the measure pass.
420 * </p>
421 *
422 * <p>
423 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
424 * {@link #getMeasuredHeight()} values must be set, along with those for all of
425 * that view's descendants. A view's measured width and measured height values
426 * must respect the constraints imposed by the view's parents. This guarantees
427 * that at the end of the measure pass, all parents accept all of their
428 * children's measurements. A parent view may call measure() more than once on
429 * its children. For example, the parent may measure each child once with
430 * unspecified dimensions to find out how big they want to be, then call
431 * measure() on them again with actual numbers if the sum of all the children's
432 * unconstrained sizes is too big or too small.
433 * </p>
434 *
435 * <p>
436 * The measure pass uses two classes to communicate dimensions. The
437 * {@link MeasureSpec} class is used by views to tell their parents how they
438 * want to be measured and positioned. The base LayoutParams class just
439 * describes how big the view wants to be for both width and height. For each
440 * dimension, it can specify one of:
441 * <ul>
442 * <li> an exact number
443 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
444 * (minus padding)
445 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
446 * enclose its content (plus padding).
447 * </ul>
448 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
449 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
450 * an X and Y value.
451 * </p>
452 *
453 * <p>
454 * MeasureSpecs are used to push requirements down the tree from parent to
455 * child. A MeasureSpec can be in one of three modes:
456 * <ul>
457 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
458 * of a child view. For example, a LinearLayout may call measure() on its child
459 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
460 * tall the child view wants to be given a width of 240 pixels.
461 * <li>EXACTLY: This is used by the parent to impose an exact size on the
462 * child. The child must use this size, and guarantee that all of its
463 * descendants will fit within this size.
464 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
465 * child. The child must guarantee that it and all of its descendants will fit
466 * within this size.
467 * </ul>
468 * </p>
469 *
470 * <p>
471 * To initiate a layout, call {@link #requestLayout}. This method is typically
472 * called by a view on itself when it believes that is can no longer fit within
473 * its current bounds.
474 * </p>
475 *
476 * <a name="Drawing"></a>
477 * <h3>Drawing</h3>
478 * <p>
479 * Drawing is handled by walking the tree and recording the drawing commands of
480 * any View that needs to update. After this, the drawing commands of the
481 * entire tree are issued to screen, clipped to the newly damaged area.
482 * </p>
483 *
484 * <p>
485 * The tree is largely recorded and drawn in order, with parents drawn before
486 * (i.e., behind) their children, with siblings drawn in the order they appear
487 * in the tree. If you set a background drawable for a View, then the View will
488 * draw it before calling back to its <code>onDraw()</code> method. The child
489 * drawing order can be overridden with
490 * {@link ViewGroup#setChildrenDrawingOrderEnabled(boolean) custom child drawing order}
491 * in a ViewGroup, and with {@link #setZ(float)} custom Z values} set on Views.
492 * </p>
493 *
494 * <p>
495 * To force a view to draw, call {@link #invalidate()}.
496 * </p>
497 *
498 * <a name="EventHandlingThreading"></a>
499 * <h3>Event Handling and Threading</h3>
500 * <p>
501 * The basic cycle of a view is as follows:
502 * <ol>
503 * <li>An event comes in and is dispatched to the appropriate view. The view
504 * handles the event and notifies any listeners.</li>
505 * <li>If in the course of processing the event, the view's bounds may need
506 * to be changed, the view will call {@link #requestLayout()}.</li>
507 * <li>Similarly, if in the course of processing the event the view's appearance
508 * may need to be changed, the view will call {@link #invalidate()}.</li>
509 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
510 * the framework will take care of measuring, laying out, and drawing the tree
511 * as appropriate.</li>
512 * </ol>
513 * </p>
514 *
515 * <p><em>Note: The entire view tree is single threaded. You must always be on
516 * the UI thread when calling any method on any view.</em>
517 * If you are doing work on other threads and want to update the state of a view
518 * from that thread, you should use a {@link Handler}.
519 * </p>
520 *
521 * <a name="FocusHandling"></a>
522 * <h3>Focus Handling</h3>
523 * <p>
524 * The framework will handle routine focus movement in response to user input.
525 * This includes changing the focus as views are removed or hidden, or as new
526 * views become available. Views indicate their willingness to take focus
527 * through the {@link #isFocusable} method. To change whether a view can take
528 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
529 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
530 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
531 * </p>
532 * <p>
533 * Focus movement is based on an algorithm which finds the nearest neighbor in a
534 * given direction. In rare cases, the default algorithm may not match the
535 * intended behavior of the developer. In these situations, you can provide
536 * explicit overrides by using these XML attributes in the layout file:
537 * <pre>
538 * nextFocusDown
539 * nextFocusLeft
540 * nextFocusRight
541 * nextFocusUp
542 * </pre>
543 * </p>
544 *
545 *
546 * <p>
547 * To get a particular view to take focus, call {@link #requestFocus()}.
548 * </p>
549 *
550 * <a name="TouchMode"></a>
551 * <h3>Touch Mode</h3>
552 * <p>
553 * When a user is navigating a user interface via directional keys such as a D-pad, it is
554 * necessary to give focus to actionable items such as buttons so the user can see
555 * what will take input.  If the device has touch capabilities, however, and the user
556 * begins interacting with the interface by touching it, it is no longer necessary to
557 * always highlight, or give focus to, a particular view.  This motivates a mode
558 * for interaction named 'touch mode'.
559 * </p>
560 * <p>
561 * For a touch capable device, once the user touches the screen, the device
562 * will enter touch mode.  From this point onward, only views for which
563 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
564 * Other views that are touchable, like buttons, will not take focus when touched; they will
565 * only fire the on click listeners.
566 * </p>
567 * <p>
568 * Any time a user hits a directional key, such as a D-pad direction, the view device will
569 * exit touch mode, and find a view to take focus, so that the user may resume interacting
570 * with the user interface without touching the screen again.
571 * </p>
572 * <p>
573 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
574 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
575 * </p>
576 *
577 * <a name="Scrolling"></a>
578 * <h3>Scrolling</h3>
579 * <p>
580 * The framework provides basic support for views that wish to internally
581 * scroll their content. This includes keeping track of the X and Y scroll
582 * offset as well as mechanisms for drawing scrollbars. See
583 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
584 * {@link #awakenScrollBars()} for more details.
585 * </p>
586 *
587 * <a name="Tags"></a>
588 * <h3>Tags</h3>
589 * <p>
590 * Unlike IDs, tags are not used to identify views. Tags are essentially an
591 * extra piece of information that can be associated with a view. They are most
592 * often used as a convenience to store data related to views in the views
593 * themselves rather than by putting them in a separate structure.
594 * </p>
595 * <p>
596 * Tags may be specified with character sequence values in layout XML as either
597 * a single tag using the {@link android.R.styleable#View_tag android:tag}
598 * attribute or multiple tags using the {@code <tag>} child element:
599 * <pre>
600 *     &lt;View ...
601 *           android:tag="@string/mytag_value" /&gt;
602 *     &lt;View ...&gt;
603 *         &lt;tag android:id="@+id/mytag"
604 *              android:value="@string/mytag_value" /&gt;
605 *     &lt;/View>
606 * </pre>
607 * </p>
608 * <p>
609 * Tags may also be specified with arbitrary objects from code using
610 * {@link #setTag(Object)} or {@link #setTag(int, Object)}.
611 * </p>
612 *
613 * <a name="Themes"></a>
614 * <h3>Themes</h3>
615 * <p>
616 * By default, Views are created using the theme of the Context object supplied
617 * to their constructor; however, a different theme may be specified by using
618 * the {@link android.R.styleable#View_theme android:theme} attribute in layout
619 * XML or by passing a {@link ContextThemeWrapper} to the constructor from
620 * code.
621 * </p>
622 * <p>
623 * When the {@link android.R.styleable#View_theme android:theme} attribute is
624 * used in XML, the specified theme is applied on top of the inflation
625 * context's theme (see {@link LayoutInflater}) and used for the view itself as
626 * well as any child elements.
627 * </p>
628 * <p>
629 * In the following example, both views will be created using the Material dark
630 * color scheme; however, because an overlay theme is used which only defines a
631 * subset of attributes, the value of
632 * {@link android.R.styleable#Theme_colorAccent android:colorAccent} defined on
633 * the inflation context's theme (e.g. the Activity theme) will be preserved.
634 * <pre>
635 *     &lt;LinearLayout
636 *             ...
637 *             android:theme="@android:theme/ThemeOverlay.Material.Dark"&gt;
638 *         &lt;View ...&gt;
639 *     &lt;/LinearLayout&gt;
640 * </pre>
641 * </p>
642 *
643 * <a name="Properties"></a>
644 * <h3>Properties</h3>
645 * <p>
646 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
647 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
648 * available both in the {@link Property} form as well as in similarly-named setter/getter
649 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
650 * be used to set persistent state associated with these rendering-related properties on the view.
651 * The properties and methods can also be used in conjunction with
652 * {@link android.animation.Animator Animator}-based animations, described more in the
653 * <a href="#Animation">Animation</a> section.
654 * </p>
655 *
656 * <a name="Animation"></a>
657 * <h3>Animation</h3>
658 * <p>
659 * Starting with Android 3.0, the preferred way of animating views is to use the
660 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
661 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
662 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
663 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
664 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
665 * makes animating these View properties particularly easy and efficient.
666 * </p>
667 * <p>
668 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
669 * You can attach an {@link Animation} object to a view using
670 * {@link #setAnimation(Animation)} or
671 * {@link #startAnimation(Animation)}. The animation can alter the scale,
672 * rotation, translation and alpha of a view over time. If the animation is
673 * attached to a view that has children, the animation will affect the entire
674 * subtree rooted by that node. When an animation is started, the framework will
675 * take care of redrawing the appropriate views until the animation completes.
676 * </p>
677 *
678 * <a name="Security"></a>
679 * <h3>Security</h3>
680 * <p>
681 * Sometimes it is essential that an application be able to verify that an action
682 * is being performed with the full knowledge and consent of the user, such as
683 * granting a permission request, making a purchase or clicking on an advertisement.
684 * Unfortunately, a malicious application could try to spoof the user into
685 * performing these actions, unaware, by concealing the intended purpose of the view.
686 * As a remedy, the framework offers a touch filtering mechanism that can be used to
687 * improve the security of views that provide access to sensitive functionality.
688 * </p><p>
689 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
690 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
691 * will discard touches that are received whenever the view's window is obscured by
692 * another visible window.  As a result, the view will not receive touches whenever a
693 * toast, dialog or other window appears above the view's window.
694 * </p><p>
695 * For more fine-grained control over security, consider overriding the
696 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
697 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
698 * </p>
699 *
700 * @attr ref android.R.styleable#View_alpha
701 * @attr ref android.R.styleable#View_background
702 * @attr ref android.R.styleable#View_clickable
703 * @attr ref android.R.styleable#View_contentDescription
704 * @attr ref android.R.styleable#View_drawingCacheQuality
705 * @attr ref android.R.styleable#View_duplicateParentState
706 * @attr ref android.R.styleable#View_id
707 * @attr ref android.R.styleable#View_requiresFadingEdge
708 * @attr ref android.R.styleable#View_fadeScrollbars
709 * @attr ref android.R.styleable#View_fadingEdgeLength
710 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
711 * @attr ref android.R.styleable#View_fitsSystemWindows
712 * @attr ref android.R.styleable#View_isScrollContainer
713 * @attr ref android.R.styleable#View_focusable
714 * @attr ref android.R.styleable#View_focusableInTouchMode
715 * @attr ref android.R.styleable#View_focusedByDefault
716 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
717 * @attr ref android.R.styleable#View_keepScreenOn
718 * @attr ref android.R.styleable#View_keyboardNavigationCluster
719 * @attr ref android.R.styleable#View_layerType
720 * @attr ref android.R.styleable#View_layoutDirection
721 * @attr ref android.R.styleable#View_longClickable
722 * @attr ref android.R.styleable#View_minHeight
723 * @attr ref android.R.styleable#View_minWidth
724 * @attr ref android.R.styleable#View_nextClusterForward
725 * @attr ref android.R.styleable#View_nextFocusDown
726 * @attr ref android.R.styleable#View_nextFocusLeft
727 * @attr ref android.R.styleable#View_nextFocusRight
728 * @attr ref android.R.styleable#View_nextFocusUp
729 * @attr ref android.R.styleable#View_onClick
730 * @attr ref android.R.styleable#View_outlineSpotShadowColor
731 * @attr ref android.R.styleable#View_outlineAmbientShadowColor
732 * @attr ref android.R.styleable#View_padding
733 * @attr ref android.R.styleable#View_paddingHorizontal
734 * @attr ref android.R.styleable#View_paddingVertical
735 * @attr ref android.R.styleable#View_paddingBottom
736 * @attr ref android.R.styleable#View_paddingLeft
737 * @attr ref android.R.styleable#View_paddingRight
738 * @attr ref android.R.styleable#View_paddingTop
739 * @attr ref android.R.styleable#View_paddingStart
740 * @attr ref android.R.styleable#View_paddingEnd
741 * @attr ref android.R.styleable#View_saveEnabled
742 * @attr ref android.R.styleable#View_rotation
743 * @attr ref android.R.styleable#View_rotationX
744 * @attr ref android.R.styleable#View_rotationY
745 * @attr ref android.R.styleable#View_scaleX
746 * @attr ref android.R.styleable#View_scaleY
747 * @attr ref android.R.styleable#View_scrollX
748 * @attr ref android.R.styleable#View_scrollY
749 * @attr ref android.R.styleable#View_scrollbarSize
750 * @attr ref android.R.styleable#View_scrollbarStyle
751 * @attr ref android.R.styleable#View_scrollbars
752 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
753 * @attr ref android.R.styleable#View_scrollbarFadeDuration
754 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
755 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
756 * @attr ref android.R.styleable#View_scrollbarThumbVertical
757 * @attr ref android.R.styleable#View_scrollbarTrackVertical
758 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
759 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
760 * @attr ref android.R.styleable#View_stateListAnimator
761 * @attr ref android.R.styleable#View_transitionName
762 * @attr ref android.R.styleable#View_soundEffectsEnabled
763 * @attr ref android.R.styleable#View_tag
764 * @attr ref android.R.styleable#View_textAlignment
765 * @attr ref android.R.styleable#View_textDirection
766 * @attr ref android.R.styleable#View_transformPivotX
767 * @attr ref android.R.styleable#View_transformPivotY
768 * @attr ref android.R.styleable#View_translationX
769 * @attr ref android.R.styleable#View_translationY
770 * @attr ref android.R.styleable#View_translationZ
771 * @attr ref android.R.styleable#View_visibility
772 * @attr ref android.R.styleable#View_theme
773 *
774 * @see android.view.ViewGroup
775 */
776@UiThread
777public class View implements Drawable.Callback, KeyEvent.Callback,
778        AccessibilityEventSource {
779    private static final boolean DBG = false;
780
781    /** @hide */
782    public static boolean DEBUG_DRAW = false;
783
784    /**
785     * The logging tag used by this class with android.util.Log.
786     */
787    protected static final String VIEW_LOG_TAG = "View";
788
789    /**
790     * When set to true, apps will draw debugging information about their layouts.
791     *
792     * @hide
793     */
794    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
795
796    /**
797     * When set to true, this view will save its attribute data.
798     *
799     * @hide
800     */
801    public static boolean mDebugViewAttributes = false;
802
803    /**
804     * Used to mark a View that has no ID.
805     */
806    public static final int NO_ID = -1;
807
808    /**
809     * Last ID that is given to Views that are no part of activities.
810     *
811     * {@hide}
812     */
813    public static final int LAST_APP_AUTOFILL_ID = Integer.MAX_VALUE / 2;
814
815    /**
816     * Attribute to find the autofilled highlight
817     *
818     * @see #getAutofilledDrawable()
819     */
820    private static final int[] AUTOFILL_HIGHLIGHT_ATTR =
821            new int[]{android.R.attr.autofilledHighlight};
822
823    /**
824     * Signals that compatibility booleans have been initialized according to
825     * target SDK versions.
826     */
827    private static boolean sCompatibilityDone = false;
828
829    /**
830     * Use the old (broken) way of building MeasureSpecs.
831     */
832    private static boolean sUseBrokenMakeMeasureSpec = false;
833
834    /**
835     * Always return a size of 0 for MeasureSpec values with a mode of UNSPECIFIED
836     */
837    static boolean sUseZeroUnspecifiedMeasureSpec = false;
838
839    /**
840     * Ignore any optimizations using the measure cache.
841     */
842    private static boolean sIgnoreMeasureCache = false;
843
844    /**
845     * Ignore an optimization that skips unnecessary EXACTLY layout passes.
846     */
847    private static boolean sAlwaysRemeasureExactly = false;
848
849    /**
850     * Relax constraints around whether setLayoutParams() must be called after
851     * modifying the layout params.
852     */
853    private static boolean sLayoutParamsAlwaysChanged = false;
854
855    /**
856     * Allow setForeground/setBackground to be called (and ignored) on a textureview,
857     * without throwing
858     */
859    static boolean sTextureViewIgnoresDrawableSetters = false;
860
861    /**
862     * Prior to N, some ViewGroups would not convert LayoutParams properly even though both extend
863     * MarginLayoutParams. For instance, converting LinearLayout.LayoutParams to
864     * RelativeLayout.LayoutParams would lose margin information. This is fixed on N but target API
865     * check is implemented for backwards compatibility.
866     *
867     * {@hide}
868     */
869    protected static boolean sPreserveMarginParamsInLayoutParamConversion;
870
871    /**
872     * Prior to N, when drag enters into child of a view that has already received an
873     * ACTION_DRAG_ENTERED event, the parent doesn't get a ACTION_DRAG_EXITED event.
874     * ACTION_DRAG_LOCATION and ACTION_DROP were delivered to the parent of a view that returned
875     * false from its event handler for these events.
876     * Starting from N, the parent will get ACTION_DRAG_EXITED event before the child gets its
877     * ACTION_DRAG_ENTERED. ACTION_DRAG_LOCATION and ACTION_DROP are never propagated to the parent.
878     * sCascadedDragDrop is true for pre-N apps for backwards compatibility implementation.
879     */
880    static boolean sCascadedDragDrop;
881
882    /**
883     * Prior to O, auto-focusable didn't exist and widgets such as ListView use hasFocusable
884     * to determine things like whether or not to permit item click events. We can't break
885     * apps that do this just because more things (clickable things) are now auto-focusable
886     * and they would get different results, so give old behavior to old apps.
887     */
888    static boolean sHasFocusableExcludeAutoFocusable;
889
890    /**
891     * Prior to O, auto-focusable didn't exist and views marked as clickable weren't implicitly
892     * made focusable by default. As a result, apps could (incorrectly) change the clickable
893     * setting of views off the UI thread. Now that clickable can effect the focusable state,
894     * changing the clickable attribute off the UI thread will cause an exception (since changing
895     * the focusable state checks). In order to prevent apps from crashing, we will handle this
896     * specific case and just not notify parents on new focusables resulting from marking views
897     * clickable from outside the UI thread.
898     */
899    private static boolean sAutoFocusableOffUIThreadWontNotifyParents;
900
901    /**
902     * Prior to P things like setScaleX() allowed passing float values that were bogus such as
903     * Float.NaN. If the app is targetting P or later then passing these values will result in an
904     * exception being thrown. If the app is targetting an earlier SDK version, then we will
905     * silently clamp these values to avoid crashes elsewhere when the rendering code hits
906     * these bogus values.
907     */
908    private static boolean sThrowOnInvalidFloatProperties;
909
910    /**
911     * Prior to P, {@code #startDragAndDrop} accepts a builder which produces an empty drag shadow.
912     * Currently zero size SurfaceControl cannot be created thus we create a dummy 1x1 surface
913     * instead.
914     */
915    private static boolean sAcceptZeroSizeDragShadow;
916
917    /** @hide */
918    @IntDef({NOT_FOCUSABLE, FOCUSABLE, FOCUSABLE_AUTO})
919    @Retention(RetentionPolicy.SOURCE)
920    public @interface Focusable {}
921
922    /**
923     * This view does not want keystrokes.
924     * <p>
925     * Use with {@link #setFocusable(int)} and <a href="#attr_android:focusable">{@code
926     * android:focusable}.
927     */
928    public static final int NOT_FOCUSABLE = 0x00000000;
929
930    /**
931     * This view wants keystrokes.
932     * <p>
933     * Use with {@link #setFocusable(int)} and <a href="#attr_android:focusable">{@code
934     * android:focusable}.
935     */
936    public static final int FOCUSABLE = 0x00000001;
937
938    /**
939     * This view determines focusability automatically. This is the default.
940     * <p>
941     * Use with {@link #setFocusable(int)} and <a href="#attr_android:focusable">{@code
942     * android:focusable}.
943     */
944    public static final int FOCUSABLE_AUTO = 0x00000010;
945
946    /**
947     * Mask for use with setFlags indicating bits used for focus.
948     */
949    private static final int FOCUSABLE_MASK = 0x00000011;
950
951    /**
952     * This view will adjust its padding to fit sytem windows (e.g. status bar)
953     */
954    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
955
956    /** @hide */
957    @IntDef({VISIBLE, INVISIBLE, GONE})
958    @Retention(RetentionPolicy.SOURCE)
959    public @interface Visibility {}
960
961    /**
962     * This view is visible.
963     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
964     * android:visibility}.
965     */
966    public static final int VISIBLE = 0x00000000;
967
968    /**
969     * This view is invisible, but it still takes up space for layout purposes.
970     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
971     * android:visibility}.
972     */
973    public static final int INVISIBLE = 0x00000004;
974
975    /**
976     * This view is invisible, and it doesn't take any space for layout
977     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
978     * android:visibility}.
979     */
980    public static final int GONE = 0x00000008;
981
982    /**
983     * Mask for use with setFlags indicating bits used for visibility.
984     * {@hide}
985     */
986    static final int VISIBILITY_MASK = 0x0000000C;
987
988    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
989
990    /**
991     * Hint indicating that this view can be autofilled with an email address.
992     *
993     * <p>Can be used with either {@link #setAutofillHints(String[])} or
994     * <a href="#attr_android:autofillHint"> {@code android:autofillHint}</a> (in which case the
995     * value should be <code>{@value #AUTOFILL_HINT_EMAIL_ADDRESS}</code>).
996     *
997     * <p>See {@link #setAutofillHints(String...)} for more info about autofill hints.
998     */
999    public static final String AUTOFILL_HINT_EMAIL_ADDRESS = "emailAddress";
1000
1001    /**
1002     * Hint indicating that this view can be autofilled with a user's real name.
1003     *
1004     * <p>Can be used with either {@link #setAutofillHints(String[])} or
1005     * <a href="#attr_android:autofillHint"> {@code android:autofillHint}</a> (in which case the
1006     * value should be <code>{@value #AUTOFILL_HINT_NAME}</code>).
1007     *
1008     * <p>See {@link #setAutofillHints(String...)} for more info about autofill hints.
1009     */
1010    public static final String AUTOFILL_HINT_NAME = "name";
1011
1012    /**
1013     * Hint indicating that this view can be autofilled with a username.
1014     *
1015     * <p>Can be used with either {@link #setAutofillHints(String[])} or
1016     * <a href="#attr_android:autofillHint"> {@code android:autofillHint}</a> (in which case the
1017     * value should be <code>{@value #AUTOFILL_HINT_USERNAME}</code>).
1018     *
1019     * <p>See {@link #setAutofillHints(String...)} for more info about autofill hints.
1020     */
1021    public static final String AUTOFILL_HINT_USERNAME = "username";
1022
1023    /**
1024     * Hint indicating that this view can be autofilled with a password.
1025     *
1026     * <p>Can be used with either {@link #setAutofillHints(String[])} or
1027     * <a href="#attr_android:autofillHint"> {@code android:autofillHint}</a> (in which case the
1028     * value should be <code>{@value #AUTOFILL_HINT_PASSWORD}</code>).
1029     *
1030     * <p>See {@link #setAutofillHints(String...)} for more info about autofill hints.
1031     */
1032    public static final String AUTOFILL_HINT_PASSWORD = "password";
1033
1034    /**
1035     * Hint indicating that this view can be autofilled with a phone number.
1036     *
1037     * <p>Can be used with either {@link #setAutofillHints(String[])} or
1038     * <a href="#attr_android:autofillHint"> {@code android:autofillHint}</a> (in which case the
1039     * value should be <code>{@value #AUTOFILL_HINT_PHONE}</code>).
1040     *
1041     * <p>See {@link #setAutofillHints(String...)} for more info about autofill hints.
1042     */
1043    public static final String AUTOFILL_HINT_PHONE = "phone";
1044
1045    /**
1046     * Hint indicating that this view can be autofilled with a postal address.
1047     *
1048     * <p>Can be used with either {@link #setAutofillHints(String[])} or
1049     * <a href="#attr_android:autofillHint"> {@code android:autofillHint}</a> (in which case the
1050     * value should be <code>{@value #AUTOFILL_HINT_POSTAL_ADDRESS}</code>).
1051     *
1052     * <p>See {@link #setAutofillHints(String...)} for more info about autofill hints.
1053     */
1054    public static final String AUTOFILL_HINT_POSTAL_ADDRESS = "postalAddress";
1055
1056    /**
1057     * Hint indicating that this view can be autofilled with a postal code.
1058     *
1059     * <p>Can be used with either {@link #setAutofillHints(String[])} or
1060     * <a href="#attr_android:autofillHint"> {@code android:autofillHint}</a> (in which case the
1061     * value should be <code>{@value #AUTOFILL_HINT_POSTAL_CODE}</code>).
1062     *
1063     * <p>See {@link #setAutofillHints(String...)} for more info about autofill hints.
1064     */
1065    public static final String AUTOFILL_HINT_POSTAL_CODE = "postalCode";
1066
1067    /**
1068     * Hint indicating that this view can be autofilled with a credit card number.
1069     *
1070     * <p>Can be used with either {@link #setAutofillHints(String[])} or
1071     * <a href="#attr_android:autofillHint"> {@code android:autofillHint}</a> (in which case the
1072     * value should be <code>{@value #AUTOFILL_HINT_CREDIT_CARD_NUMBER}</code>).
1073     *
1074     * <p>See {@link #setAutofillHints(String...)} for more info about autofill hints.
1075     */
1076    public static final String AUTOFILL_HINT_CREDIT_CARD_NUMBER = "creditCardNumber";
1077
1078    /**
1079     * Hint indicating that this view can be autofilled with a credit card security code.
1080     *
1081     * <p>Can be used with either {@link #setAutofillHints(String[])} or
1082     * <a href="#attr_android:autofillHint"> {@code android:autofillHint}</a> (in which case the
1083     * value should be <code>{@value #AUTOFILL_HINT_CREDIT_CARD_SECURITY_CODE}</code>).
1084     *
1085     * <p>See {@link #setAutofillHints(String...)} for more info about autofill hints.
1086     */
1087    public static final String AUTOFILL_HINT_CREDIT_CARD_SECURITY_CODE = "creditCardSecurityCode";
1088
1089    /**
1090     * Hint indicating that this view can be autofilled with a credit card expiration date.
1091     *
1092     * <p>It should be used when the credit card expiration date is represented by just one view;
1093     * if it is represented by more than one (for example, one view for the month and another view
1094     * for the year), then each of these views should use the hint specific for the unit
1095     * ({@link #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DAY},
1096     * {@link #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_MONTH},
1097     * or {@link #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_YEAR}).
1098     *
1099     * <p>Can be used with either {@link #setAutofillHints(String[])} or
1100     * <a href="#attr_android:autofillHint"> {@code android:autofillHint}</a> (in which case the
1101     * value should be <code>{@value #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DATE}</code>).
1102     *
1103     * <p>When annotating a view with this hint, it's recommended to use a date autofill value to
1104     * avoid ambiguity when the autofill service provides a value for it. To understand why a
1105     * value can be ambiguous, consider "April of 2020", which could be represented as either of
1106     * the following options:
1107     *
1108     * <ul>
1109     *   <li>{@code "04/2020"}
1110     *   <li>{@code "4/2020"}
1111     *   <li>{@code "2020/04"}
1112     *   <li>{@code "2020/4"}
1113     *   <li>{@code "April/2020"}
1114     *   <li>{@code "Apr/2020"}
1115     * </ul>
1116     *
1117     * <p>You define a date autofill value for the view by overriding the following methods:
1118     *
1119     * <ol>
1120     *   <li>{@link #getAutofillType()} to return {@link #AUTOFILL_TYPE_DATE}.
1121     *   <li>{@link #getAutofillValue()} to return a
1122     *       {@link AutofillValue#forDate(long) date autofillvalue}.
1123     *   <li>{@link #autofill(AutofillValue)} to expect a data autofillvalue.
1124     * </ol>
1125     *
1126     * <p>See {@link #setAutofillHints(String...)} for more info about autofill hints.
1127     */
1128    public static final String AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DATE =
1129            "creditCardExpirationDate";
1130
1131    /**
1132     * Hint indicating that this view can be autofilled with a credit card expiration month.
1133     *
1134     * <p>Can be used with either {@link #setAutofillHints(String[])} or
1135     * <a href="#attr_android:autofillHint"> {@code android:autofillHint}</a> (in which case the
1136     * value should be <code>{@value #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_MONTH}</code>).
1137     *
1138     * <p>When annotating a view with this hint, it's recommended to use a text autofill value
1139     * whose value is the numerical representation of the month, starting on {@code 1} to avoid
1140     * ambiguity when the autofill service provides a value for it. To understand why a
1141     * value can be ambiguous, consider "January", which could be represented as either of
1142     *
1143     * <ul>
1144     *   <li>{@code "1"}: recommended way.
1145     *   <li>{@code "0"}: if following the {@link Calendar#MONTH} convention.
1146     *   <li>{@code "January"}: full name, in English.
1147     *   <li>{@code "jan"}: abbreviated name, in English.
1148     *   <li>{@code "Janeiro"}: full name, in another language.
1149     * </ul>
1150     *
1151     * <p>Another recommended approach is to use a date autofill value - see
1152     * {@link #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DATE} for more details.
1153     *
1154     * <p>See {@link #setAutofillHints(String...)} for more info about autofill hints.
1155     */
1156    public static final String AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_MONTH =
1157            "creditCardExpirationMonth";
1158
1159    /**
1160     * Hint indicating that this view can be autofilled with a credit card expiration year.
1161     *
1162     * <p>Can be used with either {@link #setAutofillHints(String[])} or
1163     * <a href="#attr_android:autofillHint"> {@code android:autofillHint}</a> (in which case the
1164     * value should be <code>{@value #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_YEAR}</code>).
1165     *
1166     * <p>See {@link #setAutofillHints(String...)} for more info about autofill hints.
1167     */
1168    public static final String AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_YEAR =
1169            "creditCardExpirationYear";
1170
1171    /**
1172     * Hint indicating that this view can be autofilled with a credit card expiration day.
1173     *
1174     * <p>Can be used with either {@link #setAutofillHints(String[])} or
1175     * <a href="#attr_android:autofillHint"> {@code android:autofillHint}</a> (in which case the
1176     * value should be <code>{@value #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DAY}</code>).
1177     *
1178     * <p>See {@link #setAutofillHints(String...)} for more info about autofill hints.
1179     */
1180    public static final String AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DAY = "creditCardExpirationDay";
1181
1182    /**
1183     * Hints for the autofill services that describes the content of the view.
1184     */
1185    private @Nullable String[] mAutofillHints;
1186
1187    /**
1188     * Autofill id, lazily created on calls to {@link #getAutofillId()}.
1189     */
1190    private AutofillId mAutofillId;
1191
1192    /** @hide */
1193    @IntDef(prefix = { "AUTOFILL_TYPE_" }, value = {
1194            AUTOFILL_TYPE_NONE,
1195            AUTOFILL_TYPE_TEXT,
1196            AUTOFILL_TYPE_TOGGLE,
1197            AUTOFILL_TYPE_LIST,
1198            AUTOFILL_TYPE_DATE
1199    })
1200    @Retention(RetentionPolicy.SOURCE)
1201    public @interface AutofillType {}
1202
1203    /**
1204     * Autofill type for views that cannot be autofilled.
1205     *
1206     * <p>Typically used when the view is read-only; for example, a text label.
1207     *
1208     * @see #getAutofillType()
1209     */
1210    public static final int AUTOFILL_TYPE_NONE = 0;
1211
1212    /**
1213     * Autofill type for a text field, which is filled by a {@link CharSequence}.
1214     *
1215     * <p>{@link AutofillValue} instances for autofilling a {@link View} can be obtained through
1216     * {@link AutofillValue#forText(CharSequence)}, and the value passed to autofill a
1217     * {@link View} can be fetched through {@link AutofillValue#getTextValue()}.
1218     *
1219     * @see #getAutofillType()
1220     */
1221    public static final int AUTOFILL_TYPE_TEXT = 1;
1222
1223    /**
1224     * Autofill type for a togglable field, which is filled by a {@code boolean}.
1225     *
1226     * <p>{@link AutofillValue} instances for autofilling a {@link View} can be obtained through
1227     * {@link AutofillValue#forToggle(boolean)}, and the value passed to autofill a
1228     * {@link View} can be fetched through {@link AutofillValue#getToggleValue()}.
1229     *
1230     * @see #getAutofillType()
1231     */
1232    public static final int AUTOFILL_TYPE_TOGGLE = 2;
1233
1234    /**
1235     * Autofill type for a selection list field, which is filled by an {@code int}
1236     * representing the element index inside the list (starting at {@code 0}).
1237     *
1238     * <p>{@link AutofillValue} instances for autofilling a {@link View} can be obtained through
1239     * {@link AutofillValue#forList(int)}, and the value passed to autofill a
1240     * {@link View} can be fetched through {@link AutofillValue#getListValue()}.
1241     *
1242     * <p>The available options in the selection list are typically provided by
1243     * {@link android.app.assist.AssistStructure.ViewNode#getAutofillOptions()}.
1244     *
1245     * @see #getAutofillType()
1246     */
1247    public static final int AUTOFILL_TYPE_LIST = 3;
1248
1249
1250    /**
1251     * Autofill type for a field that contains a date, which is represented by a long representing
1252     * the number of milliseconds since the standard base time known as "the epoch", namely
1253     * January 1, 1970, 00:00:00 GMT (see {@link java.util.Date#getTime()}.
1254     *
1255     * <p>{@link AutofillValue} instances for autofilling a {@link View} can be obtained through
1256     * {@link AutofillValue#forDate(long)}, and the values passed to
1257     * autofill a {@link View} can be fetched through {@link AutofillValue#getDateValue()}.
1258     *
1259     * @see #getAutofillType()
1260     */
1261    public static final int AUTOFILL_TYPE_DATE = 4;
1262
1263    /** @hide */
1264    @IntDef(prefix = { "IMPORTANT_FOR_AUTOFILL_" }, value = {
1265            IMPORTANT_FOR_AUTOFILL_AUTO,
1266            IMPORTANT_FOR_AUTOFILL_YES,
1267            IMPORTANT_FOR_AUTOFILL_NO,
1268            IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS,
1269            IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS
1270    })
1271    @Retention(RetentionPolicy.SOURCE)
1272    public @interface AutofillImportance {}
1273
1274    /**
1275     * Automatically determine whether a view is important for autofill.
1276     *
1277     * @see #isImportantForAutofill()
1278     * @see #setImportantForAutofill(int)
1279     */
1280    public static final int IMPORTANT_FOR_AUTOFILL_AUTO = 0x0;
1281
1282    /**
1283     * The view is important for autofill, and its children (if any) will be traversed.
1284     *
1285     * @see #isImportantForAutofill()
1286     * @see #setImportantForAutofill(int)
1287     */
1288    public static final int IMPORTANT_FOR_AUTOFILL_YES = 0x1;
1289
1290    /**
1291     * The view is not important for autofill, but its children (if any) will be traversed.
1292     *
1293     * @see #isImportantForAutofill()
1294     * @see #setImportantForAutofill(int)
1295     */
1296    public static final int IMPORTANT_FOR_AUTOFILL_NO = 0x2;
1297
1298    /**
1299     * The view is important for autofill, but its children (if any) will not be traversed.
1300     *
1301     * @see #isImportantForAutofill()
1302     * @see #setImportantForAutofill(int)
1303     */
1304    public static final int IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS = 0x4;
1305
1306    /**
1307     * The view is not important for autofill, and its children (if any) will not be traversed.
1308     *
1309     * @see #isImportantForAutofill()
1310     * @see #setImportantForAutofill(int)
1311     */
1312    public static final int IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS = 0x8;
1313
1314    /** @hide */
1315    @IntDef(flag = true, prefix = { "AUTOFILL_FLAG_" }, value = {
1316            AUTOFILL_FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
1317    })
1318    @Retention(RetentionPolicy.SOURCE)
1319    public @interface AutofillFlags {}
1320
1321    /**
1322     * Flag requesting you to add views that are marked as not important for autofill
1323     * (see {@link #setImportantForAutofill(int)}) to a {@link ViewStructure}.
1324     */
1325    public static final int AUTOFILL_FLAG_INCLUDE_NOT_IMPORTANT_VIEWS = 0x1;
1326
1327    /**
1328     * This view is enabled. Interpretation varies by subclass.
1329     * Use with ENABLED_MASK when calling setFlags.
1330     * {@hide}
1331     */
1332    static final int ENABLED = 0x00000000;
1333
1334    /**
1335     * This view is disabled. Interpretation varies by subclass.
1336     * Use with ENABLED_MASK when calling setFlags.
1337     * {@hide}
1338     */
1339    static final int DISABLED = 0x00000020;
1340
1341   /**
1342    * Mask for use with setFlags indicating bits used for indicating whether
1343    * this view is enabled
1344    * {@hide}
1345    */
1346    static final int ENABLED_MASK = 0x00000020;
1347
1348    /**
1349     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
1350     * called and further optimizations will be performed. It is okay to have
1351     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
1352     * {@hide}
1353     */
1354    static final int WILL_NOT_DRAW = 0x00000080;
1355
1356    /**
1357     * Mask for use with setFlags indicating bits used for indicating whether
1358     * this view is will draw
1359     * {@hide}
1360     */
1361    static final int DRAW_MASK = 0x00000080;
1362
1363    /**
1364     * <p>This view doesn't show scrollbars.</p>
1365     * {@hide}
1366     */
1367    static final int SCROLLBARS_NONE = 0x00000000;
1368
1369    /**
1370     * <p>This view shows horizontal scrollbars.</p>
1371     * {@hide}
1372     */
1373    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
1374
1375    /**
1376     * <p>This view shows vertical scrollbars.</p>
1377     * {@hide}
1378     */
1379    static final int SCROLLBARS_VERTICAL = 0x00000200;
1380
1381    /**
1382     * <p>Mask for use with setFlags indicating bits used for indicating which
1383     * scrollbars are enabled.</p>
1384     * {@hide}
1385     */
1386    static final int SCROLLBARS_MASK = 0x00000300;
1387
1388    /**
1389     * Indicates that the view should filter touches when its window is obscured.
1390     * Refer to the class comments for more information about this security feature.
1391     * {@hide}
1392     */
1393    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
1394
1395    /**
1396     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
1397     * that they are optional and should be skipped if the window has
1398     * requested system UI flags that ignore those insets for layout.
1399     */
1400    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
1401
1402    /**
1403     * <p>This view doesn't show fading edges.</p>
1404     * {@hide}
1405     */
1406    static final int FADING_EDGE_NONE = 0x00000000;
1407
1408    /**
1409     * <p>This view shows horizontal fading edges.</p>
1410     * {@hide}
1411     */
1412    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
1413
1414    /**
1415     * <p>This view shows vertical fading edges.</p>
1416     * {@hide}
1417     */
1418    static final int FADING_EDGE_VERTICAL = 0x00002000;
1419
1420    /**
1421     * <p>Mask for use with setFlags indicating bits used for indicating which
1422     * fading edges are enabled.</p>
1423     * {@hide}
1424     */
1425    static final int FADING_EDGE_MASK = 0x00003000;
1426
1427    /**
1428     * <p>Indicates this view can be clicked. When clickable, a View reacts
1429     * to clicks by notifying the OnClickListener.<p>
1430     * {@hide}
1431     */
1432    static final int CLICKABLE = 0x00004000;
1433
1434    /**
1435     * <p>Indicates this view is caching its drawing into a bitmap.</p>
1436     * {@hide}
1437     */
1438    static final int DRAWING_CACHE_ENABLED = 0x00008000;
1439
1440    /**
1441     * <p>Indicates that no icicle should be saved for this view.<p>
1442     * {@hide}
1443     */
1444    static final int SAVE_DISABLED = 0x000010000;
1445
1446    /**
1447     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
1448     * property.</p>
1449     * {@hide}
1450     */
1451    static final int SAVE_DISABLED_MASK = 0x000010000;
1452
1453    /**
1454     * <p>Indicates that no drawing cache should ever be created for this view.<p>
1455     * {@hide}
1456     */
1457    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
1458
1459    /**
1460     * <p>Indicates this view can take / keep focus when int touch mode.</p>
1461     * {@hide}
1462     */
1463    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
1464
1465    /** @hide */
1466    @Retention(RetentionPolicy.SOURCE)
1467    @IntDef(prefix = { "DRAWING_CACHE_QUALITY_" }, value = {
1468            DRAWING_CACHE_QUALITY_LOW,
1469            DRAWING_CACHE_QUALITY_HIGH,
1470            DRAWING_CACHE_QUALITY_AUTO
1471    })
1472    public @interface DrawingCacheQuality {}
1473
1474    /**
1475     * <p>Enables low quality mode for the drawing cache.</p>
1476     *
1477     * @deprecated The view drawing cache was largely made obsolete with the introduction of
1478     * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
1479     * layers are largely unnecessary and can easily result in a net loss in performance due to the
1480     * cost of creating and updating the layer. In the rare cases where caching layers are useful,
1481     * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
1482     * rendering. For software-rendered snapshots of a small part of the View hierarchy or
1483     * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
1484     * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
1485     * software-rendered usages are discouraged and have compatibility issues with hardware-only
1486     * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
1487     * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
1488     * reports or unit testing the {@link PixelCopy} API is recommended.
1489     */
1490    @Deprecated
1491    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
1492
1493    /**
1494     * <p>Enables high quality mode for the drawing cache.</p>
1495     *
1496     * @deprecated The view drawing cache was largely made obsolete with the introduction of
1497     * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
1498     * layers are largely unnecessary and can easily result in a net loss in performance due to the
1499     * cost of creating and updating the layer. In the rare cases where caching layers are useful,
1500     * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
1501     * rendering. For software-rendered snapshots of a small part of the View hierarchy or
1502     * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
1503     * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
1504     * software-rendered usages are discouraged and have compatibility issues with hardware-only
1505     * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
1506     * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
1507     * reports or unit testing the {@link PixelCopy} API is recommended.
1508     */
1509    @Deprecated
1510    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
1511
1512    /**
1513     * <p>Enables automatic quality mode for the drawing cache.</p>
1514     *
1515     * @deprecated The view drawing cache was largely made obsolete with the introduction of
1516     * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
1517     * layers are largely unnecessary and can easily result in a net loss in performance due to the
1518     * cost of creating and updating the layer. In the rare cases where caching layers are useful,
1519     * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
1520     * rendering. For software-rendered snapshots of a small part of the View hierarchy or
1521     * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
1522     * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
1523     * software-rendered usages are discouraged and have compatibility issues with hardware-only
1524     * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
1525     * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
1526     * reports or unit testing the {@link PixelCopy} API is recommended.
1527     */
1528    @Deprecated
1529    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
1530
1531    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
1532            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
1533    };
1534
1535    /**
1536     * <p>Mask for use with setFlags indicating bits used for the cache
1537     * quality property.</p>
1538     * {@hide}
1539     */
1540    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
1541
1542    /**
1543     * <p>
1544     * Indicates this view can be long clicked. When long clickable, a View
1545     * reacts to long clicks by notifying the OnLongClickListener or showing a
1546     * context menu.
1547     * </p>
1548     * {@hide}
1549     */
1550    static final int LONG_CLICKABLE = 0x00200000;
1551
1552    /**
1553     * <p>Indicates that this view gets its drawable states from its direct parent
1554     * and ignores its original internal states.</p>
1555     *
1556     * @hide
1557     */
1558    static final int DUPLICATE_PARENT_STATE = 0x00400000;
1559
1560    /**
1561     * <p>
1562     * Indicates this view can be context clicked. When context clickable, a View reacts to a
1563     * context click (e.g. a primary stylus button press or right mouse click) by notifying the
1564     * OnContextClickListener.
1565     * </p>
1566     * {@hide}
1567     */
1568    static final int CONTEXT_CLICKABLE = 0x00800000;
1569
1570    /** @hide */
1571    @IntDef(prefix = { "SCROLLBARS_" }, value = {
1572            SCROLLBARS_INSIDE_OVERLAY,
1573            SCROLLBARS_INSIDE_INSET,
1574            SCROLLBARS_OUTSIDE_OVERLAY,
1575            SCROLLBARS_OUTSIDE_INSET
1576    })
1577    @Retention(RetentionPolicy.SOURCE)
1578    public @interface ScrollBarStyle {}
1579
1580    /**
1581     * The scrollbar style to display the scrollbars inside the content area,
1582     * without increasing the padding. The scrollbars will be overlaid with
1583     * translucency on the view's content.
1584     */
1585    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
1586
1587    /**
1588     * The scrollbar style to display the scrollbars inside the padded area,
1589     * increasing the padding of the view. The scrollbars will not overlap the
1590     * content area of the view.
1591     */
1592    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
1593
1594    /**
1595     * The scrollbar style to display the scrollbars at the edge of the view,
1596     * without increasing the padding. The scrollbars will be overlaid with
1597     * translucency.
1598     */
1599    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
1600
1601    /**
1602     * The scrollbar style to display the scrollbars at the edge of the view,
1603     * increasing the padding of the view. The scrollbars will only overlap the
1604     * background, if any.
1605     */
1606    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
1607
1608    /**
1609     * Mask to check if the scrollbar style is overlay or inset.
1610     * {@hide}
1611     */
1612    static final int SCROLLBARS_INSET_MASK = 0x01000000;
1613
1614    /**
1615     * Mask to check if the scrollbar style is inside or outside.
1616     * {@hide}
1617     */
1618    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
1619
1620    /**
1621     * Mask for scrollbar style.
1622     * {@hide}
1623     */
1624    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
1625
1626    /**
1627     * View flag indicating that the screen should remain on while the
1628     * window containing this view is visible to the user.  This effectively
1629     * takes care of automatically setting the WindowManager's
1630     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
1631     */
1632    public static final int KEEP_SCREEN_ON = 0x04000000;
1633
1634    /**
1635     * View flag indicating whether this view should have sound effects enabled
1636     * for events such as clicking and touching.
1637     */
1638    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
1639
1640    /**
1641     * View flag indicating whether this view should have haptic feedback
1642     * enabled for events such as long presses.
1643     */
1644    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
1645
1646    /**
1647     * <p>Indicates that the view hierarchy should stop saving state when
1648     * it reaches this view.  If state saving is initiated immediately at
1649     * the view, it will be allowed.
1650     * {@hide}
1651     */
1652    static final int PARENT_SAVE_DISABLED = 0x20000000;
1653
1654    /**
1655     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1656     * {@hide}
1657     */
1658    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1659
1660    private static Paint sDebugPaint;
1661
1662    /**
1663     * <p>Indicates this view can display a tooltip on hover or long press.</p>
1664     * {@hide}
1665     */
1666    static final int TOOLTIP = 0x40000000;
1667
1668    /** @hide */
1669    @IntDef(flag = true, prefix = { "FOCUSABLES_" }, value = {
1670            FOCUSABLES_ALL,
1671            FOCUSABLES_TOUCH_MODE
1672    })
1673    @Retention(RetentionPolicy.SOURCE)
1674    public @interface FocusableMode {}
1675
1676    /**
1677     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1678     * should add all focusable Views regardless if they are focusable in touch mode.
1679     */
1680    public static final int FOCUSABLES_ALL = 0x00000000;
1681
1682    /**
1683     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1684     * should add only Views focusable in touch mode.
1685     */
1686    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1687
1688    /** @hide */
1689    @IntDef(prefix = { "FOCUS_" }, value = {
1690            FOCUS_BACKWARD,
1691            FOCUS_FORWARD,
1692            FOCUS_LEFT,
1693            FOCUS_UP,
1694            FOCUS_RIGHT,
1695            FOCUS_DOWN
1696    })
1697    @Retention(RetentionPolicy.SOURCE)
1698    public @interface FocusDirection {}
1699
1700    /** @hide */
1701    @IntDef(prefix = { "FOCUS_" }, value = {
1702            FOCUS_LEFT,
1703            FOCUS_UP,
1704            FOCUS_RIGHT,
1705            FOCUS_DOWN
1706    })
1707    @Retention(RetentionPolicy.SOURCE)
1708    public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward
1709
1710    /**
1711     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1712     * item.
1713     */
1714    public static final int FOCUS_BACKWARD = 0x00000001;
1715
1716    /**
1717     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1718     * item.
1719     */
1720    public static final int FOCUS_FORWARD = 0x00000002;
1721
1722    /**
1723     * Use with {@link #focusSearch(int)}. Move focus to the left.
1724     */
1725    public static final int FOCUS_LEFT = 0x00000011;
1726
1727    /**
1728     * Use with {@link #focusSearch(int)}. Move focus up.
1729     */
1730    public static final int FOCUS_UP = 0x00000021;
1731
1732    /**
1733     * Use with {@link #focusSearch(int)}. Move focus to the right.
1734     */
1735    public static final int FOCUS_RIGHT = 0x00000042;
1736
1737    /**
1738     * Use with {@link #focusSearch(int)}. Move focus down.
1739     */
1740    public static final int FOCUS_DOWN = 0x00000082;
1741
1742    /**
1743     * Bits of {@link #getMeasuredWidthAndState()} and
1744     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1745     */
1746    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1747
1748    /**
1749     * Bits of {@link #getMeasuredWidthAndState()} and
1750     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1751     */
1752    public static final int MEASURED_STATE_MASK = 0xff000000;
1753
1754    /**
1755     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1756     * for functions that combine both width and height into a single int,
1757     * such as {@link #getMeasuredState()} and the childState argument of
1758     * {@link #resolveSizeAndState(int, int, int)}.
1759     */
1760    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1761
1762    /**
1763     * Bit of {@link #getMeasuredWidthAndState()} and
1764     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1765     * is smaller that the space the view would like to have.
1766     */
1767    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1768
1769    /**
1770     * Base View state sets
1771     */
1772    // Singles
1773    /**
1774     * Indicates the view has no states set. States are used with
1775     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1776     * view depending on its state.
1777     *
1778     * @see android.graphics.drawable.Drawable
1779     * @see #getDrawableState()
1780     */
1781    protected static final int[] EMPTY_STATE_SET;
1782    /**
1783     * Indicates the view is enabled. States are used with
1784     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1785     * view depending on its state.
1786     *
1787     * @see android.graphics.drawable.Drawable
1788     * @see #getDrawableState()
1789     */
1790    protected static final int[] ENABLED_STATE_SET;
1791    /**
1792     * Indicates the view is focused. States are used with
1793     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1794     * view depending on its state.
1795     *
1796     * @see android.graphics.drawable.Drawable
1797     * @see #getDrawableState()
1798     */
1799    protected static final int[] FOCUSED_STATE_SET;
1800    /**
1801     * Indicates the view is selected. States are used with
1802     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1803     * view depending on its state.
1804     *
1805     * @see android.graphics.drawable.Drawable
1806     * @see #getDrawableState()
1807     */
1808    protected static final int[] SELECTED_STATE_SET;
1809    /**
1810     * Indicates the view is pressed. States are used with
1811     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1812     * view depending on its state.
1813     *
1814     * @see android.graphics.drawable.Drawable
1815     * @see #getDrawableState()
1816     */
1817    protected static final int[] PRESSED_STATE_SET;
1818    /**
1819     * Indicates the view's window has focus. States are used with
1820     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1821     * view depending on its state.
1822     *
1823     * @see android.graphics.drawable.Drawable
1824     * @see #getDrawableState()
1825     */
1826    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1827    // Doubles
1828    /**
1829     * Indicates the view is enabled and has the focus.
1830     *
1831     * @see #ENABLED_STATE_SET
1832     * @see #FOCUSED_STATE_SET
1833     */
1834    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1835    /**
1836     * Indicates the view is enabled and selected.
1837     *
1838     * @see #ENABLED_STATE_SET
1839     * @see #SELECTED_STATE_SET
1840     */
1841    protected static final int[] ENABLED_SELECTED_STATE_SET;
1842    /**
1843     * Indicates the view is enabled and that its window has focus.
1844     *
1845     * @see #ENABLED_STATE_SET
1846     * @see #WINDOW_FOCUSED_STATE_SET
1847     */
1848    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1849    /**
1850     * Indicates the view is focused and selected.
1851     *
1852     * @see #FOCUSED_STATE_SET
1853     * @see #SELECTED_STATE_SET
1854     */
1855    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1856    /**
1857     * Indicates the view has the focus and that its window has the focus.
1858     *
1859     * @see #FOCUSED_STATE_SET
1860     * @see #WINDOW_FOCUSED_STATE_SET
1861     */
1862    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1863    /**
1864     * Indicates the view is selected and that its window has the focus.
1865     *
1866     * @see #SELECTED_STATE_SET
1867     * @see #WINDOW_FOCUSED_STATE_SET
1868     */
1869    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1870    // Triples
1871    /**
1872     * Indicates the view is enabled, focused and selected.
1873     *
1874     * @see #ENABLED_STATE_SET
1875     * @see #FOCUSED_STATE_SET
1876     * @see #SELECTED_STATE_SET
1877     */
1878    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1879    /**
1880     * Indicates the view is enabled, focused and its window has the focus.
1881     *
1882     * @see #ENABLED_STATE_SET
1883     * @see #FOCUSED_STATE_SET
1884     * @see #WINDOW_FOCUSED_STATE_SET
1885     */
1886    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1887    /**
1888     * Indicates the view is enabled, selected and its window has the focus.
1889     *
1890     * @see #ENABLED_STATE_SET
1891     * @see #SELECTED_STATE_SET
1892     * @see #WINDOW_FOCUSED_STATE_SET
1893     */
1894    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1895    /**
1896     * Indicates the view is focused, selected and its window has the focus.
1897     *
1898     * @see #FOCUSED_STATE_SET
1899     * @see #SELECTED_STATE_SET
1900     * @see #WINDOW_FOCUSED_STATE_SET
1901     */
1902    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1903    /**
1904     * Indicates the view is enabled, focused, selected and its window
1905     * has the focus.
1906     *
1907     * @see #ENABLED_STATE_SET
1908     * @see #FOCUSED_STATE_SET
1909     * @see #SELECTED_STATE_SET
1910     * @see #WINDOW_FOCUSED_STATE_SET
1911     */
1912    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1913    /**
1914     * Indicates the view is pressed and its window has the focus.
1915     *
1916     * @see #PRESSED_STATE_SET
1917     * @see #WINDOW_FOCUSED_STATE_SET
1918     */
1919    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1920    /**
1921     * Indicates the view is pressed and selected.
1922     *
1923     * @see #PRESSED_STATE_SET
1924     * @see #SELECTED_STATE_SET
1925     */
1926    protected static final int[] PRESSED_SELECTED_STATE_SET;
1927    /**
1928     * Indicates the view is pressed, selected and its window has the focus.
1929     *
1930     * @see #PRESSED_STATE_SET
1931     * @see #SELECTED_STATE_SET
1932     * @see #WINDOW_FOCUSED_STATE_SET
1933     */
1934    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1935    /**
1936     * Indicates the view is pressed and focused.
1937     *
1938     * @see #PRESSED_STATE_SET
1939     * @see #FOCUSED_STATE_SET
1940     */
1941    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1942    /**
1943     * Indicates the view is pressed, focused and its window has the focus.
1944     *
1945     * @see #PRESSED_STATE_SET
1946     * @see #FOCUSED_STATE_SET
1947     * @see #WINDOW_FOCUSED_STATE_SET
1948     */
1949    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1950    /**
1951     * Indicates the view is pressed, focused and selected.
1952     *
1953     * @see #PRESSED_STATE_SET
1954     * @see #SELECTED_STATE_SET
1955     * @see #FOCUSED_STATE_SET
1956     */
1957    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1958    /**
1959     * Indicates the view is pressed, focused, selected and its window has the focus.
1960     *
1961     * @see #PRESSED_STATE_SET
1962     * @see #FOCUSED_STATE_SET
1963     * @see #SELECTED_STATE_SET
1964     * @see #WINDOW_FOCUSED_STATE_SET
1965     */
1966    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1967    /**
1968     * Indicates the view is pressed and enabled.
1969     *
1970     * @see #PRESSED_STATE_SET
1971     * @see #ENABLED_STATE_SET
1972     */
1973    protected static final int[] PRESSED_ENABLED_STATE_SET;
1974    /**
1975     * Indicates the view is pressed, enabled and its window has the focus.
1976     *
1977     * @see #PRESSED_STATE_SET
1978     * @see #ENABLED_STATE_SET
1979     * @see #WINDOW_FOCUSED_STATE_SET
1980     */
1981    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1982    /**
1983     * Indicates the view is pressed, enabled and selected.
1984     *
1985     * @see #PRESSED_STATE_SET
1986     * @see #ENABLED_STATE_SET
1987     * @see #SELECTED_STATE_SET
1988     */
1989    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1990    /**
1991     * Indicates the view is pressed, enabled, selected and its window has the
1992     * focus.
1993     *
1994     * @see #PRESSED_STATE_SET
1995     * @see #ENABLED_STATE_SET
1996     * @see #SELECTED_STATE_SET
1997     * @see #WINDOW_FOCUSED_STATE_SET
1998     */
1999    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
2000    /**
2001     * Indicates the view is pressed, enabled and focused.
2002     *
2003     * @see #PRESSED_STATE_SET
2004     * @see #ENABLED_STATE_SET
2005     * @see #FOCUSED_STATE_SET
2006     */
2007    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
2008    /**
2009     * Indicates the view is pressed, enabled, focused and its window has the
2010     * focus.
2011     *
2012     * @see #PRESSED_STATE_SET
2013     * @see #ENABLED_STATE_SET
2014     * @see #FOCUSED_STATE_SET
2015     * @see #WINDOW_FOCUSED_STATE_SET
2016     */
2017    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
2018    /**
2019     * Indicates the view is pressed, enabled, focused and selected.
2020     *
2021     * @see #PRESSED_STATE_SET
2022     * @see #ENABLED_STATE_SET
2023     * @see #SELECTED_STATE_SET
2024     * @see #FOCUSED_STATE_SET
2025     */
2026    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
2027    /**
2028     * Indicates the view is pressed, enabled, focused, selected and its window
2029     * has the focus.
2030     *
2031     * @see #PRESSED_STATE_SET
2032     * @see #ENABLED_STATE_SET
2033     * @see #SELECTED_STATE_SET
2034     * @see #FOCUSED_STATE_SET
2035     * @see #WINDOW_FOCUSED_STATE_SET
2036     */
2037    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
2038
2039    static {
2040        EMPTY_STATE_SET = StateSet.get(0);
2041
2042        WINDOW_FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_WINDOW_FOCUSED);
2043
2044        SELECTED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_SELECTED);
2045        SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
2046                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED);
2047
2048        FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_FOCUSED);
2049        FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
2050                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED);
2051        FOCUSED_SELECTED_STATE_SET = StateSet.get(
2052                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED);
2053        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
2054                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
2055                        | StateSet.VIEW_STATE_FOCUSED);
2056
2057        ENABLED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_ENABLED);
2058        ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
2059                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED);
2060        ENABLED_SELECTED_STATE_SET = StateSet.get(
2061                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED);
2062        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
2063                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
2064                        | StateSet.VIEW_STATE_ENABLED);
2065        ENABLED_FOCUSED_STATE_SET = StateSet.get(
2066                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED);
2067        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
2068                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
2069                        | StateSet.VIEW_STATE_ENABLED);
2070        ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
2071                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
2072                        | StateSet.VIEW_STATE_ENABLED);
2073        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
2074                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
2075                        | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED);
2076
2077        PRESSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_PRESSED);
2078        PRESSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
2079                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_PRESSED);
2080        PRESSED_SELECTED_STATE_SET = StateSet.get(
2081                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_PRESSED);
2082        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
2083                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
2084                        | StateSet.VIEW_STATE_PRESSED);
2085        PRESSED_FOCUSED_STATE_SET = StateSet.get(
2086                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED);
2087        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
2088                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
2089                        | StateSet.VIEW_STATE_PRESSED);
2090        PRESSED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
2091                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
2092                        | StateSet.VIEW_STATE_PRESSED);
2093        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
2094                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
2095                        | StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED);
2096        PRESSED_ENABLED_STATE_SET = StateSet.get(
2097                StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
2098        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
2099                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED
2100                        | StateSet.VIEW_STATE_PRESSED);
2101        PRESSED_ENABLED_SELECTED_STATE_SET = StateSet.get(
2102                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED
2103                        | StateSet.VIEW_STATE_PRESSED);
2104        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
2105                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
2106                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
2107        PRESSED_ENABLED_FOCUSED_STATE_SET = StateSet.get(
2108                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED
2109                        | StateSet.VIEW_STATE_PRESSED);
2110        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
2111                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
2112                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
2113        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
2114                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
2115                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
2116        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
2117                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
2118                        | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED
2119                        | StateSet.VIEW_STATE_PRESSED);
2120    }
2121
2122    /**
2123     * Accessibility event types that are dispatched for text population.
2124     */
2125    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
2126            AccessibilityEvent.TYPE_VIEW_CLICKED
2127            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
2128            | AccessibilityEvent.TYPE_VIEW_SELECTED
2129            | AccessibilityEvent.TYPE_VIEW_FOCUSED
2130            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
2131            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
2132            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
2133            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
2134            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
2135            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
2136            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
2137
2138    static final int DEBUG_CORNERS_COLOR = Color.rgb(63, 127, 255);
2139
2140    static final int DEBUG_CORNERS_SIZE_DIP = 8;
2141
2142    /**
2143     * Temporary Rect currently for use in setBackground().  This will probably
2144     * be extended in the future to hold our own class with more than just
2145     * a Rect. :)
2146     */
2147    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
2148
2149    /**
2150     * Map used to store views' tags.
2151     */
2152    private SparseArray<Object> mKeyedTags;
2153
2154    /**
2155     * The next available accessibility id.
2156     */
2157    private static int sNextAccessibilityViewId;
2158
2159    /**
2160     * The animation currently associated with this view.
2161     * @hide
2162     */
2163    protected Animation mCurrentAnimation = null;
2164
2165    /**
2166     * Width as measured during measure pass.
2167     * {@hide}
2168     */
2169    @ViewDebug.ExportedProperty(category = "measurement")
2170    int mMeasuredWidth;
2171
2172    /**
2173     * Height as measured during measure pass.
2174     * {@hide}
2175     */
2176    @ViewDebug.ExportedProperty(category = "measurement")
2177    int mMeasuredHeight;
2178
2179    /**
2180     * Flag to indicate that this view was marked INVALIDATED, or had its display list
2181     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
2182     * its display list. This flag, used only when hw accelerated, allows us to clear the
2183     * flag while retaining this information until it's needed (at getDisplayList() time and
2184     * in drawChild(), when we decide to draw a view's children's display lists into our own).
2185     *
2186     * {@hide}
2187     */
2188    boolean mRecreateDisplayList = false;
2189
2190    /**
2191     * The view's identifier.
2192     * {@hide}
2193     *
2194     * @see #setId(int)
2195     * @see #getId()
2196     */
2197    @IdRes
2198    @ViewDebug.ExportedProperty(resolveId = true)
2199    int mID = NO_ID;
2200
2201    /** The ID of this view for autofill purposes.
2202     * <ul>
2203     *     <li>== {@link #NO_ID}: ID has not been assigned yet
2204     *     <li>&le; {@link #LAST_APP_AUTOFILL_ID}: View is not part of a activity. The ID is
2205     *                                                  unique in the process. This might change
2206     *                                                  over activity lifecycle events.
2207     *     <li>&gt; {@link #LAST_APP_AUTOFILL_ID}: View is part of a activity. The ID is
2208     *                                                  unique in the activity. This stays the same
2209     *                                                  over activity lifecycle events.
2210     */
2211    private int mAutofillViewId = NO_ID;
2212
2213    // ID for accessibility purposes. This ID must be unique for every window
2214    private int mAccessibilityViewId = NO_ID;
2215
2216    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
2217
2218    /**
2219     * The view's tag.
2220     * {@hide}
2221     *
2222     * @see #setTag(Object)
2223     * @see #getTag()
2224     */
2225    protected Object mTag = null;
2226
2227    // for mPrivateFlags:
2228    /** {@hide} */
2229    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
2230    /** {@hide} */
2231    static final int PFLAG_FOCUSED                     = 0x00000002;
2232    /** {@hide} */
2233    static final int PFLAG_SELECTED                    = 0x00000004;
2234    /** {@hide} */
2235    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
2236    /** {@hide} */
2237    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
2238    /** {@hide} */
2239    static final int PFLAG_DRAWN                       = 0x00000020;
2240    /**
2241     * When this flag is set, this view is running an animation on behalf of its
2242     * children and should therefore not cancel invalidate requests, even if they
2243     * lie outside of this view's bounds.
2244     *
2245     * {@hide}
2246     */
2247    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
2248    /** {@hide} */
2249    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
2250    /** {@hide} */
2251    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
2252    /** {@hide} */
2253    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
2254    /** {@hide} */
2255    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
2256    /** {@hide} */
2257    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
2258    /** {@hide} */
2259    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
2260
2261    private static final int PFLAG_PRESSED             = 0x00004000;
2262
2263    /** {@hide} */
2264    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
2265    /**
2266     * Flag used to indicate that this view should be drawn once more (and only once
2267     * more) after its animation has completed.
2268     * {@hide}
2269     */
2270    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
2271
2272    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
2273
2274    /**
2275     * Indicates that the View returned true when onSetAlpha() was called and that
2276     * the alpha must be restored.
2277     * {@hide}
2278     */
2279    static final int PFLAG_ALPHA_SET                   = 0x00040000;
2280
2281    /**
2282     * Set by {@link #setScrollContainer(boolean)}.
2283     */
2284    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
2285
2286    /**
2287     * Set by {@link #setScrollContainer(boolean)}.
2288     */
2289    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
2290
2291    /**
2292     * View flag indicating whether this view was invalidated (fully or partially.)
2293     *
2294     * @hide
2295     */
2296    static final int PFLAG_DIRTY                       = 0x00200000;
2297
2298    /**
2299     * View flag indicating whether this view was invalidated by an opaque
2300     * invalidate request.
2301     *
2302     * @hide
2303     */
2304    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
2305
2306    /**
2307     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
2308     *
2309     * @hide
2310     */
2311    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
2312
2313    /**
2314     * Indicates whether the background is opaque.
2315     *
2316     * @hide
2317     */
2318    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
2319
2320    /**
2321     * Indicates whether the scrollbars are opaque.
2322     *
2323     * @hide
2324     */
2325    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
2326
2327    /**
2328     * Indicates whether the view is opaque.
2329     *
2330     * @hide
2331     */
2332    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
2333
2334    /**
2335     * Indicates a prepressed state;
2336     * the short time between ACTION_DOWN and recognizing
2337     * a 'real' press. Prepressed is used to recognize quick taps
2338     * even when they are shorter than ViewConfiguration.getTapTimeout().
2339     *
2340     * @hide
2341     */
2342    private static final int PFLAG_PREPRESSED          = 0x02000000;
2343
2344    /**
2345     * Indicates whether the view is temporarily detached.
2346     *
2347     * @hide
2348     */
2349    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
2350
2351    /**
2352     * Indicates that we should awaken scroll bars once attached
2353     *
2354     * PLEASE NOTE: This flag is now unused as we now send onVisibilityChanged
2355     * during window attachment and it is no longer needed. Feel free to repurpose it.
2356     *
2357     * @hide
2358     */
2359    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
2360
2361    /**
2362     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
2363     * @hide
2364     */
2365    private static final int PFLAG_HOVERED             = 0x10000000;
2366
2367    /**
2368     * Flag set by {@link AutofillManager} if it needs to be notified when this view is clicked.
2369     */
2370    private static final int PFLAG_NOTIFY_AUTOFILL_MANAGER_ON_CLICK = 0x20000000;
2371
2372    /** {@hide} */
2373    static final int PFLAG_ACTIVATED                   = 0x40000000;
2374
2375    /**
2376     * Indicates that this view was specifically invalidated, not just dirtied because some
2377     * child view was invalidated. The flag is used to determine when we need to recreate
2378     * a view's display list (as opposed to just returning a reference to its existing
2379     * display list).
2380     *
2381     * @hide
2382     */
2383    static final int PFLAG_INVALIDATED                 = 0x80000000;
2384
2385    /**
2386     * Masks for mPrivateFlags2, as generated by dumpFlags():
2387     *
2388     * |-------|-------|-------|-------|
2389     *                                 1 PFLAG2_DRAG_CAN_ACCEPT
2390     *                                1  PFLAG2_DRAG_HOVERED
2391     *                              11   PFLAG2_LAYOUT_DIRECTION_MASK
2392     *                             1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
2393     *                            1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
2394     *                            11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
2395     *                           1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
2396     *                          1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
2397     *                          11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
2398     *                         1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
2399     *                         1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
2400     *                         11        PFLAG2_TEXT_DIRECTION_FLAGS[6]
2401     *                         111       PFLAG2_TEXT_DIRECTION_FLAGS[7]
2402     *                         111       PFLAG2_TEXT_DIRECTION_MASK
2403     *                        1          PFLAG2_TEXT_DIRECTION_RESOLVED
2404     *                       1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
2405     *                     111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
2406     *                    1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
2407     *                   1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
2408     *                   11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
2409     *                  1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
2410     *                  1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
2411     *                  11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
2412     *                  111              PFLAG2_TEXT_ALIGNMENT_MASK
2413     *                 1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
2414     *                1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
2415     *              111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
2416     *           111                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
2417     *         11                        PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK
2418     *       1                           PFLAG2_ACCESSIBILITY_FOCUSED
2419     *      1                            PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED
2420     *     1                             PFLAG2_VIEW_QUICK_REJECTED
2421     *    1                              PFLAG2_PADDING_RESOLVED
2422     *   1                               PFLAG2_DRAWABLE_RESOLVED
2423     *  1                                PFLAG2_HAS_TRANSIENT_STATE
2424     * |-------|-------|-------|-------|
2425     */
2426
2427    /**
2428     * Indicates that this view has reported that it can accept the current drag's content.
2429     * Cleared when the drag operation concludes.
2430     * @hide
2431     */
2432    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
2433
2434    /**
2435     * Indicates that this view is currently directly under the drag location in a
2436     * drag-and-drop operation involving content that it can accept.  Cleared when
2437     * the drag exits the view, or when the drag operation concludes.
2438     * @hide
2439     */
2440    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
2441
2442    /** @hide */
2443    @IntDef(prefix = { "LAYOUT_DIRECTION_" }, value = {
2444            LAYOUT_DIRECTION_LTR,
2445            LAYOUT_DIRECTION_RTL,
2446            LAYOUT_DIRECTION_INHERIT,
2447            LAYOUT_DIRECTION_LOCALE
2448    })
2449    @Retention(RetentionPolicy.SOURCE)
2450    // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection
2451    public @interface LayoutDir {}
2452
2453    /** @hide */
2454    @IntDef(prefix = { "LAYOUT_DIRECTION_" }, value = {
2455            LAYOUT_DIRECTION_LTR,
2456            LAYOUT_DIRECTION_RTL
2457    })
2458    @Retention(RetentionPolicy.SOURCE)
2459    public @interface ResolvedLayoutDir {}
2460
2461    /**
2462     * A flag to indicate that the layout direction of this view has not been defined yet.
2463     * @hide
2464     */
2465    public static final int LAYOUT_DIRECTION_UNDEFINED = LayoutDirection.UNDEFINED;
2466
2467    /**
2468     * Horizontal layout direction of this view is from Left to Right.
2469     * Use with {@link #setLayoutDirection}.
2470     */
2471    public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR;
2472
2473    /**
2474     * Horizontal layout direction of this view is from Right to Left.
2475     * Use with {@link #setLayoutDirection}.
2476     */
2477    public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL;
2478
2479    /**
2480     * Horizontal layout direction of this view is inherited from its parent.
2481     * Use with {@link #setLayoutDirection}.
2482     */
2483    public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT;
2484
2485    /**
2486     * Horizontal layout direction of this view is from deduced from the default language
2487     * script for the locale. Use with {@link #setLayoutDirection}.
2488     */
2489    public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE;
2490
2491    /**
2492     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2493     * @hide
2494     */
2495    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
2496
2497    /**
2498     * Mask for use with private flags indicating bits used for horizontal layout direction.
2499     * @hide
2500     */
2501    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2502
2503    /**
2504     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
2505     * right-to-left direction.
2506     * @hide
2507     */
2508    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2509
2510    /**
2511     * Indicates whether the view horizontal layout direction has been resolved.
2512     * @hide
2513     */
2514    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2515
2516    /**
2517     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
2518     * @hide
2519     */
2520    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
2521            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2522
2523    /*
2524     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
2525     * flag value.
2526     * @hide
2527     */
2528    private static final int[] LAYOUT_DIRECTION_FLAGS = {
2529            LAYOUT_DIRECTION_LTR,
2530            LAYOUT_DIRECTION_RTL,
2531            LAYOUT_DIRECTION_INHERIT,
2532            LAYOUT_DIRECTION_LOCALE
2533    };
2534
2535    /**
2536     * Default horizontal layout direction.
2537     */
2538    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
2539
2540    /**
2541     * Default horizontal layout direction.
2542     * @hide
2543     */
2544    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
2545
2546    /**
2547     * Text direction is inherited through {@link ViewGroup}
2548     */
2549    public static final int TEXT_DIRECTION_INHERIT = 0;
2550
2551    /**
2552     * Text direction is using "first strong algorithm". The first strong directional character
2553     * determines the paragraph direction. If there is no strong directional character, the
2554     * paragraph direction is the view's resolved layout direction.
2555     */
2556    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
2557
2558    /**
2559     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
2560     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
2561     * If there are neither, the paragraph direction is the view's resolved layout direction.
2562     */
2563    public static final int TEXT_DIRECTION_ANY_RTL = 2;
2564
2565    /**
2566     * Text direction is forced to LTR.
2567     */
2568    public static final int TEXT_DIRECTION_LTR = 3;
2569
2570    /**
2571     * Text direction is forced to RTL.
2572     */
2573    public static final int TEXT_DIRECTION_RTL = 4;
2574
2575    /**
2576     * Text direction is coming from the system Locale.
2577     */
2578    public static final int TEXT_DIRECTION_LOCALE = 5;
2579
2580    /**
2581     * Text direction is using "first strong algorithm". The first strong directional character
2582     * determines the paragraph direction. If there is no strong directional character, the
2583     * paragraph direction is LTR.
2584     */
2585    public static final int TEXT_DIRECTION_FIRST_STRONG_LTR = 6;
2586
2587    /**
2588     * Text direction is using "first strong algorithm". The first strong directional character
2589     * determines the paragraph direction. If there is no strong directional character, the
2590     * paragraph direction is RTL.
2591     */
2592    public static final int TEXT_DIRECTION_FIRST_STRONG_RTL = 7;
2593
2594    /**
2595     * Default text direction is inherited
2596     */
2597    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
2598
2599    /**
2600     * Default resolved text direction
2601     * @hide
2602     */
2603    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
2604
2605    /**
2606     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
2607     * @hide
2608     */
2609    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
2610
2611    /**
2612     * Mask for use with private flags indicating bits used for text direction.
2613     * @hide
2614     */
2615    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
2616            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2617
2618    /**
2619     * Array of text direction flags for mapping attribute "textDirection" to correct
2620     * flag value.
2621     * @hide
2622     */
2623    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
2624            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2625            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2626            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2627            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2628            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2629            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2630            TEXT_DIRECTION_FIRST_STRONG_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2631            TEXT_DIRECTION_FIRST_STRONG_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
2632    };
2633
2634    /**
2635     * Indicates whether the view text direction has been resolved.
2636     * @hide
2637     */
2638    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
2639            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2640
2641    /**
2642     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2643     * @hide
2644     */
2645    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
2646
2647    /**
2648     * Mask for use with private flags indicating bits used for resolved text direction.
2649     * @hide
2650     */
2651    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
2652            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2653
2654    /**
2655     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
2656     * @hide
2657     */
2658    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
2659            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2660
2661    /** @hide */
2662    @IntDef(prefix = { "TEXT_ALIGNMENT_" }, value = {
2663            TEXT_ALIGNMENT_INHERIT,
2664            TEXT_ALIGNMENT_GRAVITY,
2665            TEXT_ALIGNMENT_CENTER,
2666            TEXT_ALIGNMENT_TEXT_START,
2667            TEXT_ALIGNMENT_TEXT_END,
2668            TEXT_ALIGNMENT_VIEW_START,
2669            TEXT_ALIGNMENT_VIEW_END
2670    })
2671    @Retention(RetentionPolicy.SOURCE)
2672    public @interface TextAlignment {}
2673
2674    /**
2675     * Default text alignment. The text alignment of this View is inherited from its parent.
2676     * Use with {@link #setTextAlignment(int)}
2677     */
2678    public static final int TEXT_ALIGNMENT_INHERIT = 0;
2679
2680    /**
2681     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
2682     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
2683     *
2684     * Use with {@link #setTextAlignment(int)}
2685     */
2686    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
2687
2688    /**
2689     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2690     *
2691     * Use with {@link #setTextAlignment(int)}
2692     */
2693    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2694
2695    /**
2696     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2697     *
2698     * Use with {@link #setTextAlignment(int)}
2699     */
2700    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2701
2702    /**
2703     * Center the paragraph, e.g. ALIGN_CENTER.
2704     *
2705     * Use with {@link #setTextAlignment(int)}
2706     */
2707    public static final int TEXT_ALIGNMENT_CENTER = 4;
2708
2709    /**
2710     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2711     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2712     *
2713     * Use with {@link #setTextAlignment(int)}
2714     */
2715    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2716
2717    /**
2718     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2719     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2720     *
2721     * Use with {@link #setTextAlignment(int)}
2722     */
2723    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2724
2725    /**
2726     * Default text alignment is inherited
2727     */
2728    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2729
2730    /**
2731     * Default resolved text alignment
2732     * @hide
2733     */
2734    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2735
2736    /**
2737      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2738      * @hide
2739      */
2740    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2741
2742    /**
2743      * Mask for use with private flags indicating bits used for text alignment.
2744      * @hide
2745      */
2746    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2747
2748    /**
2749     * Array of text direction flags for mapping attribute "textAlignment" to correct
2750     * flag value.
2751     * @hide
2752     */
2753    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2754            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2755            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2756            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2757            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2758            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2759            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2760            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2761    };
2762
2763    /**
2764     * Indicates whether the view text alignment has been resolved.
2765     * @hide
2766     */
2767    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2768
2769    /**
2770     * Bit shift to get the resolved text alignment.
2771     * @hide
2772     */
2773    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2774
2775    /**
2776     * Mask for use with private flags indicating bits used for text alignment.
2777     * @hide
2778     */
2779    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2780            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2781
2782    /**
2783     * Indicates whether if the view text alignment has been resolved to gravity
2784     */
2785    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2786            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2787
2788    // Accessiblity constants for mPrivateFlags2
2789
2790    /**
2791     * Shift for the bits in {@link #mPrivateFlags2} related to the
2792     * "importantForAccessibility" attribute.
2793     */
2794    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2795
2796    /**
2797     * Automatically determine whether a view is important for accessibility.
2798     */
2799    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2800
2801    /**
2802     * The view is important for accessibility.
2803     */
2804    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2805
2806    /**
2807     * The view is not important for accessibility.
2808     */
2809    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2810
2811    /**
2812     * The view is not important for accessibility, nor are any of its
2813     * descendant views.
2814     */
2815    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004;
2816
2817    /**
2818     * The default whether the view is important for accessibility.
2819     */
2820    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2821
2822    /**
2823     * Mask for obtaining the bits which specify how to determine
2824     * whether a view is important for accessibility.
2825     */
2826    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2827        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO
2828        | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS)
2829        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2830
2831    /**
2832     * Shift for the bits in {@link #mPrivateFlags2} related to the
2833     * "accessibilityLiveRegion" attribute.
2834     */
2835    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23;
2836
2837    /**
2838     * Live region mode specifying that accessibility services should not
2839     * automatically announce changes to this view. This is the default live
2840     * region mode for most views.
2841     * <p>
2842     * Use with {@link #setAccessibilityLiveRegion(int)}.
2843     */
2844    public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000;
2845
2846    /**
2847     * Live region mode specifying that accessibility services should announce
2848     * changes to this view.
2849     * <p>
2850     * Use with {@link #setAccessibilityLiveRegion(int)}.
2851     */
2852    public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001;
2853
2854    /**
2855     * Live region mode specifying that accessibility services should interrupt
2856     * ongoing speech to immediately announce changes to this view.
2857     * <p>
2858     * Use with {@link #setAccessibilityLiveRegion(int)}.
2859     */
2860    public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002;
2861
2862    /**
2863     * The default whether the view is important for accessibility.
2864     */
2865    static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE;
2866
2867    /**
2868     * Mask for obtaining the bits which specify a view's accessibility live
2869     * region mode.
2870     */
2871    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE
2872            | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE)
2873            << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
2874
2875    /**
2876     * Flag indicating whether a view has accessibility focus.
2877     */
2878    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000;
2879
2880    /**
2881     * Flag whether the accessibility state of the subtree rooted at this view changed.
2882     */
2883    static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000;
2884
2885    /**
2886     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2887     * is used to check whether later changes to the view's transform should invalidate the
2888     * view to force the quickReject test to run again.
2889     */
2890    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2891
2892    /**
2893     * Flag indicating that start/end padding has been resolved into left/right padding
2894     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2895     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2896     * during measurement. In some special cases this is required such as when an adapter-based
2897     * view measures prospective children without attaching them to a window.
2898     */
2899    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2900
2901    /**
2902     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2903     */
2904    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2905
2906    /**
2907     * Indicates that the view is tracking some sort of transient state
2908     * that the app should not need to be aware of, but that the framework
2909     * should take special care to preserve.
2910     */
2911    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000;
2912
2913    /**
2914     * Group of bits indicating that RTL properties resolution is done.
2915     */
2916    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2917            PFLAG2_TEXT_DIRECTION_RESOLVED |
2918            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2919            PFLAG2_PADDING_RESOLVED |
2920            PFLAG2_DRAWABLE_RESOLVED;
2921
2922    // There are a couple of flags left in mPrivateFlags2
2923
2924    /* End of masks for mPrivateFlags2 */
2925
2926    /**
2927     * Masks for mPrivateFlags3, as generated by dumpFlags():
2928     *
2929     * |-------|-------|-------|-------|
2930     *                                 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM
2931     *                                1  PFLAG3_VIEW_IS_ANIMATING_ALPHA
2932     *                               1   PFLAG3_IS_LAID_OUT
2933     *                              1    PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT
2934     *                             1     PFLAG3_CALLED_SUPER
2935     *                            1      PFLAG3_APPLYING_INSETS
2936     *                           1       PFLAG3_FITTING_SYSTEM_WINDOWS
2937     *                          1        PFLAG3_NESTED_SCROLLING_ENABLED
2938     *                         1         PFLAG3_SCROLL_INDICATOR_TOP
2939     *                        1          PFLAG3_SCROLL_INDICATOR_BOTTOM
2940     *                       1           PFLAG3_SCROLL_INDICATOR_LEFT
2941     *                      1            PFLAG3_SCROLL_INDICATOR_RIGHT
2942     *                     1             PFLAG3_SCROLL_INDICATOR_START
2943     *                    1              PFLAG3_SCROLL_INDICATOR_END
2944     *                   1               PFLAG3_ASSIST_BLOCKED
2945     *                  1                PFLAG3_CLUSTER
2946     *                 1                 PFLAG3_IS_AUTOFILLED
2947     *                1                  PFLAG3_FINGER_DOWN
2948     *               1                   PFLAG3_FOCUSED_BY_DEFAULT
2949     *           1111                    PFLAG3_IMPORTANT_FOR_AUTOFILL
2950     *          1                        PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE
2951     *         1                         PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED
2952     *        1                          PFLAG3_TEMPORARY_DETACH
2953     *       1                           PFLAG3_NO_REVEAL_ON_FOCUS
2954     *      1                            PFLAG3_NOTIFY_AUTOFILL_ENTER_ON_LAYOUT
2955     *     1                             PFLAG3_SCREEN_READER_FOCUSABLE
2956     *    1                              PFLAG3_AGGREGATED_VISIBLE
2957     *   1                               PFLAG3_AUTOFILLID_EXPLICITLY_SET
2958     *  1                                available
2959     * |-------|-------|-------|-------|
2960     */
2961
2962    /**
2963     * Flag indicating that view has a transform animation set on it. This is used to track whether
2964     * an animation is cleared between successive frames, in order to tell the associated
2965     * DisplayList to clear its animation matrix.
2966     */
2967    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2968
2969    /**
2970     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2971     * animation is cleared between successive frames, in order to tell the associated
2972     * DisplayList to restore its alpha value.
2973     */
2974    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2975
2976    /**
2977     * Flag indicating that the view has been through at least one layout since it
2978     * was last attached to a window.
2979     */
2980    static final int PFLAG3_IS_LAID_OUT = 0x4;
2981
2982    /**
2983     * Flag indicating that a call to measure() was skipped and should be done
2984     * instead when layout() is invoked.
2985     */
2986    static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8;
2987
2988    /**
2989     * Flag indicating that an overridden method correctly called down to
2990     * the superclass implementation as required by the API spec.
2991     */
2992    static final int PFLAG3_CALLED_SUPER = 0x10;
2993
2994    /**
2995     * Flag indicating that we're in the process of applying window insets.
2996     */
2997    static final int PFLAG3_APPLYING_INSETS = 0x20;
2998
2999    /**
3000     * Flag indicating that we're in the process of fitting system windows using the old method.
3001     */
3002    static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40;
3003
3004    /**
3005     * Flag indicating that nested scrolling is enabled for this view.
3006     * The view will optionally cooperate with views up its parent chain to allow for
3007     * integrated nested scrolling along the same axis.
3008     */
3009    static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80;
3010
3011    /**
3012     * Flag indicating that the bottom scroll indicator should be displayed
3013     * when this view can scroll up.
3014     */
3015    static final int PFLAG3_SCROLL_INDICATOR_TOP = 0x0100;
3016
3017    /**
3018     * Flag indicating that the bottom scroll indicator should be displayed
3019     * when this view can scroll down.
3020     */
3021    static final int PFLAG3_SCROLL_INDICATOR_BOTTOM = 0x0200;
3022
3023    /**
3024     * Flag indicating that the left scroll indicator should be displayed
3025     * when this view can scroll left.
3026     */
3027    static final int PFLAG3_SCROLL_INDICATOR_LEFT = 0x0400;
3028
3029    /**
3030     * Flag indicating that the right scroll indicator should be displayed
3031     * when this view can scroll right.
3032     */
3033    static final int PFLAG3_SCROLL_INDICATOR_RIGHT = 0x0800;
3034
3035    /**
3036     * Flag indicating that the start scroll indicator should be displayed
3037     * when this view can scroll in the start direction.
3038     */
3039    static final int PFLAG3_SCROLL_INDICATOR_START = 0x1000;
3040
3041    /**
3042     * Flag indicating that the end scroll indicator should be displayed
3043     * when this view can scroll in the end direction.
3044     */
3045    static final int PFLAG3_SCROLL_INDICATOR_END = 0x2000;
3046
3047    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
3048
3049    static final int SCROLL_INDICATORS_NONE = 0x0000;
3050
3051    /**
3052     * Mask for use with setFlags indicating bits used for indicating which
3053     * scroll indicators are enabled.
3054     */
3055    static final int SCROLL_INDICATORS_PFLAG3_MASK = PFLAG3_SCROLL_INDICATOR_TOP
3056            | PFLAG3_SCROLL_INDICATOR_BOTTOM | PFLAG3_SCROLL_INDICATOR_LEFT
3057            | PFLAG3_SCROLL_INDICATOR_RIGHT | PFLAG3_SCROLL_INDICATOR_START
3058            | PFLAG3_SCROLL_INDICATOR_END;
3059
3060    /**
3061     * Left-shift required to translate between public scroll indicator flags
3062     * and internal PFLAGS3 flags. When used as a right-shift, translates
3063     * PFLAGS3 flags to public flags.
3064     */
3065    static final int SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT = 8;
3066
3067    /** @hide */
3068    @Retention(RetentionPolicy.SOURCE)
3069    @IntDef(flag = true, prefix = { "SCROLL_INDICATOR_" }, value = {
3070            SCROLL_INDICATOR_TOP,
3071            SCROLL_INDICATOR_BOTTOM,
3072            SCROLL_INDICATOR_LEFT,
3073            SCROLL_INDICATOR_RIGHT,
3074            SCROLL_INDICATOR_START,
3075            SCROLL_INDICATOR_END,
3076    })
3077    public @interface ScrollIndicators {}
3078
3079    /**
3080     * Scroll indicator direction for the top edge of the view.
3081     *
3082     * @see #setScrollIndicators(int)
3083     * @see #setScrollIndicators(int, int)
3084     * @see #getScrollIndicators()
3085     */
3086    public static final int SCROLL_INDICATOR_TOP =
3087            PFLAG3_SCROLL_INDICATOR_TOP >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
3088
3089    /**
3090     * Scroll indicator direction for the bottom edge of the view.
3091     *
3092     * @see #setScrollIndicators(int)
3093     * @see #setScrollIndicators(int, int)
3094     * @see #getScrollIndicators()
3095     */
3096    public static final int SCROLL_INDICATOR_BOTTOM =
3097            PFLAG3_SCROLL_INDICATOR_BOTTOM >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
3098
3099    /**
3100     * Scroll indicator direction for the left edge of the view.
3101     *
3102     * @see #setScrollIndicators(int)
3103     * @see #setScrollIndicators(int, int)
3104     * @see #getScrollIndicators()
3105     */
3106    public static final int SCROLL_INDICATOR_LEFT =
3107            PFLAG3_SCROLL_INDICATOR_LEFT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
3108
3109    /**
3110     * Scroll indicator direction for the right edge of the view.
3111     *
3112     * @see #setScrollIndicators(int)
3113     * @see #setScrollIndicators(int, int)
3114     * @see #getScrollIndicators()
3115     */
3116    public static final int SCROLL_INDICATOR_RIGHT =
3117            PFLAG3_SCROLL_INDICATOR_RIGHT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
3118
3119    /**
3120     * Scroll indicator direction for the starting edge of the view.
3121     * <p>
3122     * Resolved according to the view's layout direction, see
3123     * {@link #getLayoutDirection()} for more information.
3124     *
3125     * @see #setScrollIndicators(int)
3126     * @see #setScrollIndicators(int, int)
3127     * @see #getScrollIndicators()
3128     */
3129    public static final int SCROLL_INDICATOR_START =
3130            PFLAG3_SCROLL_INDICATOR_START >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
3131
3132    /**
3133     * Scroll indicator direction for the ending edge of the view.
3134     * <p>
3135     * Resolved according to the view's layout direction, see
3136     * {@link #getLayoutDirection()} for more information.
3137     *
3138     * @see #setScrollIndicators(int)
3139     * @see #setScrollIndicators(int, int)
3140     * @see #getScrollIndicators()
3141     */
3142    public static final int SCROLL_INDICATOR_END =
3143            PFLAG3_SCROLL_INDICATOR_END >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
3144
3145    /**
3146     * <p>Indicates that we are allowing {@link ViewStructure} to traverse
3147     * into this view.<p>
3148     */
3149    static final int PFLAG3_ASSIST_BLOCKED = 0x4000;
3150
3151    /**
3152     * Flag indicating that the view is a root of a keyboard navigation cluster.
3153     *
3154     * @see #isKeyboardNavigationCluster()
3155     * @see #setKeyboardNavigationCluster(boolean)
3156     */
3157    private static final int PFLAG3_CLUSTER = 0x8000;
3158
3159    /**
3160     * Flag indicating that the view is autofilled
3161     *
3162     * @see #isAutofilled()
3163     * @see #setAutofilled(boolean)
3164     */
3165    private static final int PFLAG3_IS_AUTOFILLED = 0x10000;
3166
3167    /**
3168     * Indicates that the user is currently touching the screen.
3169     * Currently used for the tooltip positioning only.
3170     */
3171    private static final int PFLAG3_FINGER_DOWN = 0x20000;
3172
3173    /**
3174     * Flag indicating that this view is the default-focus view.
3175     *
3176     * @see #isFocusedByDefault()
3177     * @see #setFocusedByDefault(boolean)
3178     */
3179    private static final int PFLAG3_FOCUSED_BY_DEFAULT = 0x40000;
3180
3181    /**
3182     * Shift for the bits in {@link #mPrivateFlags3} related to the
3183     * "importantForAutofill" attribute.
3184     */
3185    static final int PFLAG3_IMPORTANT_FOR_AUTOFILL_SHIFT = 19;
3186
3187    /**
3188     * Mask for obtaining the bits which specify how to determine
3189     * whether a view is important for autofill.
3190     */
3191    static final int PFLAG3_IMPORTANT_FOR_AUTOFILL_MASK = (IMPORTANT_FOR_AUTOFILL_AUTO
3192            | IMPORTANT_FOR_AUTOFILL_YES | IMPORTANT_FOR_AUTOFILL_NO
3193            | IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS
3194            | IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS)
3195            << PFLAG3_IMPORTANT_FOR_AUTOFILL_SHIFT;
3196
3197    /**
3198     * Whether this view has rendered elements that overlap (see {@link
3199     * #hasOverlappingRendering()}, {@link #forceHasOverlappingRendering(boolean)}, and
3200     * {@link #getHasOverlappingRendering()} ). The value in this bit is only valid when
3201     * PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED has been set. Otherwise, the value is
3202     * determined by whatever {@link #hasOverlappingRendering()} returns.
3203     */
3204    private static final int PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE = 0x800000;
3205
3206    /**
3207     * Whether {@link #forceHasOverlappingRendering(boolean)} has been called. When true, value
3208     * in PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE is valid.
3209     */
3210    private static final int PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED = 0x1000000;
3211
3212    /**
3213     * Flag indicating that the view is temporarily detached from the parent view.
3214     *
3215     * @see #onStartTemporaryDetach()
3216     * @see #onFinishTemporaryDetach()
3217     */
3218    static final int PFLAG3_TEMPORARY_DETACH = 0x2000000;
3219
3220    /**
3221     * Flag indicating that the view does not wish to be revealed within its parent
3222     * hierarchy when it gains focus. Expressed in the negative since the historical
3223     * default behavior is to reveal on focus; this flag suppresses that behavior.
3224     *
3225     * @see #setRevealOnFocusHint(boolean)
3226     * @see #getRevealOnFocusHint()
3227     */
3228    private static final int PFLAG3_NO_REVEAL_ON_FOCUS = 0x4000000;
3229
3230    /**
3231     * Flag indicating that when layout is completed we should notify
3232     * that the view was entered for autofill purposes. To minimize
3233     * showing autofill for views not visible to the user we evaluate
3234     * user visibility which cannot be done until the view is laid out.
3235     */
3236    static final int PFLAG3_NOTIFY_AUTOFILL_ENTER_ON_LAYOUT = 0x8000000;
3237
3238    /**
3239     * Works like focusable for screen readers, but without the side effects on input focus.
3240     * @see #setScreenReaderFocusable(boolean)
3241     */
3242    private static final int PFLAG3_SCREEN_READER_FOCUSABLE = 0x10000000;
3243
3244    /**
3245     * The last aggregated visibility. Used to detect when it truly changes.
3246     */
3247    private static final int PFLAG3_AGGREGATED_VISIBLE = 0x20000000;
3248
3249    /**
3250     * Used to indicate that {@link #mAutofillId} was explicitly set through
3251     * {@link #setAutofillId(AutofillId)}.
3252     */
3253    private static final int PFLAG3_AUTOFILLID_EXPLICITLY_SET = 0x40000000;
3254
3255    /* End of masks for mPrivateFlags3 */
3256
3257    /**
3258     * Always allow a user to over-scroll this view, provided it is a
3259     * view that can scroll.
3260     *
3261     * @see #getOverScrollMode()
3262     * @see #setOverScrollMode(int)
3263     */
3264    public static final int OVER_SCROLL_ALWAYS = 0;
3265
3266    /**
3267     * Allow a user to over-scroll this view only if the content is large
3268     * enough to meaningfully scroll, provided it is a view that can scroll.
3269     *
3270     * @see #getOverScrollMode()
3271     * @see #setOverScrollMode(int)
3272     */
3273    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
3274
3275    /**
3276     * Never allow a user to over-scroll this view.
3277     *
3278     * @see #getOverScrollMode()
3279     * @see #setOverScrollMode(int)
3280     */
3281    public static final int OVER_SCROLL_NEVER = 2;
3282
3283    /**
3284     * Special constant for {@link #setSystemUiVisibility(int)}: View has
3285     * requested the system UI (status bar) to be visible (the default).
3286     *
3287     * @see #setSystemUiVisibility(int)
3288     */
3289    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
3290
3291    /**
3292     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
3293     * system UI to enter an unobtrusive "low profile" mode.
3294     *
3295     * <p>This is for use in games, book readers, video players, or any other
3296     * "immersive" application where the usual system chrome is deemed too distracting.
3297     *
3298     * <p>In low profile mode, the status bar and/or navigation icons may dim.
3299     *
3300     * @see #setSystemUiVisibility(int)
3301     */
3302    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
3303
3304    /**
3305     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
3306     * system navigation be temporarily hidden.
3307     *
3308     * <p>This is an even less obtrusive state than that called for by
3309     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
3310     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
3311     * those to disappear. This is useful (in conjunction with the
3312     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
3313     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
3314     * window flags) for displaying content using every last pixel on the display.
3315     *
3316     * <p>There is a limitation: because navigation controls are so important, the least user
3317     * interaction will cause them to reappear immediately.  When this happens, both
3318     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
3319     * so that both elements reappear at the same time.
3320     *
3321     * @see #setSystemUiVisibility(int)
3322     */
3323    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
3324
3325    /**
3326     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
3327     * into the normal fullscreen mode so that its content can take over the screen
3328     * while still allowing the user to interact with the application.
3329     *
3330     * <p>This has the same visual effect as
3331     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
3332     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
3333     * meaning that non-critical screen decorations (such as the status bar) will be
3334     * hidden while the user is in the View's window, focusing the experience on
3335     * that content.  Unlike the window flag, if you are using ActionBar in
3336     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
3337     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
3338     * hide the action bar.
3339     *
3340     * <p>This approach to going fullscreen is best used over the window flag when
3341     * it is a transient state -- that is, the application does this at certain
3342     * points in its user interaction where it wants to allow the user to focus
3343     * on content, but not as a continuous state.  For situations where the application
3344     * would like to simply stay full screen the entire time (such as a game that
3345     * wants to take over the screen), the
3346     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
3347     * is usually a better approach.  The state set here will be removed by the system
3348     * in various situations (such as the user moving to another application) like
3349     * the other system UI states.
3350     *
3351     * <p>When using this flag, the application should provide some easy facility
3352     * for the user to go out of it.  A common example would be in an e-book
3353     * reader, where tapping on the screen brings back whatever screen and UI
3354     * decorations that had been hidden while the user was immersed in reading
3355     * the book.
3356     *
3357     * @see #setSystemUiVisibility(int)
3358     */
3359    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
3360
3361    /**
3362     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
3363     * flags, we would like a stable view of the content insets given to
3364     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
3365     * will always represent the worst case that the application can expect
3366     * as a continuous state.  In the stock Android UI this is the space for
3367     * the system bar, nav bar, and status bar, but not more transient elements
3368     * such as an input method.
3369     *
3370     * The stable layout your UI sees is based on the system UI modes you can
3371     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
3372     * then you will get a stable layout for changes of the
3373     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
3374     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
3375     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
3376     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
3377     * with a stable layout.  (Note that you should avoid using
3378     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
3379     *
3380     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
3381     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
3382     * then a hidden status bar will be considered a "stable" state for purposes
3383     * here.  This allows your UI to continually hide the status bar, while still
3384     * using the system UI flags to hide the action bar while still retaining
3385     * a stable layout.  Note that changing the window fullscreen flag will never
3386     * provide a stable layout for a clean transition.
3387     *
3388     * <p>If you are using ActionBar in
3389     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
3390     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
3391     * insets it adds to those given to the application.
3392     */
3393    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
3394
3395    /**
3396     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
3397     * to be laid out as if it has requested
3398     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
3399     * allows it to avoid artifacts when switching in and out of that mode, at
3400     * the expense that some of its user interface may be covered by screen
3401     * decorations when they are shown.  You can perform layout of your inner
3402     * UI elements to account for the navigation system UI through the
3403     * {@link #fitSystemWindows(Rect)} method.
3404     */
3405    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
3406
3407    /**
3408     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
3409     * to be laid out as if it has requested
3410     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
3411     * allows it to avoid artifacts when switching in and out of that mode, at
3412     * the expense that some of its user interface may be covered by screen
3413     * decorations when they are shown.  You can perform layout of your inner
3414     * UI elements to account for non-fullscreen system UI through the
3415     * {@link #fitSystemWindows(Rect)} method.
3416     *
3417     * <p>Note: on displays that have a {@link DisplayCutout}, the window may still be placed
3418     *  differently than if {@link #SYSTEM_UI_FLAG_FULLSCREEN} was set, if the
3419     *  window's {@link WindowManager.LayoutParams#layoutInDisplayCutoutMode
3420     *  layoutInDisplayCutoutMode} is
3421     *  {@link WindowManager.LayoutParams#LAYOUT_IN_DISPLAY_CUTOUT_MODE_DEFAULT
3422     *  LAYOUT_IN_DISPLAY_CUTOUT_MODE_DEFAULT}. To avoid this, use either of the other modes.
3423     *
3424     * @see WindowManager.LayoutParams#layoutInDisplayCutoutMode
3425     * @see WindowManager.LayoutParams#LAYOUT_IN_DISPLAY_CUTOUT_MODE_DEFAULT
3426     * @see WindowManager.LayoutParams#LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS
3427     * @see WindowManager.LayoutParams#LAYOUT_IN_DISPLAY_CUTOUT_MODE_NEVER
3428     */
3429    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
3430
3431    /**
3432     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
3433     * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  If this flag is
3434     * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any
3435     * user interaction.
3436     * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only
3437     * has an effect when used in combination with that flag.</p>
3438     */
3439    public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800;
3440
3441    /**
3442     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
3443     * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation
3444     * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  Use this flag to create an immersive
3445     * experience while also hiding the system bars.  If this flag is not set,
3446     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user
3447     * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system
3448     * if the user swipes from the top of the screen.
3449     * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with
3450     * system gestures, such as swiping from the top of the screen.  These transient system bars
3451     * will overlay app’s content, may have some degree of transparency, and will automatically
3452     * hide after a short timeout.
3453     * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and
3454     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination
3455     * with one or both of those flags.</p>
3456     */
3457    public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000;
3458
3459    /**
3460     * Flag for {@link #setSystemUiVisibility(int)}: Requests the status bar to draw in a mode that
3461     * is compatible with light status bar backgrounds.
3462     *
3463     * <p>For this to take effect, the window must request
3464     * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS
3465     *         FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not
3466     * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_STATUS
3467     *         FLAG_TRANSLUCENT_STATUS}.
3468     *
3469     * @see android.R.attr#windowLightStatusBar
3470     */
3471    public static final int SYSTEM_UI_FLAG_LIGHT_STATUS_BAR = 0x00002000;
3472
3473    /**
3474     * This flag was previously used for a private API. DO NOT reuse it for a public API as it might
3475     * trigger undefined behavior on older platforms with apps compiled against a new SDK.
3476     */
3477    private static final int SYSTEM_UI_RESERVED_LEGACY1 = 0x00004000;
3478
3479    /**
3480     * This flag was previously used for a private API. DO NOT reuse it for a public API as it might
3481     * trigger undefined behavior on older platforms with apps compiled against a new SDK.
3482     */
3483    private static final int SYSTEM_UI_RESERVED_LEGACY2 = 0x00010000;
3484
3485    /**
3486     * Flag for {@link #setSystemUiVisibility(int)}: Requests the navigation bar to draw in a mode
3487     * that is compatible with light navigation bar backgrounds.
3488     *
3489     * <p>For this to take effect, the window must request
3490     * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS
3491     *         FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not
3492     * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_NAVIGATION
3493     *         FLAG_TRANSLUCENT_NAVIGATION}.
3494     *
3495     * @see android.R.attr#windowLightNavigationBar
3496     */
3497    public static final int SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR = 0x00000010;
3498
3499    /**
3500     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
3501     */
3502    @Deprecated
3503    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
3504
3505    /**
3506     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
3507     */
3508    @Deprecated
3509    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
3510
3511    /**
3512     * @hide
3513     *
3514     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3515     * out of the public fields to keep the undefined bits out of the developer's way.
3516     *
3517     * Flag to make the status bar not expandable.  Unless you also
3518     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
3519     */
3520    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
3521
3522    /**
3523     * @hide
3524     *
3525     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3526     * out of the public fields to keep the undefined bits out of the developer's way.
3527     *
3528     * Flag to hide notification icons and scrolling ticker text.
3529     */
3530    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
3531
3532    /**
3533     * @hide
3534     *
3535     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3536     * out of the public fields to keep the undefined bits out of the developer's way.
3537     *
3538     * Flag to disable incoming notification alerts.  This will not block
3539     * icons, but it will block sound, vibrating and other visual or aural notifications.
3540     */
3541    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
3542
3543    /**
3544     * @hide
3545     *
3546     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3547     * out of the public fields to keep the undefined bits out of the developer's way.
3548     *
3549     * Flag to hide only the scrolling ticker.  Note that
3550     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
3551     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
3552     */
3553    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
3554
3555    /**
3556     * @hide
3557     *
3558     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3559     * out of the public fields to keep the undefined bits out of the developer's way.
3560     *
3561     * Flag to hide the center system info area.
3562     */
3563    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
3564
3565    /**
3566     * @hide
3567     *
3568     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3569     * out of the public fields to keep the undefined bits out of the developer's way.
3570     *
3571     * Flag to hide only the home button.  Don't use this
3572     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3573     */
3574    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
3575
3576    /**
3577     * @hide
3578     *
3579     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3580     * out of the public fields to keep the undefined bits out of the developer's way.
3581     *
3582     * Flag to hide only the back button. Don't use this
3583     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3584     */
3585    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
3586
3587    /**
3588     * @hide
3589     *
3590     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3591     * out of the public fields to keep the undefined bits out of the developer's way.
3592     *
3593     * Flag to hide only the clock.  You might use this if your activity has
3594     * its own clock making the status bar's clock redundant.
3595     */
3596    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
3597
3598    /**
3599     * @hide
3600     *
3601     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3602     * out of the public fields to keep the undefined bits out of the developer's way.
3603     *
3604     * Flag to hide only the recent apps button. Don't use this
3605     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3606     */
3607    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
3608
3609    /**
3610     * @hide
3611     *
3612     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3613     * out of the public fields to keep the undefined bits out of the developer's way.
3614     *
3615     * Flag to disable the global search gesture. Don't use this
3616     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3617     */
3618    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
3619
3620    /**
3621     * @hide
3622     *
3623     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3624     * out of the public fields to keep the undefined bits out of the developer's way.
3625     *
3626     * Flag to specify that the status bar is displayed in transient mode.
3627     */
3628    public static final int STATUS_BAR_TRANSIENT = 0x04000000;
3629
3630    /**
3631     * @hide
3632     *
3633     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3634     * out of the public fields to keep the undefined bits out of the developer's way.
3635     *
3636     * Flag to specify that the navigation bar is displayed in transient mode.
3637     */
3638    public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000;
3639
3640    /**
3641     * @hide
3642     *
3643     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3644     * out of the public fields to keep the undefined bits out of the developer's way.
3645     *
3646     * Flag to specify that the hidden status bar would like to be shown.
3647     */
3648    public static final int STATUS_BAR_UNHIDE = 0x10000000;
3649
3650    /**
3651     * @hide
3652     *
3653     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3654     * out of the public fields to keep the undefined bits out of the developer's way.
3655     *
3656     * Flag to specify that the hidden navigation bar would like to be shown.
3657     */
3658    public static final int NAVIGATION_BAR_UNHIDE = 0x20000000;
3659
3660    /**
3661     * @hide
3662     *
3663     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3664     * out of the public fields to keep the undefined bits out of the developer's way.
3665     *
3666     * Flag to specify that the status bar is displayed in translucent mode.
3667     */
3668    public static final int STATUS_BAR_TRANSLUCENT = 0x40000000;
3669
3670    /**
3671     * @hide
3672     *
3673     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3674     * out of the public fields to keep the undefined bits out of the developer's way.
3675     *
3676     * Flag to specify that the navigation bar is displayed in translucent mode.
3677     */
3678    public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000;
3679
3680    /**
3681     * @hide
3682     *
3683     * Makes navigation bar transparent (but not the status bar).
3684     */
3685    public static final int NAVIGATION_BAR_TRANSPARENT = 0x00008000;
3686
3687    /**
3688     * @hide
3689     *
3690     * Makes status bar transparent (but not the navigation bar).
3691     */
3692    public static final int STATUS_BAR_TRANSPARENT = 0x00000008;
3693
3694    /**
3695     * @hide
3696     *
3697     * Makes both status bar and navigation bar transparent.
3698     */
3699    public static final int SYSTEM_UI_TRANSPARENT = NAVIGATION_BAR_TRANSPARENT
3700            | STATUS_BAR_TRANSPARENT;
3701
3702    /**
3703     * @hide
3704     */
3705    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FF7;
3706
3707    /**
3708     * These are the system UI flags that can be cleared by events outside
3709     * of an application.  Currently this is just the ability to tap on the
3710     * screen while hiding the navigation bar to have it return.
3711     * @hide
3712     */
3713    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
3714            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
3715            | SYSTEM_UI_FLAG_FULLSCREEN;
3716
3717    /**
3718     * Flags that can impact the layout in relation to system UI.
3719     */
3720    public static final int SYSTEM_UI_LAYOUT_FLAGS =
3721            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
3722            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
3723
3724    /** @hide */
3725    @IntDef(flag = true, prefix = { "FIND_VIEWS_" }, value = {
3726            FIND_VIEWS_WITH_TEXT,
3727            FIND_VIEWS_WITH_CONTENT_DESCRIPTION
3728    })
3729    @Retention(RetentionPolicy.SOURCE)
3730    public @interface FindViewFlags {}
3731
3732    /**
3733     * Find views that render the specified text.
3734     *
3735     * @see #findViewsWithText(ArrayList, CharSequence, int)
3736     */
3737    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
3738
3739    /**
3740     * Find find views that contain the specified content description.
3741     *
3742     * @see #findViewsWithText(ArrayList, CharSequence, int)
3743     */
3744    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
3745
3746    /**
3747     * Find views that contain {@link AccessibilityNodeProvider}. Such
3748     * a View is a root of virtual view hierarchy and may contain the searched
3749     * text. If this flag is set Views with providers are automatically
3750     * added and it is a responsibility of the client to call the APIs of
3751     * the provider to determine whether the virtual tree rooted at this View
3752     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
3753     * representing the virtual views with this text.
3754     *
3755     * @see #findViewsWithText(ArrayList, CharSequence, int)
3756     *
3757     * @hide
3758     */
3759    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
3760
3761    /**
3762     * The undefined cursor position.
3763     *
3764     * @hide
3765     */
3766    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
3767
3768    /**
3769     * Indicates that the screen has changed state and is now off.
3770     *
3771     * @see #onScreenStateChanged(int)
3772     */
3773    public static final int SCREEN_STATE_OFF = 0x0;
3774
3775    /**
3776     * Indicates that the screen has changed state and is now on.
3777     *
3778     * @see #onScreenStateChanged(int)
3779     */
3780    public static final int SCREEN_STATE_ON = 0x1;
3781
3782    /**
3783     * Indicates no axis of view scrolling.
3784     */
3785    public static final int SCROLL_AXIS_NONE = 0;
3786
3787    /**
3788     * Indicates scrolling along the horizontal axis.
3789     */
3790    public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0;
3791
3792    /**
3793     * Indicates scrolling along the vertical axis.
3794     */
3795    public static final int SCROLL_AXIS_VERTICAL = 1 << 1;
3796
3797    /**
3798     * Controls the over-scroll mode for this view.
3799     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
3800     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
3801     * and {@link #OVER_SCROLL_NEVER}.
3802     */
3803    private int mOverScrollMode;
3804
3805    /**
3806     * The parent this view is attached to.
3807     * {@hide}
3808     *
3809     * @see #getParent()
3810     */
3811    protected ViewParent mParent;
3812
3813    /**
3814     * {@hide}
3815     */
3816    AttachInfo mAttachInfo;
3817
3818    /**
3819     * {@hide}
3820     */
3821    @ViewDebug.ExportedProperty(flagMapping = {
3822        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
3823                name = "FORCE_LAYOUT"),
3824        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
3825                name = "LAYOUT_REQUIRED"),
3826        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
3827            name = "DRAWING_CACHE_INVALID", outputIf = false),
3828        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
3829        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
3830        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
3831        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
3832    }, formatToHexString = true)
3833
3834    /* @hide */
3835    public int mPrivateFlags;
3836    int mPrivateFlags2;
3837    int mPrivateFlags3;
3838
3839    /**
3840     * This view's request for the visibility of the status bar.
3841     * @hide
3842     */
3843    @ViewDebug.ExportedProperty(flagMapping = {
3844            @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
3845                    equals = SYSTEM_UI_FLAG_LOW_PROFILE,
3846                    name = "LOW_PROFILE"),
3847            @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
3848                    equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
3849                    name = "HIDE_NAVIGATION"),
3850            @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_FULLSCREEN,
3851                    equals = SYSTEM_UI_FLAG_FULLSCREEN,
3852                    name = "FULLSCREEN"),
3853            @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LAYOUT_STABLE,
3854                    equals = SYSTEM_UI_FLAG_LAYOUT_STABLE,
3855                    name = "LAYOUT_STABLE"),
3856            @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION,
3857                    equals = SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION,
3858                    name = "LAYOUT_HIDE_NAVIGATION"),
3859            @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN,
3860                    equals = SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN,
3861                    name = "LAYOUT_FULLSCREEN"),
3862            @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_IMMERSIVE,
3863                    equals = SYSTEM_UI_FLAG_IMMERSIVE,
3864                    name = "IMMERSIVE"),
3865            @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_IMMERSIVE_STICKY,
3866                    equals = SYSTEM_UI_FLAG_IMMERSIVE_STICKY,
3867                    name = "IMMERSIVE_STICKY"),
3868            @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LIGHT_STATUS_BAR,
3869                    equals = SYSTEM_UI_FLAG_LIGHT_STATUS_BAR,
3870                    name = "LIGHT_STATUS_BAR"),
3871            @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR,
3872                    equals = SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR,
3873                    name = "LIGHT_NAVIGATION_BAR"),
3874            @ViewDebug.FlagToString(mask = STATUS_BAR_DISABLE_EXPAND,
3875                    equals = STATUS_BAR_DISABLE_EXPAND,
3876                    name = "STATUS_BAR_DISABLE_EXPAND"),
3877            @ViewDebug.FlagToString(mask = STATUS_BAR_DISABLE_NOTIFICATION_ICONS,
3878                    equals = STATUS_BAR_DISABLE_NOTIFICATION_ICONS,
3879                    name = "STATUS_BAR_DISABLE_NOTIFICATION_ICONS"),
3880            @ViewDebug.FlagToString(mask = STATUS_BAR_DISABLE_NOTIFICATION_ALERTS,
3881                    equals = STATUS_BAR_DISABLE_NOTIFICATION_ALERTS,
3882                    name = "STATUS_BAR_DISABLE_NOTIFICATION_ALERTS"),
3883            @ViewDebug.FlagToString(mask = STATUS_BAR_DISABLE_NOTIFICATION_TICKER,
3884                    equals = STATUS_BAR_DISABLE_NOTIFICATION_TICKER,
3885                    name = "STATUS_BAR_DISABLE_NOTIFICATION_TICKER"),
3886            @ViewDebug.FlagToString(mask = STATUS_BAR_DISABLE_SYSTEM_INFO,
3887                    equals = STATUS_BAR_DISABLE_SYSTEM_INFO,
3888                    name = "STATUS_BAR_DISABLE_SYSTEM_INFO"),
3889            @ViewDebug.FlagToString(mask = STATUS_BAR_DISABLE_HOME,
3890                    equals = STATUS_BAR_DISABLE_HOME,
3891                    name = "STATUS_BAR_DISABLE_HOME"),
3892            @ViewDebug.FlagToString(mask = STATUS_BAR_DISABLE_BACK,
3893                    equals = STATUS_BAR_DISABLE_BACK,
3894                    name = "STATUS_BAR_DISABLE_BACK"),
3895            @ViewDebug.FlagToString(mask = STATUS_BAR_DISABLE_CLOCK,
3896                    equals = STATUS_BAR_DISABLE_CLOCK,
3897                    name = "STATUS_BAR_DISABLE_CLOCK"),
3898            @ViewDebug.FlagToString(mask = STATUS_BAR_DISABLE_RECENT,
3899                    equals = STATUS_BAR_DISABLE_RECENT,
3900                    name = "STATUS_BAR_DISABLE_RECENT"),
3901            @ViewDebug.FlagToString(mask = STATUS_BAR_DISABLE_SEARCH,
3902                    equals = STATUS_BAR_DISABLE_SEARCH,
3903                    name = "STATUS_BAR_DISABLE_SEARCH"),
3904            @ViewDebug.FlagToString(mask = STATUS_BAR_TRANSIENT,
3905                    equals = STATUS_BAR_TRANSIENT,
3906                    name = "STATUS_BAR_TRANSIENT"),
3907            @ViewDebug.FlagToString(mask = NAVIGATION_BAR_TRANSIENT,
3908                    equals = NAVIGATION_BAR_TRANSIENT,
3909                    name = "NAVIGATION_BAR_TRANSIENT"),
3910            @ViewDebug.FlagToString(mask = STATUS_BAR_UNHIDE,
3911                    equals = STATUS_BAR_UNHIDE,
3912                    name = "STATUS_BAR_UNHIDE"),
3913            @ViewDebug.FlagToString(mask = NAVIGATION_BAR_UNHIDE,
3914                    equals = NAVIGATION_BAR_UNHIDE,
3915                    name = "NAVIGATION_BAR_UNHIDE"),
3916            @ViewDebug.FlagToString(mask = STATUS_BAR_TRANSLUCENT,
3917                    equals = STATUS_BAR_TRANSLUCENT,
3918                    name = "STATUS_BAR_TRANSLUCENT"),
3919            @ViewDebug.FlagToString(mask = NAVIGATION_BAR_TRANSLUCENT,
3920                    equals = NAVIGATION_BAR_TRANSLUCENT,
3921                    name = "NAVIGATION_BAR_TRANSLUCENT"),
3922            @ViewDebug.FlagToString(mask = NAVIGATION_BAR_TRANSPARENT,
3923                    equals = NAVIGATION_BAR_TRANSPARENT,
3924                    name = "NAVIGATION_BAR_TRANSPARENT"),
3925            @ViewDebug.FlagToString(mask = STATUS_BAR_TRANSPARENT,
3926                    equals = STATUS_BAR_TRANSPARENT,
3927                    name = "STATUS_BAR_TRANSPARENT")
3928    }, formatToHexString = true)
3929    int mSystemUiVisibility;
3930
3931    /**
3932     * Reference count for transient state.
3933     * @see #setHasTransientState(boolean)
3934     */
3935    int mTransientStateCount = 0;
3936
3937    /**
3938     * Count of how many windows this view has been attached to.
3939     */
3940    int mWindowAttachCount;
3941
3942    /**
3943     * The layout parameters associated with this view and used by the parent
3944     * {@link android.view.ViewGroup} to determine how this view should be
3945     * laid out.
3946     * {@hide}
3947     */
3948    protected ViewGroup.LayoutParams mLayoutParams;
3949
3950    /**
3951     * The view flags hold various views states.
3952     * {@hide}
3953     */
3954    @ViewDebug.ExportedProperty(formatToHexString = true)
3955    int mViewFlags;
3956
3957    static class TransformationInfo {
3958        /**
3959         * The transform matrix for the View. This transform is calculated internally
3960         * based on the translation, rotation, and scale properties.
3961         *
3962         * Do *not* use this variable directly; instead call getMatrix(), which will
3963         * load the value from the View's RenderNode.
3964         */
3965        private final Matrix mMatrix = new Matrix();
3966
3967        /**
3968         * The inverse transform matrix for the View. This transform is calculated
3969         * internally based on the translation, rotation, and scale properties.
3970         *
3971         * Do *not* use this variable directly; instead call getInverseMatrix(),
3972         * which will load the value from the View's RenderNode.
3973         */
3974        private Matrix mInverseMatrix;
3975
3976        /**
3977         * The opacity of the View. This is a value from 0 to 1, where 0 means
3978         * completely transparent and 1 means completely opaque.
3979         */
3980        @ViewDebug.ExportedProperty
3981        float mAlpha = 1f;
3982
3983        /**
3984         * The opacity of the view as manipulated by the Fade transition. This is a hidden
3985         * property only used by transitions, which is composited with the other alpha
3986         * values to calculate the final visual alpha value.
3987         */
3988        float mTransitionAlpha = 1f;
3989    }
3990
3991    /** @hide */
3992    public TransformationInfo mTransformationInfo;
3993
3994    /**
3995     * Current clip bounds. to which all drawing of this view are constrained.
3996     */
3997    @ViewDebug.ExportedProperty(category = "drawing")
3998    Rect mClipBounds = null;
3999
4000    private boolean mLastIsOpaque;
4001
4002    /**
4003     * The distance in pixels from the left edge of this view's parent
4004     * to the left edge of this view.
4005     * {@hide}
4006     */
4007    @ViewDebug.ExportedProperty(category = "layout")
4008    protected int mLeft;
4009    /**
4010     * The distance in pixels from the left edge of this view's parent
4011     * to the right edge of this view.
4012     * {@hide}
4013     */
4014    @ViewDebug.ExportedProperty(category = "layout")
4015    protected int mRight;
4016    /**
4017     * The distance in pixels from the top edge of this view's parent
4018     * to the top edge of this view.
4019     * {@hide}
4020     */
4021    @ViewDebug.ExportedProperty(category = "layout")
4022    protected int mTop;
4023    /**
4024     * The distance in pixels from the top edge of this view's parent
4025     * to the bottom edge of this view.
4026     * {@hide}
4027     */
4028    @ViewDebug.ExportedProperty(category = "layout")
4029    protected int mBottom;
4030
4031    /**
4032     * The offset, in pixels, by which the content of this view is scrolled
4033     * horizontally.
4034     * {@hide}
4035     */
4036    @ViewDebug.ExportedProperty(category = "scrolling")
4037    protected int mScrollX;
4038    /**
4039     * The offset, in pixels, by which the content of this view is scrolled
4040     * vertically.
4041     * {@hide}
4042     */
4043    @ViewDebug.ExportedProperty(category = "scrolling")
4044    protected int mScrollY;
4045
4046    /**
4047     * The left padding in pixels, that is the distance in pixels between the
4048     * left edge of this view and the left edge of its content.
4049     * {@hide}
4050     */
4051    @ViewDebug.ExportedProperty(category = "padding")
4052    protected int mPaddingLeft = 0;
4053    /**
4054     * The right padding in pixels, that is the distance in pixels between the
4055     * right edge of this view and the right edge of its content.
4056     * {@hide}
4057     */
4058    @ViewDebug.ExportedProperty(category = "padding")
4059    protected int mPaddingRight = 0;
4060    /**
4061     * The top padding in pixels, that is the distance in pixels between the
4062     * top edge of this view and the top edge of its content.
4063     * {@hide}
4064     */
4065    @ViewDebug.ExportedProperty(category = "padding")
4066    protected int mPaddingTop;
4067    /**
4068     * The bottom padding in pixels, that is the distance in pixels between the
4069     * bottom edge of this view and the bottom edge of its content.
4070     * {@hide}
4071     */
4072    @ViewDebug.ExportedProperty(category = "padding")
4073    protected int mPaddingBottom;
4074
4075    /**
4076     * The layout insets in pixels, that is the distance in pixels between the
4077     * visible edges of this view its bounds.
4078     */
4079    private Insets mLayoutInsets;
4080
4081    /**
4082     * Briefly describes the view and is primarily used for accessibility support.
4083     */
4084    private CharSequence mContentDescription;
4085
4086    /**
4087     * If this view represents a distinct part of the window, it can have a title that labels the
4088     * area.
4089     */
4090    private CharSequence mAccessibilityPaneTitle;
4091
4092    /**
4093     * Specifies the id of a view for which this view serves as a label for
4094     * accessibility purposes.
4095     */
4096    private int mLabelForId = View.NO_ID;
4097
4098    /**
4099     * Predicate for matching labeled view id with its label for
4100     * accessibility purposes.
4101     */
4102    private MatchLabelForPredicate mMatchLabelForPredicate;
4103
4104    /**
4105     * Specifies a view before which this one is visited in accessibility traversal.
4106     */
4107    private int mAccessibilityTraversalBeforeId = NO_ID;
4108
4109    /**
4110     * Specifies a view after which this one is visited in accessibility traversal.
4111     */
4112    private int mAccessibilityTraversalAfterId = NO_ID;
4113
4114    /**
4115     * Predicate for matching a view by its id.
4116     */
4117    private MatchIdPredicate mMatchIdPredicate;
4118
4119    /**
4120     * Cache the paddingRight set by the user to append to the scrollbar's size.
4121     *
4122     * @hide
4123     */
4124    @ViewDebug.ExportedProperty(category = "padding")
4125    protected int mUserPaddingRight;
4126
4127    /**
4128     * Cache the paddingBottom set by the user to append to the scrollbar's size.
4129     *
4130     * @hide
4131     */
4132    @ViewDebug.ExportedProperty(category = "padding")
4133    protected int mUserPaddingBottom;
4134
4135    /**
4136     * Cache the paddingLeft set by the user to append to the scrollbar's size.
4137     *
4138     * @hide
4139     */
4140    @ViewDebug.ExportedProperty(category = "padding")
4141    protected int mUserPaddingLeft;
4142
4143    /**
4144     * Cache the paddingStart set by the user to append to the scrollbar's size.
4145     *
4146     */
4147    @ViewDebug.ExportedProperty(category = "padding")
4148    int mUserPaddingStart;
4149
4150    /**
4151     * Cache the paddingEnd set by the user to append to the scrollbar's size.
4152     *
4153     */
4154    @ViewDebug.ExportedProperty(category = "padding")
4155    int mUserPaddingEnd;
4156
4157    /**
4158     * Cache initial left padding.
4159     *
4160     * @hide
4161     */
4162    int mUserPaddingLeftInitial;
4163
4164    /**
4165     * Cache initial right padding.
4166     *
4167     * @hide
4168     */
4169    int mUserPaddingRightInitial;
4170
4171    /**
4172     * Default undefined padding
4173     */
4174    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
4175
4176    /**
4177     * Cache if a left padding has been defined
4178     */
4179    private boolean mLeftPaddingDefined = false;
4180
4181    /**
4182     * Cache if a right padding has been defined
4183     */
4184    private boolean mRightPaddingDefined = false;
4185
4186    /**
4187     * @hide
4188     */
4189    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
4190    /**
4191     * @hide
4192     */
4193    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
4194
4195    private LongSparseLongArray mMeasureCache;
4196
4197    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
4198    private Drawable mBackground;
4199    private TintInfo mBackgroundTint;
4200
4201    @ViewDebug.ExportedProperty(deepExport = true, prefix = "fg_")
4202    private ForegroundInfo mForegroundInfo;
4203
4204    private Drawable mScrollIndicatorDrawable;
4205
4206    /**
4207     * RenderNode used for backgrounds.
4208     * <p>
4209     * When non-null and valid, this is expected to contain an up-to-date copy
4210     * of the background drawable. It is cleared on temporary detach, and reset
4211     * on cleanup.
4212     */
4213    private RenderNode mBackgroundRenderNode;
4214
4215    private int mBackgroundResource;
4216    private boolean mBackgroundSizeChanged;
4217
4218    /** The default focus highlight.
4219     * @see #mDefaultFocusHighlightEnabled
4220     * @see Drawable#hasFocusStateSpecified()
4221     */
4222    private Drawable mDefaultFocusHighlight;
4223    private Drawable mDefaultFocusHighlightCache;
4224    private boolean mDefaultFocusHighlightSizeChanged;
4225    /**
4226     * True if the default focus highlight is needed on the target device.
4227     */
4228    private static boolean sUseDefaultFocusHighlight;
4229
4230    /**
4231     * True if zero-sized views can be focused.
4232     */
4233    private static boolean sCanFocusZeroSized;
4234
4235    /**
4236     * Always assign focus if a focusable View is available.
4237     */
4238    private static boolean sAlwaysAssignFocus;
4239
4240    private String mTransitionName;
4241
4242    static class TintInfo {
4243        ColorStateList mTintList;
4244        PorterDuff.Mode mTintMode;
4245        boolean mHasTintMode;
4246        boolean mHasTintList;
4247    }
4248
4249    private static class ForegroundInfo {
4250        private Drawable mDrawable;
4251        private TintInfo mTintInfo;
4252        private int mGravity = Gravity.FILL;
4253        private boolean mInsidePadding = true;
4254        private boolean mBoundsChanged = true;
4255        private final Rect mSelfBounds = new Rect();
4256        private final Rect mOverlayBounds = new Rect();
4257    }
4258
4259    static class ListenerInfo {
4260        /**
4261         * Listener used to dispatch focus change events.
4262         * This field should be made private, so it is hidden from the SDK.
4263         * {@hide}
4264         */
4265        protected OnFocusChangeListener mOnFocusChangeListener;
4266
4267        /**
4268         * Listeners for layout change events.
4269         */
4270        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
4271
4272        protected OnScrollChangeListener mOnScrollChangeListener;
4273
4274        /**
4275         * Listeners for attach events.
4276         */
4277        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
4278
4279        /**
4280         * Listener used to dispatch click events.
4281         * This field should be made private, so it is hidden from the SDK.
4282         * {@hide}
4283         */
4284        public OnClickListener mOnClickListener;
4285
4286        /**
4287         * Listener used to dispatch long click events.
4288         * This field should be made private, so it is hidden from the SDK.
4289         * {@hide}
4290         */
4291        protected OnLongClickListener mOnLongClickListener;
4292
4293        /**
4294         * Listener used to dispatch context click events. This field should be made private, so it
4295         * is hidden from the SDK.
4296         * {@hide}
4297         */
4298        protected OnContextClickListener mOnContextClickListener;
4299
4300        /**
4301         * Listener used to build the context menu.
4302         * This field should be made private, so it is hidden from the SDK.
4303         * {@hide}
4304         */
4305        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
4306
4307        private OnKeyListener mOnKeyListener;
4308
4309        private OnTouchListener mOnTouchListener;
4310
4311        private OnHoverListener mOnHoverListener;
4312
4313        private OnGenericMotionListener mOnGenericMotionListener;
4314
4315        private OnDragListener mOnDragListener;
4316
4317        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
4318
4319        OnApplyWindowInsetsListener mOnApplyWindowInsetsListener;
4320
4321        OnCapturedPointerListener mOnCapturedPointerListener;
4322
4323        private ArrayList<OnKeyFallbackListener> mKeyFallbackListeners;
4324    }
4325
4326    ListenerInfo mListenerInfo;
4327
4328    private static class TooltipInfo {
4329        /**
4330         * Text to be displayed in a tooltip popup.
4331         */
4332        @Nullable
4333        CharSequence mTooltipText;
4334
4335        /**
4336         * View-relative position of the tooltip anchor point.
4337         */
4338        int mAnchorX;
4339        int mAnchorY;
4340
4341        /**
4342         * The tooltip popup.
4343         */
4344        @Nullable
4345        TooltipPopup mTooltipPopup;
4346
4347        /**
4348         * Set to true if the tooltip was shown as a result of a long click.
4349         */
4350        boolean mTooltipFromLongClick;
4351
4352        /**
4353         * Keep these Runnables so that they can be used to reschedule.
4354         */
4355        Runnable mShowTooltipRunnable;
4356        Runnable mHideTooltipRunnable;
4357
4358        /**
4359         * Hover move is ignored if it is within this distance in pixels from the previous one.
4360         */
4361        int mHoverSlop;
4362
4363        /**
4364         * Update the anchor position if it significantly (that is by at least mHoverSlop)
4365         * different from the previously stored position. Ignoring insignificant changes
4366         * filters out the jitter which is typical for such input sources as stylus.
4367         *
4368         * @return True if the position has been updated.
4369         */
4370        private boolean updateAnchorPos(MotionEvent event) {
4371            final int newAnchorX = (int) event.getX();
4372            final int newAnchorY = (int) event.getY();
4373            if (Math.abs(newAnchorX - mAnchorX) <= mHoverSlop
4374                    && Math.abs(newAnchorY - mAnchorY) <= mHoverSlop) {
4375                return false;
4376            }
4377            mAnchorX = newAnchorX;
4378            mAnchorY = newAnchorY;
4379            return true;
4380        }
4381
4382        /**
4383         *  Clear the anchor position to ensure that the next change is considered significant.
4384         */
4385        private void clearAnchorPos() {
4386            mAnchorX = Integer.MAX_VALUE;
4387            mAnchorY = Integer.MAX_VALUE;
4388        }
4389    }
4390
4391    TooltipInfo mTooltipInfo;
4392
4393    // Temporary values used to hold (x,y) coordinates when delegating from the
4394    // two-arg performLongClick() method to the legacy no-arg version.
4395    private float mLongClickX = Float.NaN;
4396    private float mLongClickY = Float.NaN;
4397
4398    /**
4399     * The application environment this view lives in.
4400     * This field should be made private, so it is hidden from the SDK.
4401     * {@hide}
4402     */
4403    @ViewDebug.ExportedProperty(deepExport = true)
4404    protected Context mContext;
4405
4406    private final Resources mResources;
4407
4408    private ScrollabilityCache mScrollCache;
4409
4410    private int[] mDrawableState = null;
4411
4412    ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND;
4413
4414    /**
4415     * Animator that automatically runs based on state changes.
4416     */
4417    private StateListAnimator mStateListAnimator;
4418
4419    /**
4420     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
4421     * the user may specify which view to go to next.
4422     */
4423    private int mNextFocusLeftId = View.NO_ID;
4424
4425    /**
4426     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
4427     * the user may specify which view to go to next.
4428     */
4429    private int mNextFocusRightId = View.NO_ID;
4430
4431    /**
4432     * When this view has focus and the next focus is {@link #FOCUS_UP},
4433     * the user may specify which view to go to next.
4434     */
4435    private int mNextFocusUpId = View.NO_ID;
4436
4437    /**
4438     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
4439     * the user may specify which view to go to next.
4440     */
4441    private int mNextFocusDownId = View.NO_ID;
4442
4443    /**
4444     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
4445     * the user may specify which view to go to next.
4446     */
4447    int mNextFocusForwardId = View.NO_ID;
4448
4449    /**
4450     * User-specified next keyboard navigation cluster in the {@link #FOCUS_FORWARD} direction.
4451     *
4452     * @see #findUserSetNextKeyboardNavigationCluster(View, int)
4453     */
4454    int mNextClusterForwardId = View.NO_ID;
4455
4456    /**
4457     * Whether this View should use a default focus highlight when it gets focused but doesn't
4458     * have {@link android.R.attr#state_focused} defined in its background.
4459     */
4460    boolean mDefaultFocusHighlightEnabled = true;
4461
4462    private CheckForLongPress mPendingCheckForLongPress;
4463    private CheckForTap mPendingCheckForTap = null;
4464    private PerformClick mPerformClick;
4465    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
4466
4467    private UnsetPressedState mUnsetPressedState;
4468
4469    /**
4470     * Whether the long press's action has been invoked.  The tap's action is invoked on the
4471     * up event while a long press is invoked as soon as the long press duration is reached, so
4472     * a long press could be performed before the tap is checked, in which case the tap's action
4473     * should not be invoked.
4474     */
4475    private boolean mHasPerformedLongPress;
4476
4477    /**
4478     * Whether a context click button is currently pressed down. This is true when the stylus is
4479     * touching the screen and the primary button has been pressed, or if a mouse's right button is
4480     * pressed. This is false once the button is released or if the stylus has been lifted.
4481     */
4482    private boolean mInContextButtonPress;
4483
4484    /**
4485     * Whether the next up event should be ignored for the purposes of gesture recognition. This is
4486     * true after a stylus button press has occured, when the next up event should not be recognized
4487     * as a tap.
4488     */
4489    private boolean mIgnoreNextUpEvent;
4490
4491    /**
4492     * The minimum height of the view. We'll try our best to have the height
4493     * of this view to at least this amount.
4494     */
4495    @ViewDebug.ExportedProperty(category = "measurement")
4496    private int mMinHeight;
4497
4498    /**
4499     * The minimum width of the view. We'll try our best to have the width
4500     * of this view to at least this amount.
4501     */
4502    @ViewDebug.ExportedProperty(category = "measurement")
4503    private int mMinWidth;
4504
4505    /**
4506     * The delegate to handle touch events that are physically in this view
4507     * but should be handled by another view.
4508     */
4509    private TouchDelegate mTouchDelegate = null;
4510
4511    /**
4512     * Solid color to use as a background when creating the drawing cache. Enables
4513     * the cache to use 16 bit bitmaps instead of 32 bit.
4514     */
4515    private int mDrawingCacheBackgroundColor = 0;
4516
4517    /**
4518     * Special tree observer used when mAttachInfo is null.
4519     */
4520    private ViewTreeObserver mFloatingTreeObserver;
4521
4522    /**
4523     * Cache the touch slop from the context that created the view.
4524     */
4525    private int mTouchSlop;
4526
4527    /**
4528     * Object that handles automatic animation of view properties.
4529     */
4530    private ViewPropertyAnimator mAnimator = null;
4531
4532    /**
4533     * List of registered FrameMetricsObservers.
4534     */
4535    private ArrayList<FrameMetricsObserver> mFrameMetricsObservers;
4536
4537    /**
4538     * Flag indicating that a drag can cross window boundaries.  When
4539     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called
4540     * with this flag set, all visible applications with targetSdkVersion >=
4541     * {@link android.os.Build.VERSION_CODES#N API 24} will be able to participate
4542     * in the drag operation and receive the dragged content.
4543     *
4544     * <p>If this is the only flag set, then the drag recipient will only have access to text data
4545     * and intents contained in the {@link ClipData} object. Access to URIs contained in the
4546     * {@link ClipData} is determined by other DRAG_FLAG_GLOBAL_* flags</p>
4547     */
4548    public static final int DRAG_FLAG_GLOBAL = 1 << 8;  // 256
4549
4550    /**
4551     * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to
4552     * request read access to the content URI(s) contained in the {@link ClipData} object.
4553     * @see android.content.Intent#FLAG_GRANT_READ_URI_PERMISSION
4554     */
4555    public static final int DRAG_FLAG_GLOBAL_URI_READ = Intent.FLAG_GRANT_READ_URI_PERMISSION;
4556
4557    /**
4558     * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to
4559     * request write access to the content URI(s) contained in the {@link ClipData} object.
4560     * @see android.content.Intent#FLAG_GRANT_WRITE_URI_PERMISSION
4561     */
4562    public static final int DRAG_FLAG_GLOBAL_URI_WRITE = Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
4563
4564    /**
4565     * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link
4566     * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant can be persisted across device
4567     * reboots until explicitly revoked with
4568     * {@link android.content.Context#revokeUriPermission(Uri, int)} Context.revokeUriPermission}.
4569     * @see android.content.Intent#FLAG_GRANT_PERSISTABLE_URI_PERMISSION
4570     */
4571    public static final int DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION =
4572            Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION;
4573
4574    /**
4575     * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link
4576     * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant applies to any URI that is a prefix
4577     * match against the original granted URI.
4578     * @see android.content.Intent#FLAG_GRANT_PREFIX_URI_PERMISSION
4579     */
4580    public static final int DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION =
4581            Intent.FLAG_GRANT_PREFIX_URI_PERMISSION;
4582
4583    /**
4584     * Flag indicating that the drag shadow will be opaque.  When
4585     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called
4586     * with this flag set, the drag shadow will be opaque, otherwise, it will be semitransparent.
4587     */
4588    public static final int DRAG_FLAG_OPAQUE = 1 << 9;
4589
4590    /**
4591     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
4592     */
4593    private float mVerticalScrollFactor;
4594
4595    /**
4596     * Position of the vertical scroll bar.
4597     */
4598    private int mVerticalScrollbarPosition;
4599
4600    /**
4601     * Position the scroll bar at the default position as determined by the system.
4602     */
4603    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
4604
4605    /**
4606     * Position the scroll bar along the left edge.
4607     */
4608    public static final int SCROLLBAR_POSITION_LEFT = 1;
4609
4610    /**
4611     * Position the scroll bar along the right edge.
4612     */
4613    public static final int SCROLLBAR_POSITION_RIGHT = 2;
4614
4615    /**
4616     * Indicates that the view does not have a layer.
4617     *
4618     * @see #getLayerType()
4619     * @see #setLayerType(int, android.graphics.Paint)
4620     * @see #LAYER_TYPE_SOFTWARE
4621     * @see #LAYER_TYPE_HARDWARE
4622     */
4623    public static final int LAYER_TYPE_NONE = 0;
4624
4625    /**
4626     * <p>Indicates that the view has a software layer. A software layer is backed
4627     * by a bitmap and causes the view to be rendered using Android's software
4628     * rendering pipeline, even if hardware acceleration is enabled.</p>
4629     *
4630     * <p>Software layers have various usages:</p>
4631     * <p>When the application is not using hardware acceleration, a software layer
4632     * is useful to apply a specific color filter and/or blending mode and/or
4633     * translucency to a view and all its children.</p>
4634     * <p>When the application is using hardware acceleration, a software layer
4635     * is useful to render drawing primitives not supported by the hardware
4636     * accelerated pipeline. It can also be used to cache a complex view tree
4637     * into a texture and reduce the complexity of drawing operations. For instance,
4638     * when animating a complex view tree with a translation, a software layer can
4639     * be used to render the view tree only once.</p>
4640     * <p>Software layers should be avoided when the affected view tree updates
4641     * often. Every update will require to re-render the software layer, which can
4642     * potentially be slow (particularly when hardware acceleration is turned on
4643     * since the layer will have to be uploaded into a hardware texture after every
4644     * update.)</p>
4645     *
4646     * @see #getLayerType()
4647     * @see #setLayerType(int, android.graphics.Paint)
4648     * @see #LAYER_TYPE_NONE
4649     * @see #LAYER_TYPE_HARDWARE
4650     */
4651    public static final int LAYER_TYPE_SOFTWARE = 1;
4652
4653    /**
4654     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
4655     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
4656     * OpenGL hardware) and causes the view to be rendered using Android's hardware
4657     * rendering pipeline, but only if hardware acceleration is turned on for the
4658     * view hierarchy. When hardware acceleration is turned off, hardware layers
4659     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
4660     *
4661     * <p>A hardware layer is useful to apply a specific color filter and/or
4662     * blending mode and/or translucency to a view and all its children.</p>
4663     * <p>A hardware layer can be used to cache a complex view tree into a
4664     * texture and reduce the complexity of drawing operations. For instance,
4665     * when animating a complex view tree with a translation, a hardware layer can
4666     * be used to render the view tree only once.</p>
4667     * <p>A hardware layer can also be used to increase the rendering quality when
4668     * rotation transformations are applied on a view. It can also be used to
4669     * prevent potential clipping issues when applying 3D transforms on a view.</p>
4670     *
4671     * @see #getLayerType()
4672     * @see #setLayerType(int, android.graphics.Paint)
4673     * @see #LAYER_TYPE_NONE
4674     * @see #LAYER_TYPE_SOFTWARE
4675     */
4676    public static final int LAYER_TYPE_HARDWARE = 2;
4677
4678    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
4679            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
4680            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
4681            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
4682    })
4683    int mLayerType = LAYER_TYPE_NONE;
4684    Paint mLayerPaint;
4685
4686    /**
4687     * Set to true when drawing cache is enabled and cannot be created.
4688     *
4689     * @hide
4690     */
4691    public boolean mCachingFailed;
4692    private Bitmap mDrawingCache;
4693    private Bitmap mUnscaledDrawingCache;
4694
4695    /**
4696     * RenderNode holding View properties, potentially holding a DisplayList of View content.
4697     * <p>
4698     * When non-null and valid, this is expected to contain an up-to-date copy
4699     * of the View content. Its DisplayList content is cleared on temporary detach and reset on
4700     * cleanup.
4701     */
4702    final RenderNode mRenderNode;
4703
4704    /**
4705     * Set to true when the view is sending hover accessibility events because it
4706     * is the innermost hovered view.
4707     */
4708    private boolean mSendingHoverAccessibilityEvents;
4709
4710    /**
4711     * Delegate for injecting accessibility functionality.
4712     */
4713    AccessibilityDelegate mAccessibilityDelegate;
4714
4715    /**
4716     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
4717     * and add/remove objects to/from the overlay directly through the Overlay methods.
4718     */
4719    ViewOverlay mOverlay;
4720
4721    /**
4722     * The currently active parent view for receiving delegated nested scrolling events.
4723     * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared
4724     * by {@link #stopNestedScroll()} at the same point where we clear
4725     * requestDisallowInterceptTouchEvent.
4726     */
4727    private ViewParent mNestedScrollingParent;
4728
4729    /**
4730     * Consistency verifier for debugging purposes.
4731     * @hide
4732     */
4733    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
4734            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
4735                    new InputEventConsistencyVerifier(this, 0) : null;
4736
4737    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
4738
4739    private int[] mTempNestedScrollConsumed;
4740
4741    /**
4742     * An overlay is going to draw this View instead of being drawn as part of this
4743     * View's parent. mGhostView is the View in the Overlay that must be invalidated
4744     * when this view is invalidated.
4745     */
4746    GhostView mGhostView;
4747
4748    /**
4749     * Holds pairs of adjacent attribute data: attribute name followed by its value.
4750     * @hide
4751     */
4752    @ViewDebug.ExportedProperty(category = "attributes", hasAdjacentMapping = true)
4753    public String[] mAttributes;
4754
4755    /**
4756     * Maps a Resource id to its name.
4757     */
4758    private static SparseArray<String> mAttributeMap;
4759
4760    /**
4761     * Queue of pending runnables. Used to postpone calls to post() until this
4762     * view is attached and has a handler.
4763     */
4764    private HandlerActionQueue mRunQueue;
4765
4766    /**
4767     * The pointer icon when the mouse hovers on this view. The default is null.
4768     */
4769    private PointerIcon mPointerIcon;
4770
4771    /**
4772     * @hide
4773     */
4774    String mStartActivityRequestWho;
4775
4776    @Nullable
4777    private RoundScrollbarRenderer mRoundScrollbarRenderer;
4778
4779    /** Used to delay visibility updates sent to the autofill manager */
4780    private Handler mVisibilityChangeForAutofillHandler;
4781
4782    /**
4783     * Simple constructor to use when creating a view from code.
4784     *
4785     * @param context The Context the view is running in, through which it can
4786     *        access the current theme, resources, etc.
4787     */
4788    public View(Context context) {
4789        mContext = context;
4790        mResources = context != null ? context.getResources() : null;
4791        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED | FOCUSABLE_AUTO;
4792        // Set some flags defaults
4793        mPrivateFlags2 =
4794                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
4795                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
4796                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
4797                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
4798                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
4799                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
4800        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
4801        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
4802        mUserPaddingStart = UNDEFINED_PADDING;
4803        mUserPaddingEnd = UNDEFINED_PADDING;
4804        mRenderNode = RenderNode.create(getClass().getName(), this);
4805
4806        if (!sCompatibilityDone && context != null) {
4807            final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
4808
4809            // Older apps may need this compatibility hack for measurement.
4810            sUseBrokenMakeMeasureSpec = targetSdkVersion <= Build.VERSION_CODES.JELLY_BEAN_MR1;
4811
4812            // Older apps expect onMeasure() to always be called on a layout pass, regardless
4813            // of whether a layout was requested on that View.
4814            sIgnoreMeasureCache = targetSdkVersion < Build.VERSION_CODES.KITKAT;
4815
4816            Canvas.sCompatibilityRestore = targetSdkVersion < Build.VERSION_CODES.M;
4817            Canvas.sCompatibilitySetBitmap = targetSdkVersion < Build.VERSION_CODES.O;
4818            Canvas.setCompatibilityVersion(targetSdkVersion);
4819
4820            // In M and newer, our widgets can pass a "hint" value in the size
4821            // for UNSPECIFIED MeasureSpecs. This lets child views of scrolling containers
4822            // know what the expected parent size is going to be, so e.g. list items can size
4823            // themselves at 1/3 the size of their container. It breaks older apps though,
4824            // specifically apps that use some popular open source libraries.
4825            sUseZeroUnspecifiedMeasureSpec = targetSdkVersion < Build.VERSION_CODES.M;
4826
4827            // Old versions of the platform would give different results from
4828            // LinearLayout measurement passes using EXACTLY and non-EXACTLY
4829            // modes, so we always need to run an additional EXACTLY pass.
4830            sAlwaysRemeasureExactly = targetSdkVersion <= Build.VERSION_CODES.M;
4831
4832            // Prior to N, layout params could change without requiring a
4833            // subsequent call to setLayoutParams() and they would usually
4834            // work. Partial layout breaks this assumption.
4835            sLayoutParamsAlwaysChanged = targetSdkVersion <= Build.VERSION_CODES.M;
4836
4837            // Prior to N, TextureView would silently ignore calls to setBackground/setForeground.
4838            // On N+, we throw, but that breaks compatibility with apps that use these methods.
4839            sTextureViewIgnoresDrawableSetters = targetSdkVersion <= Build.VERSION_CODES.M;
4840
4841            // Prior to N, we would drop margins in LayoutParam conversions. The fix triggers bugs
4842            // in apps so we target check it to avoid breaking existing apps.
4843            sPreserveMarginParamsInLayoutParamConversion =
4844                    targetSdkVersion >= Build.VERSION_CODES.N;
4845
4846            sCascadedDragDrop = targetSdkVersion < Build.VERSION_CODES.N;
4847
4848            sHasFocusableExcludeAutoFocusable = targetSdkVersion < Build.VERSION_CODES.O;
4849
4850            sAutoFocusableOffUIThreadWontNotifyParents = targetSdkVersion < Build.VERSION_CODES.O;
4851
4852            sUseDefaultFocusHighlight = context.getResources().getBoolean(
4853                    com.android.internal.R.bool.config_useDefaultFocusHighlight);
4854
4855            sThrowOnInvalidFloatProperties = targetSdkVersion >= Build.VERSION_CODES.P;
4856
4857            sCanFocusZeroSized = targetSdkVersion < Build.VERSION_CODES.P;
4858
4859            sAlwaysAssignFocus = targetSdkVersion < Build.VERSION_CODES.P;
4860
4861            sAcceptZeroSizeDragShadow = targetSdkVersion < Build.VERSION_CODES.P;
4862
4863            sCompatibilityDone = true;
4864        }
4865    }
4866
4867    /**
4868     * Constructor that is called when inflating a view from XML. This is called
4869     * when a view is being constructed from an XML file, supplying attributes
4870     * that were specified in the XML file. This version uses a default style of
4871     * 0, so the only attribute values applied are those in the Context's Theme
4872     * and the given AttributeSet.
4873     *
4874     * <p>
4875     * The method onFinishInflate() will be called after all children have been
4876     * added.
4877     *
4878     * @param context The Context the view is running in, through which it can
4879     *        access the current theme, resources, etc.
4880     * @param attrs The attributes of the XML tag that is inflating the view.
4881     * @see #View(Context, AttributeSet, int)
4882     */
4883    public View(Context context, @Nullable AttributeSet attrs) {
4884        this(context, attrs, 0);
4885    }
4886
4887    /**
4888     * Perform inflation from XML and apply a class-specific base style from a
4889     * theme attribute. This constructor of View allows subclasses to use their
4890     * own base style when they are inflating. For example, a Button class's
4891     * constructor would call this version of the super class constructor and
4892     * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this
4893     * allows the theme's button style to modify all of the base view attributes
4894     * (in particular its background) as well as the Button class's attributes.
4895     *
4896     * @param context The Context the view is running in, through which it can
4897     *        access the current theme, resources, etc.
4898     * @param attrs The attributes of the XML tag that is inflating the view.
4899     * @param defStyleAttr An attribute in the current theme that contains a
4900     *        reference to a style resource that supplies default values for
4901     *        the view. Can be 0 to not look for defaults.
4902     * @see #View(Context, AttributeSet)
4903     */
4904    public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
4905        this(context, attrs, defStyleAttr, 0);
4906    }
4907
4908    /**
4909     * Perform inflation from XML and apply a class-specific base style from a
4910     * theme attribute or style resource. This constructor of View allows
4911     * subclasses to use their own base style when they are inflating.
4912     * <p>
4913     * When determining the final value of a particular attribute, there are
4914     * four inputs that come into play:
4915     * <ol>
4916     * <li>Any attribute values in the given AttributeSet.
4917     * <li>The style resource specified in the AttributeSet (named "style").
4918     * <li>The default style specified by <var>defStyleAttr</var>.
4919     * <li>The default style specified by <var>defStyleRes</var>.
4920     * <li>The base values in this theme.
4921     * </ol>
4922     * <p>
4923     * Each of these inputs is considered in-order, with the first listed taking
4924     * precedence over the following ones. In other words, if in the
4925     * AttributeSet you have supplied <code>&lt;Button * textColor="#ff000000"&gt;</code>
4926     * , then the button's text will <em>always</em> be black, regardless of
4927     * what is specified in any of the styles.
4928     *
4929     * @param context The Context the view is running in, through which it can
4930     *        access the current theme, resources, etc.
4931     * @param attrs The attributes of the XML tag that is inflating the view.
4932     * @param defStyleAttr An attribute in the current theme that contains a
4933     *        reference to a style resource that supplies default values for
4934     *        the view. Can be 0 to not look for defaults.
4935     * @param defStyleRes A resource identifier of a style resource that
4936     *        supplies default values for the view, used only if
4937     *        defStyleAttr is 0 or can not be found in the theme. Can be 0
4938     *        to not look for defaults.
4939     * @see #View(Context, AttributeSet, int)
4940     */
4941    public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
4942        this(context);
4943
4944        final TypedArray a = context.obtainStyledAttributes(
4945                attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes);
4946
4947        if (mDebugViewAttributes) {
4948            saveAttributeData(attrs, a);
4949        }
4950
4951        Drawable background = null;
4952
4953        int leftPadding = -1;
4954        int topPadding = -1;
4955        int rightPadding = -1;
4956        int bottomPadding = -1;
4957        int startPadding = UNDEFINED_PADDING;
4958        int endPadding = UNDEFINED_PADDING;
4959
4960        int padding = -1;
4961        int paddingHorizontal = -1;
4962        int paddingVertical = -1;
4963
4964        int viewFlagValues = 0;
4965        int viewFlagMasks = 0;
4966
4967        boolean setScrollContainer = false;
4968
4969        int x = 0;
4970        int y = 0;
4971
4972        float tx = 0;
4973        float ty = 0;
4974        float tz = 0;
4975        float elevation = 0;
4976        float rotation = 0;
4977        float rotationX = 0;
4978        float rotationY = 0;
4979        float sx = 1f;
4980        float sy = 1f;
4981        boolean transformSet = false;
4982
4983        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
4984        int overScrollMode = mOverScrollMode;
4985        boolean initializeScrollbars = false;
4986        boolean initializeScrollIndicators = false;
4987
4988        boolean startPaddingDefined = false;
4989        boolean endPaddingDefined = false;
4990        boolean leftPaddingDefined = false;
4991        boolean rightPaddingDefined = false;
4992
4993        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
4994
4995        // Set default values.
4996        viewFlagValues |= FOCUSABLE_AUTO;
4997        viewFlagMasks |= FOCUSABLE_AUTO;
4998
4999        final int N = a.getIndexCount();
5000        for (int i = 0; i < N; i++) {
5001            int attr = a.getIndex(i);
5002            switch (attr) {
5003                case com.android.internal.R.styleable.View_background:
5004                    background = a.getDrawable(attr);
5005                    break;
5006                case com.android.internal.R.styleable.View_padding:
5007                    padding = a.getDimensionPixelSize(attr, -1);
5008                    mUserPaddingLeftInitial = padding;
5009                    mUserPaddingRightInitial = padding;
5010                    leftPaddingDefined = true;
5011                    rightPaddingDefined = true;
5012                    break;
5013                case com.android.internal.R.styleable.View_paddingHorizontal:
5014                    paddingHorizontal = a.getDimensionPixelSize(attr, -1);
5015                    mUserPaddingLeftInitial = paddingHorizontal;
5016                    mUserPaddingRightInitial = paddingHorizontal;
5017                    leftPaddingDefined = true;
5018                    rightPaddingDefined = true;
5019                    break;
5020                case com.android.internal.R.styleable.View_paddingVertical:
5021                    paddingVertical = a.getDimensionPixelSize(attr, -1);
5022                    break;
5023                 case com.android.internal.R.styleable.View_paddingLeft:
5024                    leftPadding = a.getDimensionPixelSize(attr, -1);
5025                    mUserPaddingLeftInitial = leftPadding;
5026                    leftPaddingDefined = true;
5027                    break;
5028                case com.android.internal.R.styleable.View_paddingTop:
5029                    topPadding = a.getDimensionPixelSize(attr, -1);
5030                    break;
5031                case com.android.internal.R.styleable.View_paddingRight:
5032                    rightPadding = a.getDimensionPixelSize(attr, -1);
5033                    mUserPaddingRightInitial = rightPadding;
5034                    rightPaddingDefined = true;
5035                    break;
5036                case com.android.internal.R.styleable.View_paddingBottom:
5037                    bottomPadding = a.getDimensionPixelSize(attr, -1);
5038                    break;
5039                case com.android.internal.R.styleable.View_paddingStart:
5040                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
5041                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
5042                    break;
5043                case com.android.internal.R.styleable.View_paddingEnd:
5044                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
5045                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
5046                    break;
5047                case com.android.internal.R.styleable.View_scrollX:
5048                    x = a.getDimensionPixelOffset(attr, 0);
5049                    break;
5050                case com.android.internal.R.styleable.View_scrollY:
5051                    y = a.getDimensionPixelOffset(attr, 0);
5052                    break;
5053                case com.android.internal.R.styleable.View_alpha:
5054                    setAlpha(a.getFloat(attr, 1f));
5055                    break;
5056                case com.android.internal.R.styleable.View_transformPivotX:
5057                    setPivotX(a.getDimension(attr, 0));
5058                    break;
5059                case com.android.internal.R.styleable.View_transformPivotY:
5060                    setPivotY(a.getDimension(attr, 0));
5061                    break;
5062                case com.android.internal.R.styleable.View_translationX:
5063                    tx = a.getDimension(attr, 0);
5064                    transformSet = true;
5065                    break;
5066                case com.android.internal.R.styleable.View_translationY:
5067                    ty = a.getDimension(attr, 0);
5068                    transformSet = true;
5069                    break;
5070                case com.android.internal.R.styleable.View_translationZ:
5071                    tz = a.getDimension(attr, 0);
5072                    transformSet = true;
5073                    break;
5074                case com.android.internal.R.styleable.View_elevation:
5075                    elevation = a.getDimension(attr, 0);
5076                    transformSet = true;
5077                    break;
5078                case com.android.internal.R.styleable.View_rotation:
5079                    rotation = a.getFloat(attr, 0);
5080                    transformSet = true;
5081                    break;
5082                case com.android.internal.R.styleable.View_rotationX:
5083                    rotationX = a.getFloat(attr, 0);
5084                    transformSet = true;
5085                    break;
5086                case com.android.internal.R.styleable.View_rotationY:
5087                    rotationY = a.getFloat(attr, 0);
5088                    transformSet = true;
5089                    break;
5090                case com.android.internal.R.styleable.View_scaleX:
5091                    sx = a.getFloat(attr, 1f);
5092                    transformSet = true;
5093                    break;
5094                case com.android.internal.R.styleable.View_scaleY:
5095                    sy = a.getFloat(attr, 1f);
5096                    transformSet = true;
5097                    break;
5098                case com.android.internal.R.styleable.View_id:
5099                    mID = a.getResourceId(attr, NO_ID);
5100                    break;
5101                case com.android.internal.R.styleable.View_tag:
5102                    mTag = a.getText(attr);
5103                    break;
5104                case com.android.internal.R.styleable.View_fitsSystemWindows:
5105                    if (a.getBoolean(attr, false)) {
5106                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
5107                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
5108                    }
5109                    break;
5110                case com.android.internal.R.styleable.View_focusable:
5111                    viewFlagValues = (viewFlagValues & ~FOCUSABLE_MASK) | getFocusableAttribute(a);
5112                    if ((viewFlagValues & FOCUSABLE_AUTO) == 0) {
5113                        viewFlagMasks |= FOCUSABLE_MASK;
5114                    }
5115                    break;
5116                case com.android.internal.R.styleable.View_focusableInTouchMode:
5117                    if (a.getBoolean(attr, false)) {
5118                        // unset auto focus since focusableInTouchMode implies explicit focusable
5119                        viewFlagValues &= ~FOCUSABLE_AUTO;
5120                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
5121                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
5122                    }
5123                    break;
5124                case com.android.internal.R.styleable.View_clickable:
5125                    if (a.getBoolean(attr, false)) {
5126                        viewFlagValues |= CLICKABLE;
5127                        viewFlagMasks |= CLICKABLE;
5128                    }
5129                    break;
5130                case com.android.internal.R.styleable.View_longClickable:
5131                    if (a.getBoolean(attr, false)) {
5132                        viewFlagValues |= LONG_CLICKABLE;
5133                        viewFlagMasks |= LONG_CLICKABLE;
5134                    }
5135                    break;
5136                case com.android.internal.R.styleable.View_contextClickable:
5137                    if (a.getBoolean(attr, false)) {
5138                        viewFlagValues |= CONTEXT_CLICKABLE;
5139                        viewFlagMasks |= CONTEXT_CLICKABLE;
5140                    }
5141                    break;
5142                case com.android.internal.R.styleable.View_saveEnabled:
5143                    if (!a.getBoolean(attr, true)) {
5144                        viewFlagValues |= SAVE_DISABLED;
5145                        viewFlagMasks |= SAVE_DISABLED_MASK;
5146                    }
5147                    break;
5148                case com.android.internal.R.styleable.View_duplicateParentState:
5149                    if (a.getBoolean(attr, false)) {
5150                        viewFlagValues |= DUPLICATE_PARENT_STATE;
5151                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
5152                    }
5153                    break;
5154                case com.android.internal.R.styleable.View_visibility:
5155                    final int visibility = a.getInt(attr, 0);
5156                    if (visibility != 0) {
5157                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
5158                        viewFlagMasks |= VISIBILITY_MASK;
5159                    }
5160                    break;
5161                case com.android.internal.R.styleable.View_layoutDirection:
5162                    // Clear any layout direction flags (included resolved bits) already set
5163                    mPrivateFlags2 &=
5164                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
5165                    // Set the layout direction flags depending on the value of the attribute
5166                    final int layoutDirection = a.getInt(attr, -1);
5167                    final int value = (layoutDirection != -1) ?
5168                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
5169                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
5170                    break;
5171                case com.android.internal.R.styleable.View_drawingCacheQuality:
5172                    final int cacheQuality = a.getInt(attr, 0);
5173                    if (cacheQuality != 0) {
5174                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
5175                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
5176                    }
5177                    break;
5178                case com.android.internal.R.styleable.View_contentDescription:
5179                    setContentDescription(a.getString(attr));
5180                    break;
5181                case com.android.internal.R.styleable.View_accessibilityTraversalBefore:
5182                    setAccessibilityTraversalBefore(a.getResourceId(attr, NO_ID));
5183                    break;
5184                case com.android.internal.R.styleable.View_accessibilityTraversalAfter:
5185                    setAccessibilityTraversalAfter(a.getResourceId(attr, NO_ID));
5186                    break;
5187                case com.android.internal.R.styleable.View_labelFor:
5188                    setLabelFor(a.getResourceId(attr, NO_ID));
5189                    break;
5190                case com.android.internal.R.styleable.View_soundEffectsEnabled:
5191                    if (!a.getBoolean(attr, true)) {
5192                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
5193                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
5194                    }
5195                    break;
5196                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
5197                    if (!a.getBoolean(attr, true)) {
5198                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
5199                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
5200                    }
5201                    break;
5202                case R.styleable.View_scrollbars:
5203                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
5204                    if (scrollbars != SCROLLBARS_NONE) {
5205                        viewFlagValues |= scrollbars;
5206                        viewFlagMasks |= SCROLLBARS_MASK;
5207                        initializeScrollbars = true;
5208                    }
5209                    break;
5210                //noinspection deprecation
5211                case R.styleable.View_fadingEdge:
5212                    if (targetSdkVersion >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
5213                        // Ignore the attribute starting with ICS
5214                        break;
5215                    }
5216                    // With builds < ICS, fall through and apply fading edges
5217                case R.styleable.View_requiresFadingEdge:
5218                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
5219                    if (fadingEdge != FADING_EDGE_NONE) {
5220                        viewFlagValues |= fadingEdge;
5221                        viewFlagMasks |= FADING_EDGE_MASK;
5222                        initializeFadingEdgeInternal(a);
5223                    }
5224                    break;
5225                case R.styleable.View_scrollbarStyle:
5226                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
5227                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
5228                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
5229                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
5230                    }
5231                    break;
5232                case R.styleable.View_isScrollContainer:
5233                    setScrollContainer = true;
5234                    if (a.getBoolean(attr, false)) {
5235                        setScrollContainer(true);
5236                    }
5237                    break;
5238                case com.android.internal.R.styleable.View_keepScreenOn:
5239                    if (a.getBoolean(attr, false)) {
5240                        viewFlagValues |= KEEP_SCREEN_ON;
5241                        viewFlagMasks |= KEEP_SCREEN_ON;
5242                    }
5243                    break;
5244                case R.styleable.View_filterTouchesWhenObscured:
5245                    if (a.getBoolean(attr, false)) {
5246                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
5247                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
5248                    }
5249                    break;
5250                case R.styleable.View_nextFocusLeft:
5251                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
5252                    break;
5253                case R.styleable.View_nextFocusRight:
5254                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
5255                    break;
5256                case R.styleable.View_nextFocusUp:
5257                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
5258                    break;
5259                case R.styleable.View_nextFocusDown:
5260                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
5261                    break;
5262                case R.styleable.View_nextFocusForward:
5263                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
5264                    break;
5265                case R.styleable.View_nextClusterForward:
5266                    mNextClusterForwardId = a.getResourceId(attr, View.NO_ID);
5267                    break;
5268                case R.styleable.View_minWidth:
5269                    mMinWidth = a.getDimensionPixelSize(attr, 0);
5270                    break;
5271                case R.styleable.View_minHeight:
5272                    mMinHeight = a.getDimensionPixelSize(attr, 0);
5273                    break;
5274                case R.styleable.View_onClick:
5275                    if (context.isRestricted()) {
5276                        throw new IllegalStateException("The android:onClick attribute cannot "
5277                                + "be used within a restricted context");
5278                    }
5279
5280                    final String handlerName = a.getString(attr);
5281                    if (handlerName != null) {
5282                        setOnClickListener(new DeclaredOnClickListener(this, handlerName));
5283                    }
5284                    break;
5285                case R.styleable.View_overScrollMode:
5286                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
5287                    break;
5288                case R.styleable.View_verticalScrollbarPosition:
5289                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
5290                    break;
5291                case R.styleable.View_layerType:
5292                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
5293                    break;
5294                case R.styleable.View_textDirection:
5295                    // Clear any text direction flag already set
5296                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
5297                    // Set the text direction flags depending on the value of the attribute
5298                    final int textDirection = a.getInt(attr, -1);
5299                    if (textDirection != -1) {
5300                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
5301                    }
5302                    break;
5303                case R.styleable.View_textAlignment:
5304                    // Clear any text alignment flag already set
5305                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
5306                    // Set the text alignment flag depending on the value of the attribute
5307                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
5308                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
5309                    break;
5310                case R.styleable.View_importantForAccessibility:
5311                    setImportantForAccessibility(a.getInt(attr,
5312                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
5313                    break;
5314                case R.styleable.View_accessibilityLiveRegion:
5315                    setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT));
5316                    break;
5317                case R.styleable.View_transitionName:
5318                    setTransitionName(a.getString(attr));
5319                    break;
5320                case R.styleable.View_nestedScrollingEnabled:
5321                    setNestedScrollingEnabled(a.getBoolean(attr, false));
5322                    break;
5323                case R.styleable.View_stateListAnimator:
5324                    setStateListAnimator(AnimatorInflater.loadStateListAnimator(context,
5325                            a.getResourceId(attr, 0)));
5326                    break;
5327                case R.styleable.View_backgroundTint:
5328                    // This will get applied later during setBackground().
5329                    if (mBackgroundTint == null) {
5330                        mBackgroundTint = new TintInfo();
5331                    }
5332                    mBackgroundTint.mTintList = a.getColorStateList(
5333                            R.styleable.View_backgroundTint);
5334                    mBackgroundTint.mHasTintList = true;
5335                    break;
5336                case R.styleable.View_backgroundTintMode:
5337                    // This will get applied later during setBackground().
5338                    if (mBackgroundTint == null) {
5339                        mBackgroundTint = new TintInfo();
5340                    }
5341                    mBackgroundTint.mTintMode = Drawable.parseTintMode(a.getInt(
5342                            R.styleable.View_backgroundTintMode, -1), null);
5343                    mBackgroundTint.mHasTintMode = true;
5344                    break;
5345                case R.styleable.View_outlineProvider:
5346                    setOutlineProviderFromAttribute(a.getInt(R.styleable.View_outlineProvider,
5347                            PROVIDER_BACKGROUND));
5348                    break;
5349                case R.styleable.View_foreground:
5350                    if (targetSdkVersion >= Build.VERSION_CODES.M || this instanceof FrameLayout) {
5351                        setForeground(a.getDrawable(attr));
5352                    }
5353                    break;
5354                case R.styleable.View_foregroundGravity:
5355                    if (targetSdkVersion >= Build.VERSION_CODES.M || this instanceof FrameLayout) {
5356                        setForegroundGravity(a.getInt(attr, Gravity.NO_GRAVITY));
5357                    }
5358                    break;
5359                case R.styleable.View_foregroundTintMode:
5360                    if (targetSdkVersion >= Build.VERSION_CODES.M || this instanceof FrameLayout) {
5361                        setForegroundTintMode(Drawable.parseTintMode(a.getInt(attr, -1), null));
5362                    }
5363                    break;
5364                case R.styleable.View_foregroundTint:
5365                    if (targetSdkVersion >= Build.VERSION_CODES.M || this instanceof FrameLayout) {
5366                        setForegroundTintList(a.getColorStateList(attr));
5367                    }
5368                    break;
5369                case R.styleable.View_foregroundInsidePadding:
5370                    if (targetSdkVersion >= Build.VERSION_CODES.M || this instanceof FrameLayout) {
5371                        if (mForegroundInfo == null) {
5372                            mForegroundInfo = new ForegroundInfo();
5373                        }
5374                        mForegroundInfo.mInsidePadding = a.getBoolean(attr,
5375                                mForegroundInfo.mInsidePadding);
5376                    }
5377                    break;
5378                case R.styleable.View_scrollIndicators:
5379                    final int scrollIndicators =
5380                            (a.getInt(attr, 0) << SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT)
5381                                    & SCROLL_INDICATORS_PFLAG3_MASK;
5382                    if (scrollIndicators != 0) {
5383                        mPrivateFlags3 |= scrollIndicators;
5384                        initializeScrollIndicators = true;
5385                    }
5386                    break;
5387                case R.styleable.View_pointerIcon:
5388                    final int resourceId = a.getResourceId(attr, 0);
5389                    if (resourceId != 0) {
5390                        setPointerIcon(PointerIcon.load(
5391                                context.getResources(), resourceId));
5392                    } else {
5393                        final int pointerType = a.getInt(attr, PointerIcon.TYPE_NOT_SPECIFIED);
5394                        if (pointerType != PointerIcon.TYPE_NOT_SPECIFIED) {
5395                            setPointerIcon(PointerIcon.getSystemIcon(context, pointerType));
5396                        }
5397                    }
5398                    break;
5399                case R.styleable.View_forceHasOverlappingRendering:
5400                    if (a.peekValue(attr) != null) {
5401                        forceHasOverlappingRendering(a.getBoolean(attr, true));
5402                    }
5403                    break;
5404                case R.styleable.View_tooltipText:
5405                    setTooltipText(a.getText(attr));
5406                    break;
5407                case R.styleable.View_keyboardNavigationCluster:
5408                    if (a.peekValue(attr) != null) {
5409                        setKeyboardNavigationCluster(a.getBoolean(attr, true));
5410                    }
5411                    break;
5412                case R.styleable.View_focusedByDefault:
5413                    if (a.peekValue(attr) != null) {
5414                        setFocusedByDefault(a.getBoolean(attr, true));
5415                    }
5416                    break;
5417                case R.styleable.View_autofillHints:
5418                    if (a.peekValue(attr) != null) {
5419                        CharSequence[] rawHints = null;
5420                        String rawString = null;
5421
5422                        if (a.getType(attr) == TypedValue.TYPE_REFERENCE) {
5423                            int resId = a.getResourceId(attr, 0);
5424
5425                            try {
5426                                rawHints = a.getTextArray(attr);
5427                            } catch (Resources.NotFoundException e) {
5428                                rawString = getResources().getString(resId);
5429                            }
5430                        } else {
5431                            rawString = a.getString(attr);
5432                        }
5433
5434                        if (rawHints == null) {
5435                            if (rawString == null) {
5436                                throw new IllegalArgumentException(
5437                                        "Could not resolve autofillHints");
5438                            } else {
5439                                rawHints = rawString.split(",");
5440                            }
5441                        }
5442
5443                        String[] hints = new String[rawHints.length];
5444
5445                        int numHints = rawHints.length;
5446                        for (int rawHintNum = 0; rawHintNum < numHints; rawHintNum++) {
5447                            hints[rawHintNum] = rawHints[rawHintNum].toString().trim();
5448                        }
5449                        setAutofillHints(hints);
5450                    }
5451                    break;
5452                case R.styleable.View_importantForAutofill:
5453                    if (a.peekValue(attr) != null) {
5454                        setImportantForAutofill(a.getInt(attr, IMPORTANT_FOR_AUTOFILL_AUTO));
5455                    }
5456                    break;
5457                case R.styleable.View_defaultFocusHighlightEnabled:
5458                    if (a.peekValue(attr) != null) {
5459                        setDefaultFocusHighlightEnabled(a.getBoolean(attr, true));
5460                    }
5461                    break;
5462                case R.styleable.View_screenReaderFocusable:
5463                    if (a.peekValue(attr) != null) {
5464                        setScreenReaderFocusable(a.getBoolean(attr, false));
5465                    }
5466                    break;
5467                case R.styleable.View_accessibilityPaneTitle:
5468                    if (a.peekValue(attr) != null) {
5469                        setAccessibilityPaneTitle(a.getString(attr));
5470                    }
5471                    break;
5472                case R.styleable.View_outlineSpotShadowColor:
5473                    setOutlineSpotShadowColor(a.getColor(attr, Color.BLACK));
5474                    break;
5475                case R.styleable.View_outlineAmbientShadowColor:
5476                    setOutlineAmbientShadowColor(a.getColor(attr, Color.BLACK));
5477                    break;
5478            }
5479        }
5480
5481        setOverScrollMode(overScrollMode);
5482
5483        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
5484        // the resolved layout direction). Those cached values will be used later during padding
5485        // resolution.
5486        mUserPaddingStart = startPadding;
5487        mUserPaddingEnd = endPadding;
5488
5489        if (background != null) {
5490            setBackground(background);
5491        }
5492
5493        // setBackground above will record that padding is currently provided by the background.
5494        // If we have padding specified via xml, record that here instead and use it.
5495        mLeftPaddingDefined = leftPaddingDefined;
5496        mRightPaddingDefined = rightPaddingDefined;
5497
5498        if (padding >= 0) {
5499            leftPadding = padding;
5500            topPadding = padding;
5501            rightPadding = padding;
5502            bottomPadding = padding;
5503            mUserPaddingLeftInitial = padding;
5504            mUserPaddingRightInitial = padding;
5505        } else {
5506            if (paddingHorizontal >= 0) {
5507                leftPadding = paddingHorizontal;
5508                rightPadding = paddingHorizontal;
5509                mUserPaddingLeftInitial = paddingHorizontal;
5510                mUserPaddingRightInitial = paddingHorizontal;
5511            }
5512            if (paddingVertical >= 0) {
5513                topPadding = paddingVertical;
5514                bottomPadding = paddingVertical;
5515            }
5516        }
5517
5518        if (isRtlCompatibilityMode()) {
5519            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
5520            // left / right padding are used if defined (meaning here nothing to do). If they are not
5521            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
5522            // start / end and resolve them as left / right (layout direction is not taken into account).
5523            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
5524            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
5525            // defined.
5526            if (!mLeftPaddingDefined && startPaddingDefined) {
5527                leftPadding = startPadding;
5528            }
5529            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
5530            if (!mRightPaddingDefined && endPaddingDefined) {
5531                rightPadding = endPadding;
5532            }
5533            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
5534        } else {
5535            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
5536            // values defined. Otherwise, left /right values are used.
5537            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
5538            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
5539            // defined.
5540            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
5541
5542            if (mLeftPaddingDefined && !hasRelativePadding) {
5543                mUserPaddingLeftInitial = leftPadding;
5544            }
5545            if (mRightPaddingDefined && !hasRelativePadding) {
5546                mUserPaddingRightInitial = rightPadding;
5547            }
5548        }
5549
5550        internalSetPadding(
5551                mUserPaddingLeftInitial,
5552                topPadding >= 0 ? topPadding : mPaddingTop,
5553                mUserPaddingRightInitial,
5554                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
5555
5556        if (viewFlagMasks != 0) {
5557            setFlags(viewFlagValues, viewFlagMasks);
5558        }
5559
5560        if (initializeScrollbars) {
5561            initializeScrollbarsInternal(a);
5562        }
5563
5564        if (initializeScrollIndicators) {
5565            initializeScrollIndicatorsInternal();
5566        }
5567
5568        a.recycle();
5569
5570        // Needs to be called after mViewFlags is set
5571        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
5572            recomputePadding();
5573        }
5574
5575        if (x != 0 || y != 0) {
5576            scrollTo(x, y);
5577        }
5578
5579        if (transformSet) {
5580            setTranslationX(tx);
5581            setTranslationY(ty);
5582            setTranslationZ(tz);
5583            setElevation(elevation);
5584            setRotation(rotation);
5585            setRotationX(rotationX);
5586            setRotationY(rotationY);
5587            setScaleX(sx);
5588            setScaleY(sy);
5589        }
5590
5591        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
5592            setScrollContainer(true);
5593        }
5594
5595        computeOpaqueFlags();
5596    }
5597
5598    /**
5599     * An implementation of OnClickListener that attempts to lazily load a
5600     * named click handling method from a parent or ancestor context.
5601     */
5602    private static class DeclaredOnClickListener implements OnClickListener {
5603        private final View mHostView;
5604        private final String mMethodName;
5605
5606        private Method mResolvedMethod;
5607        private Context mResolvedContext;
5608
5609        public DeclaredOnClickListener(@NonNull View hostView, @NonNull String methodName) {
5610            mHostView = hostView;
5611            mMethodName = methodName;
5612        }
5613
5614        @Override
5615        public void onClick(@NonNull View v) {
5616            if (mResolvedMethod == null) {
5617                resolveMethod(mHostView.getContext(), mMethodName);
5618            }
5619
5620            try {
5621                mResolvedMethod.invoke(mResolvedContext, v);
5622            } catch (IllegalAccessException e) {
5623                throw new IllegalStateException(
5624                        "Could not execute non-public method for android:onClick", e);
5625            } catch (InvocationTargetException e) {
5626                throw new IllegalStateException(
5627                        "Could not execute method for android:onClick", e);
5628            }
5629        }
5630
5631        @NonNull
5632        private void resolveMethod(@Nullable Context context, @NonNull String name) {
5633            while (context != null) {
5634                try {
5635                    if (!context.isRestricted()) {
5636                        final Method method = context.getClass().getMethod(mMethodName, View.class);
5637                        if (method != null) {
5638                            mResolvedMethod = method;
5639                            mResolvedContext = context;
5640                            return;
5641                        }
5642                    }
5643                } catch (NoSuchMethodException e) {
5644                    // Failed to find method, keep searching up the hierarchy.
5645                }
5646
5647                if (context instanceof ContextWrapper) {
5648                    context = ((ContextWrapper) context).getBaseContext();
5649                } else {
5650                    // Can't search up the hierarchy, null out and fail.
5651                    context = null;
5652                }
5653            }
5654
5655            final int id = mHostView.getId();
5656            final String idText = id == NO_ID ? "" : " with id '"
5657                    + mHostView.getContext().getResources().getResourceEntryName(id) + "'";
5658            throw new IllegalStateException("Could not find method " + mMethodName
5659                    + "(View) in a parent or ancestor Context for android:onClick "
5660                    + "attribute defined on view " + mHostView.getClass() + idText);
5661        }
5662    }
5663
5664    /**
5665     * Non-public constructor for use in testing
5666     */
5667    View() {
5668        mResources = null;
5669        mRenderNode = RenderNode.create(getClass().getName(), this);
5670    }
5671
5672    final boolean debugDraw() {
5673        return DEBUG_DRAW || mAttachInfo != null && mAttachInfo.mDebugLayout;
5674    }
5675
5676    private static SparseArray<String> getAttributeMap() {
5677        if (mAttributeMap == null) {
5678            mAttributeMap = new SparseArray<>();
5679        }
5680        return mAttributeMap;
5681    }
5682
5683    private void saveAttributeData(@Nullable AttributeSet attrs, @NonNull TypedArray t) {
5684        final int attrsCount = attrs == null ? 0 : attrs.getAttributeCount();
5685        final int indexCount = t.getIndexCount();
5686        final String[] attributes = new String[(attrsCount + indexCount) * 2];
5687
5688        int i = 0;
5689
5690        // Store raw XML attributes.
5691        for (int j = 0; j < attrsCount; ++j) {
5692            attributes[i] = attrs.getAttributeName(j);
5693            attributes[i + 1] = attrs.getAttributeValue(j);
5694            i += 2;
5695        }
5696
5697        // Store resolved styleable attributes.
5698        final Resources res = t.getResources();
5699        final SparseArray<String> attributeMap = getAttributeMap();
5700        for (int j = 0; j < indexCount; ++j) {
5701            final int index = t.getIndex(j);
5702            if (!t.hasValueOrEmpty(index)) {
5703                // Value is undefined. Skip it.
5704                continue;
5705            }
5706
5707            final int resourceId = t.getResourceId(index, 0);
5708            if (resourceId == 0) {
5709                // Value is not a reference. Skip it.
5710                continue;
5711            }
5712
5713            String resourceName = attributeMap.get(resourceId);
5714            if (resourceName == null) {
5715                try {
5716                    resourceName = res.getResourceName(resourceId);
5717                } catch (Resources.NotFoundException e) {
5718                    resourceName = "0x" + Integer.toHexString(resourceId);
5719                }
5720                attributeMap.put(resourceId, resourceName);
5721            }
5722
5723            attributes[i] = resourceName;
5724            attributes[i + 1] = t.getString(index);
5725            i += 2;
5726        }
5727
5728        // Trim to fit contents.
5729        final String[] trimmed = new String[i];
5730        System.arraycopy(attributes, 0, trimmed, 0, i);
5731        mAttributes = trimmed;
5732    }
5733
5734    public String toString() {
5735        StringBuilder out = new StringBuilder(128);
5736        out.append(getClass().getName());
5737        out.append('{');
5738        out.append(Integer.toHexString(System.identityHashCode(this)));
5739        out.append(' ');
5740        switch (mViewFlags&VISIBILITY_MASK) {
5741            case VISIBLE: out.append('V'); break;
5742            case INVISIBLE: out.append('I'); break;
5743            case GONE: out.append('G'); break;
5744            default: out.append('.'); break;
5745        }
5746        out.append((mViewFlags & FOCUSABLE) == FOCUSABLE ? 'F' : '.');
5747        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
5748        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
5749        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
5750        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
5751        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
5752        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
5753        out.append((mViewFlags&CONTEXT_CLICKABLE) != 0 ? 'X' : '.');
5754        out.append(' ');
5755        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
5756        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
5757        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
5758        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
5759            out.append('p');
5760        } else {
5761            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
5762        }
5763        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
5764        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
5765        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
5766        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
5767        out.append(' ');
5768        out.append(mLeft);
5769        out.append(',');
5770        out.append(mTop);
5771        out.append('-');
5772        out.append(mRight);
5773        out.append(',');
5774        out.append(mBottom);
5775        final int id = getId();
5776        if (id != NO_ID) {
5777            out.append(" #");
5778            out.append(Integer.toHexString(id));
5779            final Resources r = mResources;
5780            if (id > 0 && Resources.resourceHasPackage(id) && r != null) {
5781                try {
5782                    String pkgname;
5783                    switch (id&0xff000000) {
5784                        case 0x7f000000:
5785                            pkgname="app";
5786                            break;
5787                        case 0x01000000:
5788                            pkgname="android";
5789                            break;
5790                        default:
5791                            pkgname = r.getResourcePackageName(id);
5792                            break;
5793                    }
5794                    String typename = r.getResourceTypeName(id);
5795                    String entryname = r.getResourceEntryName(id);
5796                    out.append(" ");
5797                    out.append(pkgname);
5798                    out.append(":");
5799                    out.append(typename);
5800                    out.append("/");
5801                    out.append(entryname);
5802                } catch (Resources.NotFoundException e) {
5803                }
5804            }
5805        }
5806        out.append("}");
5807        return out.toString();
5808    }
5809
5810    /**
5811     * <p>
5812     * Initializes the fading edges from a given set of styled attributes. This
5813     * method should be called by subclasses that need fading edges and when an
5814     * instance of these subclasses is created programmatically rather than
5815     * being inflated from XML. This method is automatically called when the XML
5816     * is inflated.
5817     * </p>
5818     *
5819     * @param a the styled attributes set to initialize the fading edges from
5820     *
5821     * @removed
5822     */
5823    protected void initializeFadingEdge(TypedArray a) {
5824        // This method probably shouldn't have been included in the SDK to begin with.
5825        // It relies on 'a' having been initialized using an attribute filter array that is
5826        // not publicly available to the SDK. The old method has been renamed
5827        // to initializeFadingEdgeInternal and hidden for framework use only;
5828        // this one initializes using defaults to make it safe to call for apps.
5829
5830        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
5831
5832        initializeFadingEdgeInternal(arr);
5833
5834        arr.recycle();
5835    }
5836
5837    /**
5838     * <p>
5839     * Initializes the fading edges from a given set of styled attributes. This
5840     * method should be called by subclasses that need fading edges and when an
5841     * instance of these subclasses is created programmatically rather than
5842     * being inflated from XML. This method is automatically called when the XML
5843     * is inflated.
5844     * </p>
5845     *
5846     * @param a the styled attributes set to initialize the fading edges from
5847     * @hide This is the real method; the public one is shimmed to be safe to call from apps.
5848     */
5849    protected void initializeFadingEdgeInternal(TypedArray a) {
5850        initScrollCache();
5851
5852        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
5853                R.styleable.View_fadingEdgeLength,
5854                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
5855    }
5856
5857    /**
5858     * Returns the size of the vertical faded edges used to indicate that more
5859     * content in this view is visible.
5860     *
5861     * @return The size in pixels of the vertical faded edge or 0 if vertical
5862     *         faded edges are not enabled for this view.
5863     * @attr ref android.R.styleable#View_fadingEdgeLength
5864     */
5865    public int getVerticalFadingEdgeLength() {
5866        if (isVerticalFadingEdgeEnabled()) {
5867            ScrollabilityCache cache = mScrollCache;
5868            if (cache != null) {
5869                return cache.fadingEdgeLength;
5870            }
5871        }
5872        return 0;
5873    }
5874
5875    /**
5876     * Set the size of the faded edge used to indicate that more content in this
5877     * view is available.  Will not change whether the fading edge is enabled; use
5878     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
5879     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
5880     * for the vertical or horizontal fading edges.
5881     *
5882     * @param length The size in pixels of the faded edge used to indicate that more
5883     *        content in this view is visible.
5884     */
5885    public void setFadingEdgeLength(int length) {
5886        initScrollCache();
5887        mScrollCache.fadingEdgeLength = length;
5888    }
5889
5890    /**
5891     * Returns the size of the horizontal faded edges used to indicate that more
5892     * content in this view is visible.
5893     *
5894     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
5895     *         faded edges are not enabled for this view.
5896     * @attr ref android.R.styleable#View_fadingEdgeLength
5897     */
5898    public int getHorizontalFadingEdgeLength() {
5899        if (isHorizontalFadingEdgeEnabled()) {
5900            ScrollabilityCache cache = mScrollCache;
5901            if (cache != null) {
5902                return cache.fadingEdgeLength;
5903            }
5904        }
5905        return 0;
5906    }
5907
5908    /**
5909     * Returns the width of the vertical scrollbar.
5910     *
5911     * @return The width in pixels of the vertical scrollbar or 0 if there
5912     *         is no vertical scrollbar.
5913     */
5914    public int getVerticalScrollbarWidth() {
5915        ScrollabilityCache cache = mScrollCache;
5916        if (cache != null) {
5917            ScrollBarDrawable scrollBar = cache.scrollBar;
5918            if (scrollBar != null) {
5919                int size = scrollBar.getSize(true);
5920                if (size <= 0) {
5921                    size = cache.scrollBarSize;
5922                }
5923                return size;
5924            }
5925            return 0;
5926        }
5927        return 0;
5928    }
5929
5930    /**
5931     * Returns the height of the horizontal scrollbar.
5932     *
5933     * @return The height in pixels of the horizontal scrollbar or 0 if
5934     *         there is no horizontal scrollbar.
5935     */
5936    protected int getHorizontalScrollbarHeight() {
5937        ScrollabilityCache cache = mScrollCache;
5938        if (cache != null) {
5939            ScrollBarDrawable scrollBar = cache.scrollBar;
5940            if (scrollBar != null) {
5941                int size = scrollBar.getSize(false);
5942                if (size <= 0) {
5943                    size = cache.scrollBarSize;
5944                }
5945                return size;
5946            }
5947            return 0;
5948        }
5949        return 0;
5950    }
5951
5952    /**
5953     * <p>
5954     * Initializes the scrollbars from a given set of styled attributes. This
5955     * method should be called by subclasses that need scrollbars and when an
5956     * instance of these subclasses is created programmatically rather than
5957     * being inflated from XML. This method is automatically called when the XML
5958     * is inflated.
5959     * </p>
5960     *
5961     * @param a the styled attributes set to initialize the scrollbars from
5962     *
5963     * @removed
5964     */
5965    protected void initializeScrollbars(TypedArray a) {
5966        // It's not safe to use this method from apps. The parameter 'a' must have been obtained
5967        // using the View filter array which is not available to the SDK. As such, internal
5968        // framework usage now uses initializeScrollbarsInternal and we grab a default
5969        // TypedArray with the right filter instead here.
5970        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
5971
5972        initializeScrollbarsInternal(arr);
5973
5974        // We ignored the method parameter. Recycle the one we actually did use.
5975        arr.recycle();
5976    }
5977
5978    /**
5979     * <p>
5980     * Initializes the scrollbars from a given set of styled attributes. This
5981     * method should be called by subclasses that need scrollbars and when an
5982     * instance of these subclasses is created programmatically rather than
5983     * being inflated from XML. This method is automatically called when the XML
5984     * is inflated.
5985     * </p>
5986     *
5987     * @param a the styled attributes set to initialize the scrollbars from
5988     * @hide
5989     */
5990    protected void initializeScrollbarsInternal(TypedArray a) {
5991        initScrollCache();
5992
5993        final ScrollabilityCache scrollabilityCache = mScrollCache;
5994
5995        if (scrollabilityCache.scrollBar == null) {
5996            scrollabilityCache.scrollBar = new ScrollBarDrawable();
5997            scrollabilityCache.scrollBar.setState(getDrawableState());
5998            scrollabilityCache.scrollBar.setCallback(this);
5999        }
6000
6001        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
6002
6003        if (!fadeScrollbars) {
6004            scrollabilityCache.state = ScrollabilityCache.ON;
6005        }
6006        scrollabilityCache.fadeScrollBars = fadeScrollbars;
6007
6008
6009        scrollabilityCache.scrollBarFadeDuration = a.getInt(
6010                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
6011                        .getScrollBarFadeDuration());
6012        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
6013                R.styleable.View_scrollbarDefaultDelayBeforeFade,
6014                ViewConfiguration.getScrollDefaultDelay());
6015
6016
6017        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
6018                com.android.internal.R.styleable.View_scrollbarSize,
6019                ViewConfiguration.get(mContext).getScaledScrollBarSize());
6020
6021        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
6022        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
6023
6024        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
6025        if (thumb != null) {
6026            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
6027        }
6028
6029        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
6030                false);
6031        if (alwaysDraw) {
6032            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
6033        }
6034
6035        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
6036        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
6037
6038        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
6039        if (thumb != null) {
6040            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
6041        }
6042
6043        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
6044                false);
6045        if (alwaysDraw) {
6046            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
6047        }
6048
6049        // Apply layout direction to the new Drawables if needed
6050        final int layoutDirection = getLayoutDirection();
6051        if (track != null) {
6052            track.setLayoutDirection(layoutDirection);
6053        }
6054        if (thumb != null) {
6055            thumb.setLayoutDirection(layoutDirection);
6056        }
6057
6058        // Re-apply user/background padding so that scrollbar(s) get added
6059        resolvePadding();
6060    }
6061
6062    private void initializeScrollIndicatorsInternal() {
6063        // Some day maybe we'll break this into top/left/start/etc. and let the
6064        // client control it. Until then, you can have any scroll indicator you
6065        // want as long as it's a 1dp foreground-colored rectangle.
6066        if (mScrollIndicatorDrawable == null) {
6067            mScrollIndicatorDrawable = mContext.getDrawable(R.drawable.scroll_indicator_material);
6068        }
6069    }
6070
6071    /**
6072     * <p>
6073     * Initalizes the scrollability cache if necessary.
6074     * </p>
6075     */
6076    private void initScrollCache() {
6077        if (mScrollCache == null) {
6078            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
6079        }
6080    }
6081
6082    private ScrollabilityCache getScrollCache() {
6083        initScrollCache();
6084        return mScrollCache;
6085    }
6086
6087    /**
6088     * Set the position of the vertical scroll bar. Should be one of
6089     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
6090     * {@link #SCROLLBAR_POSITION_RIGHT}.
6091     *
6092     * @param position Where the vertical scroll bar should be positioned.
6093     */
6094    public void setVerticalScrollbarPosition(int position) {
6095        if (mVerticalScrollbarPosition != position) {
6096            mVerticalScrollbarPosition = position;
6097            computeOpaqueFlags();
6098            resolvePadding();
6099        }
6100    }
6101
6102    /**
6103     * @return The position where the vertical scroll bar will show, if applicable.
6104     * @see #setVerticalScrollbarPosition(int)
6105     */
6106    public int getVerticalScrollbarPosition() {
6107        return mVerticalScrollbarPosition;
6108    }
6109
6110    boolean isOnScrollbar(float x, float y) {
6111        if (mScrollCache == null) {
6112            return false;
6113        }
6114        x += getScrollX();
6115        y += getScrollY();
6116        if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) {
6117            final Rect touchBounds = mScrollCache.mScrollBarTouchBounds;
6118            getVerticalScrollBarBounds(null, touchBounds);
6119            if (touchBounds.contains((int) x, (int) y)) {
6120                return true;
6121            }
6122        }
6123        if (isHorizontalScrollBarEnabled()) {
6124            final Rect touchBounds = mScrollCache.mScrollBarTouchBounds;
6125            getHorizontalScrollBarBounds(null, touchBounds);
6126            if (touchBounds.contains((int) x, (int) y)) {
6127                return true;
6128            }
6129        }
6130        return false;
6131    }
6132
6133    boolean isOnScrollbarThumb(float x, float y) {
6134        return isOnVerticalScrollbarThumb(x, y) || isOnHorizontalScrollbarThumb(x, y);
6135    }
6136
6137    private boolean isOnVerticalScrollbarThumb(float x, float y) {
6138        if (mScrollCache == null) {
6139            return false;
6140        }
6141        if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) {
6142            x += getScrollX();
6143            y += getScrollY();
6144            final Rect bounds = mScrollCache.mScrollBarBounds;
6145            final Rect touchBounds = mScrollCache.mScrollBarTouchBounds;
6146            getVerticalScrollBarBounds(bounds, touchBounds);
6147            final int range = computeVerticalScrollRange();
6148            final int offset = computeVerticalScrollOffset();
6149            final int extent = computeVerticalScrollExtent();
6150            final int thumbLength = ScrollBarUtils.getThumbLength(bounds.height(), bounds.width(),
6151                    extent, range);
6152            final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.height(), thumbLength,
6153                    extent, range, offset);
6154            final int thumbTop = bounds.top + thumbOffset;
6155            final int adjust = Math.max(mScrollCache.scrollBarMinTouchTarget - thumbLength, 0) / 2;
6156            if (x >= touchBounds.left && x <= touchBounds.right
6157                    && y >= thumbTop - adjust && y <= thumbTop + thumbLength + adjust) {
6158                return true;
6159            }
6160        }
6161        return false;
6162    }
6163
6164    private boolean isOnHorizontalScrollbarThumb(float x, float y) {
6165        if (mScrollCache == null) {
6166            return false;
6167        }
6168        if (isHorizontalScrollBarEnabled()) {
6169            x += getScrollX();
6170            y += getScrollY();
6171            final Rect bounds = mScrollCache.mScrollBarBounds;
6172            final Rect touchBounds = mScrollCache.mScrollBarTouchBounds;
6173            getHorizontalScrollBarBounds(bounds, touchBounds);
6174            final int range = computeHorizontalScrollRange();
6175            final int offset = computeHorizontalScrollOffset();
6176            final int extent = computeHorizontalScrollExtent();
6177            final int thumbLength = ScrollBarUtils.getThumbLength(bounds.width(), bounds.height(),
6178                    extent, range);
6179            final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.width(), thumbLength,
6180                    extent, range, offset);
6181            final int thumbLeft = bounds.left + thumbOffset;
6182            final int adjust = Math.max(mScrollCache.scrollBarMinTouchTarget - thumbLength, 0) / 2;
6183            if (x >= thumbLeft - adjust && x <= thumbLeft + thumbLength + adjust
6184                    && y >= touchBounds.top && y <= touchBounds.bottom) {
6185                return true;
6186            }
6187        }
6188        return false;
6189    }
6190
6191    boolean isDraggingScrollBar() {
6192        return mScrollCache != null
6193                && mScrollCache.mScrollBarDraggingState != ScrollabilityCache.NOT_DRAGGING;
6194    }
6195
6196    /**
6197     * Sets the state of all scroll indicators.
6198     * <p>
6199     * See {@link #setScrollIndicators(int, int)} for usage information.
6200     *
6201     * @param indicators a bitmask of indicators that should be enabled, or
6202     *                   {@code 0} to disable all indicators
6203     * @see #setScrollIndicators(int, int)
6204     * @see #getScrollIndicators()
6205     * @attr ref android.R.styleable#View_scrollIndicators
6206     */
6207    public void setScrollIndicators(@ScrollIndicators int indicators) {
6208        setScrollIndicators(indicators,
6209                SCROLL_INDICATORS_PFLAG3_MASK >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT);
6210    }
6211
6212    /**
6213     * Sets the state of the scroll indicators specified by the mask. To change
6214     * all scroll indicators at once, see {@link #setScrollIndicators(int)}.
6215     * <p>
6216     * When a scroll indicator is enabled, it will be displayed if the view
6217     * can scroll in the direction of the indicator.
6218     * <p>
6219     * Multiple indicator types may be enabled or disabled by passing the
6220     * logical OR of the desired types. If multiple types are specified, they
6221     * will all be set to the same enabled state.
6222     * <p>
6223     * For example, to enable the top scroll indicatorExample: {@code setScrollIndicators
6224     *
6225     * @param indicators the indicator direction, or the logical OR of multiple
6226     *             indicator directions. One or more of:
6227     *             <ul>
6228     *               <li>{@link #SCROLL_INDICATOR_TOP}</li>
6229     *               <li>{@link #SCROLL_INDICATOR_BOTTOM}</li>
6230     *               <li>{@link #SCROLL_INDICATOR_LEFT}</li>
6231     *               <li>{@link #SCROLL_INDICATOR_RIGHT}</li>
6232     *               <li>{@link #SCROLL_INDICATOR_START}</li>
6233     *               <li>{@link #SCROLL_INDICATOR_END}</li>
6234     *             </ul>
6235     * @see #setScrollIndicators(int)
6236     * @see #getScrollIndicators()
6237     * @attr ref android.R.styleable#View_scrollIndicators
6238     */
6239    public void setScrollIndicators(@ScrollIndicators int indicators, @ScrollIndicators int mask) {
6240        // Shift and sanitize mask.
6241        mask <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
6242        mask &= SCROLL_INDICATORS_PFLAG3_MASK;
6243
6244        // Shift and mask indicators.
6245        indicators <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
6246        indicators &= mask;
6247
6248        // Merge with non-masked flags.
6249        final int updatedFlags = indicators | (mPrivateFlags3 & ~mask);
6250
6251        if (mPrivateFlags3 != updatedFlags) {
6252            mPrivateFlags3 = updatedFlags;
6253
6254            if (indicators != 0) {
6255                initializeScrollIndicatorsInternal();
6256            }
6257            invalidate();
6258        }
6259    }
6260
6261    /**
6262     * Returns a bitmask representing the enabled scroll indicators.
6263     * <p>
6264     * For example, if the top and left scroll indicators are enabled and all
6265     * other indicators are disabled, the return value will be
6266     * {@code View.SCROLL_INDICATOR_TOP | View.SCROLL_INDICATOR_LEFT}.
6267     * <p>
6268     * To check whether the bottom scroll indicator is enabled, use the value
6269     * of {@code (getScrollIndicators() & View.SCROLL_INDICATOR_BOTTOM) != 0}.
6270     *
6271     * @return a bitmask representing the enabled scroll indicators
6272     */
6273    @ScrollIndicators
6274    public int getScrollIndicators() {
6275        return (mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK)
6276                >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
6277    }
6278
6279    ListenerInfo getListenerInfo() {
6280        if (mListenerInfo != null) {
6281            return mListenerInfo;
6282        }
6283        mListenerInfo = new ListenerInfo();
6284        return mListenerInfo;
6285    }
6286
6287    /**
6288     * Register a callback to be invoked when the scroll X or Y positions of
6289     * this view change.
6290     * <p>
6291     * <b>Note:</b> Some views handle scrolling independently from View and may
6292     * have their own separate listeners for scroll-type events. For example,
6293     * {@link android.widget.ListView ListView} allows clients to register an
6294     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
6295     * to listen for changes in list scroll position.
6296     *
6297     * @param l The listener to notify when the scroll X or Y position changes.
6298     * @see android.view.View#getScrollX()
6299     * @see android.view.View#getScrollY()
6300     */
6301    public void setOnScrollChangeListener(OnScrollChangeListener l) {
6302        getListenerInfo().mOnScrollChangeListener = l;
6303    }
6304
6305    /**
6306     * Register a callback to be invoked when focus of this view changed.
6307     *
6308     * @param l The callback that will run.
6309     */
6310    public void setOnFocusChangeListener(OnFocusChangeListener l) {
6311        getListenerInfo().mOnFocusChangeListener = l;
6312    }
6313
6314    /**
6315     * Add a listener that will be called when the bounds of the view change due to
6316     * layout processing.
6317     *
6318     * @param listener The listener that will be called when layout bounds change.
6319     */
6320    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
6321        ListenerInfo li = getListenerInfo();
6322        if (li.mOnLayoutChangeListeners == null) {
6323            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
6324        }
6325        if (!li.mOnLayoutChangeListeners.contains(listener)) {
6326            li.mOnLayoutChangeListeners.add(listener);
6327        }
6328    }
6329
6330    /**
6331     * Remove a listener for layout changes.
6332     *
6333     * @param listener The listener for layout bounds change.
6334     */
6335    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
6336        ListenerInfo li = mListenerInfo;
6337        if (li == null || li.mOnLayoutChangeListeners == null) {
6338            return;
6339        }
6340        li.mOnLayoutChangeListeners.remove(listener);
6341    }
6342
6343    /**
6344     * Add a listener for attach state changes.
6345     *
6346     * This listener will be called whenever this view is attached or detached
6347     * from a window. Remove the listener using
6348     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
6349     *
6350     * @param listener Listener to attach
6351     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
6352     */
6353    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
6354        ListenerInfo li = getListenerInfo();
6355        if (li.mOnAttachStateChangeListeners == null) {
6356            li.mOnAttachStateChangeListeners
6357                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
6358        }
6359        li.mOnAttachStateChangeListeners.add(listener);
6360    }
6361
6362    /**
6363     * Remove a listener for attach state changes. The listener will receive no further
6364     * notification of window attach/detach events.
6365     *
6366     * @param listener Listener to remove
6367     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
6368     */
6369    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
6370        ListenerInfo li = mListenerInfo;
6371        if (li == null || li.mOnAttachStateChangeListeners == null) {
6372            return;
6373        }
6374        li.mOnAttachStateChangeListeners.remove(listener);
6375    }
6376
6377    /**
6378     * Returns the focus-change callback registered for this view.
6379     *
6380     * @return The callback, or null if one is not registered.
6381     */
6382    public OnFocusChangeListener getOnFocusChangeListener() {
6383        ListenerInfo li = mListenerInfo;
6384        return li != null ? li.mOnFocusChangeListener : null;
6385    }
6386
6387    /**
6388     * Register a callback to be invoked when this view is clicked. If this view is not
6389     * clickable, it becomes clickable.
6390     *
6391     * @param l The callback that will run
6392     *
6393     * @see #setClickable(boolean)
6394     */
6395    public void setOnClickListener(@Nullable OnClickListener l) {
6396        if (!isClickable()) {
6397            setClickable(true);
6398        }
6399        getListenerInfo().mOnClickListener = l;
6400    }
6401
6402    /**
6403     * Return whether this view has an attached OnClickListener.  Returns
6404     * true if there is a listener, false if there is none.
6405     */
6406    public boolean hasOnClickListeners() {
6407        ListenerInfo li = mListenerInfo;
6408        return (li != null && li.mOnClickListener != null);
6409    }
6410
6411    /**
6412     * Register a callback to be invoked when this view is clicked and held. If this view is not
6413     * long clickable, it becomes long clickable.
6414     *
6415     * @param l The callback that will run
6416     *
6417     * @see #setLongClickable(boolean)
6418     */
6419    public void setOnLongClickListener(@Nullable OnLongClickListener l) {
6420        if (!isLongClickable()) {
6421            setLongClickable(true);
6422        }
6423        getListenerInfo().mOnLongClickListener = l;
6424    }
6425
6426    /**
6427     * Register a callback to be invoked when this view is context clicked. If the view is not
6428     * context clickable, it becomes context clickable.
6429     *
6430     * @param l The callback that will run
6431     * @see #setContextClickable(boolean)
6432     */
6433    public void setOnContextClickListener(@Nullable OnContextClickListener l) {
6434        if (!isContextClickable()) {
6435            setContextClickable(true);
6436        }
6437        getListenerInfo().mOnContextClickListener = l;
6438    }
6439
6440    /**
6441     * Register a callback to be invoked when the context menu for this view is
6442     * being built. If this view is not long clickable, it becomes long clickable.
6443     *
6444     * @param l The callback that will run
6445     *
6446     */
6447    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
6448        if (!isLongClickable()) {
6449            setLongClickable(true);
6450        }
6451        getListenerInfo().mOnCreateContextMenuListener = l;
6452    }
6453
6454    /**
6455     * Set an observer to collect stats for each frame rendered for this view.
6456     *
6457     * @hide
6458     */
6459    public void addFrameMetricsListener(Window window,
6460            Window.OnFrameMetricsAvailableListener listener,
6461            Handler handler) {
6462        if (mAttachInfo != null) {
6463            if (mAttachInfo.mThreadedRenderer != null) {
6464                if (mFrameMetricsObservers == null) {
6465                    mFrameMetricsObservers = new ArrayList<>();
6466                }
6467
6468                FrameMetricsObserver fmo = new FrameMetricsObserver(window,
6469                        handler.getLooper(), listener);
6470                mFrameMetricsObservers.add(fmo);
6471                mAttachInfo.mThreadedRenderer.addFrameMetricsObserver(fmo);
6472            } else {
6473                Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats");
6474            }
6475        } else {
6476            if (mFrameMetricsObservers == null) {
6477                mFrameMetricsObservers = new ArrayList<>();
6478            }
6479
6480            FrameMetricsObserver fmo = new FrameMetricsObserver(window,
6481                    handler.getLooper(), listener);
6482            mFrameMetricsObservers.add(fmo);
6483        }
6484    }
6485
6486    /**
6487     * Remove observer configured to collect frame stats for this view.
6488     *
6489     * @hide
6490     */
6491    public void removeFrameMetricsListener(
6492            Window.OnFrameMetricsAvailableListener listener) {
6493        ThreadedRenderer renderer = getThreadedRenderer();
6494        FrameMetricsObserver fmo = findFrameMetricsObserver(listener);
6495        if (fmo == null) {
6496            throw new IllegalArgumentException(
6497                    "attempt to remove OnFrameMetricsAvailableListener that was never added");
6498        }
6499
6500        if (mFrameMetricsObservers != null) {
6501            mFrameMetricsObservers.remove(fmo);
6502            if (renderer != null) {
6503                renderer.removeFrameMetricsObserver(fmo);
6504            }
6505        }
6506    }
6507
6508    private void registerPendingFrameMetricsObservers() {
6509        if (mFrameMetricsObservers != null) {
6510            ThreadedRenderer renderer = getThreadedRenderer();
6511            if (renderer != null) {
6512                for (FrameMetricsObserver fmo : mFrameMetricsObservers) {
6513                    renderer.addFrameMetricsObserver(fmo);
6514                }
6515            } else {
6516                Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats");
6517            }
6518        }
6519    }
6520
6521    private FrameMetricsObserver findFrameMetricsObserver(
6522            Window.OnFrameMetricsAvailableListener listener) {
6523        for (int i = 0; i < mFrameMetricsObservers.size(); i++) {
6524            FrameMetricsObserver observer = mFrameMetricsObservers.get(i);
6525            if (observer.mListener == listener) {
6526                return observer;
6527            }
6528        }
6529
6530        return null;
6531    }
6532
6533    /** @hide */
6534    public void setNotifyAutofillManagerOnClick(boolean notify) {
6535        if (notify) {
6536            mPrivateFlags |= PFLAG_NOTIFY_AUTOFILL_MANAGER_ON_CLICK;
6537        } else {
6538            mPrivateFlags &= ~PFLAG_NOTIFY_AUTOFILL_MANAGER_ON_CLICK;
6539        }
6540    }
6541
6542    private void notifyAutofillManagerOnClick() {
6543        if ((mPrivateFlags & PFLAG_NOTIFY_AUTOFILL_MANAGER_ON_CLICK) != 0) {
6544            try {
6545                getAutofillManager().notifyViewClicked(this);
6546            } finally {
6547                // Set it to already called so it's not called twice when called by
6548                // performClickInternal()
6549                mPrivateFlags &= ~PFLAG_NOTIFY_AUTOFILL_MANAGER_ON_CLICK;
6550            }
6551        }
6552    }
6553
6554    /**
6555     * Entry point for {@link #performClick()} - other methods on View should call it instead of
6556     * {@code performClick()} directly to make sure the autofill manager is notified when
6557     * necessary (as subclasses could extend {@code performClick()} without calling the parent's
6558     * method).
6559     */
6560    private boolean performClickInternal() {
6561        // Must notify autofill manager before performing the click actions to avoid scenarios where
6562        // the app has a click listener that changes the state of views the autofill service might
6563        // be interested on.
6564        notifyAutofillManagerOnClick();
6565
6566        return performClick();
6567    }
6568
6569    /**
6570     * Call this view's OnClickListener, if it is defined.  Performs all normal
6571     * actions associated with clicking: reporting accessibility event, playing
6572     * a sound, etc.
6573     *
6574     * @return True there was an assigned OnClickListener that was called, false
6575     *         otherwise is returned.
6576     */
6577    // NOTE: other methods on View should not call this method directly, but performClickInternal()
6578    // instead, to guarantee that the autofill manager is notified when necessary (as subclasses
6579    // could extend this method without calling super.performClick()).
6580    public boolean performClick() {
6581        // We still need to call this method to handle the cases where performClick() was called
6582        // externally, instead of through performClickInternal()
6583        notifyAutofillManagerOnClick();
6584
6585        final boolean result;
6586        final ListenerInfo li = mListenerInfo;
6587        if (li != null && li.mOnClickListener != null) {
6588            playSoundEffect(SoundEffectConstants.CLICK);
6589            li.mOnClickListener.onClick(this);
6590            result = true;
6591        } else {
6592            result = false;
6593        }
6594
6595        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
6596
6597        notifyEnterOrExitForAutoFillIfNeeded(true);
6598
6599        return result;
6600    }
6601
6602    /**
6603     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
6604     * this only calls the listener, and does not do any associated clicking
6605     * actions like reporting an accessibility event.
6606     *
6607     * @return True there was an assigned OnClickListener that was called, false
6608     *         otherwise is returned.
6609     */
6610    public boolean callOnClick() {
6611        ListenerInfo li = mListenerInfo;
6612        if (li != null && li.mOnClickListener != null) {
6613            li.mOnClickListener.onClick(this);
6614            return true;
6615        }
6616        return false;
6617    }
6618
6619    /**
6620     * Calls this view's OnLongClickListener, if it is defined. Invokes the
6621     * context menu if the OnLongClickListener did not consume the event.
6622     *
6623     * @return {@code true} if one of the above receivers consumed the event,
6624     *         {@code false} otherwise
6625     */
6626    public boolean performLongClick() {
6627        return performLongClickInternal(mLongClickX, mLongClickY);
6628    }
6629
6630    /**
6631     * Calls this view's OnLongClickListener, if it is defined. Invokes the
6632     * context menu if the OnLongClickListener did not consume the event,
6633     * anchoring it to an (x,y) coordinate.
6634     *
6635     * @param x x coordinate of the anchoring touch event, or {@link Float#NaN}
6636     *          to disable anchoring
6637     * @param y y coordinate of the anchoring touch event, or {@link Float#NaN}
6638     *          to disable anchoring
6639     * @return {@code true} if one of the above receivers consumed the event,
6640     *         {@code false} otherwise
6641     */
6642    public boolean performLongClick(float x, float y) {
6643        mLongClickX = x;
6644        mLongClickY = y;
6645        final boolean handled = performLongClick();
6646        mLongClickX = Float.NaN;
6647        mLongClickY = Float.NaN;
6648        return handled;
6649    }
6650
6651    /**
6652     * Calls this view's OnLongClickListener, if it is defined. Invokes the
6653     * context menu if the OnLongClickListener did not consume the event,
6654     * optionally anchoring it to an (x,y) coordinate.
6655     *
6656     * @param x x coordinate of the anchoring touch event, or {@link Float#NaN}
6657     *          to disable anchoring
6658     * @param y y coordinate of the anchoring touch event, or {@link Float#NaN}
6659     *          to disable anchoring
6660     * @return {@code true} if one of the above receivers consumed the event,
6661     *         {@code false} otherwise
6662     */
6663    private boolean performLongClickInternal(float x, float y) {
6664        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
6665
6666        boolean handled = false;
6667        final ListenerInfo li = mListenerInfo;
6668        if (li != null && li.mOnLongClickListener != null) {
6669            handled = li.mOnLongClickListener.onLongClick(View.this);
6670        }
6671        if (!handled) {
6672            final boolean isAnchored = !Float.isNaN(x) && !Float.isNaN(y);
6673            handled = isAnchored ? showContextMenu(x, y) : showContextMenu();
6674        }
6675        if ((mViewFlags & TOOLTIP) == TOOLTIP) {
6676            if (!handled) {
6677                handled = showLongClickTooltip((int) x, (int) y);
6678            }
6679        }
6680        if (handled) {
6681            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
6682        }
6683        return handled;
6684    }
6685
6686    /**
6687     * Call this view's OnContextClickListener, if it is defined.
6688     *
6689     * @param x the x coordinate of the context click
6690     * @param y the y coordinate of the context click
6691     * @return True if there was an assigned OnContextClickListener that consumed the event, false
6692     *         otherwise.
6693     */
6694    public boolean performContextClick(float x, float y) {
6695        return performContextClick();
6696    }
6697
6698    /**
6699     * Call this view's OnContextClickListener, if it is defined.
6700     *
6701     * @return True if there was an assigned OnContextClickListener that consumed the event, false
6702     *         otherwise.
6703     */
6704    public boolean performContextClick() {
6705        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CONTEXT_CLICKED);
6706
6707        boolean handled = false;
6708        ListenerInfo li = mListenerInfo;
6709        if (li != null && li.mOnContextClickListener != null) {
6710            handled = li.mOnContextClickListener.onContextClick(View.this);
6711        }
6712        if (handled) {
6713            performHapticFeedback(HapticFeedbackConstants.CONTEXT_CLICK);
6714        }
6715        return handled;
6716    }
6717
6718    /**
6719     * Performs button-related actions during a touch down event.
6720     *
6721     * @param event The event.
6722     * @return True if the down was consumed.
6723     *
6724     * @hide
6725     */
6726    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
6727        if (event.isFromSource(InputDevice.SOURCE_MOUSE) &&
6728            (event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
6729            showContextMenu(event.getX(), event.getY());
6730            mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
6731            return true;
6732        }
6733        return false;
6734    }
6735
6736    /**
6737     * Shows the context menu for this view.
6738     *
6739     * @return {@code true} if the context menu was shown, {@code false}
6740     *         otherwise
6741     * @see #showContextMenu(float, float)
6742     */
6743    public boolean showContextMenu() {
6744        return getParent().showContextMenuForChild(this);
6745    }
6746
6747    /**
6748     * Shows the context menu for this view anchored to the specified
6749     * view-relative coordinate.
6750     *
6751     * @param x the X coordinate in pixels relative to the view to which the
6752     *          menu should be anchored, or {@link Float#NaN} to disable anchoring
6753     * @param y the Y coordinate in pixels relative to the view to which the
6754     *          menu should be anchored, or {@link Float#NaN} to disable anchoring
6755     * @return {@code true} if the context menu was shown, {@code false}
6756     *         otherwise
6757     */
6758    public boolean showContextMenu(float x, float y) {
6759        return getParent().showContextMenuForChild(this, x, y);
6760    }
6761
6762    /**
6763     * Start an action mode with the default type {@link ActionMode#TYPE_PRIMARY}.
6764     *
6765     * @param callback Callback that will control the lifecycle of the action mode
6766     * @return The new action mode if it is started, null otherwise
6767     *
6768     * @see ActionMode
6769     * @see #startActionMode(android.view.ActionMode.Callback, int)
6770     */
6771    public ActionMode startActionMode(ActionMode.Callback callback) {
6772        return startActionMode(callback, ActionMode.TYPE_PRIMARY);
6773    }
6774
6775    /**
6776     * Start an action mode with the given type.
6777     *
6778     * @param callback Callback that will control the lifecycle of the action mode
6779     * @param type One of {@link ActionMode#TYPE_PRIMARY} or {@link ActionMode#TYPE_FLOATING}.
6780     * @return The new action mode if it is started, null otherwise
6781     *
6782     * @see ActionMode
6783     */
6784    public ActionMode startActionMode(ActionMode.Callback callback, int type) {
6785        ViewParent parent = getParent();
6786        if (parent == null) return null;
6787        try {
6788            return parent.startActionModeForChild(this, callback, type);
6789        } catch (AbstractMethodError ame) {
6790            // Older implementations of custom views might not implement this.
6791            return parent.startActionModeForChild(this, callback);
6792        }
6793    }
6794
6795    /**
6796     * Call {@link Context#startActivityForResult(String, Intent, int, Bundle)} for the View's
6797     * Context, creating a unique View identifier to retrieve the result.
6798     *
6799     * @param intent The Intent to be started.
6800     * @param requestCode The request code to use.
6801     * @hide
6802     */
6803    public void startActivityForResult(Intent intent, int requestCode) {
6804        mStartActivityRequestWho = "@android:view:" + System.identityHashCode(this);
6805        getContext().startActivityForResult(mStartActivityRequestWho, intent, requestCode, null);
6806    }
6807
6808    /**
6809     * If this View corresponds to the calling who, dispatches the activity result.
6810     * @param who The identifier for the targeted View to receive the result.
6811     * @param requestCode The integer request code originally supplied to
6812     *                    startActivityForResult(), allowing you to identify who this
6813     *                    result came from.
6814     * @param resultCode The integer result code returned by the child activity
6815     *                   through its setResult().
6816     * @param data An Intent, which can return result data to the caller
6817     *               (various data can be attached to Intent "extras").
6818     * @return {@code true} if the activity result was dispatched.
6819     * @hide
6820     */
6821    public boolean dispatchActivityResult(
6822            String who, int requestCode, int resultCode, Intent data) {
6823        if (mStartActivityRequestWho != null && mStartActivityRequestWho.equals(who)) {
6824            onActivityResult(requestCode, resultCode, data);
6825            mStartActivityRequestWho = null;
6826            return true;
6827        }
6828        return false;
6829    }
6830
6831    /**
6832     * Receive the result from a previous call to {@link #startActivityForResult(Intent, int)}.
6833     *
6834     * @param requestCode The integer request code originally supplied to
6835     *                    startActivityForResult(), allowing you to identify who this
6836     *                    result came from.
6837     * @param resultCode The integer result code returned by the child activity
6838     *                   through its setResult().
6839     * @param data An Intent, which can return result data to the caller
6840     *               (various data can be attached to Intent "extras").
6841     * @hide
6842     */
6843    public void onActivityResult(int requestCode, int resultCode, Intent data) {
6844        // Do nothing.
6845    }
6846
6847    /**
6848     * Register a callback to be invoked when a hardware key is pressed in this view.
6849     * Key presses in software input methods will generally not trigger the methods of
6850     * this listener.
6851     * @param l the key listener to attach to this view
6852     */
6853    public void setOnKeyListener(OnKeyListener l) {
6854        getListenerInfo().mOnKeyListener = l;
6855    }
6856
6857    /**
6858     * Register a callback to be invoked when a touch event is sent to this view.
6859     * @param l the touch listener to attach to this view
6860     */
6861    public void setOnTouchListener(OnTouchListener l) {
6862        getListenerInfo().mOnTouchListener = l;
6863    }
6864
6865    /**
6866     * Register a callback to be invoked when a generic motion event is sent to this view.
6867     * @param l the generic motion listener to attach to this view
6868     */
6869    public void setOnGenericMotionListener(OnGenericMotionListener l) {
6870        getListenerInfo().mOnGenericMotionListener = l;
6871    }
6872
6873    /**
6874     * Register a callback to be invoked when a hover event is sent to this view.
6875     * @param l the hover listener to attach to this view
6876     */
6877    public void setOnHoverListener(OnHoverListener l) {
6878        getListenerInfo().mOnHoverListener = l;
6879    }
6880
6881    /**
6882     * Register a drag event listener callback object for this View. The parameter is
6883     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
6884     * View, the system calls the
6885     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
6886     * @param l An implementation of {@link android.view.View.OnDragListener}.
6887     */
6888    public void setOnDragListener(OnDragListener l) {
6889        getListenerInfo().mOnDragListener = l;
6890    }
6891
6892    /**
6893     * Give this view focus. This will cause
6894     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
6895     *
6896     * Note: this does not check whether this {@link View} should get focus, it just
6897     * gives it focus no matter what.  It should only be called internally by framework
6898     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
6899     *
6900     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
6901     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
6902     *        focus moved when requestFocus() is called. It may not always
6903     *        apply, in which case use the default View.FOCUS_DOWN.
6904     * @param previouslyFocusedRect The rectangle of the view that had focus
6905     *        prior in this View's coordinate system.
6906     */
6907    void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) {
6908        if (DBG) {
6909            System.out.println(this + " requestFocus()");
6910        }
6911
6912        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
6913            mPrivateFlags |= PFLAG_FOCUSED;
6914
6915            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
6916
6917            if (mParent != null) {
6918                mParent.requestChildFocus(this, this);
6919                updateFocusedInCluster(oldFocus, direction);
6920            }
6921
6922            if (mAttachInfo != null) {
6923                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
6924            }
6925
6926            onFocusChanged(true, direction, previouslyFocusedRect);
6927            refreshDrawableState();
6928        }
6929    }
6930
6931    /**
6932     * Sets this view's preference for reveal behavior when it gains focus.
6933     *
6934     * <p>When set to true, this is a signal to ancestor views in the hierarchy that
6935     * this view would prefer to be brought fully into view when it gains focus.
6936     * For example, a text field that a user is meant to type into. Other views such
6937     * as scrolling containers may prefer to opt-out of this behavior.</p>
6938     *
6939     * <p>The default value for views is true, though subclasses may change this
6940     * based on their preferred behavior.</p>
6941     *
6942     * @param revealOnFocus true to request reveal on focus in ancestors, false otherwise
6943     *
6944     * @see #getRevealOnFocusHint()
6945     */
6946    public final void setRevealOnFocusHint(boolean revealOnFocus) {
6947        if (revealOnFocus) {
6948            mPrivateFlags3 &= ~PFLAG3_NO_REVEAL_ON_FOCUS;
6949        } else {
6950            mPrivateFlags3 |= PFLAG3_NO_REVEAL_ON_FOCUS;
6951        }
6952    }
6953
6954    /**
6955     * Returns this view's preference for reveal behavior when it gains focus.
6956     *
6957     * <p>When this method returns true for a child view requesting focus, ancestor
6958     * views responding to a focus change in {@link ViewParent#requestChildFocus(View, View)}
6959     * should make a best effort to make the newly focused child fully visible to the user.
6960     * When it returns false, ancestor views should preferably not disrupt scroll positioning or
6961     * other properties affecting visibility to the user as part of the focus change.</p>
6962     *
6963     * @return true if this view would prefer to become fully visible when it gains focus,
6964     *         false if it would prefer not to disrupt scroll positioning
6965     *
6966     * @see #setRevealOnFocusHint(boolean)
6967     */
6968    public final boolean getRevealOnFocusHint() {
6969        return (mPrivateFlags3 & PFLAG3_NO_REVEAL_ON_FOCUS) == 0;
6970    }
6971
6972    /**
6973     * Populates <code>outRect</code> with the hotspot bounds. By default,
6974     * the hotspot bounds are identical to the screen bounds.
6975     *
6976     * @param outRect rect to populate with hotspot bounds
6977     * @hide Only for internal use by views and widgets.
6978     */
6979    public void getHotspotBounds(Rect outRect) {
6980        final Drawable background = getBackground();
6981        if (background != null) {
6982            background.getHotspotBounds(outRect);
6983        } else {
6984            getBoundsOnScreen(outRect);
6985        }
6986    }
6987
6988    /**
6989     * Request that a rectangle of this view be visible on the screen,
6990     * scrolling if necessary just enough.
6991     *
6992     * <p>A View should call this if it maintains some notion of which part
6993     * of its content is interesting.  For example, a text editing view
6994     * should call this when its cursor moves.
6995     * <p>The Rectangle passed into this method should be in the View's content coordinate space.
6996     * It should not be affected by which part of the View is currently visible or its scroll
6997     * position.
6998     *
6999     * @param rectangle The rectangle in the View's content coordinate space
7000     * @return Whether any parent scrolled.
7001     */
7002    public boolean requestRectangleOnScreen(Rect rectangle) {
7003        return requestRectangleOnScreen(rectangle, false);
7004    }
7005
7006    /**
7007     * Request that a rectangle of this view be visible on the screen,
7008     * scrolling if necessary just enough.
7009     *
7010     * <p>A View should call this if it maintains some notion of which part
7011     * of its content is interesting.  For example, a text editing view
7012     * should call this when its cursor moves.
7013     * <p>The Rectangle passed into this method should be in the View's content coordinate space.
7014     * It should not be affected by which part of the View is currently visible or its scroll
7015     * position.
7016     * <p>When <code>immediate</code> is set to true, scrolling will not be
7017     * animated.
7018     *
7019     * @param rectangle The rectangle in the View's content coordinate space
7020     * @param immediate True to forbid animated scrolling, false otherwise
7021     * @return Whether any parent scrolled.
7022     */
7023    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
7024        if (mParent == null) {
7025            return false;
7026        }
7027
7028        View child = this;
7029
7030        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
7031        position.set(rectangle);
7032
7033        ViewParent parent = mParent;
7034        boolean scrolled = false;
7035        while (parent != null) {
7036            rectangle.set((int) position.left, (int) position.top,
7037                    (int) position.right, (int) position.bottom);
7038
7039            scrolled |= parent.requestChildRectangleOnScreen(child, rectangle, immediate);
7040
7041            if (!(parent instanceof View)) {
7042                break;
7043            }
7044
7045            // move it from child's content coordinate space to parent's content coordinate space
7046            position.offset(child.mLeft - child.getScrollX(), child.mTop -child.getScrollY());
7047
7048            child = (View) parent;
7049            parent = child.getParent();
7050        }
7051
7052        return scrolled;
7053    }
7054
7055    /**
7056     * Called when this view wants to give up focus. If focus is cleared
7057     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
7058     * <p>
7059     * <strong>Note:</strong> When not in touch-mode, the framework will try to give focus
7060     * to the first focusable View from the top after focus is cleared. Hence, if this
7061     * View is the first from the top that can take focus, then all callbacks
7062     * related to clearing focus will be invoked after which the framework will
7063     * give focus to this view.
7064     * </p>
7065     */
7066    public void clearFocus() {
7067        if (DBG) {
7068            System.out.println(this + " clearFocus()");
7069        }
7070
7071        final boolean refocus = sAlwaysAssignFocus || !isInTouchMode();
7072        clearFocusInternal(null, true, refocus);
7073    }
7074
7075    /**
7076     * Clears focus from the view, optionally propagating the change up through
7077     * the parent hierarchy and requesting that the root view place new focus.
7078     *
7079     * @param propagate whether to propagate the change up through the parent
7080     *            hierarchy
7081     * @param refocus when propagate is true, specifies whether to request the
7082     *            root view place new focus
7083     */
7084    void clearFocusInternal(View focused, boolean propagate, boolean refocus) {
7085        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
7086            mPrivateFlags &= ~PFLAG_FOCUSED;
7087            clearParentsWantFocus();
7088
7089            if (propagate && mParent != null) {
7090                mParent.clearChildFocus(this);
7091            }
7092
7093            onFocusChanged(false, 0, null);
7094            refreshDrawableState();
7095
7096            if (propagate && (!refocus || !rootViewRequestFocus())) {
7097                notifyGlobalFocusCleared(this);
7098            }
7099        }
7100    }
7101
7102    void notifyGlobalFocusCleared(View oldFocus) {
7103        if (oldFocus != null && mAttachInfo != null) {
7104            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
7105        }
7106    }
7107
7108    boolean rootViewRequestFocus() {
7109        final View root = getRootView();
7110        return root != null && root.requestFocus();
7111    }
7112
7113    /**
7114     * Called internally by the view system when a new view is getting focus.
7115     * This is what clears the old focus.
7116     * <p>
7117     * <b>NOTE:</b> The parent view's focused child must be updated manually
7118     * after calling this method. Otherwise, the view hierarchy may be left in
7119     * an inconstent state.
7120     */
7121    void unFocus(View focused) {
7122        if (DBG) {
7123            System.out.println(this + " unFocus()");
7124        }
7125
7126        clearFocusInternal(focused, false, false);
7127    }
7128
7129    /**
7130     * Returns true if this view has focus itself, or is the ancestor of the
7131     * view that has focus.
7132     *
7133     * @return True if this view has or contains focus, false otherwise.
7134     */
7135    @ViewDebug.ExportedProperty(category = "focus")
7136    public boolean hasFocus() {
7137        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
7138    }
7139
7140    /**
7141     * Returns true if this view is focusable or if it contains a reachable View
7142     * for which {@link #hasFocusable()} returns {@code true}. A "reachable hasFocusable()"
7143     * is a view whose parents do not block descendants focus.
7144     * Only {@link #VISIBLE} views are considered focusable.
7145     *
7146     * <p>As of {@link Build.VERSION_CODES#O} views that are determined to be focusable
7147     * through {@link #FOCUSABLE_AUTO} will also cause this method to return {@code true}.
7148     * Apps that declare a {@link android.content.pm.ApplicationInfo#targetSdkVersion} of
7149     * earlier than {@link Build.VERSION_CODES#O} will continue to see this method return
7150     * {@code false} for views not explicitly marked as focusable.
7151     * Use {@link #hasExplicitFocusable()} if you require the pre-{@link Build.VERSION_CODES#O}
7152     * behavior.</p>
7153     *
7154     * @return {@code true} if the view is focusable or if the view contains a focusable
7155     *         view, {@code false} otherwise
7156     *
7157     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
7158     * @see ViewGroup#getTouchscreenBlocksFocus()
7159     * @see #hasExplicitFocusable()
7160     */
7161    public boolean hasFocusable() {
7162        return hasFocusable(!sHasFocusableExcludeAutoFocusable, false);
7163    }
7164
7165    /**
7166     * Returns true if this view is focusable or if it contains a reachable View
7167     * for which {@link #hasExplicitFocusable()} returns {@code true}.
7168     * A "reachable hasExplicitFocusable()" is a view whose parents do not block descendants focus.
7169     * Only {@link #VISIBLE} views for which {@link #getFocusable()} would return
7170     * {@link #FOCUSABLE} are considered focusable.
7171     *
7172     * <p>This method preserves the pre-{@link Build.VERSION_CODES#O} behavior of
7173     * {@link #hasFocusable()} in that only views explicitly set focusable will cause
7174     * this method to return true. A view set to {@link #FOCUSABLE_AUTO} that resolves
7175     * to focusable will not.</p>
7176     *
7177     * @return {@code true} if the view is focusable or if the view contains a focusable
7178     *         view, {@code false} otherwise
7179     *
7180     * @see #hasFocusable()
7181     */
7182    public boolean hasExplicitFocusable() {
7183        return hasFocusable(false, true);
7184    }
7185
7186    boolean hasFocusable(boolean allowAutoFocus, boolean dispatchExplicit) {
7187        if (!isFocusableInTouchMode()) {
7188            for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) {
7189                final ViewGroup g = (ViewGroup) p;
7190                if (g.shouldBlockFocusForTouchscreen()) {
7191                    return false;
7192                }
7193            }
7194        }
7195
7196        // Invisible, gone, or disabled views are never focusable.
7197        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE
7198                || (mViewFlags & ENABLED_MASK) != ENABLED) {
7199            return false;
7200        }
7201
7202        // Only use effective focusable value when allowed.
7203        if ((allowAutoFocus || getFocusable() != FOCUSABLE_AUTO) && isFocusable()) {
7204            return true;
7205        }
7206
7207        return false;
7208    }
7209
7210    /**
7211     * Called by the view system when the focus state of this view changes.
7212     * When the focus change event is caused by directional navigation, direction
7213     * and previouslyFocusedRect provide insight into where the focus is coming from.
7214     * When overriding, be sure to call up through to the super class so that
7215     * the standard focus handling will occur.
7216     *
7217     * @param gainFocus True if the View has focus; false otherwise.
7218     * @param direction The direction focus has moved when requestFocus()
7219     *                  is called to give this view focus. Values are
7220     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
7221     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
7222     *                  It may not always apply, in which case use the default.
7223     * @param previouslyFocusedRect The rectangle, in this view's coordinate
7224     *        system, of the previously focused view.  If applicable, this will be
7225     *        passed in as finer grained information about where the focus is coming
7226     *        from (in addition to direction).  Will be <code>null</code> otherwise.
7227     */
7228    @CallSuper
7229    protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction,
7230            @Nullable Rect previouslyFocusedRect) {
7231        if (gainFocus) {
7232            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
7233        } else {
7234            notifyViewAccessibilityStateChangedIfNeeded(
7235                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7236        }
7237
7238        // Here we check whether we still need the default focus highlight, and switch it on/off.
7239        switchDefaultFocusHighlight();
7240
7241        InputMethodManager imm = InputMethodManager.peekInstance();
7242        if (!gainFocus) {
7243            if (isPressed()) {
7244                setPressed(false);
7245            }
7246            if (imm != null && mAttachInfo != null && mAttachInfo.mHasWindowFocus) {
7247                imm.focusOut(this);
7248            }
7249            onFocusLost();
7250        } else if (imm != null && mAttachInfo != null && mAttachInfo.mHasWindowFocus) {
7251            imm.focusIn(this);
7252        }
7253
7254        invalidate(true);
7255        ListenerInfo li = mListenerInfo;
7256        if (li != null && li.mOnFocusChangeListener != null) {
7257            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
7258        }
7259
7260        if (mAttachInfo != null) {
7261            mAttachInfo.mKeyDispatchState.reset(this);
7262        }
7263
7264        notifyEnterOrExitForAutoFillIfNeeded(gainFocus);
7265    }
7266
7267    /** @hide */
7268    public void notifyEnterOrExitForAutoFillIfNeeded(boolean enter) {
7269        if (canNotifyAutofillEnterExitEvent()) {
7270            AutofillManager afm = getAutofillManager();
7271            if (afm != null) {
7272                if (enter && isFocused()) {
7273                    // We have not been laid out yet, hence cannot evaluate
7274                    // whether this view is visible to the user, we will do
7275                    // the evaluation once layout is complete.
7276                    if (!isLaidOut()) {
7277                        mPrivateFlags3 |= PFLAG3_NOTIFY_AUTOFILL_ENTER_ON_LAYOUT;
7278                    } else if (isVisibleToUser()) {
7279                        // TODO This is a potential problem that View gets focus before it's visible
7280                        // to User. Ideally View should handle the event when isVisibleToUser()
7281                        // becomes true where it should issue notifyViewEntered().
7282                        afm.notifyViewEntered(this);
7283                    }
7284                } else if (!enter && !isFocused()) {
7285                    afm.notifyViewExited(this);
7286                }
7287            }
7288        }
7289    }
7290
7291    /**
7292     * Visually distinct portion of a window with window-like semantics are considered panes for
7293     * accessibility purposes. One example is the content view of a fragment that is replaced.
7294     * In order for accessibility services to understand a pane's window-like behavior, panes
7295     * should have descriptive titles. Views with pane titles produce {@link AccessibilityEvent}s
7296     * when they appear, disappear, or change title.
7297     *
7298     * @param accessibilityPaneTitle The pane's title. Setting to {@code null} indicates that this
7299     *                               View is not a pane.
7300     *
7301     * {@see AccessibilityNodeInfo#setPaneTitle(CharSequence)}
7302     */
7303    public void setAccessibilityPaneTitle(@Nullable CharSequence accessibilityPaneTitle) {
7304        if (!TextUtils.equals(accessibilityPaneTitle, mAccessibilityPaneTitle)) {
7305            mAccessibilityPaneTitle = accessibilityPaneTitle;
7306            notifyViewAccessibilityStateChangedIfNeeded(
7307                    AccessibilityEvent.CONTENT_CHANGE_TYPE_PANE_TITLE);
7308        }
7309    }
7310
7311    /**
7312     * Get the title of the pane for purposes of accessibility.
7313     *
7314     * @return The current pane title.
7315     *
7316     * {@see #setAccessibilityPaneTitle}.
7317     */
7318    @Nullable public CharSequence getAccessibilityPaneTitle() {
7319        return mAccessibilityPaneTitle;
7320    }
7321
7322    private boolean isAccessibilityPane() {
7323        return mAccessibilityPaneTitle != null;
7324    }
7325
7326    /**
7327     * Sends an accessibility event of the given type. If accessibility is
7328     * not enabled this method has no effect. The default implementation calls
7329     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
7330     * to populate information about the event source (this View), then calls
7331     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
7332     * populate the text content of the event source including its descendants,
7333     * and last calls
7334     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
7335     * on its parent to request sending of the event to interested parties.
7336     * <p>
7337     * If an {@link AccessibilityDelegate} has been specified via calling
7338     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7339     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
7340     * responsible for handling this call.
7341     * </p>
7342     *
7343     * @param eventType The type of the event to send, as defined by several types from
7344     * {@link android.view.accessibility.AccessibilityEvent}, such as
7345     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
7346     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
7347     *
7348     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
7349     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
7350     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
7351     * @see AccessibilityDelegate
7352     */
7353    public void sendAccessibilityEvent(int eventType) {
7354        if (mAccessibilityDelegate != null) {
7355            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
7356        } else {
7357            sendAccessibilityEventInternal(eventType);
7358        }
7359    }
7360
7361    /**
7362     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
7363     * {@link AccessibilityEvent} to make an announcement which is related to some
7364     * sort of a context change for which none of the events representing UI transitions
7365     * is a good fit. For example, announcing a new page in a book. If accessibility
7366     * is not enabled this method does nothing.
7367     *
7368     * @param text The announcement text.
7369     */
7370    public void announceForAccessibility(CharSequence text) {
7371        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
7372            AccessibilityEvent event = AccessibilityEvent.obtain(
7373                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
7374            onInitializeAccessibilityEvent(event);
7375            event.getText().add(text);
7376            event.setContentDescription(null);
7377            mParent.requestSendAccessibilityEvent(this, event);
7378        }
7379    }
7380
7381    /**
7382     * @see #sendAccessibilityEvent(int)
7383     *
7384     * Note: Called from the default {@link AccessibilityDelegate}.
7385     *
7386     * @hide
7387     */
7388    public void sendAccessibilityEventInternal(int eventType) {
7389        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
7390            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
7391        }
7392    }
7393
7394    /**
7395     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
7396     * takes as an argument an empty {@link AccessibilityEvent} and does not
7397     * perform a check whether accessibility is enabled.
7398     * <p>
7399     * If an {@link AccessibilityDelegate} has been specified via calling
7400     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7401     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
7402     * is responsible for handling this call.
7403     * </p>
7404     *
7405     * @param event The event to send.
7406     *
7407     * @see #sendAccessibilityEvent(int)
7408     */
7409    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
7410        if (mAccessibilityDelegate != null) {
7411            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
7412        } else {
7413            sendAccessibilityEventUncheckedInternal(event);
7414        }
7415    }
7416
7417    /**
7418     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
7419     *
7420     * Note: Called from the default {@link AccessibilityDelegate}.
7421     *
7422     * @hide
7423     */
7424    public void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
7425        // Panes disappearing are relevant even if though the view is no longer visible.
7426        boolean isWindowStateChanged =
7427                (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
7428        boolean isWindowDisappearedEvent = isWindowStateChanged && ((event.getContentChangeTypes()
7429                & AccessibilityEvent.CONTENT_CHANGE_TYPE_PANE_DISAPPEARED) != 0);
7430        if (!isShown() && !isWindowDisappearedEvent) {
7431            return;
7432        }
7433        onInitializeAccessibilityEvent(event);
7434        // Only a subset of accessibility events populates text content.
7435        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
7436            dispatchPopulateAccessibilityEvent(event);
7437        }
7438        // In the beginning we called #isShown(), so we know that getParent() is not null.
7439        ViewParent parent = getParent();
7440        if (parent != null) {
7441            getParent().requestSendAccessibilityEvent(this, event);
7442        }
7443    }
7444
7445    /**
7446     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
7447     * to its children for adding their text content to the event. Note that the
7448     * event text is populated in a separate dispatch path since we add to the
7449     * event not only the text of the source but also the text of all its descendants.
7450     * A typical implementation will call
7451     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
7452     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
7453     * on each child. Override this method if custom population of the event text
7454     * content is required.
7455     * <p>
7456     * If an {@link AccessibilityDelegate} has been specified via calling
7457     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7458     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
7459     * is responsible for handling this call.
7460     * </p>
7461     * <p>
7462     * <em>Note:</em> Accessibility events of certain types are not dispatched for
7463     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
7464     * </p>
7465     *
7466     * @param event The event.
7467     *
7468     * @return True if the event population was completed.
7469     */
7470    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
7471        if (mAccessibilityDelegate != null) {
7472            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
7473        } else {
7474            return dispatchPopulateAccessibilityEventInternal(event);
7475        }
7476    }
7477
7478    /**
7479     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
7480     *
7481     * Note: Called from the default {@link AccessibilityDelegate}.
7482     *
7483     * @hide
7484     */
7485    public boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
7486        onPopulateAccessibilityEvent(event);
7487        return false;
7488    }
7489
7490    /**
7491     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
7492     * giving a chance to this View to populate the accessibility event with its
7493     * text content. While this method is free to modify event
7494     * attributes other than text content, doing so should normally be performed in
7495     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
7496     * <p>
7497     * Example: Adding formatted date string to an accessibility event in addition
7498     *          to the text added by the super implementation:
7499     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
7500     *     super.onPopulateAccessibilityEvent(event);
7501     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
7502     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
7503     *         mCurrentDate.getTimeInMillis(), flags);
7504     *     event.getText().add(selectedDateUtterance);
7505     * }</pre>
7506     * <p>
7507     * If an {@link AccessibilityDelegate} has been specified via calling
7508     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7509     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
7510     * is responsible for handling this call.
7511     * </p>
7512     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
7513     * information to the event, in case the default implementation has basic information to add.
7514     * </p>
7515     *
7516     * @param event The accessibility event which to populate.
7517     *
7518     * @see #sendAccessibilityEvent(int)
7519     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
7520     */
7521    @CallSuper
7522    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
7523        if (mAccessibilityDelegate != null) {
7524            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
7525        } else {
7526            onPopulateAccessibilityEventInternal(event);
7527        }
7528    }
7529
7530    /**
7531     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
7532     *
7533     * Note: Called from the default {@link AccessibilityDelegate}.
7534     *
7535     * @hide
7536     */
7537    public void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
7538        if ((event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED)
7539                && !TextUtils.isEmpty(getAccessibilityPaneTitle())) {
7540            event.getText().add(getAccessibilityPaneTitle());
7541        }
7542    }
7543
7544    /**
7545     * Initializes an {@link AccessibilityEvent} with information about
7546     * this View which is the event source. In other words, the source of
7547     * an accessibility event is the view whose state change triggered firing
7548     * the event.
7549     * <p>
7550     * Example: Setting the password property of an event in addition
7551     *          to properties set by the super implementation:
7552     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
7553     *     super.onInitializeAccessibilityEvent(event);
7554     *     event.setPassword(true);
7555     * }</pre>
7556     * <p>
7557     * If an {@link AccessibilityDelegate} has been specified via calling
7558     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7559     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
7560     * is responsible for handling this call.
7561     * </p>
7562     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
7563     * information to the event, in case the default implementation has basic information to add.
7564     * </p>
7565     * @param event The event to initialize.
7566     *
7567     * @see #sendAccessibilityEvent(int)
7568     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
7569     */
7570    @CallSuper
7571    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
7572        if (mAccessibilityDelegate != null) {
7573            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
7574        } else {
7575            onInitializeAccessibilityEventInternal(event);
7576        }
7577    }
7578
7579    /**
7580     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
7581     *
7582     * Note: Called from the default {@link AccessibilityDelegate}.
7583     *
7584     * @hide
7585     */
7586    public void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
7587        event.setSource(this);
7588        event.setClassName(getAccessibilityClassName());
7589        event.setPackageName(getContext().getPackageName());
7590        event.setEnabled(isEnabled());
7591        event.setContentDescription(mContentDescription);
7592
7593        switch (event.getEventType()) {
7594            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
7595                ArrayList<View> focusablesTempList = (mAttachInfo != null)
7596                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
7597                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
7598                event.setItemCount(focusablesTempList.size());
7599                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
7600                if (mAttachInfo != null) {
7601                    focusablesTempList.clear();
7602                }
7603            } break;
7604            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
7605                CharSequence text = getIterableTextForAccessibility();
7606                if (text != null && text.length() > 0) {
7607                    event.setFromIndex(getAccessibilitySelectionStart());
7608                    event.setToIndex(getAccessibilitySelectionEnd());
7609                    event.setItemCount(text.length());
7610                }
7611            } break;
7612        }
7613    }
7614
7615    /**
7616     * Returns an {@link AccessibilityNodeInfo} representing this view from the
7617     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
7618     * This method is responsible for obtaining an accessibility node info from a
7619     * pool of reusable instances and calling
7620     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
7621     * initialize the former.
7622     * <p>
7623     * Note: The client is responsible for recycling the obtained instance by calling
7624     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
7625     * </p>
7626     *
7627     * @return A populated {@link AccessibilityNodeInfo}.
7628     *
7629     * @see AccessibilityNodeInfo
7630     */
7631    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
7632        if (mAccessibilityDelegate != null) {
7633            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
7634        } else {
7635            return createAccessibilityNodeInfoInternal();
7636        }
7637    }
7638
7639    /**
7640     * @see #createAccessibilityNodeInfo()
7641     *
7642     * @hide
7643     */
7644    public AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
7645        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
7646        if (provider != null) {
7647            return provider.createAccessibilityNodeInfo(AccessibilityNodeProvider.HOST_VIEW_ID);
7648        } else {
7649            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
7650            onInitializeAccessibilityNodeInfo(info);
7651            return info;
7652        }
7653    }
7654
7655    /**
7656     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
7657     * The base implementation sets:
7658     * <ul>
7659     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
7660     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
7661     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
7662     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
7663     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
7664     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
7665     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
7666     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
7667     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
7668     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
7669     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
7670     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
7671     *   <li>{@link AccessibilityNodeInfo#setContextClickable(boolean)}</li>
7672     * </ul>
7673     * <p>
7674     * Subclasses should override this method, call the super implementation,
7675     * and set additional attributes.
7676     * </p>
7677     * <p>
7678     * If an {@link AccessibilityDelegate} has been specified via calling
7679     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7680     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
7681     * is responsible for handling this call.
7682     * </p>
7683     *
7684     * @param info The instance to initialize.
7685     */
7686    @CallSuper
7687    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
7688        if (mAccessibilityDelegate != null) {
7689            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
7690        } else {
7691            onInitializeAccessibilityNodeInfoInternal(info);
7692        }
7693    }
7694
7695    /**
7696     * Gets the location of this view in screen coordinates.
7697     *
7698     * @param outRect The output location
7699     * @hide
7700     */
7701    public void getBoundsOnScreen(Rect outRect) {
7702        getBoundsOnScreen(outRect, false);
7703    }
7704
7705    /**
7706     * Gets the location of this view in screen coordinates.
7707     *
7708     * @param outRect The output location
7709     * @param clipToParent Whether to clip child bounds to the parent ones.
7710     * @hide
7711     */
7712    public void getBoundsOnScreen(Rect outRect, boolean clipToParent) {
7713        if (mAttachInfo == null) {
7714            return;
7715        }
7716
7717        RectF position = mAttachInfo.mTmpTransformRect;
7718        position.set(0, 0, mRight - mLeft, mBottom - mTop);
7719        mapRectFromViewToScreenCoords(position, clipToParent);
7720        outRect.set(Math.round(position.left), Math.round(position.top),
7721                Math.round(position.right), Math.round(position.bottom));
7722    }
7723
7724    /**
7725     * Map a rectangle from view-relative coordinates to screen-relative coordinates
7726     *
7727     * @param rect The rectangle to be mapped
7728     * @param clipToParent Whether to clip child bounds to the parent ones.
7729     * @hide
7730     */
7731    public void mapRectFromViewToScreenCoords(RectF rect, boolean clipToParent) {
7732        if (!hasIdentityMatrix()) {
7733            getMatrix().mapRect(rect);
7734        }
7735
7736        rect.offset(mLeft, mTop);
7737
7738        ViewParent parent = mParent;
7739        while (parent instanceof View) {
7740            View parentView = (View) parent;
7741
7742            rect.offset(-parentView.mScrollX, -parentView.mScrollY);
7743
7744            if (clipToParent) {
7745                rect.left = Math.max(rect.left, 0);
7746                rect.top = Math.max(rect.top, 0);
7747                rect.right = Math.min(rect.right, parentView.getWidth());
7748                rect.bottom = Math.min(rect.bottom, parentView.getHeight());
7749            }
7750
7751            if (!parentView.hasIdentityMatrix()) {
7752                parentView.getMatrix().mapRect(rect);
7753            }
7754
7755            rect.offset(parentView.mLeft, parentView.mTop);
7756
7757            parent = parentView.mParent;
7758        }
7759
7760        if (parent instanceof ViewRootImpl) {
7761            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
7762            rect.offset(0, -viewRootImpl.mCurScrollY);
7763        }
7764
7765        rect.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
7766    }
7767
7768    /**
7769     * Return the class name of this object to be used for accessibility purposes.
7770     * Subclasses should only override this if they are implementing something that
7771     * should be seen as a completely new class of view when used by accessibility,
7772     * unrelated to the class it is deriving from.  This is used to fill in
7773     * {@link AccessibilityNodeInfo#setClassName AccessibilityNodeInfo.setClassName}.
7774     */
7775    public CharSequence getAccessibilityClassName() {
7776        return View.class.getName();
7777    }
7778
7779    /**
7780     * Called when assist structure is being retrieved from a view as part of
7781     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData}.
7782     * @param structure Fill in with structured view data.  The default implementation
7783     * fills in all data that can be inferred from the view itself.
7784     */
7785    public void onProvideStructure(ViewStructure structure) {
7786        onProvideStructureForAssistOrAutofill(structure, false, 0);
7787    }
7788
7789    /**
7790     * Populates a {@link ViewStructure} to fullfil an autofill request.
7791     *
7792     * <p>The structure should contain at least the following properties:
7793     * <ul>
7794     *   <li>Autofill id ({@link ViewStructure#setAutofillId(AutofillId, int)}).
7795     *   <li>Autofill type ({@link ViewStructure#setAutofillType(int)}).
7796     *   <li>Autofill value ({@link ViewStructure#setAutofillValue(AutofillValue)}).
7797     *   <li>Whether the data is sensitive ({@link ViewStructure#setDataIsSensitive(boolean)}).
7798     * </ul>
7799     *
7800     * <p>It's also recommended to set the following properties - the more properties the structure
7801     * has, the higher the changes of an {@link android.service.autofill.AutofillService} properly
7802     * using the structure:
7803     *
7804     * <ul>
7805     *   <li>Autofill hints ({@link ViewStructure#setAutofillHints(String[])}).
7806     *   <li>Autofill options ({@link ViewStructure#setAutofillOptions(CharSequence[])}) when the
7807     *       view can only be filled with predefined values (typically used when the autofill type
7808     *       is {@link #AUTOFILL_TYPE_LIST}).
7809     *   <li>Resource id ({@link ViewStructure#setId(int, String, String, String)}).
7810     *   <li>Class name ({@link ViewStructure#setClassName(String)}).
7811     *   <li>Content description ({@link ViewStructure#setContentDescription(CharSequence)}).
7812     *   <li>Visual properties such as visibility ({@link ViewStructure#setVisibility(int)}),
7813     *       dimensions ({@link ViewStructure#setDimens(int, int, int, int, int, int)}), and
7814     *       opacity ({@link ViewStructure#setOpaque(boolean)}).
7815     *   <li>For views representing text fields, text properties such as the text itself
7816     *       ({@link ViewStructure#setText(CharSequence)}), text hints
7817     *       ({@link ViewStructure#setHint(CharSequence)}, input type
7818     *       ({@link ViewStructure#setInputType(int)}),
7819     *   <li>For views representing HTML nodes, its web domain
7820     *       ({@link ViewStructure#setWebDomain(String)}) and HTML properties
7821     *       (({@link ViewStructure#setHtmlInfo(android.view.ViewStructure.HtmlInfo)}).
7822     * </ul>
7823     *
7824     * <p>The default implementation of this method already sets most of these properties based on
7825     * related {@link View} methods (for example, the autofill id is set using
7826     * {@link #getAutofillId()}, the autofill type set using {@link #getAutofillType()}, etc.),
7827     * and views in the standard Android widgets library also override it to set their
7828     * relevant properties (for example, {@link android.widget.TextView} already sets the text
7829     * properties), so it's recommended to only override this method
7830     * (and call {@code super.onProvideAutofillStructure()}) when:
7831     *
7832     * <ul>
7833     *   <li>The view contents does not include PII (Personally Identifiable Information), so it
7834     *       can call {@link ViewStructure#setDataIsSensitive(boolean)} passing {@code false}.
7835     *   <li>The view can only be autofilled with predefined options, so it can call
7836     *       {@link ViewStructure#setAutofillOptions(CharSequence[])}.
7837     * </ul>
7838     *
7839     * <p><b>Note:</b> The {@code left} and {@code top} values set in
7840     * {@link ViewStructure#setDimens(int, int, int, int, int, int)} must be relative to the next
7841     * {@link ViewGroup#isImportantForAutofill()} predecessor view included in the structure.
7842     *
7843     * <p>Views support the Autofill Framework mainly by:
7844     * <ul>
7845     *   <li>Providing the metadata defining what the view means and how it can be autofilled.
7846     *   <li>Notifying the Android System when the view value changed by calling
7847     *       {@link AutofillManager#notifyValueChanged(View)}.
7848     *   <li>Implementing the methods that autofill the view.
7849     * </ul>
7850     * <p>This method is responsible for the former; {@link #autofill(AutofillValue)} is responsible
7851     * for the latter.
7852     *
7853     * @param structure fill in with structured view data for autofill purposes.
7854     * @param flags optional flags.
7855     *
7856     * @see #AUTOFILL_FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
7857     */
7858    public void onProvideAutofillStructure(ViewStructure structure, @AutofillFlags int flags) {
7859        onProvideStructureForAssistOrAutofill(structure, true, flags);
7860    }
7861
7862    private void onProvideStructureForAssistOrAutofill(ViewStructure structure,
7863            boolean forAutofill, @AutofillFlags int flags) {
7864        final int id = mID;
7865        if (id != NO_ID && !isViewIdGenerated(id)) {
7866            String pkg, type, entry;
7867            try {
7868                final Resources res = getResources();
7869                entry = res.getResourceEntryName(id);
7870                type = res.getResourceTypeName(id);
7871                pkg = res.getResourcePackageName(id);
7872            } catch (Resources.NotFoundException e) {
7873                entry = type = pkg = null;
7874            }
7875            structure.setId(id, pkg, type, entry);
7876        } else {
7877            structure.setId(id, null, null, null);
7878        }
7879
7880        if (forAutofill) {
7881            final @AutofillType int autofillType = getAutofillType();
7882            // Don't need to fill autofill info if view does not support it.
7883            // For example, only TextViews that are editable support autofill
7884            if (autofillType != AUTOFILL_TYPE_NONE) {
7885                structure.setAutofillType(autofillType);
7886                structure.setAutofillHints(getAutofillHints());
7887                structure.setAutofillValue(getAutofillValue());
7888            }
7889            structure.setImportantForAutofill(getImportantForAutofill());
7890        }
7891
7892        int ignoredParentLeft = 0;
7893        int ignoredParentTop = 0;
7894        if (forAutofill && (flags & AUTOFILL_FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) == 0) {
7895            View parentGroup = null;
7896
7897            ViewParent viewParent = getParent();
7898            if (viewParent instanceof View) {
7899                parentGroup = (View) viewParent;
7900            }
7901
7902            while (parentGroup != null && !parentGroup.isImportantForAutofill()) {
7903                ignoredParentLeft += parentGroup.mLeft;
7904                ignoredParentTop += parentGroup.mTop;
7905
7906                viewParent = parentGroup.getParent();
7907                if (viewParent instanceof View) {
7908                    parentGroup = (View) viewParent;
7909                } else {
7910                    break;
7911                }
7912            }
7913        }
7914
7915        structure.setDimens(ignoredParentLeft + mLeft, ignoredParentTop + mTop, mScrollX, mScrollY,
7916                mRight - mLeft, mBottom - mTop);
7917        if (!forAutofill) {
7918            if (!hasIdentityMatrix()) {
7919                structure.setTransformation(getMatrix());
7920            }
7921            structure.setElevation(getZ());
7922        }
7923        structure.setVisibility(getVisibility());
7924        structure.setEnabled(isEnabled());
7925        if (isClickable()) {
7926            structure.setClickable(true);
7927        }
7928        if (isFocusable()) {
7929            structure.setFocusable(true);
7930        }
7931        if (isFocused()) {
7932            structure.setFocused(true);
7933        }
7934        if (isAccessibilityFocused()) {
7935            structure.setAccessibilityFocused(true);
7936        }
7937        if (isSelected()) {
7938            structure.setSelected(true);
7939        }
7940        if (isActivated()) {
7941            structure.setActivated(true);
7942        }
7943        if (isLongClickable()) {
7944            structure.setLongClickable(true);
7945        }
7946        if (this instanceof Checkable) {
7947            structure.setCheckable(true);
7948            if (((Checkable)this).isChecked()) {
7949                structure.setChecked(true);
7950            }
7951        }
7952        if (isOpaque()) {
7953            structure.setOpaque(true);
7954        }
7955        if (isContextClickable()) {
7956            structure.setContextClickable(true);
7957        }
7958        structure.setClassName(getAccessibilityClassName().toString());
7959        structure.setContentDescription(getContentDescription());
7960    }
7961
7962    /**
7963     * Called when assist structure is being retrieved from a view as part of
7964     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData} to
7965     * generate additional virtual structure under this view.  The defaullt implementation
7966     * uses {@link #getAccessibilityNodeProvider()} to try to generate this from the
7967     * view's virtual accessibility nodes, if any.  You can override this for a more
7968     * optimal implementation providing this data.
7969     */
7970    public void onProvideVirtualStructure(ViewStructure structure) {
7971        onProvideVirtualStructureCompat(structure, false);
7972    }
7973
7974    /**
7975     * Fallback implementation to populate a ViewStructure from accessibility state.
7976     *
7977     * @param structure The structure to populate.
7978     * @param forAutofill Whether the structure is needed for autofill.
7979     */
7980    private void onProvideVirtualStructureCompat(ViewStructure structure, boolean forAutofill) {
7981        final AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
7982        if (provider != null) {
7983            if (android.view.autofill.Helper.sVerbose && forAutofill) {
7984                Log.v(VIEW_LOG_TAG, "onProvideVirtualStructureCompat() for " + this);
7985            }
7986
7987            final AccessibilityNodeInfo info = createAccessibilityNodeInfo();
7988            structure.setChildCount(1);
7989            final ViewStructure root = structure.newChild(0);
7990            populateVirtualStructure(root, provider, info, forAutofill);
7991            info.recycle();
7992        }
7993    }
7994
7995    /**
7996     * Populates a {@link ViewStructure} containing virtual children to fullfil an autofill
7997     * request.
7998     *
7999     * <p>This method should be used when the view manages a virtual structure under this view. For
8000     * example, a view that draws input fields using {@link #draw(Canvas)}.
8001     *
8002     * <p>When implementing this method, subclasses must follow the rules below:
8003     *
8004     * <ul>
8005     *   <li>Add virtual children by calling the {@link ViewStructure#newChild(int)} or
8006     *       {@link ViewStructure#asyncNewChild(int)} methods, where the {@code id} is an unique id
8007     *       identifying the children in the virtual structure.
8008     *   <li>The children hierarchy can have multiple levels if necessary, but ideally it should
8009     *       exclude intermediate levels that are irrelevant for autofill; that would improve the
8010     *       autofill performance.
8011     *   <li>Also implement {@link #autofill(SparseArray)} to autofill the virtual
8012     *       children.
8013     *   <li>Set the autofill properties of the child structure as defined by
8014     *       {@link #onProvideAutofillStructure(ViewStructure, int)}, using
8015     *       {@link ViewStructure#setAutofillId(AutofillId, int)} to set its autofill id.
8016     *   <li>Call {@link android.view.autofill.AutofillManager#notifyViewEntered(View, int, Rect)}
8017     *       and/or {@link android.view.autofill.AutofillManager#notifyViewExited(View, int)}
8018     *       when the focused virtual child changed.
8019     *   <li>Override {@link #isVisibleToUserForAutofill(int)} to allow the platform to query
8020     *       whether a given virtual view is visible to the user in order to support triggering
8021     *       save when all views of interest go away.
8022     *   <li>Call
8023     *    {@link android.view.autofill.AutofillManager#notifyValueChanged(View, int, AutofillValue)}
8024     *       when the value of a virtual child changed.
8025     *   <li>Call {@link
8026     *    android.view.autofill.AutofillManager#notifyViewVisibilityChanged(View, int, boolean)}
8027     *       when the visibility of a virtual child changed.
8028     *   <li>Call
8029     *    {@link android.view.autofill.AutofillManager#notifyViewClicked(View, int)} when a virtual
8030     *       child is clicked.
8031     *   <li>Call {@link AutofillManager#commit()} when the autofill context of the view structure
8032     *       changed and the current context should be committed (for example, when the user tapped
8033     *       a {@code SUBMIT} button in an HTML page).
8034     *   <li>Call {@link AutofillManager#cancel()} when the autofill context of the view structure
8035     *       changed and the current context should be canceled (for example, when the user tapped
8036     *       a {@code CANCEL} button in an HTML page).
8037     *   <li>Provide ways for users to manually request autofill by calling
8038     *       {@link AutofillManager#requestAutofill(View, int, Rect)}.
8039     *   <li>The {@code left} and {@code top} values set in
8040     *       {@link ViewStructure#setDimens(int, int, int, int, int, int)} must be relative to the
8041     *       next {@link ViewGroup#isImportantForAutofill()} predecessor view included in the
8042     *       structure.
8043     * </ul>
8044     *
8045     * <p>Views with virtual children support the Autofill Framework mainly by:
8046     * <ul>
8047     *   <li>Providing the metadata defining what the virtual children mean and how they can be
8048     *       autofilled.
8049     *   <li>Implementing the methods that autofill the virtual children.
8050     * </ul>
8051     * <p>This method is responsible for the former; {@link #autofill(SparseArray)} is responsible
8052     * for the latter.
8053     *
8054     * @param structure fill in with virtual children data for autofill purposes.
8055     * @param flags optional flags.
8056     *
8057     * @see #AUTOFILL_FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
8058     */
8059    public void onProvideAutofillVirtualStructure(ViewStructure structure, int flags) {
8060        if (mContext.isAutofillCompatibilityEnabled()) {
8061            onProvideVirtualStructureCompat(structure, true);
8062        }
8063    }
8064
8065    /**
8066     * Automatically fills the content of this view with the {@code value}.
8067     *
8068     * <p>Views support the Autofill Framework mainly by:
8069     * <ul>
8070     *   <li>Providing the metadata defining what the view means and how it can be autofilled.
8071     *   <li>Implementing the methods that autofill the view.
8072     * </ul>
8073     * <p>{@link #onProvideAutofillStructure(ViewStructure, int)} is responsible for the former,
8074     * this method is responsible for latter.
8075     *
8076     * <p>This method does nothing by default, but when overridden it typically:
8077     * <ol>
8078     *   <li>Checks if the provided value matches the expected type (which is defined by
8079     *       {@link #getAutofillType()}).
8080     *   <li>Checks if the view is editable - if it isn't, it should return right away.
8081     *   <li>Call the proper getter method on {@link AutofillValue} to fetch the actual value.
8082     *   <li>Pass the actual value to the equivalent setter in the view.
8083     * </ol>
8084     *
8085     * <p>For example, a text-field view could implement the method this way:
8086     *
8087     * <pre class="prettyprint">
8088     * &#64;Override
8089     * public void autofill(AutofillValue value) {
8090     *   if (!value.isText() || !this.isEditable()) {
8091     *      return;
8092     *   }
8093     *   CharSequence text = value.getTextValue();
8094     *   if (text != null) {
8095     *     this.setText(text);
8096     *   }
8097     * }
8098     * </pre>
8099     *
8100     * <p>If the value is updated asynchronously, the next call to
8101     * {@link AutofillManager#notifyValueChanged(View)} must happen <b>after</b> the value was
8102     * changed to the autofilled value. If not, the view will not be considered autofilled.
8103     *
8104     * <p><b>Note:</b> After this method is called, the value returned by
8105     * {@link #getAutofillValue()} must be equal to the {@code value} passed to it, otherwise the
8106     * view will not be highlighted as autofilled.
8107     *
8108     * @param value value to be autofilled.
8109     */
8110    public void autofill(@SuppressWarnings("unused") AutofillValue value) {
8111    }
8112
8113    /**
8114     * Automatically fills the content of the virtual children within this view.
8115     *
8116     * <p>Views with virtual children support the Autofill Framework mainly by:
8117     * <ul>
8118     *   <li>Providing the metadata defining what the virtual children mean and how they can be
8119     *       autofilled.
8120     *   <li>Implementing the methods that autofill the virtual children.
8121     * </ul>
8122     * <p>{@link #onProvideAutofillVirtualStructure(ViewStructure, int)} is responsible for the
8123     * former, this method is responsible for the latter - see {@link #autofill(AutofillValue)} and
8124     * {@link #onProvideAutofillVirtualStructure(ViewStructure, int)} for more info about autofill.
8125     *
8126     * <p>If a child value is updated asynchronously, the next call to
8127     * {@link AutofillManager#notifyValueChanged(View, int, AutofillValue)} must happen
8128     * <b>after</b> the value was changed to the autofilled value. If not, the child will not be
8129     * considered autofilled.
8130     *
8131     * <p><b>Note:</b> To indicate that a virtual view was autofilled,
8132     * <code>?android:attr/autofilledHighlight</code> should be drawn over it until the data
8133     * changes.
8134     *
8135     * @param values map of values to be autofilled, keyed by virtual child id.
8136     *
8137     * @attr ref android.R.styleable#Theme_autofilledHighlight
8138     */
8139    public void autofill(@NonNull @SuppressWarnings("unused") SparseArray<AutofillValue> values) {
8140        if (!mContext.isAutofillCompatibilityEnabled()) {
8141            return;
8142        }
8143        final AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
8144        if (provider == null) {
8145            return;
8146        }
8147        final int valueCount = values.size();
8148        for (int i = 0; i < valueCount; i++) {
8149            final AutofillValue value = values.valueAt(i);
8150            if (value.isText()) {
8151                final int virtualId = values.keyAt(i);
8152                final CharSequence text = value.getTextValue();
8153                final Bundle arguments = new Bundle();
8154                arguments.putCharSequence(
8155                        AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, text);
8156                provider.performAction(virtualId, AccessibilityNodeInfo.ACTION_SET_TEXT, arguments);
8157            }
8158        }
8159    }
8160
8161    /**
8162     * Gets the unique, logical identifier of this view in the activity, for autofill purposes.
8163     *
8164     * <p>The autofill id is created on demand, unless it is explicitly set by
8165     * {@link #setAutofillId(AutofillId)}.
8166     *
8167     * <p>See {@link #setAutofillId(AutofillId)} for more info.
8168     *
8169     * @return The View's autofill id.
8170     */
8171    public final AutofillId getAutofillId() {
8172        if (mAutofillId == null) {
8173            // The autofill id needs to be unique, but its value doesn't matter,
8174            // so it's better to reuse the accessibility id to save space.
8175            mAutofillId = new AutofillId(getAutofillViewId());
8176        }
8177        return mAutofillId;
8178    }
8179
8180    /**
8181     * Sets the unique, logical identifier of this view in the activity, for autofill purposes.
8182     *
8183     * <p>The autofill id is created on demand, and this method should only be called when a view is
8184     * reused after {@link #dispatchProvideAutofillStructure(ViewStructure, int)} is called, as
8185     * that method creates a snapshot of the view that is passed along to the autofill service.
8186     *
8187     * <p>This method is typically used when view subtrees are recycled to represent different
8188     * content* &mdash;in this case, the autofill id can be saved before the view content is swapped
8189     * out, and restored later when it's swapped back in. For example:
8190     *
8191     * <pre>
8192     * EditText reusableView = ...;
8193     * ViewGroup parentView = ...;
8194     * AutofillManager afm = ...;
8195     *
8196     * // Swap out the view and change its contents
8197     * AutofillId oldId = reusableView.getAutofillId();
8198     * CharSequence oldText = reusableView.getText();
8199     * parentView.removeView(reusableView);
8200     * AutofillId newId = afm.getNextAutofillId();
8201     * reusableView.setText("New I am");
8202     * reusableView.setAutofillId(newId);
8203     * parentView.addView(reusableView);
8204     *
8205     * // Later, swap the old content back in
8206     * parentView.removeView(reusableView);
8207     * reusableView.setAutofillId(oldId);
8208     * reusableView.setText(oldText);
8209     * parentView.addView(reusableView);
8210     * </pre>
8211     *
8212     * @param id an autofill ID that is unique in the {@link android.app.Activity} hosting the view,
8213     * or {@code null} to reset it. Usually it's an id previously allocated to another view (and
8214     * obtained through {@link #getAutofillId()}), or a new value obtained through
8215     * {@link AutofillManager#getNextAutofillId()}.
8216     *
8217     * @throws IllegalStateException if the view is already {@link #isAttachedToWindow() attached to
8218     * a window}.
8219     *
8220     * @throws IllegalArgumentException if the id is an autofill id associated with a virtual view.
8221     */
8222    public void setAutofillId(@Nullable AutofillId id) {
8223        // TODO(b/37566627): add unit / CTS test for all possible combinations below
8224        if (android.view.autofill.Helper.sVerbose) {
8225            Log.v(VIEW_LOG_TAG, "setAutofill(): from " + mAutofillId + " to " + id);
8226        }
8227        if (isAttachedToWindow()) {
8228            throw new IllegalStateException("Cannot set autofill id when view is attached");
8229        }
8230        if (id != null && id.isVirtual()) {
8231            throw new IllegalStateException("Cannot set autofill id assigned to virtual views");
8232        }
8233        if (id == null && (mPrivateFlags3 & PFLAG3_AUTOFILLID_EXPLICITLY_SET) == 0) {
8234            // Ignore reset because it was never explicitly set before.
8235            return;
8236        }
8237        mAutofillId = id;
8238        if (id != null) {
8239            mAutofillViewId = id.getViewId();
8240            mPrivateFlags3 |= PFLAG3_AUTOFILLID_EXPLICITLY_SET;
8241        } else {
8242            mAutofillViewId = NO_ID;
8243            mPrivateFlags3 &= ~PFLAG3_AUTOFILLID_EXPLICITLY_SET;
8244        }
8245    }
8246
8247    /**
8248     * Describes the autofill type of this view, so an
8249     * {@link android.service.autofill.AutofillService} can create the proper {@link AutofillValue}
8250     * when autofilling the view.
8251     *
8252     * <p>By default returns {@link #AUTOFILL_TYPE_NONE}, but views should override it to properly
8253     * support the Autofill Framework.
8254     *
8255     * @return either {@link #AUTOFILL_TYPE_NONE}, {@link #AUTOFILL_TYPE_TEXT},
8256     * {@link #AUTOFILL_TYPE_LIST}, {@link #AUTOFILL_TYPE_DATE}, or {@link #AUTOFILL_TYPE_TOGGLE}.
8257     *
8258     * @see #onProvideAutofillStructure(ViewStructure, int)
8259     * @see #autofill(AutofillValue)
8260     */
8261    public @AutofillType int getAutofillType() {
8262        return AUTOFILL_TYPE_NONE;
8263    }
8264
8265    /**
8266     * Gets the hints that help an {@link android.service.autofill.AutofillService} determine how
8267     * to autofill the view with the user's data.
8268     *
8269     * <p>See {@link #setAutofillHints(String...)} for more info about these hints.
8270     *
8271     * @return The hints set via the attribute or {@link #setAutofillHints(String...)}, or
8272     * {@code null} if no hints were set.
8273     *
8274     * @attr ref android.R.styleable#View_autofillHints
8275     */
8276    @ViewDebug.ExportedProperty()
8277    @Nullable public String[] getAutofillHints() {
8278        return mAutofillHints;
8279    }
8280
8281    /**
8282     * @hide
8283     */
8284    public boolean isAutofilled() {
8285        return (mPrivateFlags3 & PFLAG3_IS_AUTOFILLED) != 0;
8286    }
8287
8288    /**
8289     * Gets the {@link View}'s current autofill value.
8290     *
8291     * <p>By default returns {@code null}, but subclasses should override it and return an
8292     * appropriate value to properly support the Autofill Framework.
8293     *
8294     * @see #onProvideAutofillStructure(ViewStructure, int)
8295     * @see #autofill(AutofillValue)
8296     */
8297    @Nullable
8298    public AutofillValue getAutofillValue() {
8299        return null;
8300    }
8301
8302    /**
8303     * Gets the mode for determining whether this view is important for autofill.
8304     *
8305     * <p>See {@link #setImportantForAutofill(int)} and {@link #isImportantForAutofill()} for more
8306     * info about this mode.
8307     *
8308     * @return {@link #IMPORTANT_FOR_AUTOFILL_AUTO} by default, or value passed to
8309     * {@link #setImportantForAutofill(int)}.
8310     *
8311     * @attr ref android.R.styleable#View_importantForAutofill
8312     */
8313    @ViewDebug.ExportedProperty(mapping = {
8314            @ViewDebug.IntToString(from = IMPORTANT_FOR_AUTOFILL_AUTO, to = "auto"),
8315            @ViewDebug.IntToString(from = IMPORTANT_FOR_AUTOFILL_YES, to = "yes"),
8316            @ViewDebug.IntToString(from = IMPORTANT_FOR_AUTOFILL_NO, to = "no"),
8317            @ViewDebug.IntToString(from = IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS,
8318                to = "yesExcludeDescendants"),
8319            @ViewDebug.IntToString(from = IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS,
8320                to = "noExcludeDescendants")})
8321    public @AutofillImportance int getImportantForAutofill() {
8322        return (mPrivateFlags3
8323                & PFLAG3_IMPORTANT_FOR_AUTOFILL_MASK) >> PFLAG3_IMPORTANT_FOR_AUTOFILL_SHIFT;
8324    }
8325
8326    /**
8327     * Sets the mode for determining whether this view is considered important for autofill.
8328     *
8329     * <p>The platform determines the importance for autofill automatically but you
8330     * can use this method to customize the behavior. For example:
8331     *
8332     * <ol>
8333     *   <li>When the view contents is irrelevant for autofill (for example, a text field used in a
8334     *       "Captcha" challenge), it should be {@link #IMPORTANT_FOR_AUTOFILL_NO}.
8335     *   <li>When both the view and its children are irrelevant for autofill (for example, the root
8336     *       view of an activity containing a spreadhseet editor), it should be
8337     *       {@link #IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS}.
8338     *   <li>When the view content is relevant for autofill but its children aren't (for example,
8339     *       a credit card expiration date represented by a custom view that overrides the proper
8340     *       autofill methods and has 2 children representing the month and year), it should
8341     *       be {@link #IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS}.
8342     * </ol>
8343     *
8344     * <p><b>Note:</b> Setting the mode as {@link #IMPORTANT_FOR_AUTOFILL_NO} or
8345     * {@link #IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS} does not guarantee the view (and its
8346     * children) will be always be considered not important; for example, when the user explicitly
8347     * makes an autofill request, all views are considered important. See
8348     * {@link #isImportantForAutofill()} for more details about how the View's importance for
8349     * autofill is used.
8350     *
8351     * @param mode {@link #IMPORTANT_FOR_AUTOFILL_AUTO}, {@link #IMPORTANT_FOR_AUTOFILL_YES},
8352     * {@link #IMPORTANT_FOR_AUTOFILL_NO}, {@link #IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS},
8353     * or {@link #IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS}.
8354     *
8355     * @attr ref android.R.styleable#View_importantForAutofill
8356     */
8357    public void setImportantForAutofill(@AutofillImportance int mode) {
8358        mPrivateFlags3 &= ~PFLAG3_IMPORTANT_FOR_AUTOFILL_MASK;
8359        mPrivateFlags3 |= (mode << PFLAG3_IMPORTANT_FOR_AUTOFILL_SHIFT)
8360                & PFLAG3_IMPORTANT_FOR_AUTOFILL_MASK;
8361    }
8362
8363    /**
8364     * Hints the Android System whether the {@link android.app.assist.AssistStructure.ViewNode}
8365     * associated with this view is considered important for autofill purposes.
8366     *
8367     * <p>Generally speaking, a view is important for autofill if:
8368     * <ol>
8369     * <li>The view can be autofilled by an {@link android.service.autofill.AutofillService}.
8370     * <li>The view contents can help an {@link android.service.autofill.AutofillService}
8371     *     determine how other views can be autofilled.
8372     * <ol>
8373     *
8374     * <p>For example, view containers should typically return {@code false} for performance reasons
8375     * (since the important info is provided by their children), but if its properties have relevant
8376     * information (for example, a resource id called {@code credentials}, it should return
8377     * {@code true}. On the other hand, views representing labels or editable fields should
8378     * typically return {@code true}, but in some cases they could return {@code false}
8379     * (for example, if they're part of a "Captcha" mechanism).
8380     *
8381     * <p>The value returned by this method depends on the value returned by
8382     * {@link #getImportantForAutofill()}:
8383     *
8384     * <ol>
8385     *   <li>if it returns {@link #IMPORTANT_FOR_AUTOFILL_YES} or
8386     *       {@link #IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS}, then it returns {@code true}
8387     *   <li>if it returns {@link #IMPORTANT_FOR_AUTOFILL_NO} or
8388     *       {@link #IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS}, then it returns {@code false}
8389     *   <li>if it returns {@link #IMPORTANT_FOR_AUTOFILL_AUTO}, then it uses some simple heuristics
8390     *       that can return {@code true} in some cases (like a container with a resource id),
8391     *       but {@code false} in most.
8392     *   <li>otherwise, it returns {@code false}.
8393     * </ol>
8394     *
8395     * <p>When a view is considered important for autofill:
8396     * <ul>
8397     *   <li>The view might automatically trigger an autofill request when focused on.
8398     *   <li>The contents of the view are included in the {@link ViewStructure} used in an autofill
8399     *       request.
8400     * </ul>
8401     *
8402     * <p>On the other hand, when a view is considered not important for autofill:
8403     * <ul>
8404     *   <li>The view never automatically triggers autofill requests, but it can trigger a manual
8405     *       request through {@link AutofillManager#requestAutofill(View)}.
8406     *   <li>The contents of the view are not included in the {@link ViewStructure} used in an
8407     *       autofill request, unless the request has the
8408     *       {@link #AUTOFILL_FLAG_INCLUDE_NOT_IMPORTANT_VIEWS} flag.
8409     * </ul>
8410     *
8411     * @return whether the view is considered important for autofill.
8412     *
8413     * @see #setImportantForAutofill(int)
8414     * @see #IMPORTANT_FOR_AUTOFILL_AUTO
8415     * @see #IMPORTANT_FOR_AUTOFILL_YES
8416     * @see #IMPORTANT_FOR_AUTOFILL_NO
8417     * @see #IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS
8418     * @see #IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS
8419     * @see AutofillManager#requestAutofill(View)
8420     */
8421    public final boolean isImportantForAutofill() {
8422        // Check parent mode to ensure we're not hidden.
8423        ViewParent parent = mParent;
8424        while (parent instanceof View) {
8425            final int parentImportance = ((View) parent).getImportantForAutofill();
8426            if (parentImportance == IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS
8427                    || parentImportance == IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS) {
8428                return false;
8429            }
8430            parent = parent.getParent();
8431        }
8432
8433        final int importance = getImportantForAutofill();
8434
8435        // First, check the explicit states.
8436        if (importance == IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS
8437                || importance == IMPORTANT_FOR_AUTOFILL_YES) {
8438            return true;
8439        }
8440        if (importance == IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS
8441                || importance == IMPORTANT_FOR_AUTOFILL_NO) {
8442            return false;
8443        }
8444
8445        // Then use some heuristics to handle AUTO.
8446
8447        // Always include views that have an explicit resource id.
8448        final int id = mID;
8449        if (id != NO_ID && !isViewIdGenerated(id)) {
8450            final Resources res = getResources();
8451            String entry = null;
8452            String pkg = null;
8453            try {
8454                entry = res.getResourceEntryName(id);
8455                pkg = res.getResourcePackageName(id);
8456            } catch (Resources.NotFoundException e) {
8457                // ignore
8458            }
8459            if (entry != null && pkg != null && pkg.equals(mContext.getPackageName())) {
8460                return true;
8461            }
8462        }
8463
8464        // If the app developer explicitly set hints for it, it's important.
8465        if (getAutofillHints() != null) {
8466            return true;
8467        }
8468
8469        // Otherwise, assume it's not important...
8470        return false;
8471    }
8472
8473    @Nullable
8474    private AutofillManager getAutofillManager() {
8475        return mContext.getSystemService(AutofillManager.class);
8476    }
8477
8478    private boolean isAutofillable() {
8479        return getAutofillType() != AUTOFILL_TYPE_NONE && isImportantForAutofill()
8480                && getAutofillViewId() > LAST_APP_AUTOFILL_ID;
8481    }
8482
8483    /** @hide */
8484    public boolean canNotifyAutofillEnterExitEvent() {
8485        return isAutofillable() && isAttachedToWindow();
8486    }
8487
8488    private void populateVirtualStructure(ViewStructure structure,
8489            AccessibilityNodeProvider provider, AccessibilityNodeInfo info,
8490            boolean forAutofill) {
8491        structure.setId(AccessibilityNodeInfo.getVirtualDescendantId(info.getSourceNodeId()),
8492                null, null, info.getViewIdResourceName());
8493        Rect rect = structure.getTempRect();
8494        info.getBoundsInParent(rect);
8495        structure.setDimens(rect.left, rect.top, 0, 0, rect.width(), rect.height());
8496        structure.setVisibility(VISIBLE);
8497        structure.setEnabled(info.isEnabled());
8498        if (info.isClickable()) {
8499            structure.setClickable(true);
8500        }
8501        if (info.isFocusable()) {
8502            structure.setFocusable(true);
8503        }
8504        if (info.isFocused()) {
8505            structure.setFocused(true);
8506        }
8507        if (info.isAccessibilityFocused()) {
8508            structure.setAccessibilityFocused(true);
8509        }
8510        if (info.isSelected()) {
8511            structure.setSelected(true);
8512        }
8513        if (info.isLongClickable()) {
8514            structure.setLongClickable(true);
8515        }
8516        if (info.isCheckable()) {
8517            structure.setCheckable(true);
8518            if (info.isChecked()) {
8519                structure.setChecked(true);
8520            }
8521        }
8522        if (info.isContextClickable()) {
8523            structure.setContextClickable(true);
8524        }
8525        if (forAutofill) {
8526            structure.setAutofillId(new AutofillId(getAutofillId(),
8527                    AccessibilityNodeInfo.getVirtualDescendantId(info.getSourceNodeId())));
8528        }
8529        CharSequence cname = info.getClassName();
8530        structure.setClassName(cname != null ? cname.toString() : null);
8531        structure.setContentDescription(info.getContentDescription());
8532        if (forAutofill) {
8533            final int maxTextLength = info.getMaxTextLength();
8534            if (maxTextLength != -1) {
8535                structure.setMaxTextLength(maxTextLength);
8536            }
8537            structure.setHint(info.getHintText());
8538        }
8539        CharSequence text = info.getText();
8540        boolean hasText = text != null || info.getError() != null;
8541        if (hasText) {
8542            structure.setText(text, info.getTextSelectionStart(), info.getTextSelectionEnd());
8543        }
8544        if (forAutofill) {
8545            if (info.isEditable()) {
8546                structure.setDataIsSensitive(true);
8547                if (hasText) {
8548                    structure.setAutofillType(AUTOFILL_TYPE_TEXT);
8549                    structure.setAutofillValue(AutofillValue.forText(text));
8550                }
8551                int inputType = info.getInputType();
8552                if (inputType == 0 && info.isPassword()) {
8553                    inputType = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD;
8554                }
8555                structure.setInputType(inputType);
8556            } else {
8557                structure.setDataIsSensitive(false);
8558            }
8559        }
8560        final int NCHILDREN = info.getChildCount();
8561        if (NCHILDREN > 0) {
8562            structure.setChildCount(NCHILDREN);
8563            for (int i=0; i<NCHILDREN; i++) {
8564                if (AccessibilityNodeInfo.getVirtualDescendantId(info.getChildNodeIds().get(i))
8565                        == AccessibilityNodeProvider.HOST_VIEW_ID) {
8566                    Log.e(VIEW_LOG_TAG, "Virtual view pointing to its host. Ignoring");
8567                    continue;
8568                }
8569                AccessibilityNodeInfo cinfo = provider.createAccessibilityNodeInfo(
8570                        AccessibilityNodeInfo.getVirtualDescendantId(info.getChildId(i)));
8571                ViewStructure child = structure.newChild(i);
8572                populateVirtualStructure(child, provider, cinfo, forAutofill);
8573                cinfo.recycle();
8574            }
8575        }
8576    }
8577
8578    /**
8579     * Dispatch creation of {@link ViewStructure} down the hierarchy.  The default
8580     * implementation calls {@link #onProvideStructure} and
8581     * {@link #onProvideVirtualStructure}.
8582     */
8583    public void dispatchProvideStructure(ViewStructure structure) {
8584        dispatchProvideStructureForAssistOrAutofill(structure, false, 0);
8585    }
8586
8587    /**
8588     * Dispatches creation of a {@link ViewStructure}s for autofill purposes down the hierarchy,
8589     * when an Assist structure is being created as part of an autofill request.
8590     *
8591     * <p>The default implementation does the following:
8592     * <ul>
8593     *   <li>Sets the {@link AutofillId} in the structure.
8594     *   <li>Calls {@link #onProvideAutofillStructure(ViewStructure, int)}.
8595     *   <li>Calls {@link #onProvideAutofillVirtualStructure(ViewStructure, int)}.
8596     * </ul>
8597     *
8598     * <p>Typically, this method should only be overridden by subclasses that provide a view
8599     * hierarchy (such as {@link ViewGroup}) - other classes should override
8600     * {@link #onProvideAutofillStructure(ViewStructure, int)} or
8601     * {@link #onProvideAutofillVirtualStructure(ViewStructure, int)} instead.
8602     *
8603     * <p>When overridden, it must:
8604     *
8605     * <ul>
8606     *   <li>Either call
8607     *       {@code super.dispatchProvideAutofillStructure(structure, flags)} or explicitly
8608     *       set the {@link AutofillId} in the structure (for example, by calling
8609     *       {@code structure.setAutofillId(getAutofillId())}).
8610     *   <li>Decide how to handle the {@link #AUTOFILL_FLAG_INCLUDE_NOT_IMPORTANT_VIEWS} flag - when
8611     *       set, all views in the structure should be considered important for autofill,
8612     *       regardless of what {@link #isImportantForAutofill()} returns. We encourage you to
8613     *       respect this flag to provide a better user experience - this flag is typically used
8614     *       when an user explicitly requested autofill. If the flag is not set,
8615     *       then only views marked as important for autofill should be included in the
8616     *       structure - skipping non-important views optimizes the overall autofill performance.
8617     * </ul>
8618     *
8619     * @param structure fill in with structured view data for autofill purposes.
8620     * @param flags optional flags.
8621     *
8622     * @see #AUTOFILL_FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
8623     */
8624    public void dispatchProvideAutofillStructure(@NonNull ViewStructure structure,
8625            @AutofillFlags int flags) {
8626        dispatchProvideStructureForAssistOrAutofill(structure, true, flags);
8627    }
8628
8629    private void dispatchProvideStructureForAssistOrAutofill(ViewStructure structure,
8630            boolean forAutofill, @AutofillFlags int flags) {
8631        if (forAutofill) {
8632            structure.setAutofillId(getAutofillId());
8633            onProvideAutofillStructure(structure, flags);
8634            onProvideAutofillVirtualStructure(structure, flags);
8635        } else if (!isAssistBlocked()) {
8636            onProvideStructure(structure);
8637            onProvideVirtualStructure(structure);
8638        } else {
8639            structure.setClassName(getAccessibilityClassName().toString());
8640            structure.setAssistBlocked(true);
8641        }
8642    }
8643
8644    /**
8645     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
8646     *
8647     * Note: Called from the default {@link AccessibilityDelegate}.
8648     *
8649     * @hide
8650     */
8651    public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
8652        if (mAttachInfo == null) {
8653            return;
8654        }
8655
8656        Rect bounds = mAttachInfo.mTmpInvalRect;
8657
8658        getDrawingRect(bounds);
8659        info.setBoundsInParent(bounds);
8660
8661        getBoundsOnScreen(bounds, true);
8662        info.setBoundsInScreen(bounds);
8663
8664        ViewParent parent = getParentForAccessibility();
8665        if (parent instanceof View) {
8666            info.setParent((View) parent);
8667        }
8668
8669        if (mID != View.NO_ID) {
8670            View rootView = getRootView();
8671            if (rootView == null) {
8672                rootView = this;
8673            }
8674
8675            View label = rootView.findLabelForView(this, mID);
8676            if (label != null) {
8677                info.setLabeledBy(label);
8678            }
8679
8680            if ((mAttachInfo.mAccessibilityFetchFlags
8681                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
8682                    && Resources.resourceHasPackage(mID)) {
8683                try {
8684                    String viewId = getResources().getResourceName(mID);
8685                    info.setViewIdResourceName(viewId);
8686                } catch (Resources.NotFoundException nfe) {
8687                    /* ignore */
8688                }
8689            }
8690        }
8691
8692        if (mLabelForId != View.NO_ID) {
8693            View rootView = getRootView();
8694            if (rootView == null) {
8695                rootView = this;
8696            }
8697            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
8698            if (labeled != null) {
8699                info.setLabelFor(labeled);
8700            }
8701        }
8702
8703        if (mAccessibilityTraversalBeforeId != View.NO_ID) {
8704            View rootView = getRootView();
8705            if (rootView == null) {
8706                rootView = this;
8707            }
8708            View next = rootView.findViewInsideOutShouldExist(this,
8709                    mAccessibilityTraversalBeforeId);
8710            if (next != null && next.includeForAccessibility()) {
8711                info.setTraversalBefore(next);
8712            }
8713        }
8714
8715        if (mAccessibilityTraversalAfterId != View.NO_ID) {
8716            View rootView = getRootView();
8717            if (rootView == null) {
8718                rootView = this;
8719            }
8720            View next = rootView.findViewInsideOutShouldExist(this,
8721                    mAccessibilityTraversalAfterId);
8722            if (next != null && next.includeForAccessibility()) {
8723                info.setTraversalAfter(next);
8724            }
8725        }
8726
8727        info.setVisibleToUser(isVisibleToUser());
8728
8729        info.setImportantForAccessibility(isImportantForAccessibility());
8730        info.setPackageName(mContext.getPackageName());
8731        info.setClassName(getAccessibilityClassName());
8732        info.setContentDescription(getContentDescription());
8733
8734        info.setEnabled(isEnabled());
8735        info.setClickable(isClickable());
8736        info.setFocusable(isFocusable());
8737        info.setScreenReaderFocusable(isScreenReaderFocusable());
8738        info.setFocused(isFocused());
8739        info.setAccessibilityFocused(isAccessibilityFocused());
8740        info.setSelected(isSelected());
8741        info.setLongClickable(isLongClickable());
8742        info.setContextClickable(isContextClickable());
8743        info.setLiveRegion(getAccessibilityLiveRegion());
8744        if ((mTooltipInfo != null) && (mTooltipInfo.mTooltipText != null)) {
8745            info.setTooltipText(mTooltipInfo.mTooltipText);
8746            info.addAction((mTooltipInfo.mTooltipPopup == null)
8747                    ? AccessibilityNodeInfo.AccessibilityAction.ACTION_SHOW_TOOLTIP
8748                    : AccessibilityNodeInfo.AccessibilityAction.ACTION_HIDE_TOOLTIP);
8749        }
8750
8751        // TODO: These make sense only if we are in an AdapterView but all
8752        // views can be selected. Maybe from accessibility perspective
8753        // we should report as selectable view in an AdapterView.
8754        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
8755        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
8756
8757        if (isFocusable()) {
8758            if (isFocused()) {
8759                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
8760            } else {
8761                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
8762            }
8763        }
8764
8765        if (!isAccessibilityFocused()) {
8766            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
8767        } else {
8768            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
8769        }
8770
8771        if (isClickable() && isEnabled()) {
8772            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
8773        }
8774
8775        if (isLongClickable() && isEnabled()) {
8776            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
8777        }
8778
8779        if (isContextClickable() && isEnabled()) {
8780            info.addAction(AccessibilityAction.ACTION_CONTEXT_CLICK);
8781        }
8782
8783        CharSequence text = getIterableTextForAccessibility();
8784        if (text != null && text.length() > 0) {
8785            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
8786
8787            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
8788            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
8789            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
8790            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
8791                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
8792                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
8793        }
8794
8795        info.addAction(AccessibilityAction.ACTION_SHOW_ON_SCREEN);
8796        populateAccessibilityNodeInfoDrawingOrderInParent(info);
8797        info.setPaneTitle(mAccessibilityPaneTitle);
8798    }
8799
8800    /**
8801     * Adds extra data to an {@link AccessibilityNodeInfo} based on an explicit request for the
8802     * additional data.
8803     * <p>
8804     * This method only needs overloading if the node is marked as having extra data available.
8805     * </p>
8806     *
8807     * @param info The info to which to add the extra data. Never {@code null}.
8808     * @param extraDataKey A key specifying the type of extra data to add to the info. The
8809     *                     extra data should be added to the {@link Bundle} returned by
8810     *                     the info's {@link AccessibilityNodeInfo#getExtras} method. Never
8811     *                     {@code null}.
8812     * @param arguments A {@link Bundle} holding any arguments relevant for this request. May be
8813     *                  {@code null} if the service provided no arguments.
8814     *
8815     * @see AccessibilityNodeInfo#setAvailableExtraData(List)
8816     */
8817    public void addExtraDataToAccessibilityNodeInfo(
8818            @NonNull AccessibilityNodeInfo info, @NonNull String extraDataKey,
8819            @Nullable Bundle arguments) {
8820    }
8821
8822    /**
8823     * Determine the order in which this view will be drawn relative to its siblings for a11y
8824     *
8825     * @param info The info whose drawing order should be populated
8826     */
8827    private void populateAccessibilityNodeInfoDrawingOrderInParent(AccessibilityNodeInfo info) {
8828        /*
8829         * If the view's bounds haven't been set yet, layout has not completed. In that situation,
8830         * drawing order may not be well-defined, and some Views with custom drawing order may
8831         * not be initialized sufficiently to respond properly getChildDrawingOrder.
8832         */
8833        if ((mPrivateFlags & PFLAG_HAS_BOUNDS) == 0) {
8834            info.setDrawingOrder(0);
8835            return;
8836        }
8837        int drawingOrderInParent = 1;
8838        // Iterate up the hierarchy if parents are not important for a11y
8839        View viewAtDrawingLevel = this;
8840        final ViewParent parent = getParentForAccessibility();
8841        while (viewAtDrawingLevel != parent) {
8842            final ViewParent currentParent = viewAtDrawingLevel.getParent();
8843            if (!(currentParent instanceof ViewGroup)) {
8844                // Should only happen for the Decor
8845                drawingOrderInParent = 0;
8846                break;
8847            } else {
8848                final ViewGroup parentGroup = (ViewGroup) currentParent;
8849                final int childCount = parentGroup.getChildCount();
8850                if (childCount > 1) {
8851                    List<View> preorderedList = parentGroup.buildOrderedChildList();
8852                    if (preorderedList != null) {
8853                        final int childDrawIndex = preorderedList.indexOf(viewAtDrawingLevel);
8854                        for (int i = 0; i < childDrawIndex; i++) {
8855                            drawingOrderInParent += numViewsForAccessibility(preorderedList.get(i));
8856                        }
8857                    } else {
8858                        final int childIndex = parentGroup.indexOfChild(viewAtDrawingLevel);
8859                        final boolean customOrder = parentGroup.isChildrenDrawingOrderEnabled();
8860                        final int childDrawIndex = ((childIndex >= 0) && customOrder) ? parentGroup
8861                                .getChildDrawingOrder(childCount, childIndex) : childIndex;
8862                        final int numChildrenToIterate = customOrder ? childCount : childDrawIndex;
8863                        if (childDrawIndex != 0) {
8864                            for (int i = 0; i < numChildrenToIterate; i++) {
8865                                final int otherDrawIndex = (customOrder ?
8866                                        parentGroup.getChildDrawingOrder(childCount, i) : i);
8867                                if (otherDrawIndex < childDrawIndex) {
8868                                    drawingOrderInParent +=
8869                                            numViewsForAccessibility(parentGroup.getChildAt(i));
8870                                }
8871                            }
8872                        }
8873                    }
8874                }
8875            }
8876            viewAtDrawingLevel = (View) currentParent;
8877        }
8878        info.setDrawingOrder(drawingOrderInParent);
8879    }
8880
8881    private static int numViewsForAccessibility(View view) {
8882        if (view != null) {
8883            if (view.includeForAccessibility()) {
8884                return 1;
8885            } else if (view instanceof ViewGroup) {
8886                return ((ViewGroup) view).getNumChildrenForAccessibility();
8887            }
8888        }
8889        return 0;
8890    }
8891
8892    private View findLabelForView(View view, int labeledId) {
8893        if (mMatchLabelForPredicate == null) {
8894            mMatchLabelForPredicate = new MatchLabelForPredicate();
8895        }
8896        mMatchLabelForPredicate.mLabeledId = labeledId;
8897        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
8898    }
8899
8900    /**
8901     * Computes whether this virtual autofill view is visible to the user.
8902     *
8903     * <p><b>Note: </b>By default it returns {@code true}, but views providing a virtual hierarchy
8904     * view must override it.
8905     *
8906     * @return Whether the view is visible on the screen.
8907     */
8908    public boolean isVisibleToUserForAutofill(int virtualId) {
8909        if (mContext.isAutofillCompatibilityEnabled()) {
8910            final AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
8911            if (provider != null) {
8912                final AccessibilityNodeInfo node = provider.createAccessibilityNodeInfo(virtualId);
8913                if (node != null) {
8914                    return node.isVisibleToUser();
8915                }
8916                // if node is null, assume it's not visible anymore
8917            } else {
8918                Log.w(VIEW_LOG_TAG, "isVisibleToUserForAutofill(" + virtualId + "): no provider");
8919            }
8920            return false;
8921        }
8922        return true;
8923    }
8924
8925    /**
8926     * Computes whether this view is visible to the user. Such a view is
8927     * attached, visible, all its predecessors are visible, it is not clipped
8928     * entirely by its predecessors, and has an alpha greater than zero.
8929     *
8930     * @return Whether the view is visible on the screen.
8931     *
8932     * @hide
8933     */
8934    public boolean isVisibleToUser() {
8935        return isVisibleToUser(null);
8936    }
8937
8938    /**
8939     * Computes whether the given portion of this view is visible to the user.
8940     * Such a view is attached, visible, all its predecessors are visible,
8941     * has an alpha greater than zero, and the specified portion is not
8942     * clipped entirely by its predecessors.
8943     *
8944     * @param boundInView the portion of the view to test; coordinates should be relative; may be
8945     *                    <code>null</code>, and the entire view will be tested in this case.
8946     *                    When <code>true</code> is returned by the function, the actual visible
8947     *                    region will be stored in this parameter; that is, if boundInView is fully
8948     *                    contained within the view, no modification will be made, otherwise regions
8949     *                    outside of the visible area of the view will be clipped.
8950     *
8951     * @return Whether the specified portion of the view is visible on the screen.
8952     *
8953     * @hide
8954     */
8955    protected boolean isVisibleToUser(Rect boundInView) {
8956        if (mAttachInfo != null) {
8957            // Attached to invisible window means this view is not visible.
8958            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
8959                return false;
8960            }
8961            // An invisible predecessor or one with alpha zero means
8962            // that this view is not visible to the user.
8963            Object current = this;
8964            while (current instanceof View) {
8965                View view = (View) current;
8966                // We have attach info so this view is attached and there is no
8967                // need to check whether we reach to ViewRootImpl on the way up.
8968                if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
8969                        view.getVisibility() != VISIBLE) {
8970                    return false;
8971                }
8972                current = view.mParent;
8973            }
8974            // Check if the view is entirely covered by its predecessors.
8975            Rect visibleRect = mAttachInfo.mTmpInvalRect;
8976            Point offset = mAttachInfo.mPoint;
8977            if (!getGlobalVisibleRect(visibleRect, offset)) {
8978                return false;
8979            }
8980            // Check if the visible portion intersects the rectangle of interest.
8981            if (boundInView != null) {
8982                visibleRect.offset(-offset.x, -offset.y);
8983                return boundInView.intersect(visibleRect);
8984            }
8985            return true;
8986        }
8987        return false;
8988    }
8989
8990    /**
8991     * Returns the delegate for implementing accessibility support via
8992     * composition. For more details see {@link AccessibilityDelegate}.
8993     *
8994     * @return The delegate, or null if none set.
8995     *
8996     * @hide
8997     */
8998    public AccessibilityDelegate getAccessibilityDelegate() {
8999        return mAccessibilityDelegate;
9000    }
9001
9002    /**
9003     * Sets a delegate for implementing accessibility support via composition
9004     * (as opposed to inheritance). For more details, see
9005     * {@link AccessibilityDelegate}.
9006     * <p>
9007     * <strong>Note:</strong> On platform versions prior to
9008     * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on
9009     * views in the {@code android.widget.*} package are called <i>before</i>
9010     * host methods. This prevents certain properties such as class name from
9011     * being modified by overriding
9012     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)},
9013     * as any changes will be overwritten by the host class.
9014     * <p>
9015     * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate
9016     * methods are called <i>after</i> host methods, which all properties to be
9017     * modified without being overwritten by the host class.
9018     *
9019     * @param delegate the object to which accessibility method calls should be
9020     *                 delegated
9021     * @see AccessibilityDelegate
9022     */
9023    public void setAccessibilityDelegate(@Nullable AccessibilityDelegate delegate) {
9024        mAccessibilityDelegate = delegate;
9025    }
9026
9027    /**
9028     * Gets the provider for managing a virtual view hierarchy rooted at this View
9029     * and reported to {@link android.accessibilityservice.AccessibilityService}s
9030     * that explore the window content.
9031     * <p>
9032     * If this method returns an instance, this instance is responsible for managing
9033     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
9034     * View including the one representing the View itself. Similarly the returned
9035     * instance is responsible for performing accessibility actions on any virtual
9036     * view or the root view itself.
9037     * </p>
9038     * <p>
9039     * If an {@link AccessibilityDelegate} has been specified via calling
9040     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
9041     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
9042     * is responsible for handling this call.
9043     * </p>
9044     *
9045     * @return The provider.
9046     *
9047     * @see AccessibilityNodeProvider
9048     */
9049    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
9050        if (mAccessibilityDelegate != null) {
9051            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
9052        } else {
9053            return null;
9054        }
9055    }
9056
9057    /**
9058     * Gets the unique identifier of this view on the screen for accessibility purposes.
9059     *
9060     * @return The view accessibility id.
9061     *
9062     * @hide
9063     */
9064    public int getAccessibilityViewId() {
9065        if (mAccessibilityViewId == NO_ID) {
9066            mAccessibilityViewId = sNextAccessibilityViewId++;
9067        }
9068        return mAccessibilityViewId;
9069    }
9070
9071    /**
9072     * Gets the unique identifier of this view on the screen for autofill purposes.
9073     *
9074     * @return The view autofill id.
9075     *
9076     * @hide
9077     */
9078    public int getAutofillViewId() {
9079        if (mAutofillViewId == NO_ID) {
9080            mAutofillViewId = mContext.getNextAutofillId();
9081        }
9082        return mAutofillViewId;
9083    }
9084
9085    /**
9086     * Gets the unique identifier of the window in which this View reseides.
9087     *
9088     * @return The window accessibility id.
9089     *
9090     * @hide
9091     */
9092    public int getAccessibilityWindowId() {
9093        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId
9094                : AccessibilityWindowInfo.UNDEFINED_WINDOW_ID;
9095    }
9096
9097    /**
9098     * Returns the {@link View}'s content description.
9099     * <p>
9100     * <strong>Note:</strong> Do not override this method, as it will have no
9101     * effect on the content description presented to accessibility services.
9102     * You must call {@link #setContentDescription(CharSequence)} to modify the
9103     * content description.
9104     *
9105     * @return the content description
9106     * @see #setContentDescription(CharSequence)
9107     * @attr ref android.R.styleable#View_contentDescription
9108     */
9109    @ViewDebug.ExportedProperty(category = "accessibility")
9110    public CharSequence getContentDescription() {
9111        return mContentDescription;
9112    }
9113
9114    /**
9115     * Sets the {@link View}'s content description.
9116     * <p>
9117     * A content description briefly describes the view and is primarily used
9118     * for accessibility support to determine how a view should be presented to
9119     * the user. In the case of a view with no textual representation, such as
9120     * {@link android.widget.ImageButton}, a useful content description
9121     * explains what the view does. For example, an image button with a phone
9122     * icon that is used to place a call may use "Call" as its content
9123     * description. An image of a floppy disk that is used to save a file may
9124     * use "Save".
9125     *
9126     * @param contentDescription The content description.
9127     * @see #getContentDescription()
9128     * @attr ref android.R.styleable#View_contentDescription
9129     */
9130    @RemotableViewMethod
9131    public void setContentDescription(CharSequence contentDescription) {
9132        if (mContentDescription == null) {
9133            if (contentDescription == null) {
9134                return;
9135            }
9136        } else if (mContentDescription.equals(contentDescription)) {
9137            return;
9138        }
9139        mContentDescription = contentDescription;
9140        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
9141        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
9142            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
9143            notifySubtreeAccessibilityStateChangedIfNeeded();
9144        } else {
9145            notifyViewAccessibilityStateChangedIfNeeded(
9146                    AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
9147        }
9148    }
9149
9150    /**
9151     * Sets the id of a view before which this one is visited in accessibility traversal.
9152     * A screen-reader must visit the content of this view before the content of the one
9153     * it precedes. For example, if view B is set to be before view A, then a screen-reader
9154     * will traverse the entire content of B before traversing the entire content of A,
9155     * regardles of what traversal strategy it is using.
9156     * <p>
9157     * Views that do not have specified before/after relationships are traversed in order
9158     * determined by the screen-reader.
9159     * </p>
9160     * <p>
9161     * Setting that this view is before a view that is not important for accessibility
9162     * or if this view is not important for accessibility will have no effect as the
9163     * screen-reader is not aware of unimportant views.
9164     * </p>
9165     *
9166     * @param beforeId The id of a view this one precedes in accessibility traversal.
9167     *
9168     * @attr ref android.R.styleable#View_accessibilityTraversalBefore
9169     *
9170     * @see #setImportantForAccessibility(int)
9171     */
9172    @RemotableViewMethod
9173    public void setAccessibilityTraversalBefore(int beforeId) {
9174        if (mAccessibilityTraversalBeforeId == beforeId) {
9175            return;
9176        }
9177        mAccessibilityTraversalBeforeId = beforeId;
9178        notifyViewAccessibilityStateChangedIfNeeded(
9179                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9180    }
9181
9182    /**
9183     * Gets the id of a view before which this one is visited in accessibility traversal.
9184     *
9185     * @return The id of a view this one precedes in accessibility traversal if
9186     *         specified, otherwise {@link #NO_ID}.
9187     *
9188     * @see #setAccessibilityTraversalBefore(int)
9189     */
9190    public int getAccessibilityTraversalBefore() {
9191        return mAccessibilityTraversalBeforeId;
9192    }
9193
9194    /**
9195     * Sets the id of a view after which this one is visited in accessibility traversal.
9196     * A screen-reader must visit the content of the other view before the content of this
9197     * one. For example, if view B is set to be after view A, then a screen-reader
9198     * will traverse the entire content of A before traversing the entire content of B,
9199     * regardles of what traversal strategy it is using.
9200     * <p>
9201     * Views that do not have specified before/after relationships are traversed in order
9202     * determined by the screen-reader.
9203     * </p>
9204     * <p>
9205     * Setting that this view is after a view that is not important for accessibility
9206     * or if this view is not important for accessibility will have no effect as the
9207     * screen-reader is not aware of unimportant views.
9208     * </p>
9209     *
9210     * @param afterId The id of a view this one succedees in accessibility traversal.
9211     *
9212     * @attr ref android.R.styleable#View_accessibilityTraversalAfter
9213     *
9214     * @see #setImportantForAccessibility(int)
9215     */
9216    @RemotableViewMethod
9217    public void setAccessibilityTraversalAfter(int afterId) {
9218        if (mAccessibilityTraversalAfterId == afterId) {
9219            return;
9220        }
9221        mAccessibilityTraversalAfterId = afterId;
9222        notifyViewAccessibilityStateChangedIfNeeded(
9223                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9224    }
9225
9226    /**
9227     * Gets the id of a view after which this one is visited in accessibility traversal.
9228     *
9229     * @return The id of a view this one succeedes in accessibility traversal if
9230     *         specified, otherwise {@link #NO_ID}.
9231     *
9232     * @see #setAccessibilityTraversalAfter(int)
9233     */
9234    public int getAccessibilityTraversalAfter() {
9235        return mAccessibilityTraversalAfterId;
9236    }
9237
9238    /**
9239     * Gets the id of a view for which this view serves as a label for
9240     * accessibility purposes.
9241     *
9242     * @return The labeled view id.
9243     */
9244    @ViewDebug.ExportedProperty(category = "accessibility")
9245    public int getLabelFor() {
9246        return mLabelForId;
9247    }
9248
9249    /**
9250     * Sets the id of a view for which this view serves as a label for
9251     * accessibility purposes.
9252     *
9253     * @param id The labeled view id.
9254     */
9255    @RemotableViewMethod
9256    public void setLabelFor(@IdRes int id) {
9257        if (mLabelForId == id) {
9258            return;
9259        }
9260        mLabelForId = id;
9261        if (mLabelForId != View.NO_ID
9262                && mID == View.NO_ID) {
9263            mID = generateViewId();
9264        }
9265        notifyViewAccessibilityStateChangedIfNeeded(
9266                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9267    }
9268
9269    /**
9270     * Invoked whenever this view loses focus, either by losing window focus or by losing
9271     * focus within its window. This method can be used to clear any state tied to the
9272     * focus. For instance, if a button is held pressed with the trackball and the window
9273     * loses focus, this method can be used to cancel the press.
9274     *
9275     * Subclasses of View overriding this method should always call super.onFocusLost().
9276     *
9277     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
9278     * @see #onWindowFocusChanged(boolean)
9279     *
9280     * @hide pending API council approval
9281     */
9282    @CallSuper
9283    protected void onFocusLost() {
9284        resetPressedState();
9285    }
9286
9287    private void resetPressedState() {
9288        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
9289            return;
9290        }
9291
9292        if (isPressed()) {
9293            setPressed(false);
9294
9295            if (!mHasPerformedLongPress) {
9296                removeLongPressCallback();
9297            }
9298        }
9299    }
9300
9301    /**
9302     * Returns true if this view has focus
9303     *
9304     * @return True if this view has focus, false otherwise.
9305     */
9306    @ViewDebug.ExportedProperty(category = "focus")
9307    public boolean isFocused() {
9308        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
9309    }
9310
9311    /**
9312     * Find the view in the hierarchy rooted at this view that currently has
9313     * focus.
9314     *
9315     * @return The view that currently has focus, or null if no focused view can
9316     *         be found.
9317     */
9318    public View findFocus() {
9319        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
9320    }
9321
9322    /**
9323     * Indicates whether this view is one of the set of scrollable containers in
9324     * its window.
9325     *
9326     * @return whether this view is one of the set of scrollable containers in
9327     * its window
9328     *
9329     * @attr ref android.R.styleable#View_isScrollContainer
9330     */
9331    public boolean isScrollContainer() {
9332        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
9333    }
9334
9335    /**
9336     * Change whether this view is one of the set of scrollable containers in
9337     * its window.  This will be used to determine whether the window can
9338     * resize or must pan when a soft input area is open -- scrollable
9339     * containers allow the window to use resize mode since the container
9340     * will appropriately shrink.
9341     *
9342     * @attr ref android.R.styleable#View_isScrollContainer
9343     */
9344    public void setScrollContainer(boolean isScrollContainer) {
9345        if (isScrollContainer) {
9346            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
9347                mAttachInfo.mScrollContainers.add(this);
9348                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
9349            }
9350            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
9351        } else {
9352            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
9353                mAttachInfo.mScrollContainers.remove(this);
9354            }
9355            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
9356        }
9357    }
9358
9359    /**
9360     * Returns the quality of the drawing cache.
9361     *
9362     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
9363     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
9364     *
9365     * @see #setDrawingCacheQuality(int)
9366     * @see #setDrawingCacheEnabled(boolean)
9367     * @see #isDrawingCacheEnabled()
9368     *
9369     * @attr ref android.R.styleable#View_drawingCacheQuality
9370     *
9371     * @deprecated The view drawing cache was largely made obsolete with the introduction of
9372     * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
9373     * layers are largely unnecessary and can easily result in a net loss in performance due to the
9374     * cost of creating and updating the layer. In the rare cases where caching layers are useful,
9375     * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
9376     * rendering. For software-rendered snapshots of a small part of the View hierarchy or
9377     * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
9378     * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
9379     * software-rendered usages are discouraged and have compatibility issues with hardware-only
9380     * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
9381     * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
9382     * reports or unit testing the {@link PixelCopy} API is recommended.
9383     */
9384    @Deprecated
9385    @DrawingCacheQuality
9386    public int getDrawingCacheQuality() {
9387        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
9388    }
9389
9390    /**
9391     * Set the drawing cache quality of this view. This value is used only when the
9392     * drawing cache is enabled
9393     *
9394     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
9395     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
9396     *
9397     * @see #getDrawingCacheQuality()
9398     * @see #setDrawingCacheEnabled(boolean)
9399     * @see #isDrawingCacheEnabled()
9400     *
9401     * @attr ref android.R.styleable#View_drawingCacheQuality
9402     *
9403     * @deprecated The view drawing cache was largely made obsolete with the introduction of
9404     * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
9405     * layers are largely unnecessary and can easily result in a net loss in performance due to the
9406     * cost of creating and updating the layer. In the rare cases where caching layers are useful,
9407     * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
9408     * rendering. For software-rendered snapshots of a small part of the View hierarchy or
9409     * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
9410     * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
9411     * software-rendered usages are discouraged and have compatibility issues with hardware-only
9412     * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
9413     * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
9414     * reports or unit testing the {@link PixelCopy} API is recommended.
9415     */
9416    @Deprecated
9417    public void setDrawingCacheQuality(@DrawingCacheQuality int quality) {
9418        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
9419    }
9420
9421    /**
9422     * Returns whether the screen should remain on, corresponding to the current
9423     * value of {@link #KEEP_SCREEN_ON}.
9424     *
9425     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
9426     *
9427     * @see #setKeepScreenOn(boolean)
9428     *
9429     * @attr ref android.R.styleable#View_keepScreenOn
9430     */
9431    public boolean getKeepScreenOn() {
9432        return (mViewFlags & KEEP_SCREEN_ON) != 0;
9433    }
9434
9435    /**
9436     * Controls whether the screen should remain on, modifying the
9437     * value of {@link #KEEP_SCREEN_ON}.
9438     *
9439     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
9440     *
9441     * @see #getKeepScreenOn()
9442     *
9443     * @attr ref android.R.styleable#View_keepScreenOn
9444     */
9445    public void setKeepScreenOn(boolean keepScreenOn) {
9446        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
9447    }
9448
9449    /**
9450     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
9451     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
9452     *
9453     * @attr ref android.R.styleable#View_nextFocusLeft
9454     */
9455    public int getNextFocusLeftId() {
9456        return mNextFocusLeftId;
9457    }
9458
9459    /**
9460     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
9461     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
9462     * decide automatically.
9463     *
9464     * @attr ref android.R.styleable#View_nextFocusLeft
9465     */
9466    public void setNextFocusLeftId(int nextFocusLeftId) {
9467        mNextFocusLeftId = nextFocusLeftId;
9468    }
9469
9470    /**
9471     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
9472     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
9473     *
9474     * @attr ref android.R.styleable#View_nextFocusRight
9475     */
9476    public int getNextFocusRightId() {
9477        return mNextFocusRightId;
9478    }
9479
9480    /**
9481     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
9482     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
9483     * decide automatically.
9484     *
9485     * @attr ref android.R.styleable#View_nextFocusRight
9486     */
9487    public void setNextFocusRightId(int nextFocusRightId) {
9488        mNextFocusRightId = nextFocusRightId;
9489    }
9490
9491    /**
9492     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
9493     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
9494     *
9495     * @attr ref android.R.styleable#View_nextFocusUp
9496     */
9497    public int getNextFocusUpId() {
9498        return mNextFocusUpId;
9499    }
9500
9501    /**
9502     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
9503     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
9504     * decide automatically.
9505     *
9506     * @attr ref android.R.styleable#View_nextFocusUp
9507     */
9508    public void setNextFocusUpId(int nextFocusUpId) {
9509        mNextFocusUpId = nextFocusUpId;
9510    }
9511
9512    /**
9513     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
9514     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
9515     *
9516     * @attr ref android.R.styleable#View_nextFocusDown
9517     */
9518    public int getNextFocusDownId() {
9519        return mNextFocusDownId;
9520    }
9521
9522    /**
9523     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
9524     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
9525     * decide automatically.
9526     *
9527     * @attr ref android.R.styleable#View_nextFocusDown
9528     */
9529    public void setNextFocusDownId(int nextFocusDownId) {
9530        mNextFocusDownId = nextFocusDownId;
9531    }
9532
9533    /**
9534     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
9535     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
9536     *
9537     * @attr ref android.R.styleable#View_nextFocusForward
9538     */
9539    public int getNextFocusForwardId() {
9540        return mNextFocusForwardId;
9541    }
9542
9543    /**
9544     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
9545     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
9546     * decide automatically.
9547     *
9548     * @attr ref android.R.styleable#View_nextFocusForward
9549     */
9550    public void setNextFocusForwardId(int nextFocusForwardId) {
9551        mNextFocusForwardId = nextFocusForwardId;
9552    }
9553
9554    /**
9555     * Gets the id of the root of the next keyboard navigation cluster.
9556     * @return The next keyboard navigation cluster ID, or {@link #NO_ID} if the framework should
9557     * decide automatically.
9558     *
9559     * @attr ref android.R.styleable#View_nextClusterForward
9560     */
9561    public int getNextClusterForwardId() {
9562        return mNextClusterForwardId;
9563    }
9564
9565    /**
9566     * Sets the id of the view to use as the root of the next keyboard navigation cluster.
9567     * @param nextClusterForwardId The next cluster ID, or {@link #NO_ID} if the framework should
9568     * decide automatically.
9569     *
9570     * @attr ref android.R.styleable#View_nextClusterForward
9571     */
9572    public void setNextClusterForwardId(int nextClusterForwardId) {
9573        mNextClusterForwardId = nextClusterForwardId;
9574    }
9575
9576    /**
9577     * Returns the visibility of this view and all of its ancestors
9578     *
9579     * @return True if this view and all of its ancestors are {@link #VISIBLE}
9580     */
9581    public boolean isShown() {
9582        View current = this;
9583        //noinspection ConstantConditions
9584        do {
9585            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
9586                return false;
9587            }
9588            ViewParent parent = current.mParent;
9589            if (parent == null) {
9590                return false; // We are not attached to the view root
9591            }
9592            if (!(parent instanceof View)) {
9593                return true;
9594            }
9595            current = (View) parent;
9596        } while (current != null);
9597
9598        return false;
9599    }
9600
9601    /**
9602     * Called by the view hierarchy when the content insets for a window have
9603     * changed, to allow it to adjust its content to fit within those windows.
9604     * The content insets tell you the space that the status bar, input method,
9605     * and other system windows infringe on the application's window.
9606     *
9607     * <p>You do not normally need to deal with this function, since the default
9608     * window decoration given to applications takes care of applying it to the
9609     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
9610     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
9611     * and your content can be placed under those system elements.  You can then
9612     * use this method within your view hierarchy if you have parts of your UI
9613     * which you would like to ensure are not being covered.
9614     *
9615     * <p>The default implementation of this method simply applies the content
9616     * insets to the view's padding, consuming that content (modifying the
9617     * insets to be 0), and returning true.  This behavior is off by default, but can
9618     * be enabled through {@link #setFitsSystemWindows(boolean)}.
9619     *
9620     * <p>This function's traversal down the hierarchy is depth-first.  The same content
9621     * insets object is propagated down the hierarchy, so any changes made to it will
9622     * be seen by all following views (including potentially ones above in
9623     * the hierarchy since this is a depth-first traversal).  The first view
9624     * that returns true will abort the entire traversal.
9625     *
9626     * <p>The default implementation works well for a situation where it is
9627     * used with a container that covers the entire window, allowing it to
9628     * apply the appropriate insets to its content on all edges.  If you need
9629     * a more complicated layout (such as two different views fitting system
9630     * windows, one on the top of the window, and one on the bottom),
9631     * you can override the method and handle the insets however you would like.
9632     * Note that the insets provided by the framework are always relative to the
9633     * far edges of the window, not accounting for the location of the called view
9634     * within that window.  (In fact when this method is called you do not yet know
9635     * where the layout will place the view, as it is done before layout happens.)
9636     *
9637     * <p>Note: unlike many View methods, there is no dispatch phase to this
9638     * call.  If you are overriding it in a ViewGroup and want to allow the
9639     * call to continue to your children, you must be sure to call the super
9640     * implementation.
9641     *
9642     * <p>Here is a sample layout that makes use of fitting system windows
9643     * to have controls for a video view placed inside of the window decorations
9644     * that it hides and shows.  This can be used with code like the second
9645     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
9646     *
9647     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
9648     *
9649     * @param insets Current content insets of the window.  Prior to
9650     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
9651     * the insets or else you and Android will be unhappy.
9652     *
9653     * @return {@code true} if this view applied the insets and it should not
9654     * continue propagating further down the hierarchy, {@code false} otherwise.
9655     * @see #getFitsSystemWindows()
9656     * @see #setFitsSystemWindows(boolean)
9657     * @see #setSystemUiVisibility(int)
9658     *
9659     * @deprecated As of API 20 use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply
9660     * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use
9661     * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)}
9662     * to implement handling their own insets.
9663     */
9664    @Deprecated
9665    protected boolean fitSystemWindows(Rect insets) {
9666        if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) {
9667            if (insets == null) {
9668                // Null insets by definition have already been consumed.
9669                // This call cannot apply insets since there are none to apply,
9670                // so return false.
9671                return false;
9672            }
9673            // If we're not in the process of dispatching the newer apply insets call,
9674            // that means we're not in the compatibility path. Dispatch into the newer
9675            // apply insets path and take things from there.
9676            try {
9677                mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS;
9678                return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed();
9679            } finally {
9680                mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS;
9681            }
9682        } else {
9683            // We're being called from the newer apply insets path.
9684            // Perform the standard fallback behavior.
9685            return fitSystemWindowsInt(insets);
9686        }
9687    }
9688
9689    private boolean fitSystemWindowsInt(Rect insets) {
9690        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
9691            mUserPaddingStart = UNDEFINED_PADDING;
9692            mUserPaddingEnd = UNDEFINED_PADDING;
9693            Rect localInsets = sThreadLocal.get();
9694            if (localInsets == null) {
9695                localInsets = new Rect();
9696                sThreadLocal.set(localInsets);
9697            }
9698            boolean res = computeFitSystemWindows(insets, localInsets);
9699            mUserPaddingLeftInitial = localInsets.left;
9700            mUserPaddingRightInitial = localInsets.right;
9701            internalSetPadding(localInsets.left, localInsets.top,
9702                    localInsets.right, localInsets.bottom);
9703            return res;
9704        }
9705        return false;
9706    }
9707
9708    /**
9709     * Called when the view should apply {@link WindowInsets} according to its internal policy.
9710     *
9711     * <p>This method should be overridden by views that wish to apply a policy different from or
9712     * in addition to the default behavior. Clients that wish to force a view subtree
9713     * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p>
9714     *
9715     * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set
9716     * it will be called during dispatch instead of this method. The listener may optionally
9717     * call this method from its own implementation if it wishes to apply the view's default
9718     * insets policy in addition to its own.</p>
9719     *
9720     * <p>Implementations of this method should either return the insets parameter unchanged
9721     * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed
9722     * that this view applied itself. This allows new inset types added in future platform
9723     * versions to pass through existing implementations unchanged without being erroneously
9724     * consumed.</p>
9725     *
9726     * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows}
9727     * property is set then the view will consume the system window insets and apply them
9728     * as padding for the view.</p>
9729     *
9730     * @param insets Insets to apply
9731     * @return The supplied insets with any applied insets consumed
9732     */
9733    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
9734        if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) {
9735            // We weren't called from within a direct call to fitSystemWindows,
9736            // call into it as a fallback in case we're in a class that overrides it
9737            // and has logic to perform.
9738            if (fitSystemWindows(insets.getSystemWindowInsets())) {
9739                return insets.consumeSystemWindowInsets();
9740            }
9741        } else {
9742            // We were called from within a direct call to fitSystemWindows.
9743            if (fitSystemWindowsInt(insets.getSystemWindowInsets())) {
9744                return insets.consumeSystemWindowInsets();
9745            }
9746        }
9747        return insets;
9748    }
9749
9750    /**
9751     * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying
9752     * window insets to this view. The listener's
9753     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
9754     * method will be called instead of the view's
9755     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
9756     *
9757     * @param listener Listener to set
9758     *
9759     * @see #onApplyWindowInsets(WindowInsets)
9760     */
9761    public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {
9762        getListenerInfo().mOnApplyWindowInsetsListener = listener;
9763    }
9764
9765    /**
9766     * Request to apply the given window insets to this view or another view in its subtree.
9767     *
9768     * <p>This method should be called by clients wishing to apply insets corresponding to areas
9769     * obscured by window decorations or overlays. This can include the status and navigation bars,
9770     * action bars, input methods and more. New inset categories may be added in the future.
9771     * The method returns the insets provided minus any that were applied by this view or its
9772     * children.</p>
9773     *
9774     * <p>Clients wishing to provide custom behavior should override the
9775     * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a
9776     * {@link OnApplyWindowInsetsListener} via the
9777     * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener}
9778     * method.</p>
9779     *
9780     * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method.
9781     * </p>
9782     *
9783     * @param insets Insets to apply
9784     * @return The provided insets minus the insets that were consumed
9785     */
9786    public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
9787        try {
9788            mPrivateFlags3 |= PFLAG3_APPLYING_INSETS;
9789            if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
9790                return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);
9791            } else {
9792                return onApplyWindowInsets(insets);
9793            }
9794        } finally {
9795            mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS;
9796        }
9797    }
9798
9799    /**
9800     * Compute the view's coordinate within the surface.
9801     *
9802     * <p>Computes the coordinates of this view in its surface. The argument
9803     * must be an array of two integers. After the method returns, the array
9804     * contains the x and y location in that order.</p>
9805     * @hide
9806     * @param location an array of two integers in which to hold the coordinates
9807     */
9808    public void getLocationInSurface(@Size(2) int[] location) {
9809        getLocationInWindow(location);
9810        if (mAttachInfo != null && mAttachInfo.mViewRootImpl != null) {
9811            location[0] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.left;
9812            location[1] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.top;
9813        }
9814    }
9815
9816    /**
9817     * Provide original WindowInsets that are dispatched to the view hierarchy. The insets are
9818     * only available if the view is attached.
9819     *
9820     * @return WindowInsets from the top of the view hierarchy or null if View is detached
9821     */
9822    public WindowInsets getRootWindowInsets() {
9823        if (mAttachInfo != null) {
9824            return mAttachInfo.mViewRootImpl.getWindowInsets(false /* forceConstruct */);
9825        }
9826        return null;
9827    }
9828
9829    /**
9830     * @hide Compute the insets that should be consumed by this view and the ones
9831     * that should propagate to those under it.
9832     */
9833    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
9834        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
9835                || mAttachInfo == null
9836                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
9837                        && !mAttachInfo.mOverscanRequested)) {
9838            outLocalInsets.set(inoutInsets);
9839            inoutInsets.set(0, 0, 0, 0);
9840            return true;
9841        } else {
9842            // The application wants to take care of fitting system window for
9843            // the content...  however we still need to take care of any overscan here.
9844            final Rect overscan = mAttachInfo.mOverscanInsets;
9845            outLocalInsets.set(overscan);
9846            inoutInsets.left -= overscan.left;
9847            inoutInsets.top -= overscan.top;
9848            inoutInsets.right -= overscan.right;
9849            inoutInsets.bottom -= overscan.bottom;
9850            return false;
9851        }
9852    }
9853
9854    /**
9855     * Compute insets that should be consumed by this view and the ones that should propagate
9856     * to those under it.
9857     *
9858     * @param in Insets currently being processed by this View, likely received as a parameter
9859     *           to {@link #onApplyWindowInsets(WindowInsets)}.
9860     * @param outLocalInsets A Rect that will receive the insets that should be consumed
9861     *                       by this view
9862     * @return Insets that should be passed along to views under this one
9863     */
9864    public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) {
9865        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
9866                || mAttachInfo == null
9867                || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
9868            outLocalInsets.set(in.getSystemWindowInsets());
9869            return in.consumeSystemWindowInsets();
9870        } else {
9871            outLocalInsets.set(0, 0, 0, 0);
9872            return in;
9873        }
9874    }
9875
9876    /**
9877     * Sets whether or not this view should account for system screen decorations
9878     * such as the status bar and inset its content; that is, controlling whether
9879     * the default implementation of {@link #fitSystemWindows(Rect)} will be
9880     * executed.  See that method for more details.
9881     *
9882     * <p>Note that if you are providing your own implementation of
9883     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
9884     * flag to true -- your implementation will be overriding the default
9885     * implementation that checks this flag.
9886     *
9887     * @param fitSystemWindows If true, then the default implementation of
9888     * {@link #fitSystemWindows(Rect)} will be executed.
9889     *
9890     * @attr ref android.R.styleable#View_fitsSystemWindows
9891     * @see #getFitsSystemWindows()
9892     * @see #fitSystemWindows(Rect)
9893     * @see #setSystemUiVisibility(int)
9894     */
9895    public void setFitsSystemWindows(boolean fitSystemWindows) {
9896        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
9897    }
9898
9899    /**
9900     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
9901     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
9902     * will be executed.
9903     *
9904     * @return {@code true} if the default implementation of
9905     * {@link #fitSystemWindows(Rect)} will be executed.
9906     *
9907     * @attr ref android.R.styleable#View_fitsSystemWindows
9908     * @see #setFitsSystemWindows(boolean)
9909     * @see #fitSystemWindows(Rect)
9910     * @see #setSystemUiVisibility(int)
9911     */
9912    @ViewDebug.ExportedProperty
9913    public boolean getFitsSystemWindows() {
9914        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
9915    }
9916
9917    /** @hide */
9918    public boolean fitsSystemWindows() {
9919        return getFitsSystemWindows();
9920    }
9921
9922    /**
9923     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
9924     * @deprecated Use {@link #requestApplyInsets()} for newer platform versions.
9925     */
9926    @Deprecated
9927    public void requestFitSystemWindows() {
9928        if (mParent != null) {
9929            mParent.requestFitSystemWindows();
9930        }
9931    }
9932
9933    /**
9934     * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed.
9935     */
9936    public void requestApplyInsets() {
9937        requestFitSystemWindows();
9938    }
9939
9940    /**
9941     * For use by PhoneWindow to make its own system window fitting optional.
9942     * @hide
9943     */
9944    public void makeOptionalFitsSystemWindows() {
9945        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
9946    }
9947
9948    /**
9949     * Returns the outsets, which areas of the device that aren't a surface, but we would like to
9950     * treat them as such.
9951     * @hide
9952     */
9953    public void getOutsets(Rect outOutsetRect) {
9954        if (mAttachInfo != null) {
9955            outOutsetRect.set(mAttachInfo.mOutsets);
9956        } else {
9957            outOutsetRect.setEmpty();
9958        }
9959    }
9960
9961    /**
9962     * Returns the visibility status for this view.
9963     *
9964     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
9965     * @attr ref android.R.styleable#View_visibility
9966     */
9967    @ViewDebug.ExportedProperty(mapping = {
9968        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
9969        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
9970        @ViewDebug.IntToString(from = GONE,      to = "GONE")
9971    })
9972    @Visibility
9973    public int getVisibility() {
9974        return mViewFlags & VISIBILITY_MASK;
9975    }
9976
9977    /**
9978     * Set the visibility state of this view.
9979     *
9980     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
9981     * @attr ref android.R.styleable#View_visibility
9982     */
9983    @RemotableViewMethod
9984    public void setVisibility(@Visibility int visibility) {
9985        setFlags(visibility, VISIBILITY_MASK);
9986    }
9987
9988    /**
9989     * Returns the enabled status for this view. The interpretation of the
9990     * enabled state varies by subclass.
9991     *
9992     * @return True if this view is enabled, false otherwise.
9993     */
9994    @ViewDebug.ExportedProperty
9995    public boolean isEnabled() {
9996        return (mViewFlags & ENABLED_MASK) == ENABLED;
9997    }
9998
9999    /**
10000     * Set the enabled state of this view. The interpretation of the enabled
10001     * state varies by subclass.
10002     *
10003     * @param enabled True if this view is enabled, false otherwise.
10004     */
10005    @RemotableViewMethod
10006    public void setEnabled(boolean enabled) {
10007        if (enabled == isEnabled()) return;
10008
10009        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
10010
10011        /*
10012         * The View most likely has to change its appearance, so refresh
10013         * the drawable state.
10014         */
10015        refreshDrawableState();
10016
10017        // Invalidate too, since the default behavior for views is to be
10018        // be drawn at 50% alpha rather than to change the drawable.
10019        invalidate(true);
10020
10021        if (!enabled) {
10022            cancelPendingInputEvents();
10023        }
10024    }
10025
10026    /**
10027     * Set whether this view can receive the focus.
10028     * <p>
10029     * Setting this to false will also ensure that this view is not focusable
10030     * in touch mode.
10031     *
10032     * @param focusable If true, this view can receive the focus.
10033     *
10034     * @see #setFocusableInTouchMode(boolean)
10035     * @see #setFocusable(int)
10036     * @attr ref android.R.styleable#View_focusable
10037     */
10038    public void setFocusable(boolean focusable) {
10039        setFocusable(focusable ? FOCUSABLE : NOT_FOCUSABLE);
10040    }
10041
10042    /**
10043     * Sets whether this view can receive focus.
10044     * <p>
10045     * Setting this to {@link #FOCUSABLE_AUTO} tells the framework to determine focusability
10046     * automatically based on the view's interactivity. This is the default.
10047     * <p>
10048     * Setting this to NOT_FOCUSABLE will ensure that this view is also not focusable
10049     * in touch mode.
10050     *
10051     * @param focusable One of {@link #NOT_FOCUSABLE}, {@link #FOCUSABLE},
10052     *                  or {@link #FOCUSABLE_AUTO}.
10053     * @see #setFocusableInTouchMode(boolean)
10054     * @attr ref android.R.styleable#View_focusable
10055     */
10056    public void setFocusable(@Focusable int focusable) {
10057        if ((focusable & (FOCUSABLE_AUTO | FOCUSABLE)) == 0) {
10058            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
10059        }
10060        setFlags(focusable, FOCUSABLE_MASK);
10061    }
10062
10063    /**
10064     * Set whether this view can receive focus while in touch mode.
10065     *
10066     * Setting this to true will also ensure that this view is focusable.
10067     *
10068     * @param focusableInTouchMode If true, this view can receive the focus while
10069     *   in touch mode.
10070     *
10071     * @see #setFocusable(boolean)
10072     * @attr ref android.R.styleable#View_focusableInTouchMode
10073     */
10074    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
10075        // Focusable in touch mode should always be set before the focusable flag
10076        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
10077        // which, in touch mode, will not successfully request focus on this view
10078        // because the focusable in touch mode flag is not set
10079        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
10080
10081        // Clear FOCUSABLE_AUTO if set.
10082        if (focusableInTouchMode) {
10083            // Clears FOCUSABLE_AUTO if set.
10084            setFlags(FOCUSABLE, FOCUSABLE_MASK);
10085        }
10086    }
10087
10088    /**
10089     * Sets the hints that help an {@link android.service.autofill.AutofillService} determine how
10090     * to autofill the view with the user's data.
10091     *
10092     * <p>Typically, there is only one way to autofill a view, but there could be more than one.
10093     * For example, if the application accepts either an username or email address to identify
10094     * an user.
10095     *
10096     * <p>These hints are not validated by the Android System, but passed "as is" to the service.
10097     * Hence, they can have any value, but it's recommended to use the {@code AUTOFILL_HINT_}
10098     * constants such as:
10099     * {@link #AUTOFILL_HINT_USERNAME}, {@link #AUTOFILL_HINT_PASSWORD},
10100     * {@link #AUTOFILL_HINT_EMAIL_ADDRESS},
10101     * {@link #AUTOFILL_HINT_NAME},
10102     * {@link #AUTOFILL_HINT_PHONE},
10103     * {@link #AUTOFILL_HINT_POSTAL_ADDRESS}, {@link #AUTOFILL_HINT_POSTAL_CODE},
10104     * {@link #AUTOFILL_HINT_CREDIT_CARD_NUMBER}, {@link #AUTOFILL_HINT_CREDIT_CARD_SECURITY_CODE},
10105     * {@link #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DATE},
10106     * {@link #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DAY},
10107     * {@link #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_MONTH} or
10108     * {@link #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_YEAR}.
10109     *
10110     * @param autofillHints The autofill hints to set. If the array is emtpy, {@code null} is set.
10111     * @attr ref android.R.styleable#View_autofillHints
10112     */
10113    public void setAutofillHints(@Nullable String... autofillHints) {
10114        if (autofillHints == null || autofillHints.length == 0) {
10115            mAutofillHints = null;
10116        } else {
10117            mAutofillHints = autofillHints;
10118        }
10119    }
10120
10121    /**
10122     * @hide
10123     */
10124    @TestApi
10125    public void setAutofilled(boolean isAutofilled) {
10126        boolean wasChanged = isAutofilled != isAutofilled();
10127
10128        if (wasChanged) {
10129            if (isAutofilled) {
10130                mPrivateFlags3 |= PFLAG3_IS_AUTOFILLED;
10131            } else {
10132                mPrivateFlags3 &= ~PFLAG3_IS_AUTOFILLED;
10133            }
10134
10135            invalidate();
10136        }
10137    }
10138
10139    /**
10140     * Set whether this view should have sound effects enabled for events such as
10141     * clicking and touching.
10142     *
10143     * <p>You may wish to disable sound effects for a view if you already play sounds,
10144     * for instance, a dial key that plays dtmf tones.
10145     *
10146     * @param soundEffectsEnabled whether sound effects are enabled for this view.
10147     * @see #isSoundEffectsEnabled()
10148     * @see #playSoundEffect(int)
10149     * @attr ref android.R.styleable#View_soundEffectsEnabled
10150     */
10151    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
10152        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
10153    }
10154
10155    /**
10156     * @return whether this view should have sound effects enabled for events such as
10157     *     clicking and touching.
10158     *
10159     * @see #setSoundEffectsEnabled(boolean)
10160     * @see #playSoundEffect(int)
10161     * @attr ref android.R.styleable#View_soundEffectsEnabled
10162     */
10163    @ViewDebug.ExportedProperty
10164    public boolean isSoundEffectsEnabled() {
10165        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
10166    }
10167
10168    /**
10169     * Set whether this view should have haptic feedback for events such as
10170     * long presses.
10171     *
10172     * <p>You may wish to disable haptic feedback if your view already controls
10173     * its own haptic feedback.
10174     *
10175     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
10176     * @see #isHapticFeedbackEnabled()
10177     * @see #performHapticFeedback(int)
10178     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
10179     */
10180    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
10181        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
10182    }
10183
10184    /**
10185     * @return whether this view should have haptic feedback enabled for events
10186     * long presses.
10187     *
10188     * @see #setHapticFeedbackEnabled(boolean)
10189     * @see #performHapticFeedback(int)
10190     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
10191     */
10192    @ViewDebug.ExportedProperty
10193    public boolean isHapticFeedbackEnabled() {
10194        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
10195    }
10196
10197    /**
10198     * Returns the layout direction for this view.
10199     *
10200     * @return One of {@link #LAYOUT_DIRECTION_LTR},
10201     *   {@link #LAYOUT_DIRECTION_RTL},
10202     *   {@link #LAYOUT_DIRECTION_INHERIT} or
10203     *   {@link #LAYOUT_DIRECTION_LOCALE}.
10204     *
10205     * @attr ref android.R.styleable#View_layoutDirection
10206     *
10207     * @hide
10208     */
10209    @ViewDebug.ExportedProperty(category = "layout", mapping = {
10210        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
10211        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
10212        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
10213        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
10214    })
10215    @LayoutDir
10216    public int getRawLayoutDirection() {
10217        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
10218    }
10219
10220    /**
10221     * Set the layout direction for this view. This will propagate a reset of layout direction
10222     * resolution to the view's children and resolve layout direction for this view.
10223     *
10224     * @param layoutDirection the layout direction to set. Should be one of:
10225     *
10226     * {@link #LAYOUT_DIRECTION_LTR},
10227     * {@link #LAYOUT_DIRECTION_RTL},
10228     * {@link #LAYOUT_DIRECTION_INHERIT},
10229     * {@link #LAYOUT_DIRECTION_LOCALE}.
10230     *
10231     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
10232     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
10233     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
10234     *
10235     * @attr ref android.R.styleable#View_layoutDirection
10236     */
10237    @RemotableViewMethod
10238    public void setLayoutDirection(@LayoutDir int layoutDirection) {
10239        if (getRawLayoutDirection() != layoutDirection) {
10240            // Reset the current layout direction and the resolved one
10241            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
10242            resetRtlProperties();
10243            // Set the new layout direction (filtered)
10244            mPrivateFlags2 |=
10245                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
10246            // We need to resolve all RTL properties as they all depend on layout direction
10247            resolveRtlPropertiesIfNeeded();
10248            requestLayout();
10249            invalidate(true);
10250        }
10251    }
10252
10253    /**
10254     * Returns the resolved layout direction for this view.
10255     *
10256     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
10257     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
10258     *
10259     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
10260     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
10261     *
10262     * @attr ref android.R.styleable#View_layoutDirection
10263     */
10264    @ViewDebug.ExportedProperty(category = "layout", mapping = {
10265        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
10266        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
10267    })
10268    @ResolvedLayoutDir
10269    public int getLayoutDirection() {
10270        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
10271        if (targetSdkVersion < Build.VERSION_CODES.JELLY_BEAN_MR1) {
10272            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
10273            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
10274        }
10275        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
10276                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
10277    }
10278
10279    /**
10280     * Indicates whether or not this view's layout is right-to-left. This is resolved from
10281     * layout attribute and/or the inherited value from the parent
10282     *
10283     * @return true if the layout is right-to-left.
10284     *
10285     * @hide
10286     */
10287    @ViewDebug.ExportedProperty(category = "layout")
10288    public boolean isLayoutRtl() {
10289        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
10290    }
10291
10292    /**
10293     * Indicates whether the view is currently tracking transient state that the
10294     * app should not need to concern itself with saving and restoring, but that
10295     * the framework should take special note to preserve when possible.
10296     *
10297     * <p>A view with transient state cannot be trivially rebound from an external
10298     * data source, such as an adapter binding item views in a list. This may be
10299     * because the view is performing an animation, tracking user selection
10300     * of content, or similar.</p>
10301     *
10302     * @return true if the view has transient state
10303     */
10304    @ViewDebug.ExportedProperty(category = "layout")
10305    public boolean hasTransientState() {
10306        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
10307    }
10308
10309    /**
10310     * Set whether this view is currently tracking transient state that the
10311     * framework should attempt to preserve when possible. This flag is reference counted,
10312     * so every call to setHasTransientState(true) should be paired with a later call
10313     * to setHasTransientState(false).
10314     *
10315     * <p>A view with transient state cannot be trivially rebound from an external
10316     * data source, such as an adapter binding item views in a list. This may be
10317     * because the view is performing an animation, tracking user selection
10318     * of content, or similar.</p>
10319     *
10320     * @param hasTransientState true if this view has transient state
10321     */
10322    public void setHasTransientState(boolean hasTransientState) {
10323        final boolean oldHasTransientState = hasTransientState();
10324        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
10325                mTransientStateCount - 1;
10326        if (mTransientStateCount < 0) {
10327            mTransientStateCount = 0;
10328            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
10329                    "unmatched pair of setHasTransientState calls");
10330        } else if ((hasTransientState && mTransientStateCount == 1) ||
10331                (!hasTransientState && mTransientStateCount == 0)) {
10332            // update flag if we've just incremented up from 0 or decremented down to 0
10333            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
10334                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
10335            final boolean newHasTransientState = hasTransientState();
10336            if (mParent != null && newHasTransientState != oldHasTransientState) {
10337                try {
10338                    mParent.childHasTransientStateChanged(this, newHasTransientState);
10339                } catch (AbstractMethodError e) {
10340                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
10341                            " does not fully implement ViewParent", e);
10342                }
10343            }
10344        }
10345    }
10346
10347    /**
10348     * Returns true if this view is currently attached to a window.
10349     */
10350    public boolean isAttachedToWindow() {
10351        return mAttachInfo != null;
10352    }
10353
10354    /**
10355     * Returns true if this view has been through at least one layout since it
10356     * was last attached to or detached from a window.
10357     */
10358    public boolean isLaidOut() {
10359        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
10360    }
10361
10362    /**
10363     * @return {@code true} if laid-out and not about to do another layout.
10364     */
10365    boolean isLayoutValid() {
10366        return isLaidOut() && ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == 0);
10367    }
10368
10369    /**
10370     * If this view doesn't do any drawing on its own, set this flag to
10371     * allow further optimizations. By default, this flag is not set on
10372     * View, but could be set on some View subclasses such as ViewGroup.
10373     *
10374     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
10375     * you should clear this flag.
10376     *
10377     * @param willNotDraw whether or not this View draw on its own
10378     */
10379    public void setWillNotDraw(boolean willNotDraw) {
10380        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
10381    }
10382
10383    /**
10384     * Returns whether or not this View draws on its own.
10385     *
10386     * @return true if this view has nothing to draw, false otherwise
10387     */
10388    @ViewDebug.ExportedProperty(category = "drawing")
10389    public boolean willNotDraw() {
10390        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
10391    }
10392
10393    /**
10394     * When a View's drawing cache is enabled, drawing is redirected to an
10395     * offscreen bitmap. Some views, like an ImageView, must be able to
10396     * bypass this mechanism if they already draw a single bitmap, to avoid
10397     * unnecessary usage of the memory.
10398     *
10399     * @param willNotCacheDrawing true if this view does not cache its
10400     *        drawing, false otherwise
10401     */
10402    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
10403        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
10404    }
10405
10406    /**
10407     * Returns whether or not this View can cache its drawing or not.
10408     *
10409     * @return true if this view does not cache its drawing, false otherwise
10410     */
10411    @ViewDebug.ExportedProperty(category = "drawing")
10412    public boolean willNotCacheDrawing() {
10413        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
10414    }
10415
10416    /**
10417     * Indicates whether this view reacts to click events or not.
10418     *
10419     * @return true if the view is clickable, false otherwise
10420     *
10421     * @see #setClickable(boolean)
10422     * @attr ref android.R.styleable#View_clickable
10423     */
10424    @ViewDebug.ExportedProperty
10425    public boolean isClickable() {
10426        return (mViewFlags & CLICKABLE) == CLICKABLE;
10427    }
10428
10429    /**
10430     * Enables or disables click events for this view. When a view
10431     * is clickable it will change its state to "pressed" on every click.
10432     * Subclasses should set the view clickable to visually react to
10433     * user's clicks.
10434     *
10435     * @param clickable true to make the view clickable, false otherwise
10436     *
10437     * @see #isClickable()
10438     * @attr ref android.R.styleable#View_clickable
10439     */
10440    public void setClickable(boolean clickable) {
10441        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
10442    }
10443
10444    /**
10445     * Indicates whether this view reacts to long click events or not.
10446     *
10447     * @return true if the view is long clickable, false otherwise
10448     *
10449     * @see #setLongClickable(boolean)
10450     * @attr ref android.R.styleable#View_longClickable
10451     */
10452    public boolean isLongClickable() {
10453        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
10454    }
10455
10456    /**
10457     * Enables or disables long click events for this view. When a view is long
10458     * clickable it reacts to the user holding down the button for a longer
10459     * duration than a tap. This event can either launch the listener or a
10460     * context menu.
10461     *
10462     * @param longClickable true to make the view long clickable, false otherwise
10463     * @see #isLongClickable()
10464     * @attr ref android.R.styleable#View_longClickable
10465     */
10466    public void setLongClickable(boolean longClickable) {
10467        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
10468    }
10469
10470    /**
10471     * Indicates whether this view reacts to context clicks or not.
10472     *
10473     * @return true if the view is context clickable, false otherwise
10474     * @see #setContextClickable(boolean)
10475     * @attr ref android.R.styleable#View_contextClickable
10476     */
10477    public boolean isContextClickable() {
10478        return (mViewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
10479    }
10480
10481    /**
10482     * Enables or disables context clicking for this view. This event can launch the listener.
10483     *
10484     * @param contextClickable true to make the view react to a context click, false otherwise
10485     * @see #isContextClickable()
10486     * @attr ref android.R.styleable#View_contextClickable
10487     */
10488    public void setContextClickable(boolean contextClickable) {
10489        setFlags(contextClickable ? CONTEXT_CLICKABLE : 0, CONTEXT_CLICKABLE);
10490    }
10491
10492    /**
10493     * Sets the pressed state for this view and provides a touch coordinate for
10494     * animation hinting.
10495     *
10496     * @param pressed Pass true to set the View's internal state to "pressed",
10497     *            or false to reverts the View's internal state from a
10498     *            previously set "pressed" state.
10499     * @param x The x coordinate of the touch that caused the press
10500     * @param y The y coordinate of the touch that caused the press
10501     */
10502    private void setPressed(boolean pressed, float x, float y) {
10503        if (pressed) {
10504            drawableHotspotChanged(x, y);
10505        }
10506
10507        setPressed(pressed);
10508    }
10509
10510    /**
10511     * Sets the pressed state for this view.
10512     *
10513     * @see #isClickable()
10514     * @see #setClickable(boolean)
10515     *
10516     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
10517     *        the View's internal state from a previously set "pressed" state.
10518     */
10519    public void setPressed(boolean pressed) {
10520        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
10521
10522        if (pressed) {
10523            mPrivateFlags |= PFLAG_PRESSED;
10524        } else {
10525            mPrivateFlags &= ~PFLAG_PRESSED;
10526        }
10527
10528        if (needsRefresh) {
10529            refreshDrawableState();
10530        }
10531        dispatchSetPressed(pressed);
10532    }
10533
10534    /**
10535     * Dispatch setPressed to all of this View's children.
10536     *
10537     * @see #setPressed(boolean)
10538     *
10539     * @param pressed The new pressed state
10540     */
10541    protected void dispatchSetPressed(boolean pressed) {
10542    }
10543
10544    /**
10545     * Indicates whether the view is currently in pressed state. Unless
10546     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
10547     * the pressed state.
10548     *
10549     * @see #setPressed(boolean)
10550     * @see #isClickable()
10551     * @see #setClickable(boolean)
10552     *
10553     * @return true if the view is currently pressed, false otherwise
10554     */
10555    @ViewDebug.ExportedProperty
10556    public boolean isPressed() {
10557        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
10558    }
10559
10560    /**
10561     * @hide
10562     * Indicates whether this view will participate in data collection through
10563     * {@link ViewStructure}.  If true, it will not provide any data
10564     * for itself or its children.  If false, the normal data collection will be allowed.
10565     *
10566     * @return Returns false if assist data collection is not blocked, else true.
10567     *
10568     * @see #setAssistBlocked(boolean)
10569     * @attr ref android.R.styleable#View_assistBlocked
10570     */
10571    public boolean isAssistBlocked() {
10572        return (mPrivateFlags3 & PFLAG3_ASSIST_BLOCKED) != 0;
10573    }
10574
10575    /**
10576     * @hide
10577     * Controls whether assist data collection from this view and its children is enabled
10578     * (that is, whether {@link #onProvideStructure} and
10579     * {@link #onProvideVirtualStructure} will be called).  The default value is false,
10580     * allowing normal assist collection.  Setting this to false will disable assist collection.
10581     *
10582     * @param enabled Set to true to <em>disable</em> assist data collection, or false
10583     * (the default) to allow it.
10584     *
10585     * @see #isAssistBlocked()
10586     * @see #onProvideStructure
10587     * @see #onProvideVirtualStructure
10588     * @attr ref android.R.styleable#View_assistBlocked
10589     */
10590    public void setAssistBlocked(boolean enabled) {
10591        if (enabled) {
10592            mPrivateFlags3 |= PFLAG3_ASSIST_BLOCKED;
10593        } else {
10594            mPrivateFlags3 &= ~PFLAG3_ASSIST_BLOCKED;
10595        }
10596    }
10597
10598    /**
10599     * Indicates whether this view will save its state (that is,
10600     * whether its {@link #onSaveInstanceState} method will be called).
10601     *
10602     * @return Returns true if the view state saving is enabled, else false.
10603     *
10604     * @see #setSaveEnabled(boolean)
10605     * @attr ref android.R.styleable#View_saveEnabled
10606     */
10607    public boolean isSaveEnabled() {
10608        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
10609    }
10610
10611    /**
10612     * Controls whether the saving of this view's state is
10613     * enabled (that is, whether its {@link #onSaveInstanceState} method
10614     * will be called).  Note that even if freezing is enabled, the
10615     * view still must have an id assigned to it (via {@link #setId(int)})
10616     * for its state to be saved.  This flag can only disable the
10617     * saving of this view; any child views may still have their state saved.
10618     *
10619     * @param enabled Set to false to <em>disable</em> state saving, or true
10620     * (the default) to allow it.
10621     *
10622     * @see #isSaveEnabled()
10623     * @see #setId(int)
10624     * @see #onSaveInstanceState()
10625     * @attr ref android.R.styleable#View_saveEnabled
10626     */
10627    public void setSaveEnabled(boolean enabled) {
10628        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
10629    }
10630
10631    /**
10632     * Gets whether the framework should discard touches when the view's
10633     * window is obscured by another visible window.
10634     * Refer to the {@link View} security documentation for more details.
10635     *
10636     * @return True if touch filtering is enabled.
10637     *
10638     * @see #setFilterTouchesWhenObscured(boolean)
10639     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
10640     */
10641    @ViewDebug.ExportedProperty
10642    public boolean getFilterTouchesWhenObscured() {
10643        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
10644    }
10645
10646    /**
10647     * Sets whether the framework should discard touches when the view's
10648     * window is obscured by another visible window.
10649     * Refer to the {@link View} security documentation for more details.
10650     *
10651     * @param enabled True if touch filtering should be enabled.
10652     *
10653     * @see #getFilterTouchesWhenObscured
10654     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
10655     */
10656    public void setFilterTouchesWhenObscured(boolean enabled) {
10657        setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0,
10658                FILTER_TOUCHES_WHEN_OBSCURED);
10659    }
10660
10661    /**
10662     * Indicates whether the entire hierarchy under this view will save its
10663     * state when a state saving traversal occurs from its parent.  The default
10664     * is true; if false, these views will not be saved unless
10665     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
10666     *
10667     * @return Returns true if the view state saving from parent is enabled, else false.
10668     *
10669     * @see #setSaveFromParentEnabled(boolean)
10670     */
10671    public boolean isSaveFromParentEnabled() {
10672        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
10673    }
10674
10675    /**
10676     * Controls whether the entire hierarchy under this view will save its
10677     * state when a state saving traversal occurs from its parent.  The default
10678     * is true; if false, these views will not be saved unless
10679     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
10680     *
10681     * @param enabled Set to false to <em>disable</em> state saving, or true
10682     * (the default) to allow it.
10683     *
10684     * @see #isSaveFromParentEnabled()
10685     * @see #setId(int)
10686     * @see #onSaveInstanceState()
10687     */
10688    public void setSaveFromParentEnabled(boolean enabled) {
10689        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
10690    }
10691
10692
10693    /**
10694     * Returns whether this View is currently able to take focus.
10695     *
10696     * @return True if this view can take focus, or false otherwise.
10697     */
10698    @ViewDebug.ExportedProperty(category = "focus")
10699    public final boolean isFocusable() {
10700        return FOCUSABLE == (mViewFlags & FOCUSABLE);
10701    }
10702
10703    /**
10704     * Returns the focusable setting for this view.
10705     *
10706     * @return One of {@link #NOT_FOCUSABLE}, {@link #FOCUSABLE}, or {@link #FOCUSABLE_AUTO}.
10707     * @attr ref android.R.styleable#View_focusable
10708     */
10709    @ViewDebug.ExportedProperty(mapping = {
10710            @ViewDebug.IntToString(from = NOT_FOCUSABLE, to = "NOT_FOCUSABLE"),
10711            @ViewDebug.IntToString(from = FOCUSABLE, to = "FOCUSABLE"),
10712            @ViewDebug.IntToString(from = FOCUSABLE_AUTO, to = "FOCUSABLE_AUTO")
10713            }, category = "focus")
10714    @Focusable
10715    public int getFocusable() {
10716        return (mViewFlags & FOCUSABLE_AUTO) > 0 ? FOCUSABLE_AUTO : mViewFlags & FOCUSABLE;
10717    }
10718
10719    /**
10720     * When a view is focusable, it may not want to take focus when in touch mode.
10721     * For example, a button would like focus when the user is navigating via a D-pad
10722     * so that the user can click on it, but once the user starts touching the screen,
10723     * the button shouldn't take focus
10724     * @return Whether the view is focusable in touch mode.
10725     * @attr ref android.R.styleable#View_focusableInTouchMode
10726     */
10727    @ViewDebug.ExportedProperty(category = "focus")
10728    public final boolean isFocusableInTouchMode() {
10729        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
10730    }
10731
10732    /**
10733     * Returns whether the view should be treated as a focusable unit by screen reader
10734     * accessibility tools.
10735     * @see #setScreenReaderFocusable(boolean)
10736     *
10737     * @return Whether the view should be treated as a focusable unit by screen reader.
10738     */
10739    public boolean isScreenReaderFocusable() {
10740        return (mPrivateFlags3 & PFLAG3_SCREEN_READER_FOCUSABLE) != 0;
10741    }
10742
10743    /**
10744     * When screen readers (one type of accessibility tool) decide what should be read to the
10745     * user, they typically look for input focusable ({@link #isFocusable()}) parents of
10746     * non-focusable text items, and read those focusable parents and their non-focusable children
10747     * as a unit. In some situations, this behavior is desirable for views that should not take
10748     * input focus. Setting an item to be screen reader focusable requests that the view be
10749     * treated as a unit by screen readers without any effect on input focusability. The default
10750     * value of {@code false} lets screen readers use other signals, like focusable, to determine
10751     * how to group items.
10752     *
10753     * @param screenReaderFocusable Whether the view should be treated as a unit by screen reader
10754     *                              accessibility tools.
10755     */
10756    public void setScreenReaderFocusable(boolean screenReaderFocusable) {
10757        int pflags3 = mPrivateFlags3;
10758        if (screenReaderFocusable) {
10759            pflags3 |= PFLAG3_SCREEN_READER_FOCUSABLE;
10760        } else {
10761            pflags3 &= ~PFLAG3_SCREEN_READER_FOCUSABLE;
10762        }
10763
10764        if (pflags3 != mPrivateFlags3) {
10765            mPrivateFlags3 = pflags3;
10766            notifyViewAccessibilityStateChangedIfNeeded(
10767                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10768        }
10769    }
10770
10771    /**
10772     * Find the nearest view in the specified direction that can take focus.
10773     * This does not actually give focus to that view.
10774     *
10775     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
10776     *
10777     * @return The nearest focusable in the specified direction, or null if none
10778     *         can be found.
10779     */
10780    public View focusSearch(@FocusRealDirection int direction) {
10781        if (mParent != null) {
10782            return mParent.focusSearch(this, direction);
10783        } else {
10784            return null;
10785        }
10786    }
10787
10788    /**
10789     * Returns whether this View is a root of a keyboard navigation cluster.
10790     *
10791     * @return True if this view is a root of a cluster, or false otherwise.
10792     * @attr ref android.R.styleable#View_keyboardNavigationCluster
10793     */
10794    @ViewDebug.ExportedProperty(category = "focus")
10795    public final boolean isKeyboardNavigationCluster() {
10796        return (mPrivateFlags3 & PFLAG3_CLUSTER) != 0;
10797    }
10798
10799    /**
10800     * Searches up the view hierarchy to find the top-most cluster. All deeper/nested clusters
10801     * will be ignored.
10802     *
10803     * @return the keyboard navigation cluster that this view is in (can be this view)
10804     *         or {@code null} if not in one
10805     */
10806    View findKeyboardNavigationCluster() {
10807        if (mParent instanceof View) {
10808            View cluster = ((View) mParent).findKeyboardNavigationCluster();
10809            if (cluster != null) {
10810                return cluster;
10811            } else if (isKeyboardNavigationCluster()) {
10812                return this;
10813            }
10814        }
10815        return null;
10816    }
10817
10818    /**
10819     * Set whether this view is a root of a keyboard navigation cluster.
10820     *
10821     * @param isCluster If true, this view is a root of a cluster.
10822     *
10823     * @attr ref android.R.styleable#View_keyboardNavigationCluster
10824     */
10825    public void setKeyboardNavigationCluster(boolean isCluster) {
10826        if (isCluster) {
10827            mPrivateFlags3 |= PFLAG3_CLUSTER;
10828        } else {
10829            mPrivateFlags3 &= ~PFLAG3_CLUSTER;
10830        }
10831    }
10832
10833    /**
10834     * Sets this View as the one which receives focus the next time cluster navigation jumps
10835     * to the cluster containing this View. This does NOT change focus even if the cluster
10836     * containing this view is current.
10837     *
10838     * @hide
10839     */
10840    @TestApi
10841    public final void setFocusedInCluster() {
10842        setFocusedInCluster(findKeyboardNavigationCluster());
10843    }
10844
10845    private void setFocusedInCluster(View cluster) {
10846        if (this instanceof ViewGroup) {
10847            ((ViewGroup) this).mFocusedInCluster = null;
10848        }
10849        if (cluster == this) {
10850            return;
10851        }
10852        ViewParent parent = mParent;
10853        View child = this;
10854        while (parent instanceof ViewGroup) {
10855            ((ViewGroup) parent).mFocusedInCluster = child;
10856            if (parent == cluster) {
10857                break;
10858            }
10859            child = (View) parent;
10860            parent = parent.getParent();
10861        }
10862    }
10863
10864    private void updateFocusedInCluster(View oldFocus, @FocusDirection int direction) {
10865        if (oldFocus != null) {
10866            View oldCluster = oldFocus.findKeyboardNavigationCluster();
10867            View cluster = findKeyboardNavigationCluster();
10868            if (oldCluster != cluster) {
10869                // Going from one cluster to another, so save last-focused.
10870                // This covers cluster jumps because they are always FOCUS_DOWN
10871                oldFocus.setFocusedInCluster(oldCluster);
10872                if (!(oldFocus.mParent instanceof ViewGroup)) {
10873                    return;
10874                }
10875                if (direction == FOCUS_FORWARD || direction == FOCUS_BACKWARD) {
10876                    // This is a result of ordered navigation so consider navigation through
10877                    // the previous cluster "complete" and clear its last-focused memory.
10878                    ((ViewGroup) oldFocus.mParent).clearFocusedInCluster(oldFocus);
10879                } else if (oldFocus instanceof ViewGroup
10880                        && ((ViewGroup) oldFocus).getDescendantFocusability()
10881                                == ViewGroup.FOCUS_AFTER_DESCENDANTS
10882                        && ViewRootImpl.isViewDescendantOf(this, oldFocus)) {
10883                    // This means oldFocus is not focusable since it obviously has a focusable
10884                    // child (this). Don't restore focus to it in the future.
10885                    ((ViewGroup) oldFocus.mParent).clearFocusedInCluster(oldFocus);
10886                }
10887            }
10888        }
10889    }
10890
10891    /**
10892     * Returns whether this View should receive focus when the focus is restored for the view
10893     * hierarchy containing this view.
10894     * <p>
10895     * Focus gets restored for a view hierarchy when the root of the hierarchy gets added to a
10896     * window or serves as a target of cluster navigation.
10897     *
10898     * @see #restoreDefaultFocus()
10899     *
10900     * @return {@code true} if this view is the default-focus view, {@code false} otherwise
10901     * @attr ref android.R.styleable#View_focusedByDefault
10902     */
10903    @ViewDebug.ExportedProperty(category = "focus")
10904    public final boolean isFocusedByDefault() {
10905        return (mPrivateFlags3 & PFLAG3_FOCUSED_BY_DEFAULT) != 0;
10906    }
10907
10908    /**
10909     * Sets whether this View should receive focus when the focus is restored for the view
10910     * hierarchy containing this view.
10911     * <p>
10912     * Focus gets restored for a view hierarchy when the root of the hierarchy gets added to a
10913     * window or serves as a target of cluster navigation.
10914     *
10915     * @param isFocusedByDefault {@code true} to set this view as the default-focus view,
10916     *                           {@code false} otherwise.
10917     *
10918     * @see #restoreDefaultFocus()
10919     *
10920     * @attr ref android.R.styleable#View_focusedByDefault
10921     */
10922    public void setFocusedByDefault(boolean isFocusedByDefault) {
10923        if (isFocusedByDefault == ((mPrivateFlags3 & PFLAG3_FOCUSED_BY_DEFAULT) != 0)) {
10924            return;
10925        }
10926
10927        if (isFocusedByDefault) {
10928            mPrivateFlags3 |= PFLAG3_FOCUSED_BY_DEFAULT;
10929        } else {
10930            mPrivateFlags3 &= ~PFLAG3_FOCUSED_BY_DEFAULT;
10931        }
10932
10933        if (mParent instanceof ViewGroup) {
10934            if (isFocusedByDefault) {
10935                ((ViewGroup) mParent).setDefaultFocus(this);
10936            } else {
10937                ((ViewGroup) mParent).clearDefaultFocus(this);
10938            }
10939        }
10940    }
10941
10942    /**
10943     * Returns whether the view hierarchy with this view as a root contain a default-focus view.
10944     *
10945     * @return {@code true} if this view has default focus, {@code false} otherwise
10946     */
10947    boolean hasDefaultFocus() {
10948        return isFocusedByDefault();
10949    }
10950
10951    /**
10952     * Find the nearest keyboard navigation cluster in the specified direction.
10953     * This does not actually give focus to that cluster.
10954     *
10955     * @param currentCluster The starting point of the search. Null means the current cluster is not
10956     *                       found yet
10957     * @param direction Direction to look
10958     *
10959     * @return The nearest keyboard navigation cluster in the specified direction, or null if none
10960     *         can be found
10961     */
10962    public View keyboardNavigationClusterSearch(View currentCluster,
10963            @FocusDirection int direction) {
10964        if (isKeyboardNavigationCluster()) {
10965            currentCluster = this;
10966        }
10967        if (isRootNamespace()) {
10968            // Root namespace means we should consider ourselves the top of the
10969            // tree for group searching; otherwise we could be group searching
10970            // into other tabs.  see LocalActivityManager and TabHost for more info.
10971            return FocusFinder.getInstance().findNextKeyboardNavigationCluster(
10972                    this, currentCluster, direction);
10973        } else if (mParent != null) {
10974            return mParent.keyboardNavigationClusterSearch(currentCluster, direction);
10975        }
10976        return null;
10977    }
10978
10979    /**
10980     * This method is the last chance for the focused view and its ancestors to
10981     * respond to an arrow key. This is called when the focused view did not
10982     * consume the key internally, nor could the view system find a new view in
10983     * the requested direction to give focus to.
10984     *
10985     * @param focused The currently focused view.
10986     * @param direction The direction focus wants to move. One of FOCUS_UP,
10987     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
10988     * @return True if the this view consumed this unhandled move.
10989     */
10990    public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) {
10991        return false;
10992    }
10993
10994    /**
10995     * Sets whether this View should use a default focus highlight when it gets focused but doesn't
10996     * have {@link android.R.attr#state_focused} defined in its background.
10997     *
10998     * @param defaultFocusHighlightEnabled {@code true} to set this view to use a default focus
10999     *                                      highlight, {@code false} otherwise.
11000     *
11001     * @attr ref android.R.styleable#View_defaultFocusHighlightEnabled
11002     */
11003    public void setDefaultFocusHighlightEnabled(boolean defaultFocusHighlightEnabled) {
11004        mDefaultFocusHighlightEnabled = defaultFocusHighlightEnabled;
11005    }
11006
11007    /**
11008
11009    /**
11010     * Returns whether this View should use a default focus highlight when it gets focused but
11011     * doesn't have {@link android.R.attr#state_focused} defined in its background.
11012     *
11013     * @return True if this View should use a default focus highlight.
11014     * @attr ref android.R.styleable#View_defaultFocusHighlightEnabled
11015     */
11016    @ViewDebug.ExportedProperty(category = "focus")
11017    public final boolean getDefaultFocusHighlightEnabled() {
11018        return mDefaultFocusHighlightEnabled;
11019    }
11020
11021    /**
11022     * If a user manually specified the next view id for a particular direction,
11023     * use the root to look up the view.
11024     * @param root The root view of the hierarchy containing this view.
11025     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
11026     * or FOCUS_BACKWARD.
11027     * @return The user specified next view, or null if there is none.
11028     */
11029    View findUserSetNextFocus(View root, @FocusDirection int direction) {
11030        switch (direction) {
11031            case FOCUS_LEFT:
11032                if (mNextFocusLeftId == View.NO_ID) return null;
11033                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
11034            case FOCUS_RIGHT:
11035                if (mNextFocusRightId == View.NO_ID) return null;
11036                return findViewInsideOutShouldExist(root, mNextFocusRightId);
11037            case FOCUS_UP:
11038                if (mNextFocusUpId == View.NO_ID) return null;
11039                return findViewInsideOutShouldExist(root, mNextFocusUpId);
11040            case FOCUS_DOWN:
11041                if (mNextFocusDownId == View.NO_ID) return null;
11042                return findViewInsideOutShouldExist(root, mNextFocusDownId);
11043            case FOCUS_FORWARD:
11044                if (mNextFocusForwardId == View.NO_ID) return null;
11045                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
11046            case FOCUS_BACKWARD: {
11047                if (mID == View.NO_ID) return null;
11048                final int id = mID;
11049                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
11050                    @Override
11051                    public boolean test(View t) {
11052                        return t.mNextFocusForwardId == id;
11053                    }
11054                });
11055            }
11056        }
11057        return null;
11058    }
11059
11060    /**
11061     * If a user manually specified the next keyboard-navigation cluster for a particular direction,
11062     * use the root to look up the view.
11063     *
11064     * @param root the root view of the hierarchy containing this view
11065     * @param direction {@link #FOCUS_FORWARD} or {@link #FOCUS_BACKWARD}
11066     * @return the user-specified next cluster, or {@code null} if there is none
11067     */
11068    View findUserSetNextKeyboardNavigationCluster(View root, @FocusDirection int direction) {
11069        switch (direction) {
11070            case FOCUS_FORWARD:
11071                if (mNextClusterForwardId == View.NO_ID) return null;
11072                return findViewInsideOutShouldExist(root, mNextClusterForwardId);
11073            case FOCUS_BACKWARD: {
11074                if (mID == View.NO_ID) return null;
11075                final int id = mID;
11076                return root.findViewByPredicateInsideOut(this,
11077                        (Predicate<View>) t -> t.mNextClusterForwardId == id);
11078            }
11079        }
11080        return null;
11081    }
11082
11083    private View findViewInsideOutShouldExist(View root, int id) {
11084        if (mMatchIdPredicate == null) {
11085            mMatchIdPredicate = new MatchIdPredicate();
11086        }
11087        mMatchIdPredicate.mId = id;
11088        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
11089        if (result == null) {
11090            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
11091        }
11092        return result;
11093    }
11094
11095    /**
11096     * Find and return all focusable views that are descendants of this view,
11097     * possibly including this view if it is focusable itself.
11098     *
11099     * @param direction The direction of the focus
11100     * @return A list of focusable views
11101     */
11102    public ArrayList<View> getFocusables(@FocusDirection int direction) {
11103        ArrayList<View> result = new ArrayList<View>(24);
11104        addFocusables(result, direction);
11105        return result;
11106    }
11107
11108    /**
11109     * Add any focusable views that are descendants of this view (possibly
11110     * including this view if it is focusable itself) to views.  If we are in touch mode,
11111     * only add views that are also focusable in touch mode.
11112     *
11113     * @param views Focusable views found so far
11114     * @param direction The direction of the focus
11115     */
11116    public void addFocusables(ArrayList<View> views, @FocusDirection int direction) {
11117        addFocusables(views, direction, isInTouchMode() ? FOCUSABLES_TOUCH_MODE : FOCUSABLES_ALL);
11118    }
11119
11120    /**
11121     * Adds any focusable views that are descendants of this view (possibly
11122     * including this view if it is focusable itself) to views. This method
11123     * adds all focusable views regardless if we are in touch mode or
11124     * only views focusable in touch mode if we are in touch mode or
11125     * only views that can take accessibility focus if accessibility is enabled
11126     * depending on the focusable mode parameter.
11127     *
11128     * @param views Focusable views found so far or null if all we are interested is
11129     *        the number of focusables.
11130     * @param direction The direction of the focus.
11131     * @param focusableMode The type of focusables to be added.
11132     *
11133     * @see #FOCUSABLES_ALL
11134     * @see #FOCUSABLES_TOUCH_MODE
11135     */
11136    public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
11137            @FocusableMode int focusableMode) {
11138        if (views == null) {
11139            return;
11140        }
11141        if (!canTakeFocus()) {
11142            return;
11143        }
11144        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
11145                && !isFocusableInTouchMode()) {
11146            return;
11147        }
11148        views.add(this);
11149    }
11150
11151    /**
11152     * Adds any keyboard navigation cluster roots that are descendants of this view (possibly
11153     * including this view if it is a cluster root itself) to views.
11154     *
11155     * @param views Keyboard navigation cluster roots found so far
11156     * @param direction Direction to look
11157     */
11158    public void addKeyboardNavigationClusters(
11159            @NonNull Collection<View> views,
11160            int direction) {
11161        if (!isKeyboardNavigationCluster()) {
11162            return;
11163        }
11164        if (!hasFocusable()) {
11165            return;
11166        }
11167        views.add(this);
11168    }
11169
11170    /**
11171     * Finds the Views that contain given text. The containment is case insensitive.
11172     * The search is performed by either the text that the View renders or the content
11173     * description that describes the view for accessibility purposes and the view does
11174     * not render or both. Clients can specify how the search is to be performed via
11175     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
11176     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
11177     *
11178     * @param outViews The output list of matching Views.
11179     * @param searched The text to match against.
11180     *
11181     * @see #FIND_VIEWS_WITH_TEXT
11182     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
11183     * @see #setContentDescription(CharSequence)
11184     */
11185    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched,
11186            @FindViewFlags int flags) {
11187        if (getAccessibilityNodeProvider() != null) {
11188            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
11189                outViews.add(this);
11190            }
11191        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
11192                && (searched != null && searched.length() > 0)
11193                && (mContentDescription != null && mContentDescription.length() > 0)) {
11194            String searchedLowerCase = searched.toString().toLowerCase();
11195            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
11196            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
11197                outViews.add(this);
11198            }
11199        }
11200    }
11201
11202    /**
11203     * Find and return all touchable views that are descendants of this view,
11204     * possibly including this view if it is touchable itself.
11205     *
11206     * @return A list of touchable views
11207     */
11208    public ArrayList<View> getTouchables() {
11209        ArrayList<View> result = new ArrayList<View>();
11210        addTouchables(result);
11211        return result;
11212    }
11213
11214    /**
11215     * Add any touchable views that are descendants of this view (possibly
11216     * including this view if it is touchable itself) to views.
11217     *
11218     * @param views Touchable views found so far
11219     */
11220    public void addTouchables(ArrayList<View> views) {
11221        final int viewFlags = mViewFlags;
11222
11223        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE
11224                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE)
11225                && (viewFlags & ENABLED_MASK) == ENABLED) {
11226            views.add(this);
11227        }
11228    }
11229
11230    /**
11231     * Returns whether this View is accessibility focused.
11232     *
11233     * @return True if this View is accessibility focused.
11234     */
11235    public boolean isAccessibilityFocused() {
11236        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
11237    }
11238
11239    /**
11240     * Call this to try to give accessibility focus to this view.
11241     *
11242     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
11243     * returns false or the view is no visible or the view already has accessibility
11244     * focus.
11245     *
11246     * See also {@link #focusSearch(int)}, which is what you call to say that you
11247     * have focus, and you want your parent to look for the next one.
11248     *
11249     * @return Whether this view actually took accessibility focus.
11250     *
11251     * @hide
11252     */
11253    public boolean requestAccessibilityFocus() {
11254        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
11255        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
11256            return false;
11257        }
11258        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
11259            return false;
11260        }
11261        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
11262            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
11263            ViewRootImpl viewRootImpl = getViewRootImpl();
11264            if (viewRootImpl != null) {
11265                viewRootImpl.setAccessibilityFocus(this, null);
11266            }
11267            invalidate();
11268            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
11269            return true;
11270        }
11271        return false;
11272    }
11273
11274    /**
11275     * Call this to try to clear accessibility focus of this view.
11276     *
11277     * See also {@link #focusSearch(int)}, which is what you call to say that you
11278     * have focus, and you want your parent to look for the next one.
11279     *
11280     * @hide
11281     */
11282    public void clearAccessibilityFocus() {
11283        clearAccessibilityFocusNoCallbacks(0);
11284
11285        // Clear the global reference of accessibility focus if this view or
11286        // any of its descendants had accessibility focus. This will NOT send
11287        // an event or update internal state if focus is cleared from a
11288        // descendant view, which may leave views in inconsistent states.
11289        final ViewRootImpl viewRootImpl = getViewRootImpl();
11290        if (viewRootImpl != null) {
11291            final View focusHost = viewRootImpl.getAccessibilityFocusedHost();
11292            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
11293                viewRootImpl.setAccessibilityFocus(null, null);
11294            }
11295        }
11296    }
11297
11298    private void sendAccessibilityHoverEvent(int eventType) {
11299        // Since we are not delivering to a client accessibility events from not
11300        // important views (unless the clinet request that) we need to fire the
11301        // event from the deepest view exposed to the client. As a consequence if
11302        // the user crosses a not exposed view the client will see enter and exit
11303        // of the exposed predecessor followed by and enter and exit of that same
11304        // predecessor when entering and exiting the not exposed descendant. This
11305        // is fine since the client has a clear idea which view is hovered at the
11306        // price of a couple more events being sent. This is a simple and
11307        // working solution.
11308        View source = this;
11309        while (true) {
11310            if (source.includeForAccessibility()) {
11311                source.sendAccessibilityEvent(eventType);
11312                return;
11313            }
11314            ViewParent parent = source.getParent();
11315            if (parent instanceof View) {
11316                source = (View) parent;
11317            } else {
11318                return;
11319            }
11320        }
11321    }
11322
11323    /**
11324     * Clears accessibility focus without calling any callback methods
11325     * normally invoked in {@link #clearAccessibilityFocus()}. This method
11326     * is used separately from that one for clearing accessibility focus when
11327     * giving this focus to another view.
11328     *
11329     * @param action The action, if any, that led to focus being cleared. Set to
11330     * AccessibilityNodeInfo#ACTION_ACCESSIBILITY_FOCUS to specify that focus is moving within
11331     * the window.
11332     */
11333    void clearAccessibilityFocusNoCallbacks(int action) {
11334        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
11335            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
11336            invalidate();
11337            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
11338                AccessibilityEvent event = AccessibilityEvent.obtain(
11339                        AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
11340                event.setAction(action);
11341                if (mAccessibilityDelegate != null) {
11342                    mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
11343                } else {
11344                    sendAccessibilityEventUnchecked(event);
11345                }
11346            }
11347        }
11348    }
11349
11350    /**
11351     * Call this to try to give focus to a specific view or to one of its
11352     * descendants.
11353     *
11354     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
11355     * false), or if it can't be focused due to other conditions (not focusable in touch mode
11356     * ({@link #isFocusableInTouchMode}) while the device is in touch mode, not visible, not
11357     * enabled, or has no size).
11358     *
11359     * See also {@link #focusSearch(int)}, which is what you call to say that you
11360     * have focus, and you want your parent to look for the next one.
11361     *
11362     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
11363     * {@link #FOCUS_DOWN} and <code>null</code>.
11364     *
11365     * @return Whether this view or one of its descendants actually took focus.
11366     */
11367    public final boolean requestFocus() {
11368        return requestFocus(View.FOCUS_DOWN);
11369    }
11370
11371    /**
11372     * This will request focus for whichever View was last focused within this
11373     * cluster before a focus-jump out of it.
11374     *
11375     * @hide
11376     */
11377    @TestApi
11378    public boolean restoreFocusInCluster(@FocusRealDirection int direction) {
11379        // Prioritize focusableByDefault over algorithmic focus selection.
11380        if (restoreDefaultFocus()) {
11381            return true;
11382        }
11383        return requestFocus(direction);
11384    }
11385
11386    /**
11387     * This will request focus for whichever View not in a cluster was last focused before a
11388     * focus-jump to a cluster. If no non-cluster View has previously had focus, this will focus
11389     * the "first" focusable view it finds.
11390     *
11391     * @hide
11392     */
11393    @TestApi
11394    public boolean restoreFocusNotInCluster() {
11395        return requestFocus(View.FOCUS_DOWN);
11396    }
11397
11398    /**
11399     * Gives focus to the default-focus view in the view hierarchy that has this view as a root.
11400     * If the default-focus view cannot be found, falls back to calling {@link #requestFocus(int)}.
11401     *
11402     * @return Whether this view or one of its descendants actually took focus
11403     */
11404    public boolean restoreDefaultFocus() {
11405        return requestFocus(View.FOCUS_DOWN);
11406    }
11407
11408    /**
11409     * Call this to try to give focus to a specific view or to one of its
11410     * descendants and give it a hint about what direction focus is heading.
11411     *
11412     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
11413     * false), or if it is focusable and it is not focusable in touch mode
11414     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
11415     *
11416     * See also {@link #focusSearch(int)}, which is what you call to say that you
11417     * have focus, and you want your parent to look for the next one.
11418     *
11419     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
11420     * <code>null</code> set for the previously focused rectangle.
11421     *
11422     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
11423     * @return Whether this view or one of its descendants actually took focus.
11424     */
11425    public final boolean requestFocus(int direction) {
11426        return requestFocus(direction, null);
11427    }
11428
11429    /**
11430     * Call this to try to give focus to a specific view or to one of its descendants
11431     * and give it hints about the direction and a specific rectangle that the focus
11432     * is coming from.  The rectangle can help give larger views a finer grained hint
11433     * about where focus is coming from, and therefore, where to show selection, or
11434     * forward focus change internally.
11435     *
11436     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
11437     * false), or if it is focusable and it is not focusable in touch mode
11438     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
11439     *
11440     * A View will not take focus if it is not visible.
11441     *
11442     * A View will not take focus if one of its parents has
11443     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
11444     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
11445     *
11446     * See also {@link #focusSearch(int)}, which is what you call to say that you
11447     * have focus, and you want your parent to look for the next one.
11448     *
11449     * You may wish to override this method if your custom {@link View} has an internal
11450     * {@link View} that it wishes to forward the request to.
11451     *
11452     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
11453     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
11454     *        to give a finer grained hint about where focus is coming from.  May be null
11455     *        if there is no hint.
11456     * @return Whether this view or one of its descendants actually took focus.
11457     */
11458    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
11459        return requestFocusNoSearch(direction, previouslyFocusedRect);
11460    }
11461
11462    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
11463        // need to be focusable
11464        if (!canTakeFocus()) {
11465            return false;
11466        }
11467
11468        // need to be focusable in touch mode if in touch mode
11469        if (isInTouchMode() &&
11470            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
11471               return false;
11472        }
11473
11474        // need to not have any parents blocking us
11475        if (hasAncestorThatBlocksDescendantFocus()) {
11476            return false;
11477        }
11478
11479        if (!isLayoutValid()) {
11480            mPrivateFlags |= PFLAG_WANTS_FOCUS;
11481        } else {
11482            clearParentsWantFocus();
11483        }
11484
11485        handleFocusGainInternal(direction, previouslyFocusedRect);
11486        return true;
11487    }
11488
11489    void clearParentsWantFocus() {
11490        if (mParent instanceof View) {
11491            ((View) mParent).mPrivateFlags &= ~PFLAG_WANTS_FOCUS;
11492            ((View) mParent).clearParentsWantFocus();
11493        }
11494    }
11495
11496    /**
11497     * Call this to try to give focus to a specific view or to one of its descendants. This is a
11498     * special variant of {@link #requestFocus() } that will allow views that are not focusable in
11499     * touch mode to request focus when they are touched.
11500     *
11501     * @return Whether this view or one of its descendants actually took focus.
11502     *
11503     * @see #isInTouchMode()
11504     *
11505     */
11506    public final boolean requestFocusFromTouch() {
11507        // Leave touch mode if we need to
11508        if (isInTouchMode()) {
11509            ViewRootImpl viewRoot = getViewRootImpl();
11510            if (viewRoot != null) {
11511                viewRoot.ensureTouchMode(false);
11512            }
11513        }
11514        return requestFocus(View.FOCUS_DOWN);
11515    }
11516
11517    /**
11518     * @return Whether any ancestor of this view blocks descendant focus.
11519     */
11520    private boolean hasAncestorThatBlocksDescendantFocus() {
11521        final boolean focusableInTouchMode = isFocusableInTouchMode();
11522        ViewParent ancestor = mParent;
11523        while (ancestor instanceof ViewGroup) {
11524            final ViewGroup vgAncestor = (ViewGroup) ancestor;
11525            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS
11526                    || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) {
11527                return true;
11528            } else {
11529                ancestor = vgAncestor.getParent();
11530            }
11531        }
11532        return false;
11533    }
11534
11535    /**
11536     * Gets the mode for determining whether this View is important for accessibility.
11537     * A view is important for accessibility if it fires accessibility events and if it
11538     * is reported to accessibility services that query the screen.
11539     *
11540     * @return The mode for determining whether a view is important for accessibility, one
11541     * of {@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, {@link #IMPORTANT_FOR_ACCESSIBILITY_YES},
11542     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO}, or
11543     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}.
11544     *
11545     * @attr ref android.R.styleable#View_importantForAccessibility
11546     *
11547     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
11548     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
11549     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
11550     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
11551     */
11552    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
11553            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
11554            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
11555            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"),
11556            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
11557                    to = "noHideDescendants")
11558        })
11559    public int getImportantForAccessibility() {
11560        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
11561                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
11562    }
11563
11564    /**
11565     * Sets the live region mode for this view. This indicates to accessibility
11566     * services whether they should automatically notify the user about changes
11567     * to the view's content description or text, or to the content descriptions
11568     * or text of the view's children (where applicable).
11569     * <p>
11570     * For example, in a login screen with a TextView that displays an "incorrect
11571     * password" notification, that view should be marked as a live region with
11572     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
11573     * <p>
11574     * To disable change notifications for this view, use
11575     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
11576     * mode for most views.
11577     * <p>
11578     * To indicate that the user should be notified of changes, use
11579     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
11580     * <p>
11581     * If the view's changes should interrupt ongoing speech and notify the user
11582     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
11583     *
11584     * @param mode The live region mode for this view, one of:
11585     *        <ul>
11586     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
11587     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
11588     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
11589     *        </ul>
11590     * @attr ref android.R.styleable#View_accessibilityLiveRegion
11591     */
11592    public void setAccessibilityLiveRegion(int mode) {
11593        if (mode != getAccessibilityLiveRegion()) {
11594            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
11595            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
11596                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
11597            notifyViewAccessibilityStateChangedIfNeeded(
11598                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
11599        }
11600    }
11601
11602    /**
11603     * Gets the live region mode for this View.
11604     *
11605     * @return The live region mode for the view.
11606     *
11607     * @attr ref android.R.styleable#View_accessibilityLiveRegion
11608     *
11609     * @see #setAccessibilityLiveRegion(int)
11610     */
11611    public int getAccessibilityLiveRegion() {
11612        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
11613                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
11614    }
11615
11616    /**
11617     * Sets how to determine whether this view is important for accessibility
11618     * which is if it fires accessibility events and if it is reported to
11619     * accessibility services that query the screen.
11620     *
11621     * @param mode How to determine whether this view is important for accessibility.
11622     *
11623     * @attr ref android.R.styleable#View_importantForAccessibility
11624     *
11625     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
11626     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
11627     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
11628     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
11629     */
11630    public void setImportantForAccessibility(int mode) {
11631        final int oldMode = getImportantForAccessibility();
11632        if (mode != oldMode) {
11633            final boolean hideDescendants =
11634                    mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS;
11635
11636            // If this node or its descendants are no longer important, try to
11637            // clear accessibility focus.
11638            if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO || hideDescendants) {
11639                final View focusHost = findAccessibilityFocusHost(hideDescendants);
11640                if (focusHost != null) {
11641                    focusHost.clearAccessibilityFocus();
11642                }
11643            }
11644
11645            // If we're moving between AUTO and another state, we might not need
11646            // to send a subtree changed notification. We'll store the computed
11647            // importance, since we'll need to check it later to make sure.
11648            final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO
11649                    || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO;
11650            final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility();
11651            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
11652            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
11653                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
11654            if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) {
11655                notifySubtreeAccessibilityStateChangedIfNeeded();
11656            } else {
11657                notifyViewAccessibilityStateChangedIfNeeded(
11658                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
11659            }
11660        }
11661    }
11662
11663    /**
11664     * Returns the view within this view's hierarchy that is hosting
11665     * accessibility focus.
11666     *
11667     * @param searchDescendants whether to search for focus in descendant views
11668     * @return the view hosting accessibility focus, or {@code null}
11669     */
11670    private View findAccessibilityFocusHost(boolean searchDescendants) {
11671        if (isAccessibilityFocusedViewOrHost()) {
11672            return this;
11673        }
11674
11675        if (searchDescendants) {
11676            final ViewRootImpl viewRoot = getViewRootImpl();
11677            if (viewRoot != null) {
11678                final View focusHost = viewRoot.getAccessibilityFocusedHost();
11679                if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
11680                    return focusHost;
11681                }
11682            }
11683        }
11684
11685        return null;
11686    }
11687
11688    /**
11689     * Computes whether this view should be exposed for accessibility. In
11690     * general, views that are interactive or provide information are exposed
11691     * while views that serve only as containers are hidden.
11692     * <p>
11693     * If an ancestor of this view has importance
11694     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method
11695     * returns <code>false</code>.
11696     * <p>
11697     * Otherwise, the value is computed according to the view's
11698     * {@link #getImportantForAccessibility()} value:
11699     * <ol>
11700     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or
11701     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false
11702     * </code>
11703     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code>
11704     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if
11705     * view satisfies any of the following:
11706     * <ul>
11707     * <li>Is actionable, e.g. {@link #isClickable()},
11708     * {@link #isLongClickable()}, or {@link #isFocusable()}
11709     * <li>Has an {@link AccessibilityDelegate}
11710     * <li>Has an interaction listener, e.g. {@link OnTouchListener},
11711     * {@link OnKeyListener}, etc.
11712     * <li>Is an accessibility live region, e.g.
11713     * {@link #getAccessibilityLiveRegion()} is not
11714     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}.
11715     * </ul>
11716     * <li>Has an accessibility pane title, see {@link #setAccessibilityPaneTitle}</li>
11717     * </ol>
11718     *
11719     * @return Whether the view is exposed for accessibility.
11720     * @see #setImportantForAccessibility(int)
11721     * @see #getImportantForAccessibility()
11722     */
11723    public boolean isImportantForAccessibility() {
11724        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
11725                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
11726        if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO
11727                || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
11728            return false;
11729        }
11730
11731        // Check parent mode to ensure we're not hidden.
11732        ViewParent parent = mParent;
11733        while (parent instanceof View) {
11734            if (((View) parent).getImportantForAccessibility()
11735                    == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
11736                return false;
11737            }
11738            parent = parent.getParent();
11739        }
11740
11741        return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
11742                || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
11743                || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE
11744                || isAccessibilityPane();
11745    }
11746
11747    /**
11748     * Gets the parent for accessibility purposes. Note that the parent for
11749     * accessibility is not necessary the immediate parent. It is the first
11750     * predecessor that is important for accessibility.
11751     *
11752     * @return The parent for accessibility purposes.
11753     */
11754    public ViewParent getParentForAccessibility() {
11755        if (mParent instanceof View) {
11756            View parentView = (View) mParent;
11757            if (parentView.includeForAccessibility()) {
11758                return mParent;
11759            } else {
11760                return mParent.getParentForAccessibility();
11761            }
11762        }
11763        return null;
11764    }
11765
11766    /**
11767     * Adds the children of this View relevant for accessibility to the given list
11768     * as output. Since some Views are not important for accessibility the added
11769     * child views are not necessarily direct children of this view, rather they are
11770     * the first level of descendants important for accessibility.
11771     *
11772     * @param outChildren The output list that will receive children for accessibility.
11773     */
11774    public void addChildrenForAccessibility(ArrayList<View> outChildren) {
11775
11776    }
11777
11778    /**
11779     * Whether to regard this view for accessibility. A view is regarded for
11780     * accessibility if it is important for accessibility or the querying
11781     * accessibility service has explicitly requested that view not
11782     * important for accessibility are regarded.
11783     *
11784     * @return Whether to regard the view for accessibility.
11785     *
11786     * @hide
11787     */
11788    public boolean includeForAccessibility() {
11789        if (mAttachInfo != null) {
11790            return (mAttachInfo.mAccessibilityFetchFlags
11791                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
11792                    || isImportantForAccessibility();
11793        }
11794        return false;
11795    }
11796
11797    /**
11798     * Returns whether the View is considered actionable from
11799     * accessibility perspective. Such view are important for
11800     * accessibility.
11801     *
11802     * @return True if the view is actionable for accessibility.
11803     *
11804     * @hide
11805     */
11806    public boolean isActionableForAccessibility() {
11807        return (isClickable() || isLongClickable() || isFocusable());
11808    }
11809
11810    /**
11811     * Returns whether the View has registered callbacks which makes it
11812     * important for accessibility.
11813     *
11814     * @return True if the view is actionable for accessibility.
11815     */
11816    private boolean hasListenersForAccessibility() {
11817        ListenerInfo info = getListenerInfo();
11818        return mTouchDelegate != null || info.mOnKeyListener != null
11819                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
11820                || info.mOnHoverListener != null || info.mOnDragListener != null;
11821    }
11822
11823    /**
11824     * Notifies that the accessibility state of this view changed. The change
11825     * is local to this view and does not represent structural changes such
11826     * as children and parent. For example, the view became focusable. The
11827     * notification is at at most once every
11828     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
11829     * to avoid unnecessary load to the system. Also once a view has a pending
11830     * notification this method is a NOP until the notification has been sent.
11831     *
11832     * @hide
11833     */
11834    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
11835        if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) {
11836            return;
11837        }
11838
11839        // Changes to views with a pane title count as window state changes, as the pane title
11840        // marks them as significant parts of the UI.
11841        if ((changeType != AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE)
11842                && isAccessibilityPane()) {
11843            // If the pane isn't visible, content changed events are sufficient unless we're
11844            // reporting that the view just disappeared
11845            if ((getVisibility() == VISIBLE)
11846                    || (changeType == AccessibilityEvent.CONTENT_CHANGE_TYPE_PANE_DISAPPEARED)) {
11847                final AccessibilityEvent event = AccessibilityEvent.obtain();
11848                event.setEventType(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
11849                event.setContentChangeTypes(changeType);
11850                event.setSource(this);
11851                onPopulateAccessibilityEvent(event);
11852                if (mParent != null) {
11853                    try {
11854                        mParent.requestSendAccessibilityEvent(this, event);
11855                    } catch (AbstractMethodError e) {
11856                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName()
11857                                + " does not fully implement ViewParent", e);
11858                    }
11859                }
11860                return;
11861            }
11862        }
11863
11864        // If this is a live region, we should send a subtree change event
11865        // from this view immediately. Otherwise, we can let it propagate up.
11866        if (getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE) {
11867            final AccessibilityEvent event = AccessibilityEvent.obtain();
11868            event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
11869            event.setContentChangeTypes(changeType);
11870            sendAccessibilityEventUnchecked(event);
11871        } else if (mParent != null) {
11872            try {
11873                mParent.notifySubtreeAccessibilityStateChanged(this, this, changeType);
11874            } catch (AbstractMethodError e) {
11875                Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
11876                        " does not fully implement ViewParent", e);
11877            }
11878        }
11879    }
11880
11881    /**
11882     * Notifies that the accessibility state of this view changed. The change
11883     * is *not* local to this view and does represent structural changes such
11884     * as children and parent. For example, the view size changed. The
11885     * notification is at at most once every
11886     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
11887     * to avoid unnecessary load to the system. Also once a view has a pending
11888     * notification this method is a NOP until the notification has been sent.
11889     *
11890     * @hide
11891     */
11892    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
11893        if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) {
11894            return;
11895        }
11896
11897        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
11898            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
11899            if (mParent != null) {
11900                try {
11901                    mParent.notifySubtreeAccessibilityStateChanged(
11902                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
11903                } catch (AbstractMethodError e) {
11904                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
11905                            " does not fully implement ViewParent", e);
11906                }
11907            }
11908        }
11909    }
11910
11911    /**
11912     * Change the visibility of the View without triggering any other changes. This is
11913     * important for transitions, where visibility changes should not adjust focus or
11914     * trigger a new layout. This is only used when the visibility has already been changed
11915     * and we need a transient value during an animation. When the animation completes,
11916     * the original visibility value is always restored.
11917     *
11918     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
11919     * @hide
11920     */
11921    public void setTransitionVisibility(@Visibility int visibility) {
11922        mViewFlags = (mViewFlags & ~View.VISIBILITY_MASK) | visibility;
11923    }
11924
11925    /**
11926     * Reset the flag indicating the accessibility state of the subtree rooted
11927     * at this view changed.
11928     */
11929    void resetSubtreeAccessibilityStateChanged() {
11930        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
11931    }
11932
11933    /**
11934     * Report an accessibility action to this view's parents for delegated processing.
11935     *
11936     * <p>Implementations of {@link #performAccessibilityAction(int, Bundle)} may internally
11937     * call this method to delegate an accessibility action to a supporting parent. If the parent
11938     * returns true from its
11939     * {@link ViewParent#onNestedPrePerformAccessibilityAction(View, int, android.os.Bundle)}
11940     * method this method will return true to signify that the action was consumed.</p>
11941     *
11942     * <p>This method is useful for implementing nested scrolling child views. If
11943     * {@link #isNestedScrollingEnabled()} returns true and the action is a scrolling action
11944     * a custom view implementation may invoke this method to allow a parent to consume the
11945     * scroll first. If this method returns true the custom view should skip its own scrolling
11946     * behavior.</p>
11947     *
11948     * @param action Accessibility action to delegate
11949     * @param arguments Optional action arguments
11950     * @return true if the action was consumed by a parent
11951     */
11952    public boolean dispatchNestedPrePerformAccessibilityAction(int action, Bundle arguments) {
11953        for (ViewParent p = getParent(); p != null; p = p.getParent()) {
11954            if (p.onNestedPrePerformAccessibilityAction(this, action, arguments)) {
11955                return true;
11956            }
11957        }
11958        return false;
11959    }
11960
11961    /**
11962     * Performs the specified accessibility action on the view. For
11963     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
11964     * <p>
11965     * If an {@link AccessibilityDelegate} has been specified via calling
11966     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
11967     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
11968     * is responsible for handling this call.
11969     * </p>
11970     *
11971     * <p>The default implementation will delegate
11972     * {@link AccessibilityNodeInfo#ACTION_SCROLL_BACKWARD} and
11973     * {@link AccessibilityNodeInfo#ACTION_SCROLL_FORWARD} to nested scrolling parents if
11974     * {@link #isNestedScrollingEnabled() nested scrolling is enabled} on this view.</p>
11975     *
11976     * @param action The action to perform.
11977     * @param arguments Optional action arguments.
11978     * @return Whether the action was performed.
11979     */
11980    public boolean performAccessibilityAction(int action, Bundle arguments) {
11981      if (mAccessibilityDelegate != null) {
11982          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
11983      } else {
11984          return performAccessibilityActionInternal(action, arguments);
11985      }
11986    }
11987
11988   /**
11989    * @see #performAccessibilityAction(int, Bundle)
11990    *
11991    * Note: Called from the default {@link AccessibilityDelegate}.
11992    *
11993    * @hide
11994    */
11995    public boolean performAccessibilityActionInternal(int action, Bundle arguments) {
11996        if (isNestedScrollingEnabled()
11997                && (action == AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD
11998                || action == AccessibilityNodeInfo.ACTION_SCROLL_FORWARD
11999                || action == R.id.accessibilityActionScrollUp
12000                || action == R.id.accessibilityActionScrollLeft
12001                || action == R.id.accessibilityActionScrollDown
12002                || action == R.id.accessibilityActionScrollRight)) {
12003            if (dispatchNestedPrePerformAccessibilityAction(action, arguments)) {
12004                return true;
12005            }
12006        }
12007
12008        switch (action) {
12009            case AccessibilityNodeInfo.ACTION_CLICK: {
12010                if (isClickable()) {
12011                    performClickInternal();
12012                    return true;
12013                }
12014            } break;
12015            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
12016                if (isLongClickable()) {
12017                    performLongClick();
12018                    return true;
12019                }
12020            } break;
12021            case AccessibilityNodeInfo.ACTION_FOCUS: {
12022                if (!hasFocus()) {
12023                    // Get out of touch mode since accessibility
12024                    // wants to move focus around.
12025                    getViewRootImpl().ensureTouchMode(false);
12026                    return requestFocus();
12027                }
12028            } break;
12029            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
12030                if (hasFocus()) {
12031                    clearFocus();
12032                    return !isFocused();
12033                }
12034            } break;
12035            case AccessibilityNodeInfo.ACTION_SELECT: {
12036                if (!isSelected()) {
12037                    setSelected(true);
12038                    return isSelected();
12039                }
12040            } break;
12041            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
12042                if (isSelected()) {
12043                    setSelected(false);
12044                    return !isSelected();
12045                }
12046            } break;
12047            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
12048                if (!isAccessibilityFocused()) {
12049                    return requestAccessibilityFocus();
12050                }
12051            } break;
12052            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
12053                if (isAccessibilityFocused()) {
12054                    clearAccessibilityFocus();
12055                    return true;
12056                }
12057            } break;
12058            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
12059                if (arguments != null) {
12060                    final int granularity = arguments.getInt(
12061                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
12062                    final boolean extendSelection = arguments.getBoolean(
12063                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
12064                    return traverseAtGranularity(granularity, true, extendSelection);
12065                }
12066            } break;
12067            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
12068                if (arguments != null) {
12069                    final int granularity = arguments.getInt(
12070                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
12071                    final boolean extendSelection = arguments.getBoolean(
12072                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
12073                    return traverseAtGranularity(granularity, false, extendSelection);
12074                }
12075            } break;
12076            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
12077                CharSequence text = getIterableTextForAccessibility();
12078                if (text == null) {
12079                    return false;
12080                }
12081                final int start = (arguments != null) ? arguments.getInt(
12082                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
12083                final int end = (arguments != null) ? arguments.getInt(
12084                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
12085                // Only cursor position can be specified (selection length == 0)
12086                if ((getAccessibilitySelectionStart() != start
12087                        || getAccessibilitySelectionEnd() != end)
12088                        && (start == end)) {
12089                    setAccessibilitySelection(start, end);
12090                    notifyViewAccessibilityStateChangedIfNeeded(
12091                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
12092                    return true;
12093                }
12094            } break;
12095            case R.id.accessibilityActionShowOnScreen: {
12096                if (mAttachInfo != null) {
12097                    final Rect r = mAttachInfo.mTmpInvalRect;
12098                    getDrawingRect(r);
12099                    return requestRectangleOnScreen(r, true);
12100                }
12101            } break;
12102            case R.id.accessibilityActionContextClick: {
12103                if (isContextClickable()) {
12104                    performContextClick();
12105                    return true;
12106                }
12107            } break;
12108            case R.id.accessibilityActionShowTooltip: {
12109                if ((mTooltipInfo != null) && (mTooltipInfo.mTooltipPopup != null)) {
12110                    // Tooltip already showing
12111                    return false;
12112                }
12113                return showLongClickTooltip(0, 0);
12114            }
12115            case R.id.accessibilityActionHideTooltip: {
12116                if ((mTooltipInfo == null) || (mTooltipInfo.mTooltipPopup == null)) {
12117                    // No tooltip showing
12118                    return false;
12119                }
12120                hideTooltip();
12121                return true;
12122            }
12123        }
12124        return false;
12125    }
12126
12127    private boolean traverseAtGranularity(int granularity, boolean forward,
12128            boolean extendSelection) {
12129        CharSequence text = getIterableTextForAccessibility();
12130        if (text == null || text.length() == 0) {
12131            return false;
12132        }
12133        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
12134        if (iterator == null) {
12135            return false;
12136        }
12137        int current = getAccessibilitySelectionEnd();
12138        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
12139            current = forward ? 0 : text.length();
12140        }
12141        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
12142        if (range == null) {
12143            return false;
12144        }
12145        final int segmentStart = range[0];
12146        final int segmentEnd = range[1];
12147        int selectionStart;
12148        int selectionEnd;
12149        if (extendSelection && isAccessibilitySelectionExtendable()) {
12150            selectionStart = getAccessibilitySelectionStart();
12151            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
12152                selectionStart = forward ? segmentStart : segmentEnd;
12153            }
12154            selectionEnd = forward ? segmentEnd : segmentStart;
12155        } else {
12156            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
12157        }
12158        setAccessibilitySelection(selectionStart, selectionEnd);
12159        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
12160                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
12161        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
12162        return true;
12163    }
12164
12165    /**
12166     * Gets the text reported for accessibility purposes.
12167     *
12168     * @return The accessibility text.
12169     *
12170     * @hide
12171     */
12172    public CharSequence getIterableTextForAccessibility() {
12173        return getContentDescription();
12174    }
12175
12176    /**
12177     * Gets whether accessibility selection can be extended.
12178     *
12179     * @return If selection is extensible.
12180     *
12181     * @hide
12182     */
12183    public boolean isAccessibilitySelectionExtendable() {
12184        return false;
12185    }
12186
12187    /**
12188     * @hide
12189     */
12190    public int getAccessibilitySelectionStart() {
12191        return mAccessibilityCursorPosition;
12192    }
12193
12194    /**
12195     * @hide
12196     */
12197    public int getAccessibilitySelectionEnd() {
12198        return getAccessibilitySelectionStart();
12199    }
12200
12201    /**
12202     * @hide
12203     */
12204    public void setAccessibilitySelection(int start, int end) {
12205        if (start ==  end && end == mAccessibilityCursorPosition) {
12206            return;
12207        }
12208        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
12209            mAccessibilityCursorPosition = start;
12210        } else {
12211            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
12212        }
12213        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
12214    }
12215
12216    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
12217            int fromIndex, int toIndex) {
12218        if (mParent == null) {
12219            return;
12220        }
12221        AccessibilityEvent event = AccessibilityEvent.obtain(
12222                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
12223        onInitializeAccessibilityEvent(event);
12224        onPopulateAccessibilityEvent(event);
12225        event.setFromIndex(fromIndex);
12226        event.setToIndex(toIndex);
12227        event.setAction(action);
12228        event.setMovementGranularity(granularity);
12229        mParent.requestSendAccessibilityEvent(this, event);
12230    }
12231
12232    /**
12233     * @hide
12234     */
12235    public TextSegmentIterator getIteratorForGranularity(int granularity) {
12236        switch (granularity) {
12237            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
12238                CharSequence text = getIterableTextForAccessibility();
12239                if (text != null && text.length() > 0) {
12240                    CharacterTextSegmentIterator iterator =
12241                        CharacterTextSegmentIterator.getInstance(
12242                                mContext.getResources().getConfiguration().locale);
12243                    iterator.initialize(text.toString());
12244                    return iterator;
12245                }
12246            } break;
12247            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
12248                CharSequence text = getIterableTextForAccessibility();
12249                if (text != null && text.length() > 0) {
12250                    WordTextSegmentIterator iterator =
12251                        WordTextSegmentIterator.getInstance(
12252                                mContext.getResources().getConfiguration().locale);
12253                    iterator.initialize(text.toString());
12254                    return iterator;
12255                }
12256            } break;
12257            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
12258                CharSequence text = getIterableTextForAccessibility();
12259                if (text != null && text.length() > 0) {
12260                    ParagraphTextSegmentIterator iterator =
12261                        ParagraphTextSegmentIterator.getInstance();
12262                    iterator.initialize(text.toString());
12263                    return iterator;
12264                }
12265            } break;
12266        }
12267        return null;
12268    }
12269
12270    /**
12271     * Tells whether the {@link View} is in the state between {@link #onStartTemporaryDetach()}
12272     * and {@link #onFinishTemporaryDetach()}.
12273     *
12274     * <p>This method always returns {@code true} when called directly or indirectly from
12275     * {@link #onStartTemporaryDetach()}. The return value when called directly or indirectly from
12276     * {@link #onFinishTemporaryDetach()}, however, depends on the OS version.
12277     * <ul>
12278     *     <li>{@code true} on {@link android.os.Build.VERSION_CODES#N API 24}</li>
12279     *     <li>{@code false} on {@link android.os.Build.VERSION_CODES#N_MR1 API 25}} and later</li>
12280     * </ul>
12281     * </p>
12282     *
12283     * @return {@code true} when the View is in the state between {@link #onStartTemporaryDetach()}
12284     * and {@link #onFinishTemporaryDetach()}.
12285     */
12286    public final boolean isTemporarilyDetached() {
12287        return (mPrivateFlags3 & PFLAG3_TEMPORARY_DETACH) != 0;
12288    }
12289
12290    /**
12291     * Dispatch {@link #onStartTemporaryDetach()} to this View and its direct children if this is
12292     * a container View.
12293     */
12294    @CallSuper
12295    public void dispatchStartTemporaryDetach() {
12296        mPrivateFlags3 |= PFLAG3_TEMPORARY_DETACH;
12297        notifyEnterOrExitForAutoFillIfNeeded(false);
12298        onStartTemporaryDetach();
12299    }
12300
12301    /**
12302     * This is called when a container is going to temporarily detach a child, with
12303     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
12304     * It will either be followed by {@link #onFinishTemporaryDetach()} or
12305     * {@link #onDetachedFromWindow()} when the container is done.
12306     */
12307    public void onStartTemporaryDetach() {
12308        removeUnsetPressCallback();
12309        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
12310    }
12311
12312    /**
12313     * Dispatch {@link #onFinishTemporaryDetach()} to this View and its direct children if this is
12314     * a container View.
12315     */
12316    @CallSuper
12317    public void dispatchFinishTemporaryDetach() {
12318        mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH;
12319        onFinishTemporaryDetach();
12320        if (hasWindowFocus() && hasFocus()) {
12321            InputMethodManager.getInstance().focusIn(this);
12322        }
12323        notifyEnterOrExitForAutoFillIfNeeded(true);
12324    }
12325
12326    /**
12327     * Called after {@link #onStartTemporaryDetach} when the container is done
12328     * changing the view.
12329     */
12330    public void onFinishTemporaryDetach() {
12331    }
12332
12333    /**
12334     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
12335     * for this view's window.  Returns null if the view is not currently attached
12336     * to the window.  Normally you will not need to use this directly, but
12337     * just use the standard high-level event callbacks like
12338     * {@link #onKeyDown(int, KeyEvent)}.
12339     */
12340    public KeyEvent.DispatcherState getKeyDispatcherState() {
12341        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
12342    }
12343
12344    /**
12345     * Dispatch a key event before it is processed by any input method
12346     * associated with the view hierarchy.  This can be used to intercept
12347     * key events in special situations before the IME consumes them; a
12348     * typical example would be handling the BACK key to update the application's
12349     * UI instead of allowing the IME to see it and close itself.
12350     *
12351     * @param event The key event to be dispatched.
12352     * @return True if the event was handled, false otherwise.
12353     */
12354    public boolean dispatchKeyEventPreIme(KeyEvent event) {
12355        return onKeyPreIme(event.getKeyCode(), event);
12356    }
12357
12358    /**
12359     * Dispatch a key event to the next view on the focus path. This path runs
12360     * from the top of the view tree down to the currently focused view. If this
12361     * view has focus, it will dispatch to itself. Otherwise it will dispatch
12362     * the next node down the focus path. This method also fires any key
12363     * listeners.
12364     *
12365     * @param event The key event to be dispatched.
12366     * @return True if the event was handled, false otherwise.
12367     */
12368    public boolean dispatchKeyEvent(KeyEvent event) {
12369        if (mInputEventConsistencyVerifier != null) {
12370            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
12371        }
12372
12373        // Give any attached key listener a first crack at the event.
12374        //noinspection SimplifiableIfStatement
12375        ListenerInfo li = mListenerInfo;
12376        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
12377                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
12378            return true;
12379        }
12380
12381        if (event.dispatch(this, mAttachInfo != null
12382                ? mAttachInfo.mKeyDispatchState : null, this)) {
12383            return true;
12384        }
12385
12386        if (mInputEventConsistencyVerifier != null) {
12387            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
12388        }
12389        return false;
12390    }
12391
12392    /**
12393     * Dispatches a key shortcut event.
12394     *
12395     * @param event The key event to be dispatched.
12396     * @return True if the event was handled by the view, false otherwise.
12397     */
12398    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
12399        return onKeyShortcut(event.getKeyCode(), event);
12400    }
12401
12402    /**
12403     * Pass the touch screen motion event down to the target view, or this
12404     * view if it is the target.
12405     *
12406     * @param event The motion event to be dispatched.
12407     * @return True if the event was handled by the view, false otherwise.
12408     */
12409    public boolean dispatchTouchEvent(MotionEvent event) {
12410        // If the event should be handled by accessibility focus first.
12411        if (event.isTargetAccessibilityFocus()) {
12412            // We don't have focus or no virtual descendant has it, do not handle the event.
12413            if (!isAccessibilityFocusedViewOrHost()) {
12414                return false;
12415            }
12416            // We have focus and got the event, then use normal event dispatch.
12417            event.setTargetAccessibilityFocus(false);
12418        }
12419
12420        boolean result = false;
12421
12422        if (mInputEventConsistencyVerifier != null) {
12423            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
12424        }
12425
12426        final int actionMasked = event.getActionMasked();
12427        if (actionMasked == MotionEvent.ACTION_DOWN) {
12428            // Defensive cleanup for new gesture
12429            stopNestedScroll();
12430        }
12431
12432        if (onFilterTouchEventForSecurity(event)) {
12433            if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
12434                result = true;
12435            }
12436            //noinspection SimplifiableIfStatement
12437            ListenerInfo li = mListenerInfo;
12438            if (li != null && li.mOnTouchListener != null
12439                    && (mViewFlags & ENABLED_MASK) == ENABLED
12440                    && li.mOnTouchListener.onTouch(this, event)) {
12441                result = true;
12442            }
12443
12444            if (!result && onTouchEvent(event)) {
12445                result = true;
12446            }
12447        }
12448
12449        if (!result && mInputEventConsistencyVerifier != null) {
12450            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
12451        }
12452
12453        // Clean up after nested scrolls if this is the end of a gesture;
12454        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
12455        // of the gesture.
12456        if (actionMasked == MotionEvent.ACTION_UP ||
12457                actionMasked == MotionEvent.ACTION_CANCEL ||
12458                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
12459            stopNestedScroll();
12460        }
12461
12462        return result;
12463    }
12464
12465    boolean isAccessibilityFocusedViewOrHost() {
12466        return isAccessibilityFocused() || (getViewRootImpl() != null && getViewRootImpl()
12467                .getAccessibilityFocusedHost() == this);
12468    }
12469
12470    /**
12471     * Filter the touch event to apply security policies.
12472     *
12473     * @param event The motion event to be filtered.
12474     * @return True if the event should be dispatched, false if the event should be dropped.
12475     *
12476     * @see #getFilterTouchesWhenObscured
12477     */
12478    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
12479        //noinspection RedundantIfStatement
12480        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
12481                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
12482            // Window is obscured, drop this touch.
12483            return false;
12484        }
12485        return true;
12486    }
12487
12488    /**
12489     * Pass a trackball motion event down to the focused view.
12490     *
12491     * @param event The motion event to be dispatched.
12492     * @return True if the event was handled by the view, false otherwise.
12493     */
12494    public boolean dispatchTrackballEvent(MotionEvent event) {
12495        if (mInputEventConsistencyVerifier != null) {
12496            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
12497        }
12498
12499        return onTrackballEvent(event);
12500    }
12501
12502    /**
12503     * Pass a captured pointer event down to the focused view.
12504     *
12505     * @param event The motion event to be dispatched.
12506     * @return True if the event was handled by the view, false otherwise.
12507     */
12508    public boolean dispatchCapturedPointerEvent(MotionEvent event) {
12509        if (!hasPointerCapture()) {
12510            return false;
12511        }
12512        //noinspection SimplifiableIfStatement
12513        ListenerInfo li = mListenerInfo;
12514        if (li != null && li.mOnCapturedPointerListener != null
12515                && li.mOnCapturedPointerListener.onCapturedPointer(this, event)) {
12516            return true;
12517        }
12518        return onCapturedPointerEvent(event);
12519    }
12520
12521    /**
12522     * Dispatch a generic motion event.
12523     * <p>
12524     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
12525     * are delivered to the view under the pointer.  All other generic motion events are
12526     * delivered to the focused view.  Hover events are handled specially and are delivered
12527     * to {@link #onHoverEvent(MotionEvent)}.
12528     * </p>
12529     *
12530     * @param event The motion event to be dispatched.
12531     * @return True if the event was handled by the view, false otherwise.
12532     */
12533    public boolean dispatchGenericMotionEvent(MotionEvent event) {
12534        if (mInputEventConsistencyVerifier != null) {
12535            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
12536        }
12537
12538        final int source = event.getSource();
12539        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
12540            final int action = event.getAction();
12541            if (action == MotionEvent.ACTION_HOVER_ENTER
12542                    || action == MotionEvent.ACTION_HOVER_MOVE
12543                    || action == MotionEvent.ACTION_HOVER_EXIT) {
12544                if (dispatchHoverEvent(event)) {
12545                    return true;
12546                }
12547            } else if (dispatchGenericPointerEvent(event)) {
12548                return true;
12549            }
12550        } else if (dispatchGenericFocusedEvent(event)) {
12551            return true;
12552        }
12553
12554        if (dispatchGenericMotionEventInternal(event)) {
12555            return true;
12556        }
12557
12558        if (mInputEventConsistencyVerifier != null) {
12559            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
12560        }
12561        return false;
12562    }
12563
12564    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
12565        //noinspection SimplifiableIfStatement
12566        ListenerInfo li = mListenerInfo;
12567        if (li != null && li.mOnGenericMotionListener != null
12568                && (mViewFlags & ENABLED_MASK) == ENABLED
12569                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
12570            return true;
12571        }
12572
12573        if (onGenericMotionEvent(event)) {
12574            return true;
12575        }
12576
12577        final int actionButton = event.getActionButton();
12578        switch (event.getActionMasked()) {
12579            case MotionEvent.ACTION_BUTTON_PRESS:
12580                if (isContextClickable() && !mInContextButtonPress && !mHasPerformedLongPress
12581                        && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY
12582                        || actionButton == MotionEvent.BUTTON_SECONDARY)) {
12583                    if (performContextClick(event.getX(), event.getY())) {
12584                        mInContextButtonPress = true;
12585                        setPressed(true, event.getX(), event.getY());
12586                        removeTapCallback();
12587                        removeLongPressCallback();
12588                        return true;
12589                    }
12590                }
12591                break;
12592
12593            case MotionEvent.ACTION_BUTTON_RELEASE:
12594                if (mInContextButtonPress && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY
12595                        || actionButton == MotionEvent.BUTTON_SECONDARY)) {
12596                    mInContextButtonPress = false;
12597                    mIgnoreNextUpEvent = true;
12598                }
12599                break;
12600        }
12601
12602        if (mInputEventConsistencyVerifier != null) {
12603            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
12604        }
12605        return false;
12606    }
12607
12608    /**
12609     * Dispatch a hover event.
12610     * <p>
12611     * Do not call this method directly.
12612     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
12613     * </p>
12614     *
12615     * @param event The motion event to be dispatched.
12616     * @return True if the event was handled by the view, false otherwise.
12617     */
12618    protected boolean dispatchHoverEvent(MotionEvent event) {
12619        ListenerInfo li = mListenerInfo;
12620        //noinspection SimplifiableIfStatement
12621        if (li != null && li.mOnHoverListener != null
12622                && (mViewFlags & ENABLED_MASK) == ENABLED
12623                && li.mOnHoverListener.onHover(this, event)) {
12624            return true;
12625        }
12626
12627        return onHoverEvent(event);
12628    }
12629
12630    /**
12631     * Returns true if the view has a child to which it has recently sent
12632     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
12633     * it does not have a hovered child, then it must be the innermost hovered view.
12634     * @hide
12635     */
12636    protected boolean hasHoveredChild() {
12637        return false;
12638    }
12639
12640    /**
12641     * Dispatch a generic motion event to the view under the first pointer.
12642     * <p>
12643     * Do not call this method directly.
12644     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
12645     * </p>
12646     *
12647     * @param event The motion event to be dispatched.
12648     * @return True if the event was handled by the view, false otherwise.
12649     */
12650    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
12651        return false;
12652    }
12653
12654    /**
12655     * Dispatch a generic motion event to the currently focused view.
12656     * <p>
12657     * Do not call this method directly.
12658     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
12659     * </p>
12660     *
12661     * @param event The motion event to be dispatched.
12662     * @return True if the event was handled by the view, false otherwise.
12663     */
12664    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
12665        return false;
12666    }
12667
12668    /**
12669     * Dispatch a pointer event.
12670     * <p>
12671     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
12672     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
12673     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
12674     * and should not be expected to handle other pointing device features.
12675     * </p>
12676     *
12677     * @param event The motion event to be dispatched.
12678     * @return True if the event was handled by the view, false otherwise.
12679     * @hide
12680     */
12681    public final boolean dispatchPointerEvent(MotionEvent event) {
12682        if (event.isTouchEvent()) {
12683            return dispatchTouchEvent(event);
12684        } else {
12685            return dispatchGenericMotionEvent(event);
12686        }
12687    }
12688
12689    /**
12690     * Called when the window containing this view gains or loses window focus.
12691     * ViewGroups should override to route to their children.
12692     *
12693     * @param hasFocus True if the window containing this view now has focus,
12694     *        false otherwise.
12695     */
12696    public void dispatchWindowFocusChanged(boolean hasFocus) {
12697        onWindowFocusChanged(hasFocus);
12698    }
12699
12700    /**
12701     * Called when the window containing this view gains or loses focus.  Note
12702     * that this is separate from view focus: to receive key events, both
12703     * your view and its window must have focus.  If a window is displayed
12704     * on top of yours that takes input focus, then your own window will lose
12705     * focus but the view focus will remain unchanged.
12706     *
12707     * @param hasWindowFocus True if the window containing this view now has
12708     *        focus, false otherwise.
12709     */
12710    public void onWindowFocusChanged(boolean hasWindowFocus) {
12711        InputMethodManager imm = InputMethodManager.peekInstance();
12712        if (!hasWindowFocus) {
12713            if (isPressed()) {
12714                setPressed(false);
12715            }
12716            mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
12717            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
12718                imm.focusOut(this);
12719            }
12720            removeLongPressCallback();
12721            removeTapCallback();
12722            onFocusLost();
12723        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
12724            imm.focusIn(this);
12725        }
12726
12727        refreshDrawableState();
12728    }
12729
12730    /**
12731     * Returns true if this view is in a window that currently has window focus.
12732     * Note that this is not the same as the view itself having focus.
12733     *
12734     * @return True if this view is in a window that currently has window focus.
12735     */
12736    public boolean hasWindowFocus() {
12737        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
12738    }
12739
12740    /**
12741     * Dispatch a view visibility change down the view hierarchy.
12742     * ViewGroups should override to route to their children.
12743     * @param changedView The view whose visibility changed. Could be 'this' or
12744     * an ancestor view.
12745     * @param visibility The new visibility of changedView: {@link #VISIBLE},
12746     * {@link #INVISIBLE} or {@link #GONE}.
12747     */
12748    protected void dispatchVisibilityChanged(@NonNull View changedView,
12749            @Visibility int visibility) {
12750        onVisibilityChanged(changedView, visibility);
12751    }
12752
12753    /**
12754     * Called when the visibility of the view or an ancestor of the view has
12755     * changed.
12756     *
12757     * @param changedView The view whose visibility changed. May be
12758     *                    {@code this} or an ancestor view.
12759     * @param visibility The new visibility, one of {@link #VISIBLE},
12760     *                   {@link #INVISIBLE} or {@link #GONE}.
12761     */
12762    protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) {
12763    }
12764
12765    /**
12766     * Dispatch a hint about whether this view is displayed. For instance, when
12767     * a View moves out of the screen, it might receives a display hint indicating
12768     * the view is not displayed. Applications should not <em>rely</em> on this hint
12769     * as there is no guarantee that they will receive one.
12770     *
12771     * @param hint A hint about whether or not this view is displayed:
12772     * {@link #VISIBLE} or {@link #INVISIBLE}.
12773     */
12774    public void dispatchDisplayHint(@Visibility int hint) {
12775        onDisplayHint(hint);
12776    }
12777
12778    /**
12779     * Gives this view a hint about whether is displayed or not. For instance, when
12780     * a View moves out of the screen, it might receives a display hint indicating
12781     * the view is not displayed. Applications should not <em>rely</em> on this hint
12782     * as there is no guarantee that they will receive one.
12783     *
12784     * @param hint A hint about whether or not this view is displayed:
12785     * {@link #VISIBLE} or {@link #INVISIBLE}.
12786     */
12787    protected void onDisplayHint(@Visibility int hint) {
12788    }
12789
12790    /**
12791     * Dispatch a window visibility change down the view hierarchy.
12792     * ViewGroups should override to route to their children.
12793     *
12794     * @param visibility The new visibility of the window.
12795     *
12796     * @see #onWindowVisibilityChanged(int)
12797     */
12798    public void dispatchWindowVisibilityChanged(@Visibility int visibility) {
12799        onWindowVisibilityChanged(visibility);
12800    }
12801
12802    /**
12803     * Called when the window containing has change its visibility
12804     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
12805     * that this tells you whether or not your window is being made visible
12806     * to the window manager; this does <em>not</em> tell you whether or not
12807     * your window is obscured by other windows on the screen, even if it
12808     * is itself visible.
12809     *
12810     * @param visibility The new visibility of the window.
12811     */
12812    protected void onWindowVisibilityChanged(@Visibility int visibility) {
12813        if (visibility == VISIBLE) {
12814            initialAwakenScrollBars();
12815        }
12816    }
12817
12818    /**
12819     * Internal dispatching method for {@link #onVisibilityAggregated}. Overridden by
12820     * ViewGroup. Intended to only be called when {@link #isAttachedToWindow()},
12821     * {@link #getWindowVisibility()} is {@link #VISIBLE} and this view's parent {@link #isShown()}.
12822     *
12823     * @param isVisible true if this view's visibility to the user is uninterrupted by its
12824     *                  ancestors or by window visibility
12825     * @return true if this view is visible to the user, not counting clipping or overlapping
12826     */
12827    boolean dispatchVisibilityAggregated(boolean isVisible) {
12828        final boolean thisVisible = getVisibility() == VISIBLE;
12829        // If we're not visible but something is telling us we are, ignore it.
12830        if (thisVisible || !isVisible) {
12831            onVisibilityAggregated(isVisible);
12832        }
12833        return thisVisible && isVisible;
12834    }
12835
12836    /**
12837     * Called when the user-visibility of this View is potentially affected by a change
12838     * to this view itself, an ancestor view or the window this view is attached to.
12839     *
12840     * @param isVisible true if this view and all of its ancestors are {@link #VISIBLE}
12841     *                  and this view's window is also visible
12842     */
12843    @CallSuper
12844    public void onVisibilityAggregated(boolean isVisible) {
12845        // Update our internal visibility tracking so we can detect changes
12846        boolean oldVisible = (mPrivateFlags3 & PFLAG3_AGGREGATED_VISIBLE) != 0;
12847        mPrivateFlags3 = isVisible ? (mPrivateFlags3 | PFLAG3_AGGREGATED_VISIBLE)
12848                : (mPrivateFlags3 & ~PFLAG3_AGGREGATED_VISIBLE);
12849        if (isVisible && mAttachInfo != null) {
12850            initialAwakenScrollBars();
12851        }
12852
12853        final Drawable dr = mBackground;
12854        if (dr != null && isVisible != dr.isVisible()) {
12855            dr.setVisible(isVisible, false);
12856        }
12857        final Drawable hl = mDefaultFocusHighlight;
12858        if (hl != null && isVisible != hl.isVisible()) {
12859            hl.setVisible(isVisible, false);
12860        }
12861        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
12862        if (fg != null && isVisible != fg.isVisible()) {
12863            fg.setVisible(isVisible, false);
12864        }
12865
12866        if (isAutofillable()) {
12867            AutofillManager afm = getAutofillManager();
12868
12869            if (afm != null && getAutofillViewId() > LAST_APP_AUTOFILL_ID) {
12870                if (mVisibilityChangeForAutofillHandler != null) {
12871                    mVisibilityChangeForAutofillHandler.removeMessages(0);
12872                }
12873
12874                // If the view is in the background but still part of the hierarchy this is called
12875                // with isVisible=false. Hence visibility==false requires further checks
12876                if (isVisible) {
12877                    afm.notifyViewVisibilityChanged(this, true);
12878                } else {
12879                    if (mVisibilityChangeForAutofillHandler == null) {
12880                        mVisibilityChangeForAutofillHandler =
12881                                new VisibilityChangeForAutofillHandler(afm, this);
12882                    }
12883                    // Let current operation (e.g. removal of the view from the hierarchy)
12884                    // finish before checking state
12885                    mVisibilityChangeForAutofillHandler.obtainMessage(0, this).sendToTarget();
12886                }
12887            }
12888        }
12889        if (!TextUtils.isEmpty(getAccessibilityPaneTitle())) {
12890            if (isVisible != oldVisible) {
12891                notifyViewAccessibilityStateChangedIfNeeded(isVisible
12892                        ? AccessibilityEvent.CONTENT_CHANGE_TYPE_PANE_APPEARED
12893                        : AccessibilityEvent.CONTENT_CHANGE_TYPE_PANE_DISAPPEARED);
12894            }
12895        }
12896    }
12897
12898    /**
12899     * Returns the current visibility of the window this view is attached to
12900     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
12901     *
12902     * @return Returns the current visibility of the view's window.
12903     */
12904    @Visibility
12905    public int getWindowVisibility() {
12906        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
12907    }
12908
12909    /**
12910     * Retrieve the overall visible display size in which the window this view is
12911     * attached to has been positioned in.  This takes into account screen
12912     * decorations above the window, for both cases where the window itself
12913     * is being position inside of them or the window is being placed under
12914     * then and covered insets are used for the window to position its content
12915     * inside.  In effect, this tells you the available area where content can
12916     * be placed and remain visible to users.
12917     *
12918     * <p>This function requires an IPC back to the window manager to retrieve
12919     * the requested information, so should not be used in performance critical
12920     * code like drawing.
12921     *
12922     * @param outRect Filled in with the visible display frame.  If the view
12923     * is not attached to a window, this is simply the raw display size.
12924     */
12925    public void getWindowVisibleDisplayFrame(Rect outRect) {
12926        if (mAttachInfo != null) {
12927            try {
12928                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
12929            } catch (RemoteException e) {
12930                return;
12931            }
12932            // XXX This is really broken, and probably all needs to be done
12933            // in the window manager, and we need to know more about whether
12934            // we want the area behind or in front of the IME.
12935            final Rect insets = mAttachInfo.mVisibleInsets;
12936            outRect.left += insets.left;
12937            outRect.top += insets.top;
12938            outRect.right -= insets.right;
12939            outRect.bottom -= insets.bottom;
12940            return;
12941        }
12942        // The view is not attached to a display so we don't have a context.
12943        // Make a best guess about the display size.
12944        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
12945        d.getRectSize(outRect);
12946    }
12947
12948    /**
12949     * Like {@link #getWindowVisibleDisplayFrame}, but returns the "full" display frame this window
12950     * is currently in without any insets.
12951     *
12952     * @hide
12953     */
12954    public void getWindowDisplayFrame(Rect outRect) {
12955        if (mAttachInfo != null) {
12956            try {
12957                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
12958            } catch (RemoteException e) {
12959                return;
12960            }
12961            return;
12962        }
12963        // The view is not attached to a display so we don't have a context.
12964        // Make a best guess about the display size.
12965        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
12966        d.getRectSize(outRect);
12967    }
12968
12969    /**
12970     * Dispatch a notification about a resource configuration change down
12971     * the view hierarchy.
12972     * ViewGroups should override to route to their children.
12973     *
12974     * @param newConfig The new resource configuration.
12975     *
12976     * @see #onConfigurationChanged(android.content.res.Configuration)
12977     */
12978    public void dispatchConfigurationChanged(Configuration newConfig) {
12979        onConfigurationChanged(newConfig);
12980    }
12981
12982    /**
12983     * Called when the current configuration of the resources being used
12984     * by the application have changed.  You can use this to decide when
12985     * to reload resources that can changed based on orientation and other
12986     * configuration characteristics.  You only need to use this if you are
12987     * not relying on the normal {@link android.app.Activity} mechanism of
12988     * recreating the activity instance upon a configuration change.
12989     *
12990     * @param newConfig The new resource configuration.
12991     */
12992    protected void onConfigurationChanged(Configuration newConfig) {
12993    }
12994
12995    /**
12996     * Private function to aggregate all per-view attributes in to the view
12997     * root.
12998     */
12999    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
13000        performCollectViewAttributes(attachInfo, visibility);
13001    }
13002
13003    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
13004        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
13005            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
13006                attachInfo.mKeepScreenOn = true;
13007            }
13008            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
13009            ListenerInfo li = mListenerInfo;
13010            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
13011                attachInfo.mHasSystemUiListeners = true;
13012            }
13013        }
13014    }
13015
13016    void needGlobalAttributesUpdate(boolean force) {
13017        final AttachInfo ai = mAttachInfo;
13018        if (ai != null && !ai.mRecomputeGlobalAttributes) {
13019            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
13020                    || ai.mHasSystemUiListeners) {
13021                ai.mRecomputeGlobalAttributes = true;
13022            }
13023        }
13024    }
13025
13026    /**
13027     * Returns whether the device is currently in touch mode.  Touch mode is entered
13028     * once the user begins interacting with the device by touch, and affects various
13029     * things like whether focus is always visible to the user.
13030     *
13031     * @return Whether the device is in touch mode.
13032     */
13033    @ViewDebug.ExportedProperty
13034    public boolean isInTouchMode() {
13035        if (mAttachInfo != null) {
13036            return mAttachInfo.mInTouchMode;
13037        } else {
13038            return ViewRootImpl.isInTouchMode();
13039        }
13040    }
13041
13042    /**
13043     * Returns the context the view is running in, through which it can
13044     * access the current theme, resources, etc.
13045     *
13046     * @return The view's Context.
13047     */
13048    @ViewDebug.CapturedViewProperty
13049    public final Context getContext() {
13050        return mContext;
13051    }
13052
13053    /**
13054     * Handle a key event before it is processed by any input method
13055     * associated with the view hierarchy.  This can be used to intercept
13056     * key events in special situations before the IME consumes them; a
13057     * typical example would be handling the BACK key to update the application's
13058     * UI instead of allowing the IME to see it and close itself.
13059     *
13060     * @param keyCode The value in event.getKeyCode().
13061     * @param event Description of the key event.
13062     * @return If you handled the event, return true. If you want to allow the
13063     *         event to be handled by the next receiver, return false.
13064     */
13065    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
13066        return false;
13067    }
13068
13069    /**
13070     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
13071     * KeyEvent.Callback.onKeyDown()}: perform press of the view
13072     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
13073     * is released, if the view is enabled and clickable.
13074     * <p>
13075     * Key presses in software keyboards will generally NOT trigger this
13076     * listener, although some may elect to do so in some situations. Do not
13077     * rely on this to catch software key presses.
13078     *
13079     * @param keyCode a key code that represents the button pressed, from
13080     *                {@link android.view.KeyEvent}
13081     * @param event the KeyEvent object that defines the button action
13082     */
13083    public boolean onKeyDown(int keyCode, KeyEvent event) {
13084        if (KeyEvent.isConfirmKey(keyCode)) {
13085            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
13086                return true;
13087            }
13088
13089            if (event.getRepeatCount() == 0) {
13090                // Long clickable items don't necessarily have to be clickable.
13091                final boolean clickable = (mViewFlags & CLICKABLE) == CLICKABLE
13092                        || (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
13093                if (clickable || (mViewFlags & TOOLTIP) == TOOLTIP) {
13094                    // For the purposes of menu anchoring and drawable hotspots,
13095                    // key events are considered to be at the center of the view.
13096                    final float x = getWidth() / 2f;
13097                    final float y = getHeight() / 2f;
13098                    if (clickable) {
13099                        setPressed(true, x, y);
13100                    }
13101                    checkForLongClick(0, x, y);
13102                    return true;
13103                }
13104            }
13105        }
13106
13107        return false;
13108    }
13109
13110    /**
13111     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
13112     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
13113     * the event).
13114     * <p>Key presses in software keyboards will generally NOT trigger this listener,
13115     * although some may elect to do so in some situations. Do not rely on this to
13116     * catch software key presses.
13117     */
13118    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
13119        return false;
13120    }
13121
13122    /**
13123     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
13124     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
13125     * when {@link KeyEvent#KEYCODE_DPAD_CENTER}, {@link KeyEvent#KEYCODE_ENTER}
13126     * or {@link KeyEvent#KEYCODE_SPACE} is released.
13127     * <p>Key presses in software keyboards will generally NOT trigger this listener,
13128     * although some may elect to do so in some situations. Do not rely on this to
13129     * catch software key presses.
13130     *
13131     * @param keyCode A key code that represents the button pressed, from
13132     *                {@link android.view.KeyEvent}.
13133     * @param event   The KeyEvent object that defines the button action.
13134     */
13135    public boolean onKeyUp(int keyCode, KeyEvent event) {
13136        if (KeyEvent.isConfirmKey(keyCode)) {
13137            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
13138                return true;
13139            }
13140            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
13141                setPressed(false);
13142
13143                if (!mHasPerformedLongPress) {
13144                    // This is a tap, so remove the longpress check
13145                    removeLongPressCallback();
13146                    if (!event.isCanceled()) {
13147                        return performClickInternal();
13148                    }
13149                }
13150            }
13151        }
13152        return false;
13153    }
13154
13155    /**
13156     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
13157     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
13158     * the event).
13159     * <p>Key presses in software keyboards will generally NOT trigger this listener,
13160     * although some may elect to do so in some situations. Do not rely on this to
13161     * catch software key presses.
13162     *
13163     * @param keyCode     A key code that represents the button pressed, from
13164     *                    {@link android.view.KeyEvent}.
13165     * @param repeatCount The number of times the action was made.
13166     * @param event       The KeyEvent object that defines the button action.
13167     */
13168    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
13169        return false;
13170    }
13171
13172    /**
13173     * Called on the focused view when a key shortcut event is not handled.
13174     * Override this method to implement local key shortcuts for the View.
13175     * Key shortcuts can also be implemented by setting the
13176     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
13177     *
13178     * @param keyCode The value in event.getKeyCode().
13179     * @param event Description of the key event.
13180     * @return If you handled the event, return true. If you want to allow the
13181     *         event to be handled by the next receiver, return false.
13182     */
13183    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
13184        return false;
13185    }
13186
13187    /**
13188     * Check whether the called view is a text editor, in which case it
13189     * would make sense to automatically display a soft input window for
13190     * it.  Subclasses should override this if they implement
13191     * {@link #onCreateInputConnection(EditorInfo)} to return true if
13192     * a call on that method would return a non-null InputConnection, and
13193     * they are really a first-class editor that the user would normally
13194     * start typing on when the go into a window containing your view.
13195     *
13196     * <p>The default implementation always returns false.  This does
13197     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
13198     * will not be called or the user can not otherwise perform edits on your
13199     * view; it is just a hint to the system that this is not the primary
13200     * purpose of this view.
13201     *
13202     * @return Returns true if this view is a text editor, else false.
13203     */
13204    public boolean onCheckIsTextEditor() {
13205        return false;
13206    }
13207
13208    /**
13209     * Create a new InputConnection for an InputMethod to interact
13210     * with the view.  The default implementation returns null, since it doesn't
13211     * support input methods.  You can override this to implement such support.
13212     * This is only needed for views that take focus and text input.
13213     *
13214     * <p>When implementing this, you probably also want to implement
13215     * {@link #onCheckIsTextEditor()} to indicate you will return a
13216     * non-null InputConnection.</p>
13217     *
13218     * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo}
13219     * object correctly and in its entirety, so that the connected IME can rely
13220     * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart}
13221     * and  {@link android.view.inputmethod.EditorInfo#initialSelEnd} members
13222     * must be filled in with the correct cursor position for IMEs to work correctly
13223     * with your application.</p>
13224     *
13225     * @param outAttrs Fill in with attribute information about the connection.
13226     */
13227    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
13228        return null;
13229    }
13230
13231    /**
13232     * Called by the {@link android.view.inputmethod.InputMethodManager}
13233     * when a view who is not the current
13234     * input connection target is trying to make a call on the manager.  The
13235     * default implementation returns false; you can override this to return
13236     * true for certain views if you are performing InputConnection proxying
13237     * to them.
13238     * @param view The View that is making the InputMethodManager call.
13239     * @return Return true to allow the call, false to reject.
13240     */
13241    public boolean checkInputConnectionProxy(View view) {
13242        return false;
13243    }
13244
13245    /**
13246     * Show the context menu for this view. It is not safe to hold on to the
13247     * menu after returning from this method.
13248     *
13249     * You should normally not overload this method. Overload
13250     * {@link #onCreateContextMenu(ContextMenu)} or define an
13251     * {@link OnCreateContextMenuListener} to add items to the context menu.
13252     *
13253     * @param menu The context menu to populate
13254     */
13255    public void createContextMenu(ContextMenu menu) {
13256        ContextMenuInfo menuInfo = getContextMenuInfo();
13257
13258        // Sets the current menu info so all items added to menu will have
13259        // my extra info set.
13260        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
13261
13262        onCreateContextMenu(menu);
13263        ListenerInfo li = mListenerInfo;
13264        if (li != null && li.mOnCreateContextMenuListener != null) {
13265            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
13266        }
13267
13268        // Clear the extra information so subsequent items that aren't mine don't
13269        // have my extra info.
13270        ((MenuBuilder)menu).setCurrentMenuInfo(null);
13271
13272        if (mParent != null) {
13273            mParent.createContextMenu(menu);
13274        }
13275    }
13276
13277    /**
13278     * Views should implement this if they have extra information to associate
13279     * with the context menu. The return result is supplied as a parameter to
13280     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
13281     * callback.
13282     *
13283     * @return Extra information about the item for which the context menu
13284     *         should be shown. This information will vary across different
13285     *         subclasses of View.
13286     */
13287    protected ContextMenuInfo getContextMenuInfo() {
13288        return null;
13289    }
13290
13291    /**
13292     * Views should implement this if the view itself is going to add items to
13293     * the context menu.
13294     *
13295     * @param menu the context menu to populate
13296     */
13297    protected void onCreateContextMenu(ContextMenu menu) {
13298    }
13299
13300    /**
13301     * Implement this method to handle trackball motion events.  The
13302     * <em>relative</em> movement of the trackball since the last event
13303     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
13304     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
13305     * that a movement of 1 corresponds to the user pressing one DPAD key (so
13306     * they will often be fractional values, representing the more fine-grained
13307     * movement information available from a trackball).
13308     *
13309     * @param event The motion event.
13310     * @return True if the event was handled, false otherwise.
13311     */
13312    public boolean onTrackballEvent(MotionEvent event) {
13313        return false;
13314    }
13315
13316    /**
13317     * Implement this method to handle generic motion events.
13318     * <p>
13319     * Generic motion events describe joystick movements, mouse hovers, track pad
13320     * touches, scroll wheel movements and other input events.  The
13321     * {@link MotionEvent#getSource() source} of the motion event specifies
13322     * the class of input that was received.  Implementations of this method
13323     * must examine the bits in the source before processing the event.
13324     * The following code example shows how this is done.
13325     * </p><p>
13326     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
13327     * are delivered to the view under the pointer.  All other generic motion events are
13328     * delivered to the focused view.
13329     * </p>
13330     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
13331     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
13332     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
13333     *             // process the joystick movement...
13334     *             return true;
13335     *         }
13336     *     }
13337     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
13338     *         switch (event.getAction()) {
13339     *             case MotionEvent.ACTION_HOVER_MOVE:
13340     *                 // process the mouse hover movement...
13341     *                 return true;
13342     *             case MotionEvent.ACTION_SCROLL:
13343     *                 // process the scroll wheel movement...
13344     *                 return true;
13345     *         }
13346     *     }
13347     *     return super.onGenericMotionEvent(event);
13348     * }</pre>
13349     *
13350     * @param event The generic motion event being processed.
13351     * @return True if the event was handled, false otherwise.
13352     */
13353    public boolean onGenericMotionEvent(MotionEvent event) {
13354        return false;
13355    }
13356
13357    /**
13358     * Implement this method to handle hover events.
13359     * <p>
13360     * This method is called whenever a pointer is hovering into, over, or out of the
13361     * bounds of a view and the view is not currently being touched.
13362     * Hover events are represented as pointer events with action
13363     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
13364     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
13365     * </p>
13366     * <ul>
13367     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
13368     * when the pointer enters the bounds of the view.</li>
13369     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
13370     * when the pointer has already entered the bounds of the view and has moved.</li>
13371     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
13372     * when the pointer has exited the bounds of the view or when the pointer is
13373     * about to go down due to a button click, tap, or similar user action that
13374     * causes the view to be touched.</li>
13375     * </ul>
13376     * <p>
13377     * The view should implement this method to return true to indicate that it is
13378     * handling the hover event, such as by changing its drawable state.
13379     * </p><p>
13380     * The default implementation calls {@link #setHovered} to update the hovered state
13381     * of the view when a hover enter or hover exit event is received, if the view
13382     * is enabled and is clickable.  The default implementation also sends hover
13383     * accessibility events.
13384     * </p>
13385     *
13386     * @param event The motion event that describes the hover.
13387     * @return True if the view handled the hover event.
13388     *
13389     * @see #isHovered
13390     * @see #setHovered
13391     * @see #onHoverChanged
13392     */
13393    public boolean onHoverEvent(MotionEvent event) {
13394        // The root view may receive hover (or touch) events that are outside the bounds of
13395        // the window.  This code ensures that we only send accessibility events for
13396        // hovers that are actually within the bounds of the root view.
13397        final int action = event.getActionMasked();
13398        if (!mSendingHoverAccessibilityEvents) {
13399            if ((action == MotionEvent.ACTION_HOVER_ENTER
13400                    || action == MotionEvent.ACTION_HOVER_MOVE)
13401                    && !hasHoveredChild()
13402                    && pointInView(event.getX(), event.getY())) {
13403                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
13404                mSendingHoverAccessibilityEvents = true;
13405            }
13406        } else {
13407            if (action == MotionEvent.ACTION_HOVER_EXIT
13408                    || (action == MotionEvent.ACTION_MOVE
13409                            && !pointInView(event.getX(), event.getY()))) {
13410                mSendingHoverAccessibilityEvents = false;
13411                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
13412            }
13413        }
13414
13415        if ((action == MotionEvent.ACTION_HOVER_ENTER || action == MotionEvent.ACTION_HOVER_MOVE)
13416                && event.isFromSource(InputDevice.SOURCE_MOUSE)
13417                && isOnScrollbar(event.getX(), event.getY())) {
13418            awakenScrollBars();
13419        }
13420
13421        // If we consider ourself hoverable, or if we we're already hovered,
13422        // handle changing state in response to ENTER and EXIT events.
13423        if (isHoverable() || isHovered()) {
13424            switch (action) {
13425                case MotionEvent.ACTION_HOVER_ENTER:
13426                    setHovered(true);
13427                    break;
13428                case MotionEvent.ACTION_HOVER_EXIT:
13429                    setHovered(false);
13430                    break;
13431            }
13432
13433            // Dispatch the event to onGenericMotionEvent before returning true.
13434            // This is to provide compatibility with existing applications that
13435            // handled HOVER_MOVE events in onGenericMotionEvent and that would
13436            // break because of the new default handling for hoverable views
13437            // in onHoverEvent.
13438            // Note that onGenericMotionEvent will be called by default when
13439            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
13440            dispatchGenericMotionEventInternal(event);
13441            // The event was already handled by calling setHovered(), so always
13442            // return true.
13443            return true;
13444        }
13445
13446        return false;
13447    }
13448
13449    /**
13450     * Returns true if the view should handle {@link #onHoverEvent}
13451     * by calling {@link #setHovered} to change its hovered state.
13452     *
13453     * @return True if the view is hoverable.
13454     */
13455    private boolean isHoverable() {
13456        final int viewFlags = mViewFlags;
13457        if ((viewFlags & ENABLED_MASK) == DISABLED) {
13458            return false;
13459        }
13460
13461        return (viewFlags & CLICKABLE) == CLICKABLE
13462                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE
13463                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
13464    }
13465
13466    /**
13467     * Returns true if the view is currently hovered.
13468     *
13469     * @return True if the view is currently hovered.
13470     *
13471     * @see #setHovered
13472     * @see #onHoverChanged
13473     */
13474    @ViewDebug.ExportedProperty
13475    public boolean isHovered() {
13476        return (mPrivateFlags & PFLAG_HOVERED) != 0;
13477    }
13478
13479    /**
13480     * Sets whether the view is currently hovered.
13481     * <p>
13482     * Calling this method also changes the drawable state of the view.  This
13483     * enables the view to react to hover by using different drawable resources
13484     * to change its appearance.
13485     * </p><p>
13486     * The {@link #onHoverChanged} method is called when the hovered state changes.
13487     * </p>
13488     *
13489     * @param hovered True if the view is hovered.
13490     *
13491     * @see #isHovered
13492     * @see #onHoverChanged
13493     */
13494    public void setHovered(boolean hovered) {
13495        if (hovered) {
13496            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
13497                mPrivateFlags |= PFLAG_HOVERED;
13498                refreshDrawableState();
13499                onHoverChanged(true);
13500            }
13501        } else {
13502            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
13503                mPrivateFlags &= ~PFLAG_HOVERED;
13504                refreshDrawableState();
13505                onHoverChanged(false);
13506            }
13507        }
13508    }
13509
13510    /**
13511     * Implement this method to handle hover state changes.
13512     * <p>
13513     * This method is called whenever the hover state changes as a result of a
13514     * call to {@link #setHovered}.
13515     * </p>
13516     *
13517     * @param hovered The current hover state, as returned by {@link #isHovered}.
13518     *
13519     * @see #isHovered
13520     * @see #setHovered
13521     */
13522    public void onHoverChanged(boolean hovered) {
13523    }
13524
13525    /**
13526     * Handles scroll bar dragging by mouse input.
13527     *
13528     * @hide
13529     * @param event The motion event.
13530     *
13531     * @return true if the event was handled as a scroll bar dragging, false otherwise.
13532     */
13533    protected boolean handleScrollBarDragging(MotionEvent event) {
13534        if (mScrollCache == null) {
13535            return false;
13536        }
13537        final float x = event.getX();
13538        final float y = event.getY();
13539        final int action = event.getAction();
13540        if ((mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING
13541                && action != MotionEvent.ACTION_DOWN)
13542                    || !event.isFromSource(InputDevice.SOURCE_MOUSE)
13543                    || !event.isButtonPressed(MotionEvent.BUTTON_PRIMARY)) {
13544            mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING;
13545            return false;
13546        }
13547
13548        switch (action) {
13549            case MotionEvent.ACTION_MOVE:
13550                if (mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING) {
13551                    return false;
13552                }
13553                if (mScrollCache.mScrollBarDraggingState
13554                        == ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR) {
13555                    final Rect bounds = mScrollCache.mScrollBarBounds;
13556                    getVerticalScrollBarBounds(bounds, null);
13557                    final int range = computeVerticalScrollRange();
13558                    final int offset = computeVerticalScrollOffset();
13559                    final int extent = computeVerticalScrollExtent();
13560
13561                    final int thumbLength = ScrollBarUtils.getThumbLength(
13562                            bounds.height(), bounds.width(), extent, range);
13563                    final int thumbOffset = ScrollBarUtils.getThumbOffset(
13564                            bounds.height(), thumbLength, extent, range, offset);
13565
13566                    final float diff = y - mScrollCache.mScrollBarDraggingPos;
13567                    final float maxThumbOffset = bounds.height() - thumbLength;
13568                    final float newThumbOffset =
13569                            Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset);
13570                    final int height = getHeight();
13571                    if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0
13572                            && height > 0 && extent > 0) {
13573                        final int newY = Math.round((range - extent)
13574                                / ((float)extent / height) * (newThumbOffset / maxThumbOffset));
13575                        if (newY != getScrollY()) {
13576                            mScrollCache.mScrollBarDraggingPos = y;
13577                            setScrollY(newY);
13578                        }
13579                    }
13580                    return true;
13581                }
13582                if (mScrollCache.mScrollBarDraggingState
13583                        == ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR) {
13584                    final Rect bounds = mScrollCache.mScrollBarBounds;
13585                    getHorizontalScrollBarBounds(bounds, null);
13586                    final int range = computeHorizontalScrollRange();
13587                    final int offset = computeHorizontalScrollOffset();
13588                    final int extent = computeHorizontalScrollExtent();
13589
13590                    final int thumbLength = ScrollBarUtils.getThumbLength(
13591                            bounds.width(), bounds.height(), extent, range);
13592                    final int thumbOffset = ScrollBarUtils.getThumbOffset(
13593                            bounds.width(), thumbLength, extent, range, offset);
13594
13595                    final float diff = x - mScrollCache.mScrollBarDraggingPos;
13596                    final float maxThumbOffset = bounds.width() - thumbLength;
13597                    final float newThumbOffset =
13598                            Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset);
13599                    final int width = getWidth();
13600                    if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0
13601                            && width > 0 && extent > 0) {
13602                        final int newX = Math.round((range - extent)
13603                                / ((float)extent / width) * (newThumbOffset / maxThumbOffset));
13604                        if (newX != getScrollX()) {
13605                            mScrollCache.mScrollBarDraggingPos = x;
13606                            setScrollX(newX);
13607                        }
13608                    }
13609                    return true;
13610                }
13611            case MotionEvent.ACTION_DOWN:
13612                if (mScrollCache.state == ScrollabilityCache.OFF) {
13613                    return false;
13614                }
13615                if (isOnVerticalScrollbarThumb(x, y)) {
13616                    mScrollCache.mScrollBarDraggingState =
13617                            ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR;
13618                    mScrollCache.mScrollBarDraggingPos = y;
13619                    return true;
13620                }
13621                if (isOnHorizontalScrollbarThumb(x, y)) {
13622                    mScrollCache.mScrollBarDraggingState =
13623                            ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR;
13624                    mScrollCache.mScrollBarDraggingPos = x;
13625                    return true;
13626                }
13627        }
13628        mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING;
13629        return false;
13630    }
13631
13632    /**
13633     * Implement this method to handle touch screen motion events.
13634     * <p>
13635     * If this method is used to detect click actions, it is recommended that
13636     * the actions be performed by implementing and calling
13637     * {@link #performClick()}. This will ensure consistent system behavior,
13638     * including:
13639     * <ul>
13640     * <li>obeying click sound preferences
13641     * <li>dispatching OnClickListener calls
13642     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
13643     * accessibility features are enabled
13644     * </ul>
13645     *
13646     * @param event The motion event.
13647     * @return True if the event was handled, false otherwise.
13648     */
13649    public boolean onTouchEvent(MotionEvent event) {
13650        final float x = event.getX();
13651        final float y = event.getY();
13652        final int viewFlags = mViewFlags;
13653        final int action = event.getAction();
13654
13655        final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE
13656                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
13657                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
13658
13659        if ((viewFlags & ENABLED_MASK) == DISABLED) {
13660            if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
13661                setPressed(false);
13662            }
13663            mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
13664            // A disabled view that is clickable still consumes the touch
13665            // events, it just doesn't respond to them.
13666            return clickable;
13667        }
13668        if (mTouchDelegate != null) {
13669            if (mTouchDelegate.onTouchEvent(event)) {
13670                return true;
13671            }
13672        }
13673
13674        if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
13675            switch (action) {
13676                case MotionEvent.ACTION_UP:
13677                    mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
13678                    if ((viewFlags & TOOLTIP) == TOOLTIP) {
13679                        handleTooltipUp();
13680                    }
13681                    if (!clickable) {
13682                        removeTapCallback();
13683                        removeLongPressCallback();
13684                        mInContextButtonPress = false;
13685                        mHasPerformedLongPress = false;
13686                        mIgnoreNextUpEvent = false;
13687                        break;
13688                    }
13689                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
13690                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
13691                        // take focus if we don't have it already and we should in
13692                        // touch mode.
13693                        boolean focusTaken = false;
13694                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
13695                            focusTaken = requestFocus();
13696                        }
13697
13698                        if (prepressed) {
13699                            // The button is being released before we actually
13700                            // showed it as pressed.  Make it show the pressed
13701                            // state now (before scheduling the click) to ensure
13702                            // the user sees it.
13703                            setPressed(true, x, y);
13704                        }
13705
13706                        if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
13707                            // This is a tap, so remove the longpress check
13708                            removeLongPressCallback();
13709
13710                            // Only perform take click actions if we were in the pressed state
13711                            if (!focusTaken) {
13712                                // Use a Runnable and post this rather than calling
13713                                // performClick directly. This lets other visual state
13714                                // of the view update before click actions start.
13715                                if (mPerformClick == null) {
13716                                    mPerformClick = new PerformClick();
13717                                }
13718                                if (!post(mPerformClick)) {
13719                                    performClickInternal();
13720                                }
13721                            }
13722                        }
13723
13724                        if (mUnsetPressedState == null) {
13725                            mUnsetPressedState = new UnsetPressedState();
13726                        }
13727
13728                        if (prepressed) {
13729                            postDelayed(mUnsetPressedState,
13730                                    ViewConfiguration.getPressedStateDuration());
13731                        } else if (!post(mUnsetPressedState)) {
13732                            // If the post failed, unpress right now
13733                            mUnsetPressedState.run();
13734                        }
13735
13736                        removeTapCallback();
13737                    }
13738                    mIgnoreNextUpEvent = false;
13739                    break;
13740
13741                case MotionEvent.ACTION_DOWN:
13742                    if (event.getSource() == InputDevice.SOURCE_TOUCHSCREEN) {
13743                        mPrivateFlags3 |= PFLAG3_FINGER_DOWN;
13744                    }
13745                    mHasPerformedLongPress = false;
13746
13747                    if (!clickable) {
13748                        checkForLongClick(0, x, y);
13749                        break;
13750                    }
13751
13752                    if (performButtonActionOnTouchDown(event)) {
13753                        break;
13754                    }
13755
13756                    // Walk up the hierarchy to determine if we're inside a scrolling container.
13757                    boolean isInScrollingContainer = isInScrollingContainer();
13758
13759                    // For views inside a scrolling container, delay the pressed feedback for
13760                    // a short period in case this is a scroll.
13761                    if (isInScrollingContainer) {
13762                        mPrivateFlags |= PFLAG_PREPRESSED;
13763                        if (mPendingCheckForTap == null) {
13764                            mPendingCheckForTap = new CheckForTap();
13765                        }
13766                        mPendingCheckForTap.x = event.getX();
13767                        mPendingCheckForTap.y = event.getY();
13768                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
13769                    } else {
13770                        // Not inside a scrolling container, so show the feedback right away
13771                        setPressed(true, x, y);
13772                        checkForLongClick(0, x, y);
13773                    }
13774                    break;
13775
13776                case MotionEvent.ACTION_CANCEL:
13777                    if (clickable) {
13778                        setPressed(false);
13779                    }
13780                    removeTapCallback();
13781                    removeLongPressCallback();
13782                    mInContextButtonPress = false;
13783                    mHasPerformedLongPress = false;
13784                    mIgnoreNextUpEvent = false;
13785                    mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
13786                    break;
13787
13788                case MotionEvent.ACTION_MOVE:
13789                    if (clickable) {
13790                        drawableHotspotChanged(x, y);
13791                    }
13792
13793                    // Be lenient about moving outside of buttons
13794                    if (!pointInView(x, y, mTouchSlop)) {
13795                        // Outside button
13796                        // Remove any future long press/tap checks
13797                        removeTapCallback();
13798                        removeLongPressCallback();
13799                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
13800                            setPressed(false);
13801                        }
13802                        mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
13803                    }
13804                    break;
13805            }
13806
13807            return true;
13808        }
13809
13810        return false;
13811    }
13812
13813    /**
13814     * @hide
13815     */
13816    public boolean isInScrollingContainer() {
13817        ViewParent p = getParent();
13818        while (p != null && p instanceof ViewGroup) {
13819            if (((ViewGroup) p).shouldDelayChildPressedState()) {
13820                return true;
13821            }
13822            p = p.getParent();
13823        }
13824        return false;
13825    }
13826
13827    /**
13828     * Remove the longpress detection timer.
13829     */
13830    private void removeLongPressCallback() {
13831        if (mPendingCheckForLongPress != null) {
13832            removeCallbacks(mPendingCheckForLongPress);
13833        }
13834    }
13835
13836    /**
13837     * Remove the pending click action
13838     */
13839    private void removePerformClickCallback() {
13840        if (mPerformClick != null) {
13841            removeCallbacks(mPerformClick);
13842        }
13843    }
13844
13845    /**
13846     * Remove the prepress detection timer.
13847     */
13848    private void removeUnsetPressCallback() {
13849        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
13850            setPressed(false);
13851            removeCallbacks(mUnsetPressedState);
13852        }
13853    }
13854
13855    /**
13856     * Remove the tap detection timer.
13857     */
13858    private void removeTapCallback() {
13859        if (mPendingCheckForTap != null) {
13860            mPrivateFlags &= ~PFLAG_PREPRESSED;
13861            removeCallbacks(mPendingCheckForTap);
13862        }
13863    }
13864
13865    /**
13866     * Cancels a pending long press.  Your subclass can use this if you
13867     * want the context menu to come up if the user presses and holds
13868     * at the same place, but you don't want it to come up if they press
13869     * and then move around enough to cause scrolling.
13870     */
13871    public void cancelLongPress() {
13872        removeLongPressCallback();
13873
13874        /*
13875         * The prepressed state handled by the tap callback is a display
13876         * construct, but the tap callback will post a long press callback
13877         * less its own timeout. Remove it here.
13878         */
13879        removeTapCallback();
13880    }
13881
13882    /**
13883     * Sets the TouchDelegate for this View.
13884     */
13885    public void setTouchDelegate(TouchDelegate delegate) {
13886        mTouchDelegate = delegate;
13887    }
13888
13889    /**
13890     * Gets the TouchDelegate for this View.
13891     */
13892    public TouchDelegate getTouchDelegate() {
13893        return mTouchDelegate;
13894    }
13895
13896    /**
13897     * Request unbuffered dispatch of the given stream of MotionEvents to this View.
13898     *
13899     * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input
13900     * system not batch {@link MotionEvent}s but instead deliver them as soon as they're
13901     * available. This method should only be called for touch events.
13902     *
13903     * <p class="note">This api is not intended for most applications. Buffered dispatch
13904     * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent
13905     * streams will not improve your input latency. Side effects include: increased latency,
13906     * jittery scrolls and inability to take advantage of system resampling. Talk to your input
13907     * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for
13908     * you.</p>
13909     */
13910    public final void requestUnbufferedDispatch(MotionEvent event) {
13911        final int action = event.getAction();
13912        if (mAttachInfo == null
13913                || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE
13914                || !event.isTouchEvent()) {
13915            return;
13916        }
13917        mAttachInfo.mUnbufferedDispatchRequested = true;
13918    }
13919
13920    private boolean canTakeFocus() {
13921        return ((mViewFlags & VISIBILITY_MASK) == VISIBLE)
13922                && ((mViewFlags & FOCUSABLE) == FOCUSABLE)
13923                && ((mViewFlags & ENABLED_MASK) == ENABLED)
13924                && (sCanFocusZeroSized || !isLayoutValid() || (mBottom > mTop) && (mRight > mLeft));
13925    }
13926
13927    /**
13928     * Set flags controlling behavior of this view.
13929     *
13930     * @param flags Constant indicating the value which should be set
13931     * @param mask Constant indicating the bit range that should be changed
13932     */
13933    void setFlags(int flags, int mask) {
13934        final boolean accessibilityEnabled =
13935                AccessibilityManager.getInstance(mContext).isEnabled();
13936        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
13937
13938        int old = mViewFlags;
13939        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
13940
13941        int changed = mViewFlags ^ old;
13942        if (changed == 0) {
13943            return;
13944        }
13945        int privateFlags = mPrivateFlags;
13946        boolean shouldNotifyFocusableAvailable = false;
13947
13948        // If focusable is auto, update the FOCUSABLE bit.
13949        int focusableChangedByAuto = 0;
13950        if (((mViewFlags & FOCUSABLE_AUTO) != 0)
13951                && (changed & (FOCUSABLE_MASK | CLICKABLE)) != 0) {
13952            // Heuristic only takes into account whether view is clickable.
13953            final int newFocus;
13954            if ((mViewFlags & CLICKABLE) != 0) {
13955                newFocus = FOCUSABLE;
13956            } else {
13957                newFocus = NOT_FOCUSABLE;
13958            }
13959            mViewFlags = (mViewFlags & ~FOCUSABLE) | newFocus;
13960            focusableChangedByAuto = (old & FOCUSABLE) ^ (newFocus & FOCUSABLE);
13961            changed = (changed & ~FOCUSABLE) | focusableChangedByAuto;
13962        }
13963
13964        /* Check if the FOCUSABLE bit has changed */
13965        if (((changed & FOCUSABLE) != 0) && ((privateFlags & PFLAG_HAS_BOUNDS) != 0)) {
13966            if (((old & FOCUSABLE) == FOCUSABLE)
13967                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
13968                /* Give up focus if we are no longer focusable */
13969                clearFocus();
13970                if (mParent instanceof ViewGroup) {
13971                    ((ViewGroup) mParent).clearFocusedInCluster();
13972                }
13973            } else if (((old & FOCUSABLE) == NOT_FOCUSABLE)
13974                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
13975                /*
13976                 * Tell the view system that we are now available to take focus
13977                 * if no one else already has it.
13978                 */
13979                if (mParent != null) {
13980                    ViewRootImpl viewRootImpl = getViewRootImpl();
13981                    if (!sAutoFocusableOffUIThreadWontNotifyParents
13982                            || focusableChangedByAuto == 0
13983                            || viewRootImpl == null
13984                            || viewRootImpl.mThread == Thread.currentThread()) {
13985                        shouldNotifyFocusableAvailable = true;
13986                    }
13987                }
13988            }
13989        }
13990
13991        final int newVisibility = flags & VISIBILITY_MASK;
13992        if (newVisibility == VISIBLE) {
13993            if ((changed & VISIBILITY_MASK) != 0) {
13994                /*
13995                 * If this view is becoming visible, invalidate it in case it changed while
13996                 * it was not visible. Marking it drawn ensures that the invalidation will
13997                 * go through.
13998                 */
13999                mPrivateFlags |= PFLAG_DRAWN;
14000                invalidate(true);
14001
14002                needGlobalAttributesUpdate(true);
14003
14004                // a view becoming visible is worth notifying the parent
14005                // about in case nothing has focus.  even if this specific view
14006                // isn't focusable, it may contain something that is, so let
14007                // the root view try to give this focus if nothing else does.
14008                shouldNotifyFocusableAvailable = true;
14009            }
14010        }
14011
14012        if ((changed & ENABLED_MASK) != 0) {
14013            if ((mViewFlags & ENABLED_MASK) == ENABLED) {
14014                // a view becoming enabled should notify the parent as long as the view is also
14015                // visible and the parent wasn't already notified by becoming visible during this
14016                // setFlags invocation.
14017                shouldNotifyFocusableAvailable = true;
14018            } else {
14019                if (isFocused()) clearFocus();
14020            }
14021        }
14022
14023        if (shouldNotifyFocusableAvailable) {
14024            if (mParent != null && canTakeFocus()) {
14025                mParent.focusableViewAvailable(this);
14026            }
14027        }
14028
14029        /* Check if the GONE bit has changed */
14030        if ((changed & GONE) != 0) {
14031            needGlobalAttributesUpdate(false);
14032            requestLayout();
14033
14034            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
14035                if (hasFocus()) {
14036                    clearFocus();
14037                    if (mParent instanceof ViewGroup) {
14038                        ((ViewGroup) mParent).clearFocusedInCluster();
14039                    }
14040                }
14041                clearAccessibilityFocus();
14042                destroyDrawingCache();
14043                if (mParent instanceof View) {
14044                    // GONE views noop invalidation, so invalidate the parent
14045                    ((View) mParent).invalidate(true);
14046                }
14047                // Mark the view drawn to ensure that it gets invalidated properly the next
14048                // time it is visible and gets invalidated
14049                mPrivateFlags |= PFLAG_DRAWN;
14050            }
14051            if (mAttachInfo != null) {
14052                mAttachInfo.mViewVisibilityChanged = true;
14053            }
14054        }
14055
14056        /* Check if the VISIBLE bit has changed */
14057        if ((changed & INVISIBLE) != 0) {
14058            needGlobalAttributesUpdate(false);
14059            /*
14060             * If this view is becoming invisible, set the DRAWN flag so that
14061             * the next invalidate() will not be skipped.
14062             */
14063            mPrivateFlags |= PFLAG_DRAWN;
14064
14065            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
14066                // root view becoming invisible shouldn't clear focus and accessibility focus
14067                if (getRootView() != this) {
14068                    if (hasFocus()) {
14069                        clearFocus();
14070                        if (mParent instanceof ViewGroup) {
14071                            ((ViewGroup) mParent).clearFocusedInCluster();
14072                        }
14073                    }
14074                    clearAccessibilityFocus();
14075                }
14076            }
14077            if (mAttachInfo != null) {
14078                mAttachInfo.mViewVisibilityChanged = true;
14079            }
14080        }
14081
14082        if ((changed & VISIBILITY_MASK) != 0) {
14083            // If the view is invisible, cleanup its display list to free up resources
14084            if (newVisibility != VISIBLE && mAttachInfo != null) {
14085                cleanupDraw();
14086            }
14087
14088            if (mParent instanceof ViewGroup) {
14089                ((ViewGroup) mParent).onChildVisibilityChanged(this,
14090                        (changed & VISIBILITY_MASK), newVisibility);
14091                ((View) mParent).invalidate(true);
14092            } else if (mParent != null) {
14093                mParent.invalidateChild(this, null);
14094            }
14095
14096            if (mAttachInfo != null) {
14097                dispatchVisibilityChanged(this, newVisibility);
14098
14099                // Aggregated visibility changes are dispatched to attached views
14100                // in visible windows where the parent is currently shown/drawn
14101                // or the parent is not a ViewGroup (and therefore assumed to be a ViewRoot),
14102                // discounting clipping or overlapping. This makes it a good place
14103                // to change animation states.
14104                if (mParent != null && getWindowVisibility() == VISIBLE &&
14105                        ((!(mParent instanceof ViewGroup)) || ((ViewGroup) mParent).isShown())) {
14106                    dispatchVisibilityAggregated(newVisibility == VISIBLE);
14107                }
14108                notifySubtreeAccessibilityStateChangedIfNeeded();
14109            }
14110        }
14111
14112        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
14113            destroyDrawingCache();
14114        }
14115
14116        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
14117            destroyDrawingCache();
14118            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
14119            invalidateParentCaches();
14120        }
14121
14122        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
14123            destroyDrawingCache();
14124            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
14125        }
14126
14127        if ((changed & DRAW_MASK) != 0) {
14128            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
14129                if (mBackground != null
14130                        || mDefaultFocusHighlight != null
14131                        || (mForegroundInfo != null && mForegroundInfo.mDrawable != null)) {
14132                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
14133                } else {
14134                    mPrivateFlags |= PFLAG_SKIP_DRAW;
14135                }
14136            } else {
14137                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
14138            }
14139            requestLayout();
14140            invalidate(true);
14141        }
14142
14143        if ((changed & KEEP_SCREEN_ON) != 0) {
14144            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
14145                mParent.recomputeViewAttributes(this);
14146            }
14147        }
14148
14149        if (accessibilityEnabled) {
14150            // If we're an accessibility pane and the visibility changed, we already have sent
14151            // a state change, so we really don't need to report other changes.
14152            if (isAccessibilityPane()) {
14153                changed &= ~VISIBILITY_MASK;
14154            }
14155            if ((changed & FOCUSABLE) != 0 || (changed & VISIBILITY_MASK) != 0
14156                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0
14157                    || (changed & CONTEXT_CLICKABLE) != 0) {
14158                if (oldIncludeForAccessibility != includeForAccessibility()) {
14159                    notifySubtreeAccessibilityStateChangedIfNeeded();
14160                } else {
14161                    notifyViewAccessibilityStateChangedIfNeeded(
14162                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
14163                }
14164            } else if ((changed & ENABLED_MASK) != 0) {
14165                notifyViewAccessibilityStateChangedIfNeeded(
14166                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
14167            }
14168        }
14169    }
14170
14171    /**
14172     * Change the view's z order in the tree, so it's on top of other sibling
14173     * views. This ordering change may affect layout, if the parent container
14174     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
14175     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
14176     * method should be followed by calls to {@link #requestLayout()} and
14177     * {@link View#invalidate()} on the view's parent to force the parent to redraw
14178     * with the new child ordering.
14179     *
14180     * @see ViewGroup#bringChildToFront(View)
14181     */
14182    public void bringToFront() {
14183        if (mParent != null) {
14184            mParent.bringChildToFront(this);
14185        }
14186    }
14187
14188    /**
14189     * This is called in response to an internal scroll in this view (i.e., the
14190     * view scrolled its own contents). This is typically as a result of
14191     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
14192     * called.
14193     *
14194     * @param l Current horizontal scroll origin.
14195     * @param t Current vertical scroll origin.
14196     * @param oldl Previous horizontal scroll origin.
14197     * @param oldt Previous vertical scroll origin.
14198     */
14199    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
14200        notifySubtreeAccessibilityStateChangedIfNeeded();
14201
14202        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
14203            postSendViewScrolledAccessibilityEventCallback(l - oldl, t - oldt);
14204        }
14205
14206        mBackgroundSizeChanged = true;
14207        mDefaultFocusHighlightSizeChanged = true;
14208        if (mForegroundInfo != null) {
14209            mForegroundInfo.mBoundsChanged = true;
14210        }
14211
14212        final AttachInfo ai = mAttachInfo;
14213        if (ai != null) {
14214            ai.mViewScrollChanged = true;
14215        }
14216
14217        if (mListenerInfo != null && mListenerInfo.mOnScrollChangeListener != null) {
14218            mListenerInfo.mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt);
14219        }
14220    }
14221
14222    /**
14223     * Interface definition for a callback to be invoked when the scroll
14224     * X or Y positions of a view change.
14225     * <p>
14226     * <b>Note:</b> Some views handle scrolling independently from View and may
14227     * have their own separate listeners for scroll-type events. For example,
14228     * {@link android.widget.ListView ListView} allows clients to register an
14229     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
14230     * to listen for changes in list scroll position.
14231     *
14232     * @see #setOnScrollChangeListener(View.OnScrollChangeListener)
14233     */
14234    public interface OnScrollChangeListener {
14235        /**
14236         * Called when the scroll position of a view changes.
14237         *
14238         * @param v The view whose scroll position has changed.
14239         * @param scrollX Current horizontal scroll origin.
14240         * @param scrollY Current vertical scroll origin.
14241         * @param oldScrollX Previous horizontal scroll origin.
14242         * @param oldScrollY Previous vertical scroll origin.
14243         */
14244        void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY);
14245    }
14246
14247    /**
14248     * Interface definition for a callback to be invoked when the layout bounds of a view
14249     * changes due to layout processing.
14250     */
14251    public interface OnLayoutChangeListener {
14252        /**
14253         * Called when the layout bounds of a view changes due to layout processing.
14254         *
14255         * @param v The view whose bounds have changed.
14256         * @param left The new value of the view's left property.
14257         * @param top The new value of the view's top property.
14258         * @param right The new value of the view's right property.
14259         * @param bottom The new value of the view's bottom property.
14260         * @param oldLeft The previous value of the view's left property.
14261         * @param oldTop The previous value of the view's top property.
14262         * @param oldRight The previous value of the view's right property.
14263         * @param oldBottom The previous value of the view's bottom property.
14264         */
14265        void onLayoutChange(View v, int left, int top, int right, int bottom,
14266            int oldLeft, int oldTop, int oldRight, int oldBottom);
14267    }
14268
14269    /**
14270     * This is called during layout when the size of this view has changed. If
14271     * you were just added to the view hierarchy, you're called with the old
14272     * values of 0.
14273     *
14274     * @param w Current width of this view.
14275     * @param h Current height of this view.
14276     * @param oldw Old width of this view.
14277     * @param oldh Old height of this view.
14278     */
14279    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
14280    }
14281
14282    /**
14283     * Called by draw to draw the child views. This may be overridden
14284     * by derived classes to gain control just before its children are drawn
14285     * (but after its own view has been drawn).
14286     * @param canvas the canvas on which to draw the view
14287     */
14288    protected void dispatchDraw(Canvas canvas) {
14289
14290    }
14291
14292    /**
14293     * Gets the parent of this view. Note that the parent is a
14294     * ViewParent and not necessarily a View.
14295     *
14296     * @return Parent of this view.
14297     */
14298    public final ViewParent getParent() {
14299        return mParent;
14300    }
14301
14302    /**
14303     * Set the horizontal scrolled position of your view. This will cause a call to
14304     * {@link #onScrollChanged(int, int, int, int)} and the view will be
14305     * invalidated.
14306     * @param value the x position to scroll to
14307     */
14308    public void setScrollX(int value) {
14309        scrollTo(value, mScrollY);
14310    }
14311
14312    /**
14313     * Set the vertical scrolled position of your view. This will cause a call to
14314     * {@link #onScrollChanged(int, int, int, int)} and the view will be
14315     * invalidated.
14316     * @param value the y position to scroll to
14317     */
14318    public void setScrollY(int value) {
14319        scrollTo(mScrollX, value);
14320    }
14321
14322    /**
14323     * Return the scrolled left position of this view. This is the left edge of
14324     * the displayed part of your view. You do not need to draw any pixels
14325     * farther left, since those are outside of the frame of your view on
14326     * screen.
14327     *
14328     * @return The left edge of the displayed part of your view, in pixels.
14329     */
14330    public final int getScrollX() {
14331        return mScrollX;
14332    }
14333
14334    /**
14335     * Return the scrolled top position of this view. This is the top edge of
14336     * the displayed part of your view. You do not need to draw any pixels above
14337     * it, since those are outside of the frame of your view on screen.
14338     *
14339     * @return The top edge of the displayed part of your view, in pixels.
14340     */
14341    public final int getScrollY() {
14342        return mScrollY;
14343    }
14344
14345    /**
14346     * Return the width of the your view.
14347     *
14348     * @return The width of your view, in pixels.
14349     */
14350    @ViewDebug.ExportedProperty(category = "layout")
14351    public final int getWidth() {
14352        return mRight - mLeft;
14353    }
14354
14355    /**
14356     * Return the height of your view.
14357     *
14358     * @return The height of your view, in pixels.
14359     */
14360    @ViewDebug.ExportedProperty(category = "layout")
14361    public final int getHeight() {
14362        return mBottom - mTop;
14363    }
14364
14365    /**
14366     * Return the visible drawing bounds of your view. Fills in the output
14367     * rectangle with the values from getScrollX(), getScrollY(),
14368     * getWidth(), and getHeight(). These bounds do not account for any
14369     * transformation properties currently set on the view, such as
14370     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
14371     *
14372     * @param outRect The (scrolled) drawing bounds of the view.
14373     */
14374    public void getDrawingRect(Rect outRect) {
14375        outRect.left = mScrollX;
14376        outRect.top = mScrollY;
14377        outRect.right = mScrollX + (mRight - mLeft);
14378        outRect.bottom = mScrollY + (mBottom - mTop);
14379    }
14380
14381    /**
14382     * Like {@link #getMeasuredWidthAndState()}, but only returns the
14383     * raw width component (that is the result is masked by
14384     * {@link #MEASURED_SIZE_MASK}).
14385     *
14386     * @return The raw measured width of this view.
14387     */
14388    public final int getMeasuredWidth() {
14389        return mMeasuredWidth & MEASURED_SIZE_MASK;
14390    }
14391
14392    /**
14393     * Return the full width measurement information for this view as computed
14394     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
14395     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
14396     * This should be used during measurement and layout calculations only. Use
14397     * {@link #getWidth()} to see how wide a view is after layout.
14398     *
14399     * @return The measured width of this view as a bit mask.
14400     */
14401    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
14402            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
14403                    name = "MEASURED_STATE_TOO_SMALL"),
14404    })
14405    public final int getMeasuredWidthAndState() {
14406        return mMeasuredWidth;
14407    }
14408
14409    /**
14410     * Like {@link #getMeasuredHeightAndState()}, but only returns the
14411     * raw height component (that is the result is masked by
14412     * {@link #MEASURED_SIZE_MASK}).
14413     *
14414     * @return The raw measured height of this view.
14415     */
14416    public final int getMeasuredHeight() {
14417        return mMeasuredHeight & MEASURED_SIZE_MASK;
14418    }
14419
14420    /**
14421     * Return the full height measurement information for this view as computed
14422     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
14423     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
14424     * This should be used during measurement and layout calculations only. Use
14425     * {@link #getHeight()} to see how wide a view is after layout.
14426     *
14427     * @return The measured height of this view as a bit mask.
14428     */
14429    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
14430            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
14431                    name = "MEASURED_STATE_TOO_SMALL"),
14432    })
14433    public final int getMeasuredHeightAndState() {
14434        return mMeasuredHeight;
14435    }
14436
14437    /**
14438     * Return only the state bits of {@link #getMeasuredWidthAndState()}
14439     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
14440     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
14441     * and the height component is at the shifted bits
14442     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
14443     */
14444    public final int getMeasuredState() {
14445        return (mMeasuredWidth&MEASURED_STATE_MASK)
14446                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
14447                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
14448    }
14449
14450    /**
14451     * The transform matrix of this view, which is calculated based on the current
14452     * rotation, scale, and pivot properties.
14453     *
14454     * @see #getRotation()
14455     * @see #getScaleX()
14456     * @see #getScaleY()
14457     * @see #getPivotX()
14458     * @see #getPivotY()
14459     * @return The current transform matrix for the view
14460     */
14461    public Matrix getMatrix() {
14462        ensureTransformationInfo();
14463        final Matrix matrix = mTransformationInfo.mMatrix;
14464        mRenderNode.getMatrix(matrix);
14465        return matrix;
14466    }
14467
14468    /**
14469     * Returns true if the transform matrix is the identity matrix.
14470     * Recomputes the matrix if necessary.
14471     *
14472     * @return True if the transform matrix is the identity matrix, false otherwise.
14473     */
14474    final boolean hasIdentityMatrix() {
14475        return mRenderNode.hasIdentityMatrix();
14476    }
14477
14478    void ensureTransformationInfo() {
14479        if (mTransformationInfo == null) {
14480            mTransformationInfo = new TransformationInfo();
14481        }
14482    }
14483
14484    /**
14485     * Utility method to retrieve the inverse of the current mMatrix property.
14486     * We cache the matrix to avoid recalculating it when transform properties
14487     * have not changed.
14488     *
14489     * @return The inverse of the current matrix of this view.
14490     * @hide
14491     */
14492    public final Matrix getInverseMatrix() {
14493        ensureTransformationInfo();
14494        if (mTransformationInfo.mInverseMatrix == null) {
14495            mTransformationInfo.mInverseMatrix = new Matrix();
14496        }
14497        final Matrix matrix = mTransformationInfo.mInverseMatrix;
14498        mRenderNode.getInverseMatrix(matrix);
14499        return matrix;
14500    }
14501
14502    /**
14503     * Gets the distance along the Z axis from the camera to this view.
14504     *
14505     * @see #setCameraDistance(float)
14506     *
14507     * @return The distance along the Z axis.
14508     */
14509    public float getCameraDistance() {
14510        final float dpi = mResources.getDisplayMetrics().densityDpi;
14511        return -(mRenderNode.getCameraDistance() * dpi);
14512    }
14513
14514    /**
14515     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
14516     * views are drawn) from the camera to this view. The camera's distance
14517     * affects 3D transformations, for instance rotations around the X and Y
14518     * axis. If the rotationX or rotationY properties are changed and this view is
14519     * large (more than half the size of the screen), it is recommended to always
14520     * use a camera distance that's greater than the height (X axis rotation) or
14521     * the width (Y axis rotation) of this view.</p>
14522     *
14523     * <p>The distance of the camera from the view plane can have an affect on the
14524     * perspective distortion of the view when it is rotated around the x or y axis.
14525     * For example, a large distance will result in a large viewing angle, and there
14526     * will not be much perspective distortion of the view as it rotates. A short
14527     * distance may cause much more perspective distortion upon rotation, and can
14528     * also result in some drawing artifacts if the rotated view ends up partially
14529     * behind the camera (which is why the recommendation is to use a distance at
14530     * least as far as the size of the view, if the view is to be rotated.)</p>
14531     *
14532     * <p>The distance is expressed in "depth pixels." The default distance depends
14533     * on the screen density. For instance, on a medium density display, the
14534     * default distance is 1280. On a high density display, the default distance
14535     * is 1920.</p>
14536     *
14537     * <p>If you want to specify a distance that leads to visually consistent
14538     * results across various densities, use the following formula:</p>
14539     * <pre>
14540     * float scale = context.getResources().getDisplayMetrics().density;
14541     * view.setCameraDistance(distance * scale);
14542     * </pre>
14543     *
14544     * <p>The density scale factor of a high density display is 1.5,
14545     * and 1920 = 1280 * 1.5.</p>
14546     *
14547     * @param distance The distance in "depth pixels", if negative the opposite
14548     *        value is used
14549     *
14550     * @see #setRotationX(float)
14551     * @see #setRotationY(float)
14552     */
14553    public void setCameraDistance(float distance) {
14554        final float dpi = mResources.getDisplayMetrics().densityDpi;
14555
14556        invalidateViewProperty(true, false);
14557        mRenderNode.setCameraDistance(-Math.abs(distance) / dpi);
14558        invalidateViewProperty(false, false);
14559
14560        invalidateParentIfNeededAndWasQuickRejected();
14561    }
14562
14563    /**
14564     * The degrees that the view is rotated around the pivot point.
14565     *
14566     * @see #setRotation(float)
14567     * @see #getPivotX()
14568     * @see #getPivotY()
14569     *
14570     * @return The degrees of rotation.
14571     */
14572    @ViewDebug.ExportedProperty(category = "drawing")
14573    public float getRotation() {
14574        return mRenderNode.getRotation();
14575    }
14576
14577    /**
14578     * Sets the degrees that the view is rotated around the pivot point. Increasing values
14579     * result in clockwise rotation.
14580     *
14581     * @param rotation The degrees of rotation.
14582     *
14583     * @see #getRotation()
14584     * @see #getPivotX()
14585     * @see #getPivotY()
14586     * @see #setRotationX(float)
14587     * @see #setRotationY(float)
14588     *
14589     * @attr ref android.R.styleable#View_rotation
14590     */
14591    public void setRotation(float rotation) {
14592        if (rotation != getRotation()) {
14593            // Double-invalidation is necessary to capture view's old and new areas
14594            invalidateViewProperty(true, false);
14595            mRenderNode.setRotation(rotation);
14596            invalidateViewProperty(false, true);
14597
14598            invalidateParentIfNeededAndWasQuickRejected();
14599            notifySubtreeAccessibilityStateChangedIfNeeded();
14600        }
14601    }
14602
14603    /**
14604     * The degrees that the view is rotated around the vertical axis through the pivot point.
14605     *
14606     * @see #getPivotX()
14607     * @see #getPivotY()
14608     * @see #setRotationY(float)
14609     *
14610     * @return The degrees of Y rotation.
14611     */
14612    @ViewDebug.ExportedProperty(category = "drawing")
14613    public float getRotationY() {
14614        return mRenderNode.getRotationY();
14615    }
14616
14617    /**
14618     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
14619     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
14620     * down the y axis.
14621     *
14622     * When rotating large views, it is recommended to adjust the camera distance
14623     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
14624     *
14625     * @param rotationY The degrees of Y rotation.
14626     *
14627     * @see #getRotationY()
14628     * @see #getPivotX()
14629     * @see #getPivotY()
14630     * @see #setRotation(float)
14631     * @see #setRotationX(float)
14632     * @see #setCameraDistance(float)
14633     *
14634     * @attr ref android.R.styleable#View_rotationY
14635     */
14636    public void setRotationY(float rotationY) {
14637        if (rotationY != getRotationY()) {
14638            invalidateViewProperty(true, false);
14639            mRenderNode.setRotationY(rotationY);
14640            invalidateViewProperty(false, true);
14641
14642            invalidateParentIfNeededAndWasQuickRejected();
14643            notifySubtreeAccessibilityStateChangedIfNeeded();
14644        }
14645    }
14646
14647    /**
14648     * The degrees that the view is rotated around the horizontal axis through the pivot point.
14649     *
14650     * @see #getPivotX()
14651     * @see #getPivotY()
14652     * @see #setRotationX(float)
14653     *
14654     * @return The degrees of X rotation.
14655     */
14656    @ViewDebug.ExportedProperty(category = "drawing")
14657    public float getRotationX() {
14658        return mRenderNode.getRotationX();
14659    }
14660
14661    /**
14662     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
14663     * Increasing values result in clockwise rotation from the viewpoint of looking down the
14664     * x axis.
14665     *
14666     * When rotating large views, it is recommended to adjust the camera distance
14667     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
14668     *
14669     * @param rotationX The degrees of X rotation.
14670     *
14671     * @see #getRotationX()
14672     * @see #getPivotX()
14673     * @see #getPivotY()
14674     * @see #setRotation(float)
14675     * @see #setRotationY(float)
14676     * @see #setCameraDistance(float)
14677     *
14678     * @attr ref android.R.styleable#View_rotationX
14679     */
14680    public void setRotationX(float rotationX) {
14681        if (rotationX != getRotationX()) {
14682            invalidateViewProperty(true, false);
14683            mRenderNode.setRotationX(rotationX);
14684            invalidateViewProperty(false, true);
14685
14686            invalidateParentIfNeededAndWasQuickRejected();
14687            notifySubtreeAccessibilityStateChangedIfNeeded();
14688        }
14689    }
14690
14691    /**
14692     * The amount that the view is scaled in x around the pivot point, as a proportion of
14693     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
14694     *
14695     * <p>By default, this is 1.0f.
14696     *
14697     * @see #getPivotX()
14698     * @see #getPivotY()
14699     * @return The scaling factor.
14700     */
14701    @ViewDebug.ExportedProperty(category = "drawing")
14702    public float getScaleX() {
14703        return mRenderNode.getScaleX();
14704    }
14705
14706    /**
14707     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
14708     * the view's unscaled width. A value of 1 means that no scaling is applied.
14709     *
14710     * @param scaleX The scaling factor.
14711     * @see #getPivotX()
14712     * @see #getPivotY()
14713     *
14714     * @attr ref android.R.styleable#View_scaleX
14715     */
14716    public void setScaleX(float scaleX) {
14717        if (scaleX != getScaleX()) {
14718            scaleX = sanitizeFloatPropertyValue(scaleX, "scaleX");
14719            invalidateViewProperty(true, false);
14720            mRenderNode.setScaleX(scaleX);
14721            invalidateViewProperty(false, true);
14722
14723            invalidateParentIfNeededAndWasQuickRejected();
14724            notifySubtreeAccessibilityStateChangedIfNeeded();
14725        }
14726    }
14727
14728    /**
14729     * The amount that the view is scaled in y around the pivot point, as a proportion of
14730     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
14731     *
14732     * <p>By default, this is 1.0f.
14733     *
14734     * @see #getPivotX()
14735     * @see #getPivotY()
14736     * @return The scaling factor.
14737     */
14738    @ViewDebug.ExportedProperty(category = "drawing")
14739    public float getScaleY() {
14740        return mRenderNode.getScaleY();
14741    }
14742
14743    /**
14744     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
14745     * the view's unscaled width. A value of 1 means that no scaling is applied.
14746     *
14747     * @param scaleY The scaling factor.
14748     * @see #getPivotX()
14749     * @see #getPivotY()
14750     *
14751     * @attr ref android.R.styleable#View_scaleY
14752     */
14753    public void setScaleY(float scaleY) {
14754        if (scaleY != getScaleY()) {
14755            scaleY = sanitizeFloatPropertyValue(scaleY, "scaleY");
14756            invalidateViewProperty(true, false);
14757            mRenderNode.setScaleY(scaleY);
14758            invalidateViewProperty(false, true);
14759
14760            invalidateParentIfNeededAndWasQuickRejected();
14761            notifySubtreeAccessibilityStateChangedIfNeeded();
14762        }
14763    }
14764
14765    /**
14766     * The x location of the point around which the view is {@link #setRotation(float) rotated}
14767     * and {@link #setScaleX(float) scaled}.
14768     *
14769     * @see #getRotation()
14770     * @see #getScaleX()
14771     * @see #getScaleY()
14772     * @see #getPivotY()
14773     * @return The x location of the pivot point.
14774     *
14775     * @attr ref android.R.styleable#View_transformPivotX
14776     */
14777    @ViewDebug.ExportedProperty(category = "drawing")
14778    public float getPivotX() {
14779        return mRenderNode.getPivotX();
14780    }
14781
14782    /**
14783     * Sets the x location of the point around which the view is
14784     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
14785     * By default, the pivot point is centered on the object.
14786     * Setting this property disables this behavior and causes the view to use only the
14787     * explicitly set pivotX and pivotY values.
14788     *
14789     * @param pivotX The x location of the pivot point.
14790     * @see #getRotation()
14791     * @see #getScaleX()
14792     * @see #getScaleY()
14793     * @see #getPivotY()
14794     *
14795     * @attr ref android.R.styleable#View_transformPivotX
14796     */
14797    public void setPivotX(float pivotX) {
14798        if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) {
14799            invalidateViewProperty(true, false);
14800            mRenderNode.setPivotX(pivotX);
14801            invalidateViewProperty(false, true);
14802
14803            invalidateParentIfNeededAndWasQuickRejected();
14804        }
14805    }
14806
14807    /**
14808     * The y location of the point around which the view is {@link #setRotation(float) rotated}
14809     * and {@link #setScaleY(float) scaled}.
14810     *
14811     * @see #getRotation()
14812     * @see #getScaleX()
14813     * @see #getScaleY()
14814     * @see #getPivotY()
14815     * @return The y location of the pivot point.
14816     *
14817     * @attr ref android.R.styleable#View_transformPivotY
14818     */
14819    @ViewDebug.ExportedProperty(category = "drawing")
14820    public float getPivotY() {
14821        return mRenderNode.getPivotY();
14822    }
14823
14824    /**
14825     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
14826     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
14827     * Setting this property disables this behavior and causes the view to use only the
14828     * explicitly set pivotX and pivotY values.
14829     *
14830     * @param pivotY The y location of the pivot point.
14831     * @see #getRotation()
14832     * @see #getScaleX()
14833     * @see #getScaleY()
14834     * @see #getPivotY()
14835     *
14836     * @attr ref android.R.styleable#View_transformPivotY
14837     */
14838    public void setPivotY(float pivotY) {
14839        if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) {
14840            invalidateViewProperty(true, false);
14841            mRenderNode.setPivotY(pivotY);
14842            invalidateViewProperty(false, true);
14843
14844            invalidateParentIfNeededAndWasQuickRejected();
14845        }
14846    }
14847
14848    /**
14849     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
14850     * completely transparent and 1 means the view is completely opaque.
14851     *
14852     * <p>By default this is 1.0f.
14853     * @return The opacity of the view.
14854     */
14855    @ViewDebug.ExportedProperty(category = "drawing")
14856    public float getAlpha() {
14857        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
14858    }
14859
14860    /**
14861     * Sets the behavior for overlapping rendering for this view (see {@link
14862     * #hasOverlappingRendering()} for more details on this behavior). Calling this method
14863     * is an alternative to overriding {@link #hasOverlappingRendering()} in a subclass,
14864     * providing the value which is then used internally. That is, when {@link
14865     * #forceHasOverlappingRendering(boolean)} is called, the value of {@link
14866     * #hasOverlappingRendering()} is ignored and the value passed into this method is used
14867     * instead.
14868     *
14869     * @param hasOverlappingRendering The value for overlapping rendering to be used internally
14870     * instead of that returned by {@link #hasOverlappingRendering()}.
14871     *
14872     * @attr ref android.R.styleable#View_forceHasOverlappingRendering
14873     */
14874    public void forceHasOverlappingRendering(boolean hasOverlappingRendering) {
14875        mPrivateFlags3 |= PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED;
14876        if (hasOverlappingRendering) {
14877            mPrivateFlags3 |= PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE;
14878        } else {
14879            mPrivateFlags3 &= ~PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE;
14880        }
14881    }
14882
14883    /**
14884     * Returns the value for overlapping rendering that is used internally. This is either
14885     * the value passed into {@link #forceHasOverlappingRendering(boolean)}, if called, or
14886     * the return value of {@link #hasOverlappingRendering()}, otherwise.
14887     *
14888     * @return The value for overlapping rendering being used internally.
14889     */
14890    public final boolean getHasOverlappingRendering() {
14891        return (mPrivateFlags3 & PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED) != 0 ?
14892                (mPrivateFlags3 & PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE) != 0 :
14893                hasOverlappingRendering();
14894    }
14895
14896    /**
14897     * Returns whether this View has content which overlaps.
14898     *
14899     * <p>This function, intended to be overridden by specific View types, is an optimization when
14900     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
14901     * an offscreen buffer and then composited into place, which can be expensive. If the view has
14902     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
14903     * directly. An example of overlapping rendering is a TextView with a background image, such as
14904     * a Button. An example of non-overlapping rendering is a TextView with no background, or an
14905     * ImageView with only the foreground image. The default implementation returns true; subclasses
14906     * should override if they have cases which can be optimized.</p>
14907     *
14908     * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas}
14909     * necessitates that a View return true if it uses the methods internally without passing the
14910     * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p>
14911     *
14912     * <p><strong>Note:</strong> The return value of this method is ignored if {@link
14913     * #forceHasOverlappingRendering(boolean)} has been called on this view.</p>
14914     *
14915     * @return true if the content in this view might overlap, false otherwise.
14916     */
14917    @ViewDebug.ExportedProperty(category = "drawing")
14918    public boolean hasOverlappingRendering() {
14919        return true;
14920    }
14921
14922    /**
14923     * Sets the opacity of the view to a value from 0 to 1, where 0 means the view is
14924     * completely transparent and 1 means the view is completely opaque.
14925     *
14926     * <p class="note"><strong>Note:</strong> setting alpha to a translucent value (0 < alpha < 1)
14927     * can have significant performance implications, especially for large views. It is best to use
14928     * the alpha property sparingly and transiently, as in the case of fading animations.</p>
14929     *
14930     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
14931     * strongly recommended for performance reasons to either override
14932     * {@link #hasOverlappingRendering()} to return <code>false</code> if appropriate, or setting a
14933     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view for the duration
14934     * of the animation. On versions {@link android.os.Build.VERSION_CODES#M} and below,
14935     * the default path for rendering an unlayered View with alpha could add multiple milliseconds
14936     * of rendering cost, even for simple or small views. Starting with
14937     * {@link android.os.Build.VERSION_CODES#M}, {@link #LAYER_TYPE_HARDWARE} is automatically
14938     * applied to the view at the rendering level.</p>
14939     *
14940     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
14941     * responsible for applying the opacity itself.</p>
14942     *
14943     * <p>On versions {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} and below, note that if
14944     * the view is backed by a {@link #setLayerType(int, android.graphics.Paint) layer} and is
14945     * associated with a {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an
14946     * alpha value less than 1.0 will supersede the alpha of the layer paint.</p>
14947     *
14948     * <p>Starting with {@link android.os.Build.VERSION_CODES#M}, setting a translucent alpha
14949     * value will clip a View to its bounds, unless the View returns <code>false</code> from
14950     * {@link #hasOverlappingRendering}.</p>
14951     *
14952     * @param alpha The opacity of the view.
14953     *
14954     * @see #hasOverlappingRendering()
14955     * @see #setLayerType(int, android.graphics.Paint)
14956     *
14957     * @attr ref android.R.styleable#View_alpha
14958     */
14959    public void setAlpha(@FloatRange(from=0.0, to=1.0) float alpha) {
14960        ensureTransformationInfo();
14961        if (mTransformationInfo.mAlpha != alpha) {
14962            // Report visibility changes, which can affect children, to accessibility
14963            if ((alpha == 0) ^ (mTransformationInfo.mAlpha == 0)) {
14964                notifySubtreeAccessibilityStateChangedIfNeeded();
14965            }
14966            mTransformationInfo.mAlpha = alpha;
14967            if (onSetAlpha((int) (alpha * 255))) {
14968                mPrivateFlags |= PFLAG_ALPHA_SET;
14969                // subclass is handling alpha - don't optimize rendering cache invalidation
14970                invalidateParentCaches();
14971                invalidate(true);
14972            } else {
14973                mPrivateFlags &= ~PFLAG_ALPHA_SET;
14974                invalidateViewProperty(true, false);
14975                mRenderNode.setAlpha(getFinalAlpha());
14976            }
14977        }
14978    }
14979
14980    /**
14981     * Faster version of setAlpha() which performs the same steps except there are
14982     * no calls to invalidate(). The caller of this function should perform proper invalidation
14983     * on the parent and this object. The return value indicates whether the subclass handles
14984     * alpha (the return value for onSetAlpha()).
14985     *
14986     * @param alpha The new value for the alpha property
14987     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
14988     *         the new value for the alpha property is different from the old value
14989     */
14990    boolean setAlphaNoInvalidation(float alpha) {
14991        ensureTransformationInfo();
14992        if (mTransformationInfo.mAlpha != alpha) {
14993            mTransformationInfo.mAlpha = alpha;
14994            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
14995            if (subclassHandlesAlpha) {
14996                mPrivateFlags |= PFLAG_ALPHA_SET;
14997                return true;
14998            } else {
14999                mPrivateFlags &= ~PFLAG_ALPHA_SET;
15000                mRenderNode.setAlpha(getFinalAlpha());
15001            }
15002        }
15003        return false;
15004    }
15005
15006    /**
15007     * This property is hidden and intended only for use by the Fade transition, which
15008     * animates it to produce a visual translucency that does not side-effect (or get
15009     * affected by) the real alpha property. This value is composited with the other
15010     * alpha value (and the AlphaAnimation value, when that is present) to produce
15011     * a final visual translucency result, which is what is passed into the DisplayList.
15012     *
15013     * @hide
15014     */
15015    public void setTransitionAlpha(float alpha) {
15016        ensureTransformationInfo();
15017        if (mTransformationInfo.mTransitionAlpha != alpha) {
15018            mTransformationInfo.mTransitionAlpha = alpha;
15019            mPrivateFlags &= ~PFLAG_ALPHA_SET;
15020            invalidateViewProperty(true, false);
15021            mRenderNode.setAlpha(getFinalAlpha());
15022        }
15023    }
15024
15025    /**
15026     * Calculates the visual alpha of this view, which is a combination of the actual
15027     * alpha value and the transitionAlpha value (if set).
15028     */
15029    private float getFinalAlpha() {
15030        if (mTransformationInfo != null) {
15031            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
15032        }
15033        return 1;
15034    }
15035
15036    /**
15037     * This property is hidden and intended only for use by the Fade transition, which
15038     * animates it to produce a visual translucency that does not side-effect (or get
15039     * affected by) the real alpha property. This value is composited with the other
15040     * alpha value (and the AlphaAnimation value, when that is present) to produce
15041     * a final visual translucency result, which is what is passed into the DisplayList.
15042     *
15043     * @hide
15044     */
15045    @ViewDebug.ExportedProperty(category = "drawing")
15046    public float getTransitionAlpha() {
15047        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
15048    }
15049
15050    /**
15051     * Top position of this view relative to its parent.
15052     *
15053     * @return The top of this view, in pixels.
15054     */
15055    @ViewDebug.CapturedViewProperty
15056    public final int getTop() {
15057        return mTop;
15058    }
15059
15060    /**
15061     * Sets the top position of this view relative to its parent. This method is meant to be called
15062     * by the layout system and should not generally be called otherwise, because the property
15063     * may be changed at any time by the layout.
15064     *
15065     * @param top The top of this view, in pixels.
15066     */
15067    public final void setTop(int top) {
15068        if (top != mTop) {
15069            final boolean matrixIsIdentity = hasIdentityMatrix();
15070            if (matrixIsIdentity) {
15071                if (mAttachInfo != null) {
15072                    int minTop;
15073                    int yLoc;
15074                    if (top < mTop) {
15075                        minTop = top;
15076                        yLoc = top - mTop;
15077                    } else {
15078                        minTop = mTop;
15079                        yLoc = 0;
15080                    }
15081                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
15082                }
15083            } else {
15084                // Double-invalidation is necessary to capture view's old and new areas
15085                invalidate(true);
15086            }
15087
15088            int width = mRight - mLeft;
15089            int oldHeight = mBottom - mTop;
15090
15091            mTop = top;
15092            mRenderNode.setTop(mTop);
15093
15094            sizeChange(width, mBottom - mTop, width, oldHeight);
15095
15096            if (!matrixIsIdentity) {
15097                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
15098                invalidate(true);
15099            }
15100            mBackgroundSizeChanged = true;
15101            mDefaultFocusHighlightSizeChanged = true;
15102            if (mForegroundInfo != null) {
15103                mForegroundInfo.mBoundsChanged = true;
15104            }
15105            invalidateParentIfNeeded();
15106            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
15107                // View was rejected last time it was drawn by its parent; this may have changed
15108                invalidateParentIfNeeded();
15109            }
15110        }
15111    }
15112
15113    /**
15114     * Bottom position of this view relative to its parent.
15115     *
15116     * @return The bottom of this view, in pixels.
15117     */
15118    @ViewDebug.CapturedViewProperty
15119    public final int getBottom() {
15120        return mBottom;
15121    }
15122
15123    /**
15124     * True if this view has changed since the last time being drawn.
15125     *
15126     * @return The dirty state of this view.
15127     */
15128    public boolean isDirty() {
15129        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
15130    }
15131
15132    /**
15133     * Sets the bottom position of this view relative to its parent. This method is meant to be
15134     * called by the layout system and should not generally be called otherwise, because the
15135     * property may be changed at any time by the layout.
15136     *
15137     * @param bottom The bottom of this view, in pixels.
15138     */
15139    public final void setBottom(int bottom) {
15140        if (bottom != mBottom) {
15141            final boolean matrixIsIdentity = hasIdentityMatrix();
15142            if (matrixIsIdentity) {
15143                if (mAttachInfo != null) {
15144                    int maxBottom;
15145                    if (bottom < mBottom) {
15146                        maxBottom = mBottom;
15147                    } else {
15148                        maxBottom = bottom;
15149                    }
15150                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
15151                }
15152            } else {
15153                // Double-invalidation is necessary to capture view's old and new areas
15154                invalidate(true);
15155            }
15156
15157            int width = mRight - mLeft;
15158            int oldHeight = mBottom - mTop;
15159
15160            mBottom = bottom;
15161            mRenderNode.setBottom(mBottom);
15162
15163            sizeChange(width, mBottom - mTop, width, oldHeight);
15164
15165            if (!matrixIsIdentity) {
15166                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
15167                invalidate(true);
15168            }
15169            mBackgroundSizeChanged = true;
15170            mDefaultFocusHighlightSizeChanged = true;
15171            if (mForegroundInfo != null) {
15172                mForegroundInfo.mBoundsChanged = true;
15173            }
15174            invalidateParentIfNeeded();
15175            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
15176                // View was rejected last time it was drawn by its parent; this may have changed
15177                invalidateParentIfNeeded();
15178            }
15179        }
15180    }
15181
15182    /**
15183     * Left position of this view relative to its parent.
15184     *
15185     * @return The left edge of this view, in pixels.
15186     */
15187    @ViewDebug.CapturedViewProperty
15188    public final int getLeft() {
15189        return mLeft;
15190    }
15191
15192    /**
15193     * Sets the left position of this view relative to its parent. This method is meant to be called
15194     * by the layout system and should not generally be called otherwise, because the property
15195     * may be changed at any time by the layout.
15196     *
15197     * @param left The left of this view, in pixels.
15198     */
15199    public final void setLeft(int left) {
15200        if (left != mLeft) {
15201            final boolean matrixIsIdentity = hasIdentityMatrix();
15202            if (matrixIsIdentity) {
15203                if (mAttachInfo != null) {
15204                    int minLeft;
15205                    int xLoc;
15206                    if (left < mLeft) {
15207                        minLeft = left;
15208                        xLoc = left - mLeft;
15209                    } else {
15210                        minLeft = mLeft;
15211                        xLoc = 0;
15212                    }
15213                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
15214                }
15215            } else {
15216                // Double-invalidation is necessary to capture view's old and new areas
15217                invalidate(true);
15218            }
15219
15220            int oldWidth = mRight - mLeft;
15221            int height = mBottom - mTop;
15222
15223            mLeft = left;
15224            mRenderNode.setLeft(left);
15225
15226            sizeChange(mRight - mLeft, height, oldWidth, height);
15227
15228            if (!matrixIsIdentity) {
15229                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
15230                invalidate(true);
15231            }
15232            mBackgroundSizeChanged = true;
15233            mDefaultFocusHighlightSizeChanged = true;
15234            if (mForegroundInfo != null) {
15235                mForegroundInfo.mBoundsChanged = true;
15236            }
15237            invalidateParentIfNeeded();
15238            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
15239                // View was rejected last time it was drawn by its parent; this may have changed
15240                invalidateParentIfNeeded();
15241            }
15242        }
15243    }
15244
15245    /**
15246     * Right position of this view relative to its parent.
15247     *
15248     * @return The right edge of this view, in pixels.
15249     */
15250    @ViewDebug.CapturedViewProperty
15251    public final int getRight() {
15252        return mRight;
15253    }
15254
15255    /**
15256     * Sets the right position of this view relative to its parent. This method is meant to be called
15257     * by the layout system and should not generally be called otherwise, because the property
15258     * may be changed at any time by the layout.
15259     *
15260     * @param right The right of this view, in pixels.
15261     */
15262    public final void setRight(int right) {
15263        if (right != mRight) {
15264            final boolean matrixIsIdentity = hasIdentityMatrix();
15265            if (matrixIsIdentity) {
15266                if (mAttachInfo != null) {
15267                    int maxRight;
15268                    if (right < mRight) {
15269                        maxRight = mRight;
15270                    } else {
15271                        maxRight = right;
15272                    }
15273                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
15274                }
15275            } else {
15276                // Double-invalidation is necessary to capture view's old and new areas
15277                invalidate(true);
15278            }
15279
15280            int oldWidth = mRight - mLeft;
15281            int height = mBottom - mTop;
15282
15283            mRight = right;
15284            mRenderNode.setRight(mRight);
15285
15286            sizeChange(mRight - mLeft, height, oldWidth, height);
15287
15288            if (!matrixIsIdentity) {
15289                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
15290                invalidate(true);
15291            }
15292            mBackgroundSizeChanged = true;
15293            mDefaultFocusHighlightSizeChanged = true;
15294            if (mForegroundInfo != null) {
15295                mForegroundInfo.mBoundsChanged = true;
15296            }
15297            invalidateParentIfNeeded();
15298            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
15299                // View was rejected last time it was drawn by its parent; this may have changed
15300                invalidateParentIfNeeded();
15301            }
15302        }
15303    }
15304
15305    private static float sanitizeFloatPropertyValue(float value, String propertyName) {
15306        return sanitizeFloatPropertyValue(value, propertyName, -Float.MAX_VALUE, Float.MAX_VALUE);
15307    }
15308
15309    private static float sanitizeFloatPropertyValue(float value, String propertyName,
15310            float min, float max) {
15311        // The expected "nothing bad happened" path
15312        if (value >= min && value <= max) return value;
15313
15314        if (value < min || value == Float.NEGATIVE_INFINITY) {
15315            if (sThrowOnInvalidFloatProperties) {
15316                throw new IllegalArgumentException("Cannot set '" + propertyName + "' to "
15317                        + value + ", the value must be >= " + min);
15318            }
15319            return min;
15320        }
15321
15322        if (value > max || value == Float.POSITIVE_INFINITY) {
15323            if (sThrowOnInvalidFloatProperties) {
15324                throw new IllegalArgumentException("Cannot set '" + propertyName + "' to "
15325                        + value + ", the value must be <= " + max);
15326            }
15327            return max;
15328        }
15329
15330        if (Float.isNaN(value)) {
15331            if (sThrowOnInvalidFloatProperties) {
15332                throw new IllegalArgumentException(
15333                        "Cannot set '" + propertyName + "' to Float.NaN");
15334            }
15335            return 0; // Unclear which direction this NaN went so... 0?
15336        }
15337
15338        // Shouldn't be possible to reach this.
15339        throw new IllegalStateException("How do you get here?? " + value);
15340    }
15341
15342    /**
15343     * The visual x position of this view, in pixels. This is equivalent to the
15344     * {@link #setTranslationX(float) translationX} property plus the current
15345     * {@link #getLeft() left} property.
15346     *
15347     * @return The visual x position of this view, in pixels.
15348     */
15349    @ViewDebug.ExportedProperty(category = "drawing")
15350    public float getX() {
15351        return mLeft + getTranslationX();
15352    }
15353
15354    /**
15355     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
15356     * {@link #setTranslationX(float) translationX} property to be the difference between
15357     * the x value passed in and the current {@link #getLeft() left} property.
15358     *
15359     * @param x The visual x position of this view, in pixels.
15360     */
15361    public void setX(float x) {
15362        setTranslationX(x - mLeft);
15363    }
15364
15365    /**
15366     * The visual y position of this view, in pixels. This is equivalent to the
15367     * {@link #setTranslationY(float) translationY} property plus the current
15368     * {@link #getTop() top} property.
15369     *
15370     * @return The visual y position of this view, in pixels.
15371     */
15372    @ViewDebug.ExportedProperty(category = "drawing")
15373    public float getY() {
15374        return mTop + getTranslationY();
15375    }
15376
15377    /**
15378     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
15379     * {@link #setTranslationY(float) translationY} property to be the difference between
15380     * the y value passed in and the current {@link #getTop() top} property.
15381     *
15382     * @param y The visual y position of this view, in pixels.
15383     */
15384    public void setY(float y) {
15385        setTranslationY(y - mTop);
15386    }
15387
15388    /**
15389     * The visual z position of this view, in pixels. This is equivalent to the
15390     * {@link #setTranslationZ(float) translationZ} property plus the current
15391     * {@link #getElevation() elevation} property.
15392     *
15393     * @return The visual z position of this view, in pixels.
15394     */
15395    @ViewDebug.ExportedProperty(category = "drawing")
15396    public float getZ() {
15397        return getElevation() + getTranslationZ();
15398    }
15399
15400    /**
15401     * Sets the visual z position of this view, in pixels. This is equivalent to setting the
15402     * {@link #setTranslationZ(float) translationZ} property to be the difference between
15403     * the x value passed in and the current {@link #getElevation() elevation} property.
15404     *
15405     * @param z The visual z position of this view, in pixels.
15406     */
15407    public void setZ(float z) {
15408        setTranslationZ(z - getElevation());
15409    }
15410
15411    /**
15412     * The base elevation of this view relative to its parent, in pixels.
15413     *
15414     * @return The base depth position of the view, in pixels.
15415     */
15416    @ViewDebug.ExportedProperty(category = "drawing")
15417    public float getElevation() {
15418        return mRenderNode.getElevation();
15419    }
15420
15421    /**
15422     * Sets the base elevation of this view, in pixels.
15423     *
15424     * @attr ref android.R.styleable#View_elevation
15425     */
15426    public void setElevation(float elevation) {
15427        if (elevation != getElevation()) {
15428            elevation = sanitizeFloatPropertyValue(elevation, "elevation");
15429            invalidateViewProperty(true, false);
15430            mRenderNode.setElevation(elevation);
15431            invalidateViewProperty(false, true);
15432
15433            invalidateParentIfNeededAndWasQuickRejected();
15434        }
15435    }
15436
15437    /**
15438     * The horizontal location of this view relative to its {@link #getLeft() left} position.
15439     * This position is post-layout, in addition to wherever the object's
15440     * layout placed it.
15441     *
15442     * @return The horizontal position of this view relative to its left position, in pixels.
15443     */
15444    @ViewDebug.ExportedProperty(category = "drawing")
15445    public float getTranslationX() {
15446        return mRenderNode.getTranslationX();
15447    }
15448
15449    /**
15450     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
15451     * This effectively positions the object post-layout, in addition to wherever the object's
15452     * layout placed it.
15453     *
15454     * @param translationX The horizontal position of this view relative to its left position,
15455     * in pixels.
15456     *
15457     * @attr ref android.R.styleable#View_translationX
15458     */
15459    public void setTranslationX(float translationX) {
15460        if (translationX != getTranslationX()) {
15461            invalidateViewProperty(true, false);
15462            mRenderNode.setTranslationX(translationX);
15463            invalidateViewProperty(false, true);
15464
15465            invalidateParentIfNeededAndWasQuickRejected();
15466            notifySubtreeAccessibilityStateChangedIfNeeded();
15467        }
15468    }
15469
15470    /**
15471     * The vertical location of this view relative to its {@link #getTop() top} position.
15472     * This position is post-layout, in addition to wherever the object's
15473     * layout placed it.
15474     *
15475     * @return The vertical position of this view relative to its top position,
15476     * in pixels.
15477     */
15478    @ViewDebug.ExportedProperty(category = "drawing")
15479    public float getTranslationY() {
15480        return mRenderNode.getTranslationY();
15481    }
15482
15483    /**
15484     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
15485     * This effectively positions the object post-layout, in addition to wherever the object's
15486     * layout placed it.
15487     *
15488     * @param translationY The vertical position of this view relative to its top position,
15489     * in pixels.
15490     *
15491     * @attr ref android.R.styleable#View_translationY
15492     */
15493    public void setTranslationY(float translationY) {
15494        if (translationY != getTranslationY()) {
15495            invalidateViewProperty(true, false);
15496            mRenderNode.setTranslationY(translationY);
15497            invalidateViewProperty(false, true);
15498
15499            invalidateParentIfNeededAndWasQuickRejected();
15500            notifySubtreeAccessibilityStateChangedIfNeeded();
15501        }
15502    }
15503
15504    /**
15505     * The depth location of this view relative to its {@link #getElevation() elevation}.
15506     *
15507     * @return The depth of this view relative to its elevation.
15508     */
15509    @ViewDebug.ExportedProperty(category = "drawing")
15510    public float getTranslationZ() {
15511        return mRenderNode.getTranslationZ();
15512    }
15513
15514    /**
15515     * Sets the depth location of this view relative to its {@link #getElevation() elevation}.
15516     *
15517     * @attr ref android.R.styleable#View_translationZ
15518     */
15519    public void setTranslationZ(float translationZ) {
15520        if (translationZ != getTranslationZ()) {
15521            translationZ = sanitizeFloatPropertyValue(translationZ, "translationZ");
15522            invalidateViewProperty(true, false);
15523            mRenderNode.setTranslationZ(translationZ);
15524            invalidateViewProperty(false, true);
15525
15526            invalidateParentIfNeededAndWasQuickRejected();
15527        }
15528    }
15529
15530    /** @hide */
15531    public void setAnimationMatrix(Matrix matrix) {
15532        invalidateViewProperty(true, false);
15533        mRenderNode.setAnimationMatrix(matrix);
15534        invalidateViewProperty(false, true);
15535
15536        invalidateParentIfNeededAndWasQuickRejected();
15537    }
15538
15539    /**
15540     * Returns the current StateListAnimator if exists.
15541     *
15542     * @return StateListAnimator or null if it does not exists
15543     * @see    #setStateListAnimator(android.animation.StateListAnimator)
15544     */
15545    public StateListAnimator getStateListAnimator() {
15546        return mStateListAnimator;
15547    }
15548
15549    /**
15550     * Attaches the provided StateListAnimator to this View.
15551     * <p>
15552     * Any previously attached StateListAnimator will be detached.
15553     *
15554     * @param stateListAnimator The StateListAnimator to update the view
15555     * @see android.animation.StateListAnimator
15556     */
15557    public void setStateListAnimator(StateListAnimator stateListAnimator) {
15558        if (mStateListAnimator == stateListAnimator) {
15559            return;
15560        }
15561        if (mStateListAnimator != null) {
15562            mStateListAnimator.setTarget(null);
15563        }
15564        mStateListAnimator = stateListAnimator;
15565        if (stateListAnimator != null) {
15566            stateListAnimator.setTarget(this);
15567            if (isAttachedToWindow()) {
15568                stateListAnimator.setState(getDrawableState());
15569            }
15570        }
15571    }
15572
15573    /**
15574     * Returns whether the Outline should be used to clip the contents of the View.
15575     * <p>
15576     * Note that this flag will only be respected if the View's Outline returns true from
15577     * {@link Outline#canClip()}.
15578     *
15579     * @see #setOutlineProvider(ViewOutlineProvider)
15580     * @see #setClipToOutline(boolean)
15581     */
15582    public final boolean getClipToOutline() {
15583        return mRenderNode.getClipToOutline();
15584    }
15585
15586    /**
15587     * Sets whether the View's Outline should be used to clip the contents of the View.
15588     * <p>
15589     * Only a single non-rectangular clip can be applied on a View at any time.
15590     * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float)
15591     * circular reveal} animation take priority over Outline clipping, and
15592     * child Outline clipping takes priority over Outline clipping done by a
15593     * parent.
15594     * <p>
15595     * Note that this flag will only be respected if the View's Outline returns true from
15596     * {@link Outline#canClip()}.
15597     *
15598     * @see #setOutlineProvider(ViewOutlineProvider)
15599     * @see #getClipToOutline()
15600     */
15601    public void setClipToOutline(boolean clipToOutline) {
15602        damageInParent();
15603        if (getClipToOutline() != clipToOutline) {
15604            mRenderNode.setClipToOutline(clipToOutline);
15605        }
15606    }
15607
15608    // correspond to the enum values of View_outlineProvider
15609    private static final int PROVIDER_BACKGROUND = 0;
15610    private static final int PROVIDER_NONE = 1;
15611    private static final int PROVIDER_BOUNDS = 2;
15612    private static final int PROVIDER_PADDED_BOUNDS = 3;
15613    private void setOutlineProviderFromAttribute(int providerInt) {
15614        switch (providerInt) {
15615            case PROVIDER_BACKGROUND:
15616                setOutlineProvider(ViewOutlineProvider.BACKGROUND);
15617                break;
15618            case PROVIDER_NONE:
15619                setOutlineProvider(null);
15620                break;
15621            case PROVIDER_BOUNDS:
15622                setOutlineProvider(ViewOutlineProvider.BOUNDS);
15623                break;
15624            case PROVIDER_PADDED_BOUNDS:
15625                setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS);
15626                break;
15627        }
15628    }
15629
15630    /**
15631     * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines
15632     * the shape of the shadow it casts, and enables outline clipping.
15633     * <p>
15634     * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline
15635     * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the
15636     * outline provider with this method allows this behavior to be overridden.
15637     * <p>
15638     * If the ViewOutlineProvider is null, if querying it for an outline returns false,
15639     * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast.
15640     * <p>
15641     * Only outlines that return true from {@link Outline#canClip()} may be used for clipping.
15642     *
15643     * @see #setClipToOutline(boolean)
15644     * @see #getClipToOutline()
15645     * @see #getOutlineProvider()
15646     */
15647    public void setOutlineProvider(ViewOutlineProvider provider) {
15648        mOutlineProvider = provider;
15649        invalidateOutline();
15650    }
15651
15652    /**
15653     * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline
15654     * that defines the shape of the shadow it casts, and enables outline clipping.
15655     *
15656     * @see #setOutlineProvider(ViewOutlineProvider)
15657     */
15658    public ViewOutlineProvider getOutlineProvider() {
15659        return mOutlineProvider;
15660    }
15661
15662    /**
15663     * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider}
15664     *
15665     * @see #setOutlineProvider(ViewOutlineProvider)
15666     */
15667    public void invalidateOutline() {
15668        rebuildOutline();
15669
15670        notifySubtreeAccessibilityStateChangedIfNeeded();
15671        invalidateViewProperty(false, false);
15672    }
15673
15674    /**
15675     * Internal version of {@link #invalidateOutline()} which invalidates the
15676     * outline without invalidating the view itself. This is intended to be called from
15677     * within methods in the View class itself which are the result of the view being
15678     * invalidated already. For example, when we are drawing the background of a View,
15679     * we invalidate the outline in case it changed in the meantime, but we do not
15680     * need to invalidate the view because we're already drawing the background as part
15681     * of drawing the view in response to an earlier invalidation of the view.
15682     */
15683    private void rebuildOutline() {
15684        // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow()
15685        if (mAttachInfo == null) return;
15686
15687        if (mOutlineProvider == null) {
15688            // no provider, remove outline
15689            mRenderNode.setOutline(null);
15690        } else {
15691            final Outline outline = mAttachInfo.mTmpOutline;
15692            outline.setEmpty();
15693            outline.setAlpha(1.0f);
15694
15695            mOutlineProvider.getOutline(this, outline);
15696            mRenderNode.setOutline(outline);
15697        }
15698    }
15699
15700    /**
15701     * HierarchyViewer only
15702     *
15703     * @hide
15704     */
15705    @ViewDebug.ExportedProperty(category = "drawing")
15706    public boolean hasShadow() {
15707        return mRenderNode.hasShadow();
15708    }
15709
15710    /**
15711     * Sets the color of the spot shadow that is drawn when the view has a positive Z or
15712     * elevation value.
15713     * <p>
15714     * By default the shadow color is black. Generally, this color will be opaque so the intensity
15715     * of the shadow is consistent between different views with different colors.
15716     * <p>
15717     * The opacity of the final spot shadow is a function of the shadow caster height, the
15718     * alpha channel of the outlineSpotShadowColor (typically opaque), and the
15719     * {@link android.R.attr#spotShadowAlpha} theme attribute.
15720     *
15721     * @attr ref android.R.styleable#View_outlineSpotShadowColor
15722     * @param color The color this View will cast for its elevation spot shadow.
15723     */
15724    public void setOutlineSpotShadowColor(@ColorInt int color) {
15725        if (mRenderNode.setSpotShadowColor(color)) {
15726            invalidateViewProperty(true, true);
15727        }
15728    }
15729
15730    /**
15731     * @return The shadow color set by {@link #setOutlineSpotShadowColor(int)}, or black if nothing
15732     * was set
15733     */
15734    public @ColorInt int getOutlineSpotShadowColor() {
15735        return mRenderNode.getSpotShadowColor();
15736    }
15737
15738    /**
15739     * Sets the color of the ambient shadow that is drawn when the view has a positive Z or
15740     * elevation value.
15741     * <p>
15742     * By default the shadow color is black. Generally, this color will be opaque so the intensity
15743     * of the shadow is consistent between different views with different colors.
15744     * <p>
15745     * The opacity of the final ambient shadow is a function of the shadow caster height, the
15746     * alpha channel of the outlineAmbientShadowColor (typically opaque), and the
15747     * {@link android.R.attr#ambientShadowAlpha} theme attribute.
15748     *
15749     * @attr ref android.R.styleable#View_outlineAmbientShadowColor
15750     * @param color The color this View will cast for its elevation shadow.
15751     */
15752    public void setOutlineAmbientShadowColor(@ColorInt int color) {
15753        if (mRenderNode.setAmbientShadowColor(color)) {
15754            invalidateViewProperty(true, true);
15755        }
15756    }
15757
15758    /**
15759     * @return The shadow color set by {@link #setOutlineAmbientShadowColor(int)}, or black if
15760     * nothing was set
15761     */
15762    public @ColorInt int getOutlineAmbientShadowColor() {
15763        return mRenderNode.getAmbientShadowColor();
15764    }
15765
15766
15767    /** @hide */
15768    public void setRevealClip(boolean shouldClip, float x, float y, float radius) {
15769        mRenderNode.setRevealClip(shouldClip, x, y, radius);
15770        invalidateViewProperty(false, false);
15771    }
15772
15773    /**
15774     * Hit rectangle in parent's coordinates
15775     *
15776     * @param outRect The hit rectangle of the view.
15777     */
15778    public void getHitRect(Rect outRect) {
15779        if (hasIdentityMatrix() || mAttachInfo == null) {
15780            outRect.set(mLeft, mTop, mRight, mBottom);
15781        } else {
15782            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
15783            tmpRect.set(0, 0, getWidth(), getHeight());
15784            getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect)
15785            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
15786                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
15787        }
15788    }
15789
15790    /**
15791     * Determines whether the given point, in local coordinates is inside the view.
15792     */
15793    /*package*/ final boolean pointInView(float localX, float localY) {
15794        return pointInView(localX, localY, 0);
15795    }
15796
15797    /**
15798     * Utility method to determine whether the given point, in local coordinates,
15799     * is inside the view, where the area of the view is expanded by the slop factor.
15800     * This method is called while processing touch-move events to determine if the event
15801     * is still within the view.
15802     *
15803     * @hide
15804     */
15805    public boolean pointInView(float localX, float localY, float slop) {
15806        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
15807                localY < ((mBottom - mTop) + slop);
15808    }
15809
15810    /**
15811     * When a view has focus and the user navigates away from it, the next view is searched for
15812     * starting from the rectangle filled in by this method.
15813     *
15814     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
15815     * of the view.  However, if your view maintains some idea of internal selection,
15816     * such as a cursor, or a selected row or column, you should override this method and
15817     * fill in a more specific rectangle.
15818     *
15819     * @param r The rectangle to fill in, in this view's coordinates.
15820     */
15821    public void getFocusedRect(Rect r) {
15822        getDrawingRect(r);
15823    }
15824
15825    /**
15826     * If some part of this view is not clipped by any of its parents, then
15827     * return that area in r in global (root) coordinates. To convert r to local
15828     * coordinates (without taking possible View rotations into account), offset
15829     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
15830     * If the view is completely clipped or translated out, return false.
15831     *
15832     * @param r If true is returned, r holds the global coordinates of the
15833     *        visible portion of this view.
15834     * @param globalOffset If true is returned, globalOffset holds the dx,dy
15835     *        between this view and its root. globalOffet may be null.
15836     * @return true if r is non-empty (i.e. part of the view is visible at the
15837     *         root level.
15838     */
15839    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
15840        int width = mRight - mLeft;
15841        int height = mBottom - mTop;
15842        if (width > 0 && height > 0) {
15843            r.set(0, 0, width, height);
15844            if (globalOffset != null) {
15845                globalOffset.set(-mScrollX, -mScrollY);
15846            }
15847            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
15848        }
15849        return false;
15850    }
15851
15852    public final boolean getGlobalVisibleRect(Rect r) {
15853        return getGlobalVisibleRect(r, null);
15854    }
15855
15856    public final boolean getLocalVisibleRect(Rect r) {
15857        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
15858        if (getGlobalVisibleRect(r, offset)) {
15859            r.offset(-offset.x, -offset.y); // make r local
15860            return true;
15861        }
15862        return false;
15863    }
15864
15865    /**
15866     * Offset this view's vertical location by the specified number of pixels.
15867     *
15868     * @param offset the number of pixels to offset the view by
15869     */
15870    public void offsetTopAndBottom(int offset) {
15871        if (offset != 0) {
15872            final boolean matrixIsIdentity = hasIdentityMatrix();
15873            if (matrixIsIdentity) {
15874                if (isHardwareAccelerated()) {
15875                    invalidateViewProperty(false, false);
15876                } else {
15877                    final ViewParent p = mParent;
15878                    if (p != null && mAttachInfo != null) {
15879                        final Rect r = mAttachInfo.mTmpInvalRect;
15880                        int minTop;
15881                        int maxBottom;
15882                        int yLoc;
15883                        if (offset < 0) {
15884                            minTop = mTop + offset;
15885                            maxBottom = mBottom;
15886                            yLoc = offset;
15887                        } else {
15888                            minTop = mTop;
15889                            maxBottom = mBottom + offset;
15890                            yLoc = 0;
15891                        }
15892                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
15893                        p.invalidateChild(this, r);
15894                    }
15895                }
15896            } else {
15897                invalidateViewProperty(false, false);
15898            }
15899
15900            mTop += offset;
15901            mBottom += offset;
15902            mRenderNode.offsetTopAndBottom(offset);
15903            if (isHardwareAccelerated()) {
15904                invalidateViewProperty(false, false);
15905                invalidateParentIfNeededAndWasQuickRejected();
15906            } else {
15907                if (!matrixIsIdentity) {
15908                    invalidateViewProperty(false, true);
15909                }
15910                invalidateParentIfNeeded();
15911            }
15912            notifySubtreeAccessibilityStateChangedIfNeeded();
15913        }
15914    }
15915
15916    /**
15917     * Offset this view's horizontal location by the specified amount of pixels.
15918     *
15919     * @param offset the number of pixels to offset the view by
15920     */
15921    public void offsetLeftAndRight(int offset) {
15922        if (offset != 0) {
15923            final boolean matrixIsIdentity = hasIdentityMatrix();
15924            if (matrixIsIdentity) {
15925                if (isHardwareAccelerated()) {
15926                    invalidateViewProperty(false, false);
15927                } else {
15928                    final ViewParent p = mParent;
15929                    if (p != null && mAttachInfo != null) {
15930                        final Rect r = mAttachInfo.mTmpInvalRect;
15931                        int minLeft;
15932                        int maxRight;
15933                        if (offset < 0) {
15934                            minLeft = mLeft + offset;
15935                            maxRight = mRight;
15936                        } else {
15937                            minLeft = mLeft;
15938                            maxRight = mRight + offset;
15939                        }
15940                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
15941                        p.invalidateChild(this, r);
15942                    }
15943                }
15944            } else {
15945                invalidateViewProperty(false, false);
15946            }
15947
15948            mLeft += offset;
15949            mRight += offset;
15950            mRenderNode.offsetLeftAndRight(offset);
15951            if (isHardwareAccelerated()) {
15952                invalidateViewProperty(false, false);
15953                invalidateParentIfNeededAndWasQuickRejected();
15954            } else {
15955                if (!matrixIsIdentity) {
15956                    invalidateViewProperty(false, true);
15957                }
15958                invalidateParentIfNeeded();
15959            }
15960            notifySubtreeAccessibilityStateChangedIfNeeded();
15961        }
15962    }
15963
15964    /**
15965     * Get the LayoutParams associated with this view. All views should have
15966     * layout parameters. These supply parameters to the <i>parent</i> of this
15967     * view specifying how it should be arranged. There are many subclasses of
15968     * ViewGroup.LayoutParams, and these correspond to the different subclasses
15969     * of ViewGroup that are responsible for arranging their children.
15970     *
15971     * This method may return null if this View is not attached to a parent
15972     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
15973     * was not invoked successfully. When a View is attached to a parent
15974     * ViewGroup, this method must not return null.
15975     *
15976     * @return The LayoutParams associated with this view, or null if no
15977     *         parameters have been set yet
15978     */
15979    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
15980    public ViewGroup.LayoutParams getLayoutParams() {
15981        return mLayoutParams;
15982    }
15983
15984    /**
15985     * Set the layout parameters associated with this view. These supply
15986     * parameters to the <i>parent</i> of this view specifying how it should be
15987     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
15988     * correspond to the different subclasses of ViewGroup that are responsible
15989     * for arranging their children.
15990     *
15991     * @param params The layout parameters for this view, cannot be null
15992     */
15993    public void setLayoutParams(ViewGroup.LayoutParams params) {
15994        if (params == null) {
15995            throw new NullPointerException("Layout parameters cannot be null");
15996        }
15997        mLayoutParams = params;
15998        resolveLayoutParams();
15999        if (mParent instanceof ViewGroup) {
16000            ((ViewGroup) mParent).onSetLayoutParams(this, params);
16001        }
16002        requestLayout();
16003    }
16004
16005    /**
16006     * Resolve the layout parameters depending on the resolved layout direction
16007     *
16008     * @hide
16009     */
16010    public void resolveLayoutParams() {
16011        if (mLayoutParams != null) {
16012            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
16013        }
16014    }
16015
16016    /**
16017     * Set the scrolled position of your view. This will cause a call to
16018     * {@link #onScrollChanged(int, int, int, int)} and the view will be
16019     * invalidated.
16020     * @param x the x position to scroll to
16021     * @param y the y position to scroll to
16022     */
16023    public void scrollTo(int x, int y) {
16024        if (mScrollX != x || mScrollY != y) {
16025            int oldX = mScrollX;
16026            int oldY = mScrollY;
16027            mScrollX = x;
16028            mScrollY = y;
16029            invalidateParentCaches();
16030            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
16031            if (!awakenScrollBars()) {
16032                postInvalidateOnAnimation();
16033            }
16034        }
16035    }
16036
16037    /**
16038     * Move the scrolled position of your view. This will cause a call to
16039     * {@link #onScrollChanged(int, int, int, int)} and the view will be
16040     * invalidated.
16041     * @param x the amount of pixels to scroll by horizontally
16042     * @param y the amount of pixels to scroll by vertically
16043     */
16044    public void scrollBy(int x, int y) {
16045        scrollTo(mScrollX + x, mScrollY + y);
16046    }
16047
16048    /**
16049     * <p>Trigger the scrollbars to draw. When invoked this method starts an
16050     * animation to fade the scrollbars out after a default delay. If a subclass
16051     * provides animated scrolling, the start delay should equal the duration
16052     * of the scrolling animation.</p>
16053     *
16054     * <p>The animation starts only if at least one of the scrollbars is
16055     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
16056     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
16057     * this method returns true, and false otherwise. If the animation is
16058     * started, this method calls {@link #invalidate()}; in that case the
16059     * caller should not call {@link #invalidate()}.</p>
16060     *
16061     * <p>This method should be invoked every time a subclass directly updates
16062     * the scroll parameters.</p>
16063     *
16064     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
16065     * and {@link #scrollTo(int, int)}.</p>
16066     *
16067     * @return true if the animation is played, false otherwise
16068     *
16069     * @see #awakenScrollBars(int)
16070     * @see #scrollBy(int, int)
16071     * @see #scrollTo(int, int)
16072     * @see #isHorizontalScrollBarEnabled()
16073     * @see #isVerticalScrollBarEnabled()
16074     * @see #setHorizontalScrollBarEnabled(boolean)
16075     * @see #setVerticalScrollBarEnabled(boolean)
16076     */
16077    protected boolean awakenScrollBars() {
16078        return mScrollCache != null &&
16079                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
16080    }
16081
16082    /**
16083     * Trigger the scrollbars to draw.
16084     * This method differs from awakenScrollBars() only in its default duration.
16085     * initialAwakenScrollBars() will show the scroll bars for longer than
16086     * usual to give the user more of a chance to notice them.
16087     *
16088     * @return true if the animation is played, false otherwise.
16089     */
16090    private boolean initialAwakenScrollBars() {
16091        return mScrollCache != null &&
16092                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
16093    }
16094
16095    /**
16096     * <p>
16097     * Trigger the scrollbars to draw. When invoked this method starts an
16098     * animation to fade the scrollbars out after a fixed delay. If a subclass
16099     * provides animated scrolling, the start delay should equal the duration of
16100     * the scrolling animation.
16101     * </p>
16102     *
16103     * <p>
16104     * The animation starts only if at least one of the scrollbars is enabled,
16105     * as specified by {@link #isHorizontalScrollBarEnabled()} and
16106     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
16107     * this method returns true, and false otherwise. If the animation is
16108     * started, this method calls {@link #invalidate()}; in that case the caller
16109     * should not call {@link #invalidate()}.
16110     * </p>
16111     *
16112     * <p>
16113     * This method should be invoked every time a subclass directly updates the
16114     * scroll parameters.
16115     * </p>
16116     *
16117     * @param startDelay the delay, in milliseconds, after which the animation
16118     *        should start; when the delay is 0, the animation starts
16119     *        immediately
16120     * @return true if the animation is played, false otherwise
16121     *
16122     * @see #scrollBy(int, int)
16123     * @see #scrollTo(int, int)
16124     * @see #isHorizontalScrollBarEnabled()
16125     * @see #isVerticalScrollBarEnabled()
16126     * @see #setHorizontalScrollBarEnabled(boolean)
16127     * @see #setVerticalScrollBarEnabled(boolean)
16128     */
16129    protected boolean awakenScrollBars(int startDelay) {
16130        return awakenScrollBars(startDelay, true);
16131    }
16132
16133    /**
16134     * <p>
16135     * Trigger the scrollbars to draw. When invoked this method starts an
16136     * animation to fade the scrollbars out after a fixed delay. If a subclass
16137     * provides animated scrolling, the start delay should equal the duration of
16138     * the scrolling animation.
16139     * </p>
16140     *
16141     * <p>
16142     * The animation starts only if at least one of the scrollbars is enabled,
16143     * as specified by {@link #isHorizontalScrollBarEnabled()} and
16144     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
16145     * this method returns true, and false otherwise. If the animation is
16146     * started, this method calls {@link #invalidate()} if the invalidate parameter
16147     * is set to true; in that case the caller
16148     * should not call {@link #invalidate()}.
16149     * </p>
16150     *
16151     * <p>
16152     * This method should be invoked every time a subclass directly updates the
16153     * scroll parameters.
16154     * </p>
16155     *
16156     * @param startDelay the delay, in milliseconds, after which the animation
16157     *        should start; when the delay is 0, the animation starts
16158     *        immediately
16159     *
16160     * @param invalidate Whether this method should call invalidate
16161     *
16162     * @return true if the animation is played, false otherwise
16163     *
16164     * @see #scrollBy(int, int)
16165     * @see #scrollTo(int, int)
16166     * @see #isHorizontalScrollBarEnabled()
16167     * @see #isVerticalScrollBarEnabled()
16168     * @see #setHorizontalScrollBarEnabled(boolean)
16169     * @see #setVerticalScrollBarEnabled(boolean)
16170     */
16171    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
16172        final ScrollabilityCache scrollCache = mScrollCache;
16173
16174        if (scrollCache == null || !scrollCache.fadeScrollBars) {
16175            return false;
16176        }
16177
16178        if (scrollCache.scrollBar == null) {
16179            scrollCache.scrollBar = new ScrollBarDrawable();
16180            scrollCache.scrollBar.setState(getDrawableState());
16181            scrollCache.scrollBar.setCallback(this);
16182        }
16183
16184        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
16185
16186            if (invalidate) {
16187                // Invalidate to show the scrollbars
16188                postInvalidateOnAnimation();
16189            }
16190
16191            if (scrollCache.state == ScrollabilityCache.OFF) {
16192                // FIXME: this is copied from WindowManagerService.
16193                // We should get this value from the system when it
16194                // is possible to do so.
16195                final int KEY_REPEAT_FIRST_DELAY = 750;
16196                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
16197            }
16198
16199            // Tell mScrollCache when we should start fading. This may
16200            // extend the fade start time if one was already scheduled
16201            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
16202            scrollCache.fadeStartTime = fadeStartTime;
16203            scrollCache.state = ScrollabilityCache.ON;
16204
16205            // Schedule our fader to run, unscheduling any old ones first
16206            if (mAttachInfo != null) {
16207                mAttachInfo.mHandler.removeCallbacks(scrollCache);
16208                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
16209            }
16210
16211            return true;
16212        }
16213
16214        return false;
16215    }
16216
16217    /**
16218     * Do not invalidate views which are not visible and which are not running an animation. They
16219     * will not get drawn and they should not set dirty flags as if they will be drawn
16220     */
16221    private boolean skipInvalidate() {
16222        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
16223                (!(mParent instanceof ViewGroup) ||
16224                        !((ViewGroup) mParent).isViewTransitioning(this));
16225    }
16226
16227    /**
16228     * Mark the area defined by dirty as needing to be drawn. If the view is
16229     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
16230     * point in the future.
16231     * <p>
16232     * This must be called from a UI thread. To call from a non-UI thread, call
16233     * {@link #postInvalidate()}.
16234     * <p>
16235     * <b>WARNING:</b> In API 19 and below, this method may be destructive to
16236     * {@code dirty}.
16237     *
16238     * @param dirty the rectangle representing the bounds of the dirty region
16239     *
16240     * @deprecated The switch to hardware accelerated rendering in API 14 reduced
16241     * the importance of the dirty rectangle. In API 21 the given rectangle is
16242     * ignored entirely in favor of an internally-calculated area instead.
16243     * Because of this, clients are encouraged to just call {@link #invalidate()}.
16244     */
16245    @Deprecated
16246    public void invalidate(Rect dirty) {
16247        final int scrollX = mScrollX;
16248        final int scrollY = mScrollY;
16249        invalidateInternal(dirty.left - scrollX, dirty.top - scrollY,
16250                dirty.right - scrollX, dirty.bottom - scrollY, true, false);
16251    }
16252
16253    /**
16254     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The
16255     * coordinates of the dirty rect are relative to the view. If the view is
16256     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
16257     * point in the future.
16258     * <p>
16259     * This must be called from a UI thread. To call from a non-UI thread, call
16260     * {@link #postInvalidate()}.
16261     *
16262     * @param l the left position of the dirty region
16263     * @param t the top position of the dirty region
16264     * @param r the right position of the dirty region
16265     * @param b the bottom position of the dirty region
16266     *
16267     * @deprecated The switch to hardware accelerated rendering in API 14 reduced
16268     * the importance of the dirty rectangle. In API 21 the given rectangle is
16269     * ignored entirely in favor of an internally-calculated area instead.
16270     * Because of this, clients are encouraged to just call {@link #invalidate()}.
16271     */
16272    @Deprecated
16273    public void invalidate(int l, int t, int r, int b) {
16274        final int scrollX = mScrollX;
16275        final int scrollY = mScrollY;
16276        invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false);
16277    }
16278
16279    /**
16280     * Invalidate the whole view. If the view is visible,
16281     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
16282     * the future.
16283     * <p>
16284     * This must be called from a UI thread. To call from a non-UI thread, call
16285     * {@link #postInvalidate()}.
16286     */
16287    public void invalidate() {
16288        invalidate(true);
16289    }
16290
16291    /**
16292     * This is where the invalidate() work actually happens. A full invalidate()
16293     * causes the drawing cache to be invalidated, but this function can be
16294     * called with invalidateCache set to false to skip that invalidation step
16295     * for cases that do not need it (for example, a component that remains at
16296     * the same dimensions with the same content).
16297     *
16298     * @param invalidateCache Whether the drawing cache for this view should be
16299     *            invalidated as well. This is usually true for a full
16300     *            invalidate, but may be set to false if the View's contents or
16301     *            dimensions have not changed.
16302     * @hide
16303     */
16304    public void invalidate(boolean invalidateCache) {
16305        invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
16306    }
16307
16308    void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
16309            boolean fullInvalidate) {
16310        if (mGhostView != null) {
16311            mGhostView.invalidate(true);
16312            return;
16313        }
16314
16315        if (skipInvalidate()) {
16316            return;
16317        }
16318
16319        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)
16320                || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID)
16321                || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED
16322                || (fullInvalidate && isOpaque() != mLastIsOpaque)) {
16323            if (fullInvalidate) {
16324                mLastIsOpaque = isOpaque();
16325                mPrivateFlags &= ~PFLAG_DRAWN;
16326            }
16327
16328            mPrivateFlags |= PFLAG_DIRTY;
16329
16330            if (invalidateCache) {
16331                mPrivateFlags |= PFLAG_INVALIDATED;
16332                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
16333            }
16334
16335            // Propagate the damage rectangle to the parent view.
16336            final AttachInfo ai = mAttachInfo;
16337            final ViewParent p = mParent;
16338            if (p != null && ai != null && l < r && t < b) {
16339                final Rect damage = ai.mTmpInvalRect;
16340                damage.set(l, t, r, b);
16341                p.invalidateChild(this, damage);
16342            }
16343
16344            // Damage the entire projection receiver, if necessary.
16345            if (mBackground != null && mBackground.isProjected()) {
16346                final View receiver = getProjectionReceiver();
16347                if (receiver != null) {
16348                    receiver.damageInParent();
16349                }
16350            }
16351        }
16352    }
16353
16354    /**
16355     * @return this view's projection receiver, or {@code null} if none exists
16356     */
16357    private View getProjectionReceiver() {
16358        ViewParent p = getParent();
16359        while (p != null && p instanceof View) {
16360            final View v = (View) p;
16361            if (v.isProjectionReceiver()) {
16362                return v;
16363            }
16364            p = p.getParent();
16365        }
16366
16367        return null;
16368    }
16369
16370    /**
16371     * @return whether the view is a projection receiver
16372     */
16373    private boolean isProjectionReceiver() {
16374        return mBackground != null;
16375    }
16376
16377    /**
16378     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
16379     * set any flags or handle all of the cases handled by the default invalidation methods.
16380     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
16381     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
16382     * walk up the hierarchy, transforming the dirty rect as necessary.
16383     *
16384     * The method also handles normal invalidation logic if display list properties are not
16385     * being used in this view. The invalidateParent and forceRedraw flags are used by that
16386     * backup approach, to handle these cases used in the various property-setting methods.
16387     *
16388     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
16389     * are not being used in this view
16390     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
16391     * list properties are not being used in this view
16392     */
16393    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
16394        if (!isHardwareAccelerated()
16395                || !mRenderNode.isValid()
16396                || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) {
16397            if (invalidateParent) {
16398                invalidateParentCaches();
16399            }
16400            if (forceRedraw) {
16401                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
16402            }
16403            invalidate(false);
16404        } else {
16405            damageInParent();
16406        }
16407    }
16408
16409    /**
16410     * Tells the parent view to damage this view's bounds.
16411     *
16412     * @hide
16413     */
16414    protected void damageInParent() {
16415        if (mParent != null && mAttachInfo != null) {
16416            mParent.onDescendantInvalidated(this, this);
16417        }
16418    }
16419
16420    /**
16421     * Utility method to transform a given Rect by the current matrix of this view.
16422     */
16423    void transformRect(final Rect rect) {
16424        if (!getMatrix().isIdentity()) {
16425            RectF boundingRect = mAttachInfo.mTmpTransformRect;
16426            boundingRect.set(rect);
16427            getMatrix().mapRect(boundingRect);
16428            rect.set((int) Math.floor(boundingRect.left),
16429                    (int) Math.floor(boundingRect.top),
16430                    (int) Math.ceil(boundingRect.right),
16431                    (int) Math.ceil(boundingRect.bottom));
16432        }
16433    }
16434
16435    /**
16436     * Used to indicate that the parent of this view should clear its caches. This functionality
16437     * is used to force the parent to rebuild its display list (when hardware-accelerated),
16438     * which is necessary when various parent-managed properties of the view change, such as
16439     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
16440     * clears the parent caches and does not causes an invalidate event.
16441     *
16442     * @hide
16443     */
16444    protected void invalidateParentCaches() {
16445        if (mParent instanceof View) {
16446            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
16447        }
16448    }
16449
16450    /**
16451     * Used to indicate that the parent of this view should be invalidated. This functionality
16452     * is used to force the parent to rebuild its display list (when hardware-accelerated),
16453     * which is necessary when various parent-managed properties of the view change, such as
16454     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
16455     * an invalidation event to the parent.
16456     *
16457     * @hide
16458     */
16459    protected void invalidateParentIfNeeded() {
16460        if (isHardwareAccelerated() && mParent instanceof View) {
16461            ((View) mParent).invalidate(true);
16462        }
16463    }
16464
16465    /**
16466     * @hide
16467     */
16468    protected void invalidateParentIfNeededAndWasQuickRejected() {
16469        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) {
16470            // View was rejected last time it was drawn by its parent; this may have changed
16471            invalidateParentIfNeeded();
16472        }
16473    }
16474
16475    /**
16476     * Indicates whether this View is opaque. An opaque View guarantees that it will
16477     * draw all the pixels overlapping its bounds using a fully opaque color.
16478     *
16479     * Subclasses of View should override this method whenever possible to indicate
16480     * whether an instance is opaque. Opaque Views are treated in a special way by
16481     * the View hierarchy, possibly allowing it to perform optimizations during
16482     * invalidate/draw passes.
16483     *
16484     * @return True if this View is guaranteed to be fully opaque, false otherwise.
16485     */
16486    @ViewDebug.ExportedProperty(category = "drawing")
16487    public boolean isOpaque() {
16488        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
16489                getFinalAlpha() >= 1.0f;
16490    }
16491
16492    /**
16493     * @hide
16494     */
16495    protected void computeOpaqueFlags() {
16496        // Opaque if:
16497        //   - Has a background
16498        //   - Background is opaque
16499        //   - Doesn't have scrollbars or scrollbars overlay
16500
16501        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
16502            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
16503        } else {
16504            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
16505        }
16506
16507        final int flags = mViewFlags;
16508        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
16509                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
16510                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
16511            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
16512        } else {
16513            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
16514        }
16515    }
16516
16517    /**
16518     * @hide
16519     */
16520    protected boolean hasOpaqueScrollbars() {
16521        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
16522    }
16523
16524    /**
16525     * @return A handler associated with the thread running the View. This
16526     * handler can be used to pump events in the UI events queue.
16527     */
16528    public Handler getHandler() {
16529        final AttachInfo attachInfo = mAttachInfo;
16530        if (attachInfo != null) {
16531            return attachInfo.mHandler;
16532        }
16533        return null;
16534    }
16535
16536    /**
16537     * Returns the queue of runnable for this view.
16538     *
16539     * @return the queue of runnables for this view
16540     */
16541    private HandlerActionQueue getRunQueue() {
16542        if (mRunQueue == null) {
16543            mRunQueue = new HandlerActionQueue();
16544        }
16545        return mRunQueue;
16546    }
16547
16548    /**
16549     * Gets the view root associated with the View.
16550     * @return The view root, or null if none.
16551     * @hide
16552     */
16553    public ViewRootImpl getViewRootImpl() {
16554        if (mAttachInfo != null) {
16555            return mAttachInfo.mViewRootImpl;
16556        }
16557        return null;
16558    }
16559
16560    /**
16561     * @hide
16562     */
16563    public ThreadedRenderer getThreadedRenderer() {
16564        return mAttachInfo != null ? mAttachInfo.mThreadedRenderer : null;
16565    }
16566
16567    /**
16568     * <p>Causes the Runnable to be added to the message queue.
16569     * The runnable will be run on the user interface thread.</p>
16570     *
16571     * @param action The Runnable that will be executed.
16572     *
16573     * @return Returns true if the Runnable was successfully placed in to the
16574     *         message queue.  Returns false on failure, usually because the
16575     *         looper processing the message queue is exiting.
16576     *
16577     * @see #postDelayed
16578     * @see #removeCallbacks
16579     */
16580    public boolean post(Runnable action) {
16581        final AttachInfo attachInfo = mAttachInfo;
16582        if (attachInfo != null) {
16583            return attachInfo.mHandler.post(action);
16584        }
16585
16586        // Postpone the runnable until we know on which thread it needs to run.
16587        // Assume that the runnable will be successfully placed after attach.
16588        getRunQueue().post(action);
16589        return true;
16590    }
16591
16592    /**
16593     * <p>Causes the Runnable to be added to the message queue, to be run
16594     * after the specified amount of time elapses.
16595     * The runnable will be run on the user interface thread.</p>
16596     *
16597     * @param action The Runnable that will be executed.
16598     * @param delayMillis The delay (in milliseconds) until the Runnable
16599     *        will be executed.
16600     *
16601     * @return true if the Runnable was successfully placed in to the
16602     *         message queue.  Returns false on failure, usually because the
16603     *         looper processing the message queue is exiting.  Note that a
16604     *         result of true does not mean the Runnable will be processed --
16605     *         if the looper is quit before the delivery time of the message
16606     *         occurs then the message will be dropped.
16607     *
16608     * @see #post
16609     * @see #removeCallbacks
16610     */
16611    public boolean postDelayed(Runnable action, long delayMillis) {
16612        final AttachInfo attachInfo = mAttachInfo;
16613        if (attachInfo != null) {
16614            return attachInfo.mHandler.postDelayed(action, delayMillis);
16615        }
16616
16617        // Postpone the runnable until we know on which thread it needs to run.
16618        // Assume that the runnable will be successfully placed after attach.
16619        getRunQueue().postDelayed(action, delayMillis);
16620        return true;
16621    }
16622
16623    /**
16624     * <p>Causes the Runnable to execute on the next animation time step.
16625     * The runnable will be run on the user interface thread.</p>
16626     *
16627     * @param action The Runnable that will be executed.
16628     *
16629     * @see #postOnAnimationDelayed
16630     * @see #removeCallbacks
16631     */
16632    public void postOnAnimation(Runnable action) {
16633        final AttachInfo attachInfo = mAttachInfo;
16634        if (attachInfo != null) {
16635            attachInfo.mViewRootImpl.mChoreographer.postCallback(
16636                    Choreographer.CALLBACK_ANIMATION, action, null);
16637        } else {
16638            // Postpone the runnable until we know
16639            // on which thread it needs to run.
16640            getRunQueue().post(action);
16641        }
16642    }
16643
16644    /**
16645     * <p>Causes the Runnable to execute on the next animation time step,
16646     * after the specified amount of time elapses.
16647     * The runnable will be run on the user interface thread.</p>
16648     *
16649     * @param action The Runnable that will be executed.
16650     * @param delayMillis The delay (in milliseconds) until the Runnable
16651     *        will be executed.
16652     *
16653     * @see #postOnAnimation
16654     * @see #removeCallbacks
16655     */
16656    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
16657        final AttachInfo attachInfo = mAttachInfo;
16658        if (attachInfo != null) {
16659            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
16660                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
16661        } else {
16662            // Postpone the runnable until we know
16663            // on which thread it needs to run.
16664            getRunQueue().postDelayed(action, delayMillis);
16665        }
16666    }
16667
16668    /**
16669     * <p>Removes the specified Runnable from the message queue.</p>
16670     *
16671     * @param action The Runnable to remove from the message handling queue
16672     *
16673     * @return true if this view could ask the Handler to remove the Runnable,
16674     *         false otherwise. When the returned value is true, the Runnable
16675     *         may or may not have been actually removed from the message queue
16676     *         (for instance, if the Runnable was not in the queue already.)
16677     *
16678     * @see #post
16679     * @see #postDelayed
16680     * @see #postOnAnimation
16681     * @see #postOnAnimationDelayed
16682     */
16683    public boolean removeCallbacks(Runnable action) {
16684        if (action != null) {
16685            final AttachInfo attachInfo = mAttachInfo;
16686            if (attachInfo != null) {
16687                attachInfo.mHandler.removeCallbacks(action);
16688                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
16689                        Choreographer.CALLBACK_ANIMATION, action, null);
16690            }
16691            getRunQueue().removeCallbacks(action);
16692        }
16693        return true;
16694    }
16695
16696    /**
16697     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
16698     * Use this to invalidate the View from a non-UI thread.</p>
16699     *
16700     * <p>This method can be invoked from outside of the UI thread
16701     * only when this View is attached to a window.</p>
16702     *
16703     * @see #invalidate()
16704     * @see #postInvalidateDelayed(long)
16705     */
16706    public void postInvalidate() {
16707        postInvalidateDelayed(0);
16708    }
16709
16710    /**
16711     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
16712     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
16713     *
16714     * <p>This method can be invoked from outside of the UI thread
16715     * only when this View is attached to a window.</p>
16716     *
16717     * @param left The left coordinate of the rectangle to invalidate.
16718     * @param top The top coordinate of the rectangle to invalidate.
16719     * @param right The right coordinate of the rectangle to invalidate.
16720     * @param bottom The bottom coordinate of the rectangle to invalidate.
16721     *
16722     * @see #invalidate(int, int, int, int)
16723     * @see #invalidate(Rect)
16724     * @see #postInvalidateDelayed(long, int, int, int, int)
16725     */
16726    public void postInvalidate(int left, int top, int right, int bottom) {
16727        postInvalidateDelayed(0, left, top, right, bottom);
16728    }
16729
16730    /**
16731     * <p>Cause an invalidate to happen on a subsequent cycle through the event
16732     * loop. Waits for the specified amount of time.</p>
16733     *
16734     * <p>This method can be invoked from outside of the UI thread
16735     * only when this View is attached to a window.</p>
16736     *
16737     * @param delayMilliseconds the duration in milliseconds to delay the
16738     *         invalidation by
16739     *
16740     * @see #invalidate()
16741     * @see #postInvalidate()
16742     */
16743    public void postInvalidateDelayed(long delayMilliseconds) {
16744        // We try only with the AttachInfo because there's no point in invalidating
16745        // if we are not attached to our window
16746        final AttachInfo attachInfo = mAttachInfo;
16747        if (attachInfo != null) {
16748            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
16749        }
16750    }
16751
16752    /**
16753     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
16754     * through the event loop. Waits for the specified amount of time.</p>
16755     *
16756     * <p>This method can be invoked from outside of the UI thread
16757     * only when this View is attached to a window.</p>
16758     *
16759     * @param delayMilliseconds the duration in milliseconds to delay the
16760     *         invalidation by
16761     * @param left The left coordinate of the rectangle to invalidate.
16762     * @param top The top coordinate of the rectangle to invalidate.
16763     * @param right The right coordinate of the rectangle to invalidate.
16764     * @param bottom The bottom coordinate of the rectangle to invalidate.
16765     *
16766     * @see #invalidate(int, int, int, int)
16767     * @see #invalidate(Rect)
16768     * @see #postInvalidate(int, int, int, int)
16769     */
16770    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
16771            int right, int bottom) {
16772
16773        // We try only with the AttachInfo because there's no point in invalidating
16774        // if we are not attached to our window
16775        final AttachInfo attachInfo = mAttachInfo;
16776        if (attachInfo != null) {
16777            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
16778            info.target = this;
16779            info.left = left;
16780            info.top = top;
16781            info.right = right;
16782            info.bottom = bottom;
16783
16784            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
16785        }
16786    }
16787
16788    /**
16789     * <p>Cause an invalidate to happen on the next animation time step, typically the
16790     * next display frame.</p>
16791     *
16792     * <p>This method can be invoked from outside of the UI thread
16793     * only when this View is attached to a window.</p>
16794     *
16795     * @see #invalidate()
16796     */
16797    public void postInvalidateOnAnimation() {
16798        // We try only with the AttachInfo because there's no point in invalidating
16799        // if we are not attached to our window
16800        final AttachInfo attachInfo = mAttachInfo;
16801        if (attachInfo != null) {
16802            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
16803        }
16804    }
16805
16806    /**
16807     * <p>Cause an invalidate of the specified area to happen on the next animation
16808     * time step, typically the next display frame.</p>
16809     *
16810     * <p>This method can be invoked from outside of the UI thread
16811     * only when this View is attached to a window.</p>
16812     *
16813     * @param left The left coordinate of the rectangle to invalidate.
16814     * @param top The top coordinate of the rectangle to invalidate.
16815     * @param right The right coordinate of the rectangle to invalidate.
16816     * @param bottom The bottom coordinate of the rectangle to invalidate.
16817     *
16818     * @see #invalidate(int, int, int, int)
16819     * @see #invalidate(Rect)
16820     */
16821    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
16822        // We try only with the AttachInfo because there's no point in invalidating
16823        // if we are not attached to our window
16824        final AttachInfo attachInfo = mAttachInfo;
16825        if (attachInfo != null) {
16826            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
16827            info.target = this;
16828            info.left = left;
16829            info.top = top;
16830            info.right = right;
16831            info.bottom = bottom;
16832
16833            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
16834        }
16835    }
16836
16837    /**
16838     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
16839     * This event is sent at most once every
16840     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
16841     */
16842    private void postSendViewScrolledAccessibilityEventCallback(int dx, int dy) {
16843        if (mSendViewScrolledAccessibilityEvent == null) {
16844            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
16845        }
16846        mSendViewScrolledAccessibilityEvent.post(dx, dy);
16847    }
16848
16849    /**
16850     * Called by a parent to request that a child update its values for mScrollX
16851     * and mScrollY if necessary. This will typically be done if the child is
16852     * animating a scroll using a {@link android.widget.Scroller Scroller}
16853     * object.
16854     */
16855    public void computeScroll() {
16856    }
16857
16858    /**
16859     * <p>Indicate whether the horizontal edges are faded when the view is
16860     * scrolled horizontally.</p>
16861     *
16862     * @return true if the horizontal edges should are faded on scroll, false
16863     *         otherwise
16864     *
16865     * @see #setHorizontalFadingEdgeEnabled(boolean)
16866     *
16867     * @attr ref android.R.styleable#View_requiresFadingEdge
16868     */
16869    public boolean isHorizontalFadingEdgeEnabled() {
16870        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
16871    }
16872
16873    /**
16874     * <p>Define whether the horizontal edges should be faded when this view
16875     * is scrolled horizontally.</p>
16876     *
16877     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
16878     *                                    be faded when the view is scrolled
16879     *                                    horizontally
16880     *
16881     * @see #isHorizontalFadingEdgeEnabled()
16882     *
16883     * @attr ref android.R.styleable#View_requiresFadingEdge
16884     */
16885    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
16886        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
16887            if (horizontalFadingEdgeEnabled) {
16888                initScrollCache();
16889            }
16890
16891            mViewFlags ^= FADING_EDGE_HORIZONTAL;
16892        }
16893    }
16894
16895    /**
16896     * <p>Indicate whether the vertical edges are faded when the view is
16897     * scrolled horizontally.</p>
16898     *
16899     * @return true if the vertical edges should are faded on scroll, false
16900     *         otherwise
16901     *
16902     * @see #setVerticalFadingEdgeEnabled(boolean)
16903     *
16904     * @attr ref android.R.styleable#View_requiresFadingEdge
16905     */
16906    public boolean isVerticalFadingEdgeEnabled() {
16907        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
16908    }
16909
16910    /**
16911     * <p>Define whether the vertical edges should be faded when this view
16912     * is scrolled vertically.</p>
16913     *
16914     * @param verticalFadingEdgeEnabled true if the vertical edges should
16915     *                                  be faded when the view is scrolled
16916     *                                  vertically
16917     *
16918     * @see #isVerticalFadingEdgeEnabled()
16919     *
16920     * @attr ref android.R.styleable#View_requiresFadingEdge
16921     */
16922    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
16923        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
16924            if (verticalFadingEdgeEnabled) {
16925                initScrollCache();
16926            }
16927
16928            mViewFlags ^= FADING_EDGE_VERTICAL;
16929        }
16930    }
16931
16932    /**
16933     * Returns the strength, or intensity, of the top faded edge. The strength is
16934     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
16935     * returns 0.0 or 1.0 but no value in between.
16936     *
16937     * Subclasses should override this method to provide a smoother fade transition
16938     * when scrolling occurs.
16939     *
16940     * @return the intensity of the top fade as a float between 0.0f and 1.0f
16941     */
16942    protected float getTopFadingEdgeStrength() {
16943        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
16944    }
16945
16946    /**
16947     * Returns the strength, or intensity, of the bottom faded edge. The strength is
16948     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
16949     * returns 0.0 or 1.0 but no value in between.
16950     *
16951     * Subclasses should override this method to provide a smoother fade transition
16952     * when scrolling occurs.
16953     *
16954     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
16955     */
16956    protected float getBottomFadingEdgeStrength() {
16957        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
16958                computeVerticalScrollRange() ? 1.0f : 0.0f;
16959    }
16960
16961    /**
16962     * Returns the strength, or intensity, of the left faded edge. The strength is
16963     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
16964     * returns 0.0 or 1.0 but no value in between.
16965     *
16966     * Subclasses should override this method to provide a smoother fade transition
16967     * when scrolling occurs.
16968     *
16969     * @return the intensity of the left fade as a float between 0.0f and 1.0f
16970     */
16971    protected float getLeftFadingEdgeStrength() {
16972        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
16973    }
16974
16975    /**
16976     * Returns the strength, or intensity, of the right faded edge. The strength is
16977     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
16978     * returns 0.0 or 1.0 but no value in between.
16979     *
16980     * Subclasses should override this method to provide a smoother fade transition
16981     * when scrolling occurs.
16982     *
16983     * @return the intensity of the right fade as a float between 0.0f and 1.0f
16984     */
16985    protected float getRightFadingEdgeStrength() {
16986        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
16987                computeHorizontalScrollRange() ? 1.0f : 0.0f;
16988    }
16989
16990    /**
16991     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
16992     * scrollbar is not drawn by default.</p>
16993     *
16994     * @return true if the horizontal scrollbar should be painted, false
16995     *         otherwise
16996     *
16997     * @see #setHorizontalScrollBarEnabled(boolean)
16998     */
16999    public boolean isHorizontalScrollBarEnabled() {
17000        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
17001    }
17002
17003    /**
17004     * <p>Define whether the horizontal scrollbar should be drawn or not. The
17005     * scrollbar is not drawn by default.</p>
17006     *
17007     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
17008     *                                   be painted
17009     *
17010     * @see #isHorizontalScrollBarEnabled()
17011     */
17012    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
17013        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
17014            mViewFlags ^= SCROLLBARS_HORIZONTAL;
17015            computeOpaqueFlags();
17016            resolvePadding();
17017        }
17018    }
17019
17020    /**
17021     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
17022     * scrollbar is not drawn by default.</p>
17023     *
17024     * @return true if the vertical scrollbar should be painted, false
17025     *         otherwise
17026     *
17027     * @see #setVerticalScrollBarEnabled(boolean)
17028     */
17029    public boolean isVerticalScrollBarEnabled() {
17030        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
17031    }
17032
17033    /**
17034     * <p>Define whether the vertical scrollbar should be drawn or not. The
17035     * scrollbar is not drawn by default.</p>
17036     *
17037     * @param verticalScrollBarEnabled true if the vertical scrollbar should
17038     *                                 be painted
17039     *
17040     * @see #isVerticalScrollBarEnabled()
17041     */
17042    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
17043        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
17044            mViewFlags ^= SCROLLBARS_VERTICAL;
17045            computeOpaqueFlags();
17046            resolvePadding();
17047        }
17048    }
17049
17050    /**
17051     * @hide
17052     */
17053    protected void recomputePadding() {
17054        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
17055    }
17056
17057    /**
17058     * Define whether scrollbars will fade when the view is not scrolling.
17059     *
17060     * @param fadeScrollbars whether to enable fading
17061     *
17062     * @attr ref android.R.styleable#View_fadeScrollbars
17063     */
17064    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
17065        initScrollCache();
17066        final ScrollabilityCache scrollabilityCache = mScrollCache;
17067        scrollabilityCache.fadeScrollBars = fadeScrollbars;
17068        if (fadeScrollbars) {
17069            scrollabilityCache.state = ScrollabilityCache.OFF;
17070        } else {
17071            scrollabilityCache.state = ScrollabilityCache.ON;
17072        }
17073    }
17074
17075    /**
17076     *
17077     * Returns true if scrollbars will fade when this view is not scrolling
17078     *
17079     * @return true if scrollbar fading is enabled
17080     *
17081     * @attr ref android.R.styleable#View_fadeScrollbars
17082     */
17083    public boolean isScrollbarFadingEnabled() {
17084        return mScrollCache != null && mScrollCache.fadeScrollBars;
17085    }
17086
17087    /**
17088     *
17089     * Returns the delay before scrollbars fade.
17090     *
17091     * @return the delay before scrollbars fade
17092     *
17093     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
17094     */
17095    public int getScrollBarDefaultDelayBeforeFade() {
17096        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
17097                mScrollCache.scrollBarDefaultDelayBeforeFade;
17098    }
17099
17100    /**
17101     * Define the delay before scrollbars fade.
17102     *
17103     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
17104     *
17105     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
17106     */
17107    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
17108        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
17109    }
17110
17111    /**
17112     *
17113     * Returns the scrollbar fade duration.
17114     *
17115     * @return the scrollbar fade duration, in milliseconds
17116     *
17117     * @attr ref android.R.styleable#View_scrollbarFadeDuration
17118     */
17119    public int getScrollBarFadeDuration() {
17120        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
17121                mScrollCache.scrollBarFadeDuration;
17122    }
17123
17124    /**
17125     * Define the scrollbar fade duration.
17126     *
17127     * @param scrollBarFadeDuration - the scrollbar fade duration, in milliseconds
17128     *
17129     * @attr ref android.R.styleable#View_scrollbarFadeDuration
17130     */
17131    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
17132        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
17133    }
17134
17135    /**
17136     *
17137     * Returns the scrollbar size.
17138     *
17139     * @return the scrollbar size
17140     *
17141     * @attr ref android.R.styleable#View_scrollbarSize
17142     */
17143    public int getScrollBarSize() {
17144        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
17145                mScrollCache.scrollBarSize;
17146    }
17147
17148    /**
17149     * Define the scrollbar size.
17150     *
17151     * @param scrollBarSize - the scrollbar size
17152     *
17153     * @attr ref android.R.styleable#View_scrollbarSize
17154     */
17155    public void setScrollBarSize(int scrollBarSize) {
17156        getScrollCache().scrollBarSize = scrollBarSize;
17157    }
17158
17159    /**
17160     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
17161     * inset. When inset, they add to the padding of the view. And the scrollbars
17162     * can be drawn inside the padding area or on the edge of the view. For example,
17163     * if a view has a background drawable and you want to draw the scrollbars
17164     * inside the padding specified by the drawable, you can use
17165     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
17166     * appear at the edge of the view, ignoring the padding, then you can use
17167     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
17168     * @param style the style of the scrollbars. Should be one of
17169     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
17170     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
17171     * @see #SCROLLBARS_INSIDE_OVERLAY
17172     * @see #SCROLLBARS_INSIDE_INSET
17173     * @see #SCROLLBARS_OUTSIDE_OVERLAY
17174     * @see #SCROLLBARS_OUTSIDE_INSET
17175     *
17176     * @attr ref android.R.styleable#View_scrollbarStyle
17177     */
17178    public void setScrollBarStyle(@ScrollBarStyle int style) {
17179        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
17180            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
17181            computeOpaqueFlags();
17182            resolvePadding();
17183        }
17184    }
17185
17186    /**
17187     * <p>Returns the current scrollbar style.</p>
17188     * @return the current scrollbar style
17189     * @see #SCROLLBARS_INSIDE_OVERLAY
17190     * @see #SCROLLBARS_INSIDE_INSET
17191     * @see #SCROLLBARS_OUTSIDE_OVERLAY
17192     * @see #SCROLLBARS_OUTSIDE_INSET
17193     *
17194     * @attr ref android.R.styleable#View_scrollbarStyle
17195     */
17196    @ViewDebug.ExportedProperty(mapping = {
17197            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
17198            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
17199            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
17200            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
17201    })
17202    @ScrollBarStyle
17203    public int getScrollBarStyle() {
17204        return mViewFlags & SCROLLBARS_STYLE_MASK;
17205    }
17206
17207    /**
17208     * <p>Compute the horizontal range that the horizontal scrollbar
17209     * represents.</p>
17210     *
17211     * <p>The range is expressed in arbitrary units that must be the same as the
17212     * units used by {@link #computeHorizontalScrollExtent()} and
17213     * {@link #computeHorizontalScrollOffset()}.</p>
17214     *
17215     * <p>The default range is the drawing width of this view.</p>
17216     *
17217     * @return the total horizontal range represented by the horizontal
17218     *         scrollbar
17219     *
17220     * @see #computeHorizontalScrollExtent()
17221     * @see #computeHorizontalScrollOffset()
17222     * @see android.widget.ScrollBarDrawable
17223     */
17224    protected int computeHorizontalScrollRange() {
17225        return getWidth();
17226    }
17227
17228    /**
17229     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
17230     * within the horizontal range. This value is used to compute the position
17231     * of the thumb within the scrollbar's track.</p>
17232     *
17233     * <p>The range is expressed in arbitrary units that must be the same as the
17234     * units used by {@link #computeHorizontalScrollRange()} and
17235     * {@link #computeHorizontalScrollExtent()}.</p>
17236     *
17237     * <p>The default offset is the scroll offset of this view.</p>
17238     *
17239     * @return the horizontal offset of the scrollbar's thumb
17240     *
17241     * @see #computeHorizontalScrollRange()
17242     * @see #computeHorizontalScrollExtent()
17243     * @see android.widget.ScrollBarDrawable
17244     */
17245    protected int computeHorizontalScrollOffset() {
17246        return mScrollX;
17247    }
17248
17249    /**
17250     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
17251     * within the horizontal range. This value is used to compute the length
17252     * of the thumb within the scrollbar's track.</p>
17253     *
17254     * <p>The range is expressed in arbitrary units that must be the same as the
17255     * units used by {@link #computeHorizontalScrollRange()} and
17256     * {@link #computeHorizontalScrollOffset()}.</p>
17257     *
17258     * <p>The default extent is the drawing width of this view.</p>
17259     *
17260     * @return the horizontal extent of the scrollbar's thumb
17261     *
17262     * @see #computeHorizontalScrollRange()
17263     * @see #computeHorizontalScrollOffset()
17264     * @see android.widget.ScrollBarDrawable
17265     */
17266    protected int computeHorizontalScrollExtent() {
17267        return getWidth();
17268    }
17269
17270    /**
17271     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
17272     *
17273     * <p>The range is expressed in arbitrary units that must be the same as the
17274     * units used by {@link #computeVerticalScrollExtent()} and
17275     * {@link #computeVerticalScrollOffset()}.</p>
17276     *
17277     * @return the total vertical range represented by the vertical scrollbar
17278     *
17279     * <p>The default range is the drawing height of this view.</p>
17280     *
17281     * @see #computeVerticalScrollExtent()
17282     * @see #computeVerticalScrollOffset()
17283     * @see android.widget.ScrollBarDrawable
17284     */
17285    protected int computeVerticalScrollRange() {
17286        return getHeight();
17287    }
17288
17289    /**
17290     * <p>Compute the vertical offset of the vertical scrollbar's thumb
17291     * within the horizontal range. This value is used to compute the position
17292     * of the thumb within the scrollbar's track.</p>
17293     *
17294     * <p>The range is expressed in arbitrary units that must be the same as the
17295     * units used by {@link #computeVerticalScrollRange()} and
17296     * {@link #computeVerticalScrollExtent()}.</p>
17297     *
17298     * <p>The default offset is the scroll offset of this view.</p>
17299     *
17300     * @return the vertical offset of the scrollbar's thumb
17301     *
17302     * @see #computeVerticalScrollRange()
17303     * @see #computeVerticalScrollExtent()
17304     * @see android.widget.ScrollBarDrawable
17305     */
17306    protected int computeVerticalScrollOffset() {
17307        return mScrollY;
17308    }
17309
17310    /**
17311     * <p>Compute the vertical extent of the vertical scrollbar's thumb
17312     * within the vertical range. This value is used to compute the length
17313     * of the thumb within the scrollbar's track.</p>
17314     *
17315     * <p>The range is expressed in arbitrary units that must be the same as the
17316     * units used by {@link #computeVerticalScrollRange()} and
17317     * {@link #computeVerticalScrollOffset()}.</p>
17318     *
17319     * <p>The default extent is the drawing height of this view.</p>
17320     *
17321     * @return the vertical extent of the scrollbar's thumb
17322     *
17323     * @see #computeVerticalScrollRange()
17324     * @see #computeVerticalScrollOffset()
17325     * @see android.widget.ScrollBarDrawable
17326     */
17327    protected int computeVerticalScrollExtent() {
17328        return getHeight();
17329    }
17330
17331    /**
17332     * Check if this view can be scrolled horizontally in a certain direction.
17333     *
17334     * @param direction Negative to check scrolling left, positive to check scrolling right.
17335     * @return true if this view can be scrolled in the specified direction, false otherwise.
17336     */
17337    public boolean canScrollHorizontally(int direction) {
17338        final int offset = computeHorizontalScrollOffset();
17339        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
17340        if (range == 0) return false;
17341        if (direction < 0) {
17342            return offset > 0;
17343        } else {
17344            return offset < range - 1;
17345        }
17346    }
17347
17348    /**
17349     * Check if this view can be scrolled vertically in a certain direction.
17350     *
17351     * @param direction Negative to check scrolling up, positive to check scrolling down.
17352     * @return true if this view can be scrolled in the specified direction, false otherwise.
17353     */
17354    public boolean canScrollVertically(int direction) {
17355        final int offset = computeVerticalScrollOffset();
17356        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
17357        if (range == 0) return false;
17358        if (direction < 0) {
17359            return offset > 0;
17360        } else {
17361            return offset < range - 1;
17362        }
17363    }
17364
17365    void getScrollIndicatorBounds(@NonNull Rect out) {
17366        out.left = mScrollX;
17367        out.right = mScrollX + mRight - mLeft;
17368        out.top = mScrollY;
17369        out.bottom = mScrollY + mBottom - mTop;
17370    }
17371
17372    private void onDrawScrollIndicators(Canvas c) {
17373        if ((mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK) == 0) {
17374            // No scroll indicators enabled.
17375            return;
17376        }
17377
17378        final Drawable dr = mScrollIndicatorDrawable;
17379        if (dr == null) {
17380            // Scroll indicators aren't supported here.
17381            return;
17382        }
17383
17384        final int h = dr.getIntrinsicHeight();
17385        final int w = dr.getIntrinsicWidth();
17386        final Rect rect = mAttachInfo.mTmpInvalRect;
17387        getScrollIndicatorBounds(rect);
17388
17389        if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_TOP) != 0) {
17390            final boolean canScrollUp = canScrollVertically(-1);
17391            if (canScrollUp) {
17392                dr.setBounds(rect.left, rect.top, rect.right, rect.top + h);
17393                dr.draw(c);
17394            }
17395        }
17396
17397        if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_BOTTOM) != 0) {
17398            final boolean canScrollDown = canScrollVertically(1);
17399            if (canScrollDown) {
17400                dr.setBounds(rect.left, rect.bottom - h, rect.right, rect.bottom);
17401                dr.draw(c);
17402            }
17403        }
17404
17405        final int leftRtl;
17406        final int rightRtl;
17407        if (getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
17408            leftRtl = PFLAG3_SCROLL_INDICATOR_END;
17409            rightRtl = PFLAG3_SCROLL_INDICATOR_START;
17410        } else {
17411            leftRtl = PFLAG3_SCROLL_INDICATOR_START;
17412            rightRtl = PFLAG3_SCROLL_INDICATOR_END;
17413        }
17414
17415        final int leftMask = PFLAG3_SCROLL_INDICATOR_LEFT | leftRtl;
17416        if ((mPrivateFlags3 & leftMask) != 0) {
17417            final boolean canScrollLeft = canScrollHorizontally(-1);
17418            if (canScrollLeft) {
17419                dr.setBounds(rect.left, rect.top, rect.left + w, rect.bottom);
17420                dr.draw(c);
17421            }
17422        }
17423
17424        final int rightMask = PFLAG3_SCROLL_INDICATOR_RIGHT | rightRtl;
17425        if ((mPrivateFlags3 & rightMask) != 0) {
17426            final boolean canScrollRight = canScrollHorizontally(1);
17427            if (canScrollRight) {
17428                dr.setBounds(rect.right - w, rect.top, rect.right, rect.bottom);
17429                dr.draw(c);
17430            }
17431        }
17432    }
17433
17434    private void getHorizontalScrollBarBounds(@Nullable Rect drawBounds,
17435            @Nullable Rect touchBounds) {
17436        final Rect bounds = drawBounds != null ? drawBounds : touchBounds;
17437        if (bounds == null) {
17438            return;
17439        }
17440        final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
17441        final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled()
17442                && !isVerticalScrollBarHidden();
17443        final int size = getHorizontalScrollbarHeight();
17444        final int verticalScrollBarGap = drawVerticalScrollBar ?
17445                getVerticalScrollbarWidth() : 0;
17446        final int width = mRight - mLeft;
17447        final int height = mBottom - mTop;
17448        bounds.top = mScrollY + height - size - (mUserPaddingBottom & inside);
17449        bounds.left = mScrollX + (mPaddingLeft & inside);
17450        bounds.right = mScrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
17451        bounds.bottom = bounds.top + size;
17452
17453        if (touchBounds == null) {
17454            return;
17455        }
17456        if (touchBounds != bounds) {
17457            touchBounds.set(bounds);
17458        }
17459        final int minTouchTarget = mScrollCache.scrollBarMinTouchTarget;
17460        if (touchBounds.height() < minTouchTarget) {
17461            final int adjust = (minTouchTarget - touchBounds.height()) / 2;
17462            touchBounds.bottom = Math.min(touchBounds.bottom + adjust, mScrollY + height);
17463            touchBounds.top = touchBounds.bottom - minTouchTarget;
17464        }
17465        if (touchBounds.width() < minTouchTarget) {
17466            final int adjust = (minTouchTarget - touchBounds.width()) / 2;
17467            touchBounds.left -= adjust;
17468            touchBounds.right = touchBounds.left + minTouchTarget;
17469        }
17470    }
17471
17472    private void getVerticalScrollBarBounds(@Nullable Rect bounds, @Nullable Rect touchBounds) {
17473        if (mRoundScrollbarRenderer == null) {
17474            getStraightVerticalScrollBarBounds(bounds, touchBounds);
17475        } else {
17476            getRoundVerticalScrollBarBounds(bounds != null ? bounds : touchBounds);
17477        }
17478    }
17479
17480    private void getRoundVerticalScrollBarBounds(Rect bounds) {
17481        final int width = mRight - mLeft;
17482        final int height = mBottom - mTop;
17483        // Do not take padding into account as we always want the scrollbars
17484        // to hug the screen for round wearable devices.
17485        bounds.left = mScrollX;
17486        bounds.top = mScrollY;
17487        bounds.right = bounds.left + width;
17488        bounds.bottom = mScrollY + height;
17489    }
17490
17491    private void getStraightVerticalScrollBarBounds(@Nullable Rect drawBounds,
17492            @Nullable Rect touchBounds) {
17493        final Rect bounds = drawBounds != null ? drawBounds : touchBounds;
17494        if (bounds == null) {
17495            return;
17496        }
17497        final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
17498        final int size = getVerticalScrollbarWidth();
17499        int verticalScrollbarPosition = mVerticalScrollbarPosition;
17500        if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
17501            verticalScrollbarPosition = isLayoutRtl() ?
17502                    SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
17503        }
17504        final int width = mRight - mLeft;
17505        final int height = mBottom - mTop;
17506        switch (verticalScrollbarPosition) {
17507            default:
17508            case SCROLLBAR_POSITION_RIGHT:
17509                bounds.left = mScrollX + width - size - (mUserPaddingRight & inside);
17510                break;
17511            case SCROLLBAR_POSITION_LEFT:
17512                bounds.left = mScrollX + (mUserPaddingLeft & inside);
17513                break;
17514        }
17515        bounds.top = mScrollY + (mPaddingTop & inside);
17516        bounds.right = bounds.left + size;
17517        bounds.bottom = mScrollY + height - (mUserPaddingBottom & inside);
17518
17519        if (touchBounds == null) {
17520            return;
17521        }
17522        if (touchBounds != bounds) {
17523            touchBounds.set(bounds);
17524        }
17525        final int minTouchTarget = mScrollCache.scrollBarMinTouchTarget;
17526        if (touchBounds.width() < minTouchTarget) {
17527            final int adjust = (minTouchTarget - touchBounds.width()) / 2;
17528            if (verticalScrollbarPosition == SCROLLBAR_POSITION_RIGHT) {
17529                touchBounds.right = Math.min(touchBounds.right + adjust, mScrollX + width);
17530                touchBounds.left = touchBounds.right - minTouchTarget;
17531            } else {
17532                touchBounds.left = Math.max(touchBounds.left + adjust, mScrollX);
17533                touchBounds.right = touchBounds.left + minTouchTarget;
17534            }
17535        }
17536        if (touchBounds.height() < minTouchTarget) {
17537            final int adjust = (minTouchTarget - touchBounds.height()) / 2;
17538            touchBounds.top -= adjust;
17539            touchBounds.bottom = touchBounds.top + minTouchTarget;
17540        }
17541    }
17542
17543    /**
17544     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
17545     * scrollbars are painted only if they have been awakened first.</p>
17546     *
17547     * @param canvas the canvas on which to draw the scrollbars
17548     *
17549     * @see #awakenScrollBars(int)
17550     */
17551    protected final void onDrawScrollBars(Canvas canvas) {
17552        // scrollbars are drawn only when the animation is running
17553        final ScrollabilityCache cache = mScrollCache;
17554
17555        if (cache != null) {
17556
17557            int state = cache.state;
17558
17559            if (state == ScrollabilityCache.OFF) {
17560                return;
17561            }
17562
17563            boolean invalidate = false;
17564
17565            if (state == ScrollabilityCache.FADING) {
17566                // We're fading -- get our fade interpolation
17567                if (cache.interpolatorValues == null) {
17568                    cache.interpolatorValues = new float[1];
17569                }
17570
17571                float[] values = cache.interpolatorValues;
17572
17573                // Stops the animation if we're done
17574                if (cache.scrollBarInterpolator.timeToValues(values) ==
17575                        Interpolator.Result.FREEZE_END) {
17576                    cache.state = ScrollabilityCache.OFF;
17577                } else {
17578                    cache.scrollBar.mutate().setAlpha(Math.round(values[0]));
17579                }
17580
17581                // This will make the scroll bars inval themselves after
17582                // drawing. We only want this when we're fading so that
17583                // we prevent excessive redraws
17584                invalidate = true;
17585            } else {
17586                // We're just on -- but we may have been fading before so
17587                // reset alpha
17588                cache.scrollBar.mutate().setAlpha(255);
17589            }
17590
17591            final boolean drawHorizontalScrollBar = isHorizontalScrollBarEnabled();
17592            final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled()
17593                    && !isVerticalScrollBarHidden();
17594
17595            // Fork out the scroll bar drawing for round wearable devices.
17596            if (mRoundScrollbarRenderer != null) {
17597                if (drawVerticalScrollBar) {
17598                    final Rect bounds = cache.mScrollBarBounds;
17599                    getVerticalScrollBarBounds(bounds, null);
17600                    mRoundScrollbarRenderer.drawRoundScrollbars(
17601                            canvas, (float) cache.scrollBar.getAlpha() / 255f, bounds);
17602                    if (invalidate) {
17603                        invalidate();
17604                    }
17605                }
17606                // Do not draw horizontal scroll bars for round wearable devices.
17607            } else if (drawVerticalScrollBar || drawHorizontalScrollBar) {
17608                final ScrollBarDrawable scrollBar = cache.scrollBar;
17609
17610                if (drawHorizontalScrollBar) {
17611                    scrollBar.setParameters(computeHorizontalScrollRange(),
17612                            computeHorizontalScrollOffset(),
17613                            computeHorizontalScrollExtent(), false);
17614                    final Rect bounds = cache.mScrollBarBounds;
17615                    getHorizontalScrollBarBounds(bounds, null);
17616                    onDrawHorizontalScrollBar(canvas, scrollBar, bounds.left, bounds.top,
17617                            bounds.right, bounds.bottom);
17618                    if (invalidate) {
17619                        invalidate(bounds);
17620                    }
17621                }
17622
17623                if (drawVerticalScrollBar) {
17624                    scrollBar.setParameters(computeVerticalScrollRange(),
17625                            computeVerticalScrollOffset(),
17626                            computeVerticalScrollExtent(), true);
17627                    final Rect bounds = cache.mScrollBarBounds;
17628                    getVerticalScrollBarBounds(bounds, null);
17629                    onDrawVerticalScrollBar(canvas, scrollBar, bounds.left, bounds.top,
17630                            bounds.right, bounds.bottom);
17631                    if (invalidate) {
17632                        invalidate(bounds);
17633                    }
17634                }
17635            }
17636        }
17637    }
17638
17639    /**
17640     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
17641     * FastScroller is visible.
17642     * @return whether to temporarily hide the vertical scrollbar
17643     * @hide
17644     */
17645    protected boolean isVerticalScrollBarHidden() {
17646        return false;
17647    }
17648
17649    /**
17650     * <p>Draw the horizontal scrollbar if
17651     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
17652     *
17653     * @param canvas the canvas on which to draw the scrollbar
17654     * @param scrollBar the scrollbar's drawable
17655     *
17656     * @see #isHorizontalScrollBarEnabled()
17657     * @see #computeHorizontalScrollRange()
17658     * @see #computeHorizontalScrollExtent()
17659     * @see #computeHorizontalScrollOffset()
17660     * @see android.widget.ScrollBarDrawable
17661     * @hide
17662     */
17663    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
17664            int l, int t, int r, int b) {
17665        scrollBar.setBounds(l, t, r, b);
17666        scrollBar.draw(canvas);
17667    }
17668
17669    /**
17670     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
17671     * returns true.</p>
17672     *
17673     * @param canvas the canvas on which to draw the scrollbar
17674     * @param scrollBar the scrollbar's drawable
17675     *
17676     * @see #isVerticalScrollBarEnabled()
17677     * @see #computeVerticalScrollRange()
17678     * @see #computeVerticalScrollExtent()
17679     * @see #computeVerticalScrollOffset()
17680     * @see android.widget.ScrollBarDrawable
17681     * @hide
17682     */
17683    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
17684            int l, int t, int r, int b) {
17685        scrollBar.setBounds(l, t, r, b);
17686        scrollBar.draw(canvas);
17687    }
17688
17689    /**
17690     * Implement this to do your drawing.
17691     *
17692     * @param canvas the canvas on which the background will be drawn
17693     */
17694    protected void onDraw(Canvas canvas) {
17695    }
17696
17697    /*
17698     * Caller is responsible for calling requestLayout if necessary.
17699     * (This allows addViewInLayout to not request a new layout.)
17700     */
17701    void assignParent(ViewParent parent) {
17702        if (mParent == null) {
17703            mParent = parent;
17704        } else if (parent == null) {
17705            mParent = null;
17706        } else {
17707            throw new RuntimeException("view " + this + " being added, but"
17708                    + " it already has a parent");
17709        }
17710    }
17711
17712    /**
17713     * This is called when the view is attached to a window.  At this point it
17714     * has a Surface and will start drawing.  Note that this function is
17715     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
17716     * however it may be called any time before the first onDraw -- including
17717     * before or after {@link #onMeasure(int, int)}.
17718     *
17719     * @see #onDetachedFromWindow()
17720     */
17721    @CallSuper
17722    protected void onAttachedToWindow() {
17723        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
17724            mParent.requestTransparentRegion(this);
17725        }
17726
17727        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
17728
17729        jumpDrawablesToCurrentState();
17730
17731        resetSubtreeAccessibilityStateChanged();
17732
17733        // rebuild, since Outline not maintained while View is detached
17734        rebuildOutline();
17735
17736        if (isFocused()) {
17737            InputMethodManager imm = InputMethodManager.peekInstance();
17738            if (imm != null) {
17739                imm.focusIn(this);
17740            }
17741        }
17742    }
17743
17744    /**
17745     * Resolve all RTL related properties.
17746     *
17747     * @return true if resolution of RTL properties has been done
17748     *
17749     * @hide
17750     */
17751    public boolean resolveRtlPropertiesIfNeeded() {
17752        if (!needRtlPropertiesResolution()) return false;
17753
17754        // Order is important here: LayoutDirection MUST be resolved first
17755        if (!isLayoutDirectionResolved()) {
17756            resolveLayoutDirection();
17757            resolveLayoutParams();
17758        }
17759        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
17760        if (!isTextDirectionResolved()) {
17761            resolveTextDirection();
17762        }
17763        if (!isTextAlignmentResolved()) {
17764            resolveTextAlignment();
17765        }
17766        // Should resolve Drawables before Padding because we need the layout direction of the
17767        // Drawable to correctly resolve Padding.
17768        if (!areDrawablesResolved()) {
17769            resolveDrawables();
17770        }
17771        if (!isPaddingResolved()) {
17772            resolvePadding();
17773        }
17774        onRtlPropertiesChanged(getLayoutDirection());
17775        return true;
17776    }
17777
17778    /**
17779     * Reset resolution of all RTL related properties.
17780     *
17781     * @hide
17782     */
17783    public void resetRtlProperties() {
17784        resetResolvedLayoutDirection();
17785        resetResolvedTextDirection();
17786        resetResolvedTextAlignment();
17787        resetResolvedPadding();
17788        resetResolvedDrawables();
17789    }
17790
17791    /**
17792     * @see #onScreenStateChanged(int)
17793     */
17794    void dispatchScreenStateChanged(int screenState) {
17795        onScreenStateChanged(screenState);
17796    }
17797
17798    /**
17799     * This method is called whenever the state of the screen this view is
17800     * attached to changes. A state change will usually occurs when the screen
17801     * turns on or off (whether it happens automatically or the user does it
17802     * manually.)
17803     *
17804     * @param screenState The new state of the screen. Can be either
17805     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
17806     */
17807    public void onScreenStateChanged(int screenState) {
17808    }
17809
17810    /**
17811     * @see #onMovedToDisplay(int, Configuration)
17812     */
17813    void dispatchMovedToDisplay(Display display, Configuration config) {
17814        mAttachInfo.mDisplay = display;
17815        mAttachInfo.mDisplayState = display.getState();
17816        onMovedToDisplay(display.getDisplayId(), config);
17817    }
17818
17819    /**
17820     * Called by the system when the hosting activity is moved from one display to another without
17821     * recreation. This means that the activity is declared to handle all changes to configuration
17822     * that happened when it was switched to another display, so it wasn't destroyed and created
17823     * again.
17824     *
17825     * <p>This call will be followed by {@link #onConfigurationChanged(Configuration)} if the
17826     * applied configuration actually changed. It is up to app developer to choose whether to handle
17827     * the change in this method or in the following {@link #onConfigurationChanged(Configuration)}
17828     * call.
17829     *
17830     * <p>Use this callback to track changes to the displays if some functionality relies on an
17831     * association with some display properties.
17832     *
17833     * @param displayId The id of the display to which the view was moved.
17834     * @param config Configuration of the resources on new display after move.
17835     *
17836     * @see #onConfigurationChanged(Configuration)
17837     * @hide
17838     */
17839    public void onMovedToDisplay(int displayId, Configuration config) {
17840    }
17841
17842    /**
17843     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
17844     */
17845    private boolean hasRtlSupport() {
17846        return mContext.getApplicationInfo().hasRtlSupport();
17847    }
17848
17849    /**
17850     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
17851     * RTL not supported)
17852     */
17853    private boolean isRtlCompatibilityMode() {
17854        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
17855        return targetSdkVersion < Build.VERSION_CODES.JELLY_BEAN_MR1 || !hasRtlSupport();
17856    }
17857
17858    /**
17859     * @return true if RTL properties need resolution.
17860     *
17861     */
17862    private boolean needRtlPropertiesResolution() {
17863        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
17864    }
17865
17866    /**
17867     * Called when any RTL property (layout direction or text direction or text alignment) has
17868     * been changed.
17869     *
17870     * Subclasses need to override this method to take care of cached information that depends on the
17871     * resolved layout direction, or to inform child views that inherit their layout direction.
17872     *
17873     * The default implementation does nothing.
17874     *
17875     * @param layoutDirection the direction of the layout
17876     *
17877     * @see #LAYOUT_DIRECTION_LTR
17878     * @see #LAYOUT_DIRECTION_RTL
17879     */
17880    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
17881    }
17882
17883    /**
17884     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
17885     * that the parent directionality can and will be resolved before its children.
17886     *
17887     * @return true if resolution has been done, false otherwise.
17888     *
17889     * @hide
17890     */
17891    public boolean resolveLayoutDirection() {
17892        // Clear any previous layout direction resolution
17893        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
17894
17895        if (hasRtlSupport()) {
17896            // Set resolved depending on layout direction
17897            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
17898                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
17899                case LAYOUT_DIRECTION_INHERIT:
17900                    // We cannot resolve yet. LTR is by default and let the resolution happen again
17901                    // later to get the correct resolved value
17902                    if (!canResolveLayoutDirection()) return false;
17903
17904                    // Parent has not yet resolved, LTR is still the default
17905                    try {
17906                        if (!mParent.isLayoutDirectionResolved()) return false;
17907
17908                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
17909                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
17910                        }
17911                    } catch (AbstractMethodError e) {
17912                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17913                                " does not fully implement ViewParent", e);
17914                    }
17915                    break;
17916                case LAYOUT_DIRECTION_RTL:
17917                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
17918                    break;
17919                case LAYOUT_DIRECTION_LOCALE:
17920                    if((LAYOUT_DIRECTION_RTL ==
17921                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
17922                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
17923                    }
17924                    break;
17925                default:
17926                    // Nothing to do, LTR by default
17927            }
17928        }
17929
17930        // Set to resolved
17931        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
17932        return true;
17933    }
17934
17935    /**
17936     * Check if layout direction resolution can be done.
17937     *
17938     * @return true if layout direction resolution can be done otherwise return false.
17939     */
17940    public boolean canResolveLayoutDirection() {
17941        switch (getRawLayoutDirection()) {
17942            case LAYOUT_DIRECTION_INHERIT:
17943                if (mParent != null) {
17944                    try {
17945                        return mParent.canResolveLayoutDirection();
17946                    } catch (AbstractMethodError e) {
17947                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17948                                " does not fully implement ViewParent", e);
17949                    }
17950                }
17951                return false;
17952
17953            default:
17954                return true;
17955        }
17956    }
17957
17958    /**
17959     * Reset the resolved layout direction. Layout direction will be resolved during a call to
17960     * {@link #onMeasure(int, int)}.
17961     *
17962     * @hide
17963     */
17964    public void resetResolvedLayoutDirection() {
17965        // Reset the current resolved bits
17966        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
17967    }
17968
17969    /**
17970     * @return true if the layout direction is inherited.
17971     *
17972     * @hide
17973     */
17974    public boolean isLayoutDirectionInherited() {
17975        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
17976    }
17977
17978    /**
17979     * @return true if layout direction has been resolved.
17980     */
17981    public boolean isLayoutDirectionResolved() {
17982        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
17983    }
17984
17985    /**
17986     * Return if padding has been resolved
17987     *
17988     * @hide
17989     */
17990    boolean isPaddingResolved() {
17991        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
17992    }
17993
17994    /**
17995     * Resolves padding depending on layout direction, if applicable, and
17996     * recomputes internal padding values to adjust for scroll bars.
17997     *
17998     * @hide
17999     */
18000    public void resolvePadding() {
18001        final int resolvedLayoutDirection = getLayoutDirection();
18002
18003        if (!isRtlCompatibilityMode()) {
18004            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
18005            // If start / end padding are defined, they will be resolved (hence overriding) to
18006            // left / right or right / left depending on the resolved layout direction.
18007            // If start / end padding are not defined, use the left / right ones.
18008            if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
18009                Rect padding = sThreadLocal.get();
18010                if (padding == null) {
18011                    padding = new Rect();
18012                    sThreadLocal.set(padding);
18013                }
18014                mBackground.getPadding(padding);
18015                if (!mLeftPaddingDefined) {
18016                    mUserPaddingLeftInitial = padding.left;
18017                }
18018                if (!mRightPaddingDefined) {
18019                    mUserPaddingRightInitial = padding.right;
18020                }
18021            }
18022            switch (resolvedLayoutDirection) {
18023                case LAYOUT_DIRECTION_RTL:
18024                    if (mUserPaddingStart != UNDEFINED_PADDING) {
18025                        mUserPaddingRight = mUserPaddingStart;
18026                    } else {
18027                        mUserPaddingRight = mUserPaddingRightInitial;
18028                    }
18029                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
18030                        mUserPaddingLeft = mUserPaddingEnd;
18031                    } else {
18032                        mUserPaddingLeft = mUserPaddingLeftInitial;
18033                    }
18034                    break;
18035                case LAYOUT_DIRECTION_LTR:
18036                default:
18037                    if (mUserPaddingStart != UNDEFINED_PADDING) {
18038                        mUserPaddingLeft = mUserPaddingStart;
18039                    } else {
18040                        mUserPaddingLeft = mUserPaddingLeftInitial;
18041                    }
18042                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
18043                        mUserPaddingRight = mUserPaddingEnd;
18044                    } else {
18045                        mUserPaddingRight = mUserPaddingRightInitial;
18046                    }
18047            }
18048
18049            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
18050        }
18051
18052        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
18053        onRtlPropertiesChanged(resolvedLayoutDirection);
18054
18055        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
18056    }
18057
18058    /**
18059     * Reset the resolved layout direction.
18060     *
18061     * @hide
18062     */
18063    public void resetResolvedPadding() {
18064        resetResolvedPaddingInternal();
18065    }
18066
18067    /**
18068     * Used when we only want to reset *this* view's padding and not trigger overrides
18069     * in ViewGroup that reset children too.
18070     */
18071    void resetResolvedPaddingInternal() {
18072        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
18073    }
18074
18075    /**
18076     * This is called when the view is detached from a window.  At this point it
18077     * no longer has a surface for drawing.
18078     *
18079     * @see #onAttachedToWindow()
18080     */
18081    @CallSuper
18082    protected void onDetachedFromWindow() {
18083    }
18084
18085    /**
18086     * This is a framework-internal mirror of onDetachedFromWindow() that's called
18087     * after onDetachedFromWindow().
18088     *
18089     * If you override this you *MUST* call super.onDetachedFromWindowInternal()!
18090     * The super method should be called at the end of the overridden method to ensure
18091     * subclasses are destroyed first
18092     *
18093     * @hide
18094     */
18095    @CallSuper
18096    protected void onDetachedFromWindowInternal() {
18097        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
18098        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
18099        mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH;
18100
18101        removeUnsetPressCallback();
18102        removeLongPressCallback();
18103        removePerformClickCallback();
18104        cancel(mSendViewScrolledAccessibilityEvent);
18105        stopNestedScroll();
18106
18107        // Anything that started animating right before detach should already
18108        // be in its final state when re-attached.
18109        jumpDrawablesToCurrentState();
18110
18111        destroyDrawingCache();
18112
18113        cleanupDraw();
18114        mCurrentAnimation = null;
18115
18116        if ((mViewFlags & TOOLTIP) == TOOLTIP) {
18117            hideTooltip();
18118        }
18119    }
18120
18121    private void cleanupDraw() {
18122        resetDisplayList();
18123        if (mAttachInfo != null) {
18124            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
18125        }
18126    }
18127
18128    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
18129    }
18130
18131    /**
18132     * @return The number of times this view has been attached to a window
18133     */
18134    protected int getWindowAttachCount() {
18135        return mWindowAttachCount;
18136    }
18137
18138    /**
18139     * Retrieve a unique token identifying the window this view is attached to.
18140     * @return Return the window's token for use in
18141     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
18142     */
18143    public IBinder getWindowToken() {
18144        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
18145    }
18146
18147    /**
18148     * Retrieve the {@link WindowId} for the window this view is
18149     * currently attached to.
18150     */
18151    public WindowId getWindowId() {
18152        AttachInfo ai = mAttachInfo;
18153        if (ai == null) {
18154            return null;
18155        }
18156        if (ai.mWindowId == null) {
18157            try {
18158                ai.mIWindowId = ai.mSession.getWindowId(ai.mWindowToken);
18159                if (ai.mIWindowId != null) {
18160                    ai.mWindowId = new WindowId(ai.mIWindowId);
18161                }
18162            } catch (RemoteException e) {
18163            }
18164        }
18165        return ai.mWindowId;
18166    }
18167
18168    /**
18169     * Retrieve a unique token identifying the top-level "real" window of
18170     * the window that this view is attached to.  That is, this is like
18171     * {@link #getWindowToken}, except if the window this view in is a panel
18172     * window (attached to another containing window), then the token of
18173     * the containing window is returned instead.
18174     *
18175     * @return Returns the associated window token, either
18176     * {@link #getWindowToken()} or the containing window's token.
18177     */
18178    public IBinder getApplicationWindowToken() {
18179        AttachInfo ai = mAttachInfo;
18180        if (ai != null) {
18181            IBinder appWindowToken = ai.mPanelParentWindowToken;
18182            if (appWindowToken == null) {
18183                appWindowToken = ai.mWindowToken;
18184            }
18185            return appWindowToken;
18186        }
18187        return null;
18188    }
18189
18190    /**
18191     * Gets the logical display to which the view's window has been attached.
18192     *
18193     * @return The logical display, or null if the view is not currently attached to a window.
18194     */
18195    public Display getDisplay() {
18196        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
18197    }
18198
18199    /**
18200     * Retrieve private session object this view hierarchy is using to
18201     * communicate with the window manager.
18202     * @return the session object to communicate with the window manager
18203     */
18204    /*package*/ IWindowSession getWindowSession() {
18205        return mAttachInfo != null ? mAttachInfo.mSession : null;
18206    }
18207
18208    /**
18209     * Return the window this view is currently attached to. Used in
18210     * {@link android.app.ActivityView} to communicate with WM.
18211     * @hide
18212     */
18213    protected IWindow getWindow() {
18214        return mAttachInfo != null ? mAttachInfo.mWindow : null;
18215    }
18216
18217    /**
18218     * Return the visibility value of the least visible component passed.
18219     */
18220    int combineVisibility(int vis1, int vis2) {
18221        // This works because VISIBLE < INVISIBLE < GONE.
18222        return Math.max(vis1, vis2);
18223    }
18224
18225    /**
18226     * @param info the {@link android.view.View.AttachInfo} to associated with
18227     *        this view
18228     */
18229    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
18230        mAttachInfo = info;
18231        if (mOverlay != null) {
18232            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
18233        }
18234        mWindowAttachCount++;
18235        // We will need to evaluate the drawable state at least once.
18236        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
18237        if (mFloatingTreeObserver != null) {
18238            info.mTreeObserver.merge(mFloatingTreeObserver);
18239            mFloatingTreeObserver = null;
18240        }
18241
18242        registerPendingFrameMetricsObservers();
18243
18244        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
18245            mAttachInfo.mScrollContainers.add(this);
18246            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
18247        }
18248        // Transfer all pending runnables.
18249        if (mRunQueue != null) {
18250            mRunQueue.executeActions(info.mHandler);
18251            mRunQueue = null;
18252        }
18253        performCollectViewAttributes(mAttachInfo, visibility);
18254        onAttachedToWindow();
18255
18256        ListenerInfo li = mListenerInfo;
18257        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
18258                li != null ? li.mOnAttachStateChangeListeners : null;
18259        if (listeners != null && listeners.size() > 0) {
18260            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
18261            // perform the dispatching. The iterator is a safe guard against listeners that
18262            // could mutate the list by calling the various add/remove methods. This prevents
18263            // the array from being modified while we iterate it.
18264            for (OnAttachStateChangeListener listener : listeners) {
18265                listener.onViewAttachedToWindow(this);
18266            }
18267        }
18268
18269        int vis = info.mWindowVisibility;
18270        if (vis != GONE) {
18271            onWindowVisibilityChanged(vis);
18272            if (isShown()) {
18273                // Calling onVisibilityAggregated directly here since the subtree will also
18274                // receive dispatchAttachedToWindow and this same call
18275                onVisibilityAggregated(vis == VISIBLE);
18276            }
18277        }
18278
18279        // Send onVisibilityChanged directly instead of dispatchVisibilityChanged.
18280        // As all views in the subtree will already receive dispatchAttachedToWindow
18281        // traversing the subtree again here is not desired.
18282        onVisibilityChanged(this, visibility);
18283
18284        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
18285            // If nobody has evaluated the drawable state yet, then do it now.
18286            refreshDrawableState();
18287        }
18288        needGlobalAttributesUpdate(false);
18289
18290        notifyEnterOrExitForAutoFillIfNeeded(true);
18291    }
18292
18293    void dispatchDetachedFromWindow() {
18294        AttachInfo info = mAttachInfo;
18295        if (info != null) {
18296            int vis = info.mWindowVisibility;
18297            if (vis != GONE) {
18298                onWindowVisibilityChanged(GONE);
18299                if (isShown()) {
18300                    // Invoking onVisibilityAggregated directly here since the subtree
18301                    // will also receive detached from window
18302                    onVisibilityAggregated(false);
18303                }
18304            }
18305        }
18306
18307        onDetachedFromWindow();
18308        onDetachedFromWindowInternal();
18309
18310        InputMethodManager imm = InputMethodManager.peekInstance();
18311        if (imm != null) {
18312            imm.onViewDetachedFromWindow(this);
18313        }
18314
18315        ListenerInfo li = mListenerInfo;
18316        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
18317                li != null ? li.mOnAttachStateChangeListeners : null;
18318        if (listeners != null && listeners.size() > 0) {
18319            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
18320            // perform the dispatching. The iterator is a safe guard against listeners that
18321            // could mutate the list by calling the various add/remove methods. This prevents
18322            // the array from being modified while we iterate it.
18323            for (OnAttachStateChangeListener listener : listeners) {
18324                listener.onViewDetachedFromWindow(this);
18325            }
18326        }
18327
18328        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
18329            mAttachInfo.mScrollContainers.remove(this);
18330            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
18331        }
18332
18333        mAttachInfo = null;
18334        if (mOverlay != null) {
18335            mOverlay.getOverlayView().dispatchDetachedFromWindow();
18336        }
18337
18338        notifyEnterOrExitForAutoFillIfNeeded(false);
18339    }
18340
18341    /**
18342     * Cancel any deferred high-level input events that were previously posted to the event queue.
18343     *
18344     * <p>Many views post high-level events such as click handlers to the event queue
18345     * to run deferred in order to preserve a desired user experience - clearing visible
18346     * pressed states before executing, etc. This method will abort any events of this nature
18347     * that are currently in flight.</p>
18348     *
18349     * <p>Custom views that generate their own high-level deferred input events should override
18350     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
18351     *
18352     * <p>This will also cancel pending input events for any child views.</p>
18353     *
18354     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
18355     * This will not impact newer events posted after this call that may occur as a result of
18356     * lower-level input events still waiting in the queue. If you are trying to prevent
18357     * double-submitted  events for the duration of some sort of asynchronous transaction
18358     * you should also take other steps to protect against unexpected double inputs e.g. calling
18359     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
18360     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
18361     */
18362    public final void cancelPendingInputEvents() {
18363        dispatchCancelPendingInputEvents();
18364    }
18365
18366    /**
18367     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
18368     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
18369     */
18370    void dispatchCancelPendingInputEvents() {
18371        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
18372        onCancelPendingInputEvents();
18373        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
18374            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
18375                    " did not call through to super.onCancelPendingInputEvents()");
18376        }
18377    }
18378
18379    /**
18380     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
18381     * a parent view.
18382     *
18383     * <p>This method is responsible for removing any pending high-level input events that were
18384     * posted to the event queue to run later. Custom view classes that post their own deferred
18385     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
18386     * {@link android.os.Handler} should override this method, call
18387     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
18388     * </p>
18389     */
18390    public void onCancelPendingInputEvents() {
18391        removePerformClickCallback();
18392        cancelLongPress();
18393        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
18394    }
18395
18396    /**
18397     * Store this view hierarchy's frozen state into the given container.
18398     *
18399     * @param container The SparseArray in which to save the view's state.
18400     *
18401     * @see #restoreHierarchyState(android.util.SparseArray)
18402     * @see #dispatchSaveInstanceState(android.util.SparseArray)
18403     * @see #onSaveInstanceState()
18404     */
18405    public void saveHierarchyState(SparseArray<Parcelable> container) {
18406        dispatchSaveInstanceState(container);
18407    }
18408
18409    /**
18410     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
18411     * this view and its children. May be overridden to modify how freezing happens to a
18412     * view's children; for example, some views may want to not store state for their children.
18413     *
18414     * @param container The SparseArray in which to save the view's state.
18415     *
18416     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
18417     * @see #saveHierarchyState(android.util.SparseArray)
18418     * @see #onSaveInstanceState()
18419     */
18420    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
18421        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
18422            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
18423            Parcelable state = onSaveInstanceState();
18424            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
18425                throw new IllegalStateException(
18426                        "Derived class did not call super.onSaveInstanceState()");
18427            }
18428            if (state != null) {
18429                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
18430                // + ": " + state);
18431                container.put(mID, state);
18432            }
18433        }
18434    }
18435
18436    /**
18437     * Hook allowing a view to generate a representation of its internal state
18438     * that can later be used to create a new instance with that same state.
18439     * This state should only contain information that is not persistent or can
18440     * not be reconstructed later. For example, you will never store your
18441     * current position on screen because that will be computed again when a
18442     * new instance of the view is placed in its view hierarchy.
18443     * <p>
18444     * Some examples of things you may store here: the current cursor position
18445     * in a text view (but usually not the text itself since that is stored in a
18446     * content provider or other persistent storage), the currently selected
18447     * item in a list view.
18448     *
18449     * @return Returns a Parcelable object containing the view's current dynamic
18450     *         state, or null if there is nothing interesting to save.
18451     * @see #onRestoreInstanceState(Parcelable)
18452     * @see #saveHierarchyState(SparseArray)
18453     * @see #dispatchSaveInstanceState(SparseArray)
18454     * @see #setSaveEnabled(boolean)
18455     */
18456    @CallSuper
18457    @Nullable protected Parcelable onSaveInstanceState() {
18458        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
18459        if (mStartActivityRequestWho != null || isAutofilled()
18460                || mAutofillViewId > LAST_APP_AUTOFILL_ID) {
18461            BaseSavedState state = new BaseSavedState(AbsSavedState.EMPTY_STATE);
18462
18463            if (mStartActivityRequestWho != null) {
18464                state.mSavedData |= BaseSavedState.START_ACTIVITY_REQUESTED_WHO_SAVED;
18465            }
18466
18467            if (isAutofilled()) {
18468                state.mSavedData |= BaseSavedState.IS_AUTOFILLED;
18469            }
18470
18471            if (mAutofillViewId > LAST_APP_AUTOFILL_ID) {
18472                state.mSavedData |= BaseSavedState.AUTOFILL_ID;
18473            }
18474
18475            state.mStartActivityRequestWhoSaved = mStartActivityRequestWho;
18476            state.mIsAutofilled = isAutofilled();
18477            state.mAutofillViewId = mAutofillViewId;
18478            return state;
18479        }
18480        return BaseSavedState.EMPTY_STATE;
18481    }
18482
18483    /**
18484     * Restore this view hierarchy's frozen state from the given container.
18485     *
18486     * @param container The SparseArray which holds previously frozen states.
18487     *
18488     * @see #saveHierarchyState(android.util.SparseArray)
18489     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
18490     * @see #onRestoreInstanceState(android.os.Parcelable)
18491     */
18492    public void restoreHierarchyState(SparseArray<Parcelable> container) {
18493        dispatchRestoreInstanceState(container);
18494    }
18495
18496    /**
18497     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
18498     * state for this view and its children. May be overridden to modify how restoring
18499     * happens to a view's children; for example, some views may want to not store state
18500     * for their children.
18501     *
18502     * @param container The SparseArray which holds previously saved state.
18503     *
18504     * @see #dispatchSaveInstanceState(android.util.SparseArray)
18505     * @see #restoreHierarchyState(android.util.SparseArray)
18506     * @see #onRestoreInstanceState(android.os.Parcelable)
18507     */
18508    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
18509        if (mID != NO_ID) {
18510            Parcelable state = container.get(mID);
18511            if (state != null) {
18512                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
18513                // + ": " + state);
18514                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
18515                onRestoreInstanceState(state);
18516                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
18517                    throw new IllegalStateException(
18518                            "Derived class did not call super.onRestoreInstanceState()");
18519                }
18520            }
18521        }
18522    }
18523
18524    /**
18525     * Hook allowing a view to re-apply a representation of its internal state that had previously
18526     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
18527     * null state.
18528     *
18529     * @param state The frozen state that had previously been returned by
18530     *        {@link #onSaveInstanceState}.
18531     *
18532     * @see #onSaveInstanceState()
18533     * @see #restoreHierarchyState(android.util.SparseArray)
18534     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
18535     */
18536    @CallSuper
18537    protected void onRestoreInstanceState(Parcelable state) {
18538        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
18539        if (state != null && !(state instanceof AbsSavedState)) {
18540            throw new IllegalArgumentException("Wrong state class, expecting View State but "
18541                    + "received " + state.getClass().toString() + " instead. This usually happens "
18542                    + "when two views of different type have the same id in the same hierarchy. "
18543                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
18544                    + "other views do not use the same id.");
18545        }
18546        if (state != null && state instanceof BaseSavedState) {
18547            BaseSavedState baseState = (BaseSavedState) state;
18548
18549            if ((baseState.mSavedData & BaseSavedState.START_ACTIVITY_REQUESTED_WHO_SAVED) != 0) {
18550                mStartActivityRequestWho = baseState.mStartActivityRequestWhoSaved;
18551            }
18552            if ((baseState.mSavedData & BaseSavedState.IS_AUTOFILLED) != 0) {
18553                setAutofilled(baseState.mIsAutofilled);
18554            }
18555            if ((baseState.mSavedData & BaseSavedState.AUTOFILL_ID) != 0) {
18556                // It can happen that views have the same view id and the restoration path will not
18557                // be able to distinguish between them. The autofill id needs to be unique though.
18558                // Hence prevent the same autofill view id from being restored multiple times.
18559                ((BaseSavedState) state).mSavedData &= ~BaseSavedState.AUTOFILL_ID;
18560
18561                if ((mPrivateFlags3 & PFLAG3_AUTOFILLID_EXPLICITLY_SET) != 0) {
18562                    // Ignore when view already set it through setAutofillId();
18563                    if (android.view.autofill.Helper.sDebug) {
18564                        Log.d(VIEW_LOG_TAG, "onRestoreInstanceState(): not setting autofillId to "
18565                                + baseState.mAutofillViewId + " because view explicitly set it to "
18566                                + mAutofillId);
18567                    }
18568                } else {
18569                    mAutofillViewId = baseState.mAutofillViewId;
18570                    mAutofillId = null; // will be set on demand by getAutofillId()
18571                }
18572            }
18573        }
18574    }
18575
18576    /**
18577     * <p>Return the time at which the drawing of the view hierarchy started.</p>
18578     *
18579     * @return the drawing start time in milliseconds
18580     */
18581    public long getDrawingTime() {
18582        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
18583    }
18584
18585    /**
18586     * <p>Enables or disables the duplication of the parent's state into this view. When
18587     * duplication is enabled, this view gets its drawable state from its parent rather
18588     * than from its own internal properties.</p>
18589     *
18590     * <p>Note: in the current implementation, setting this property to true after the
18591     * view was added to a ViewGroup might have no effect at all. This property should
18592     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
18593     *
18594     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
18595     * property is enabled, an exception will be thrown.</p>
18596     *
18597     * <p>Note: if the child view uses and updates additional states which are unknown to the
18598     * parent, these states should not be affected by this method.</p>
18599     *
18600     * @param enabled True to enable duplication of the parent's drawable state, false
18601     *                to disable it.
18602     *
18603     * @see #getDrawableState()
18604     * @see #isDuplicateParentStateEnabled()
18605     */
18606    public void setDuplicateParentStateEnabled(boolean enabled) {
18607        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
18608    }
18609
18610    /**
18611     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
18612     *
18613     * @return True if this view's drawable state is duplicated from the parent,
18614     *         false otherwise
18615     *
18616     * @see #getDrawableState()
18617     * @see #setDuplicateParentStateEnabled(boolean)
18618     */
18619    public boolean isDuplicateParentStateEnabled() {
18620        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
18621    }
18622
18623    /**
18624     * <p>Specifies the type of layer backing this view. The layer can be
18625     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
18626     * {@link #LAYER_TYPE_HARDWARE}.</p>
18627     *
18628     * <p>A layer is associated with an optional {@link android.graphics.Paint}
18629     * instance that controls how the layer is composed on screen. The following
18630     * properties of the paint are taken into account when composing the layer:</p>
18631     * <ul>
18632     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
18633     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
18634     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
18635     * </ul>
18636     *
18637     * <p>If this view has an alpha value set to < 1.0 by calling
18638     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superseded
18639     * by this view's alpha value.</p>
18640     *
18641     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
18642     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
18643     * for more information on when and how to use layers.</p>
18644     *
18645     * @param layerType The type of layer to use with this view, must be one of
18646     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
18647     *        {@link #LAYER_TYPE_HARDWARE}
18648     * @param paint The paint used to compose the layer. This argument is optional
18649     *        and can be null. It is ignored when the layer type is
18650     *        {@link #LAYER_TYPE_NONE}
18651     *
18652     * @see #getLayerType()
18653     * @see #LAYER_TYPE_NONE
18654     * @see #LAYER_TYPE_SOFTWARE
18655     * @see #LAYER_TYPE_HARDWARE
18656     * @see #setAlpha(float)
18657     *
18658     * @attr ref android.R.styleable#View_layerType
18659     */
18660    public void setLayerType(int layerType, @Nullable Paint paint) {
18661        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
18662            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
18663                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
18664        }
18665
18666        boolean typeChanged = mRenderNode.setLayerType(layerType);
18667
18668        if (!typeChanged) {
18669            setLayerPaint(paint);
18670            return;
18671        }
18672
18673        if (layerType != LAYER_TYPE_SOFTWARE) {
18674            // Destroy any previous software drawing cache if present
18675            // NOTE: even if previous layer type is HW, we do this to ensure we've cleaned up
18676            // drawing cache created in View#draw when drawing to a SW canvas.
18677            destroyDrawingCache();
18678        }
18679
18680        mLayerType = layerType;
18681        mLayerPaint = mLayerType == LAYER_TYPE_NONE ? null : paint;
18682        mRenderNode.setLayerPaint(mLayerPaint);
18683
18684        // draw() behaves differently if we are on a layer, so we need to
18685        // invalidate() here
18686        invalidateParentCaches();
18687        invalidate(true);
18688    }
18689
18690    /**
18691     * Updates the {@link Paint} object used with the current layer (used only if the current
18692     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
18693     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
18694     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
18695     * ensure that the view gets redrawn immediately.
18696     *
18697     * <p>A layer is associated with an optional {@link android.graphics.Paint}
18698     * instance that controls how the layer is composed on screen. The following
18699     * properties of the paint are taken into account when composing the layer:</p>
18700     * <ul>
18701     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
18702     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
18703     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
18704     * </ul>
18705     *
18706     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
18707     * alpha value of the layer's paint is superseded by this view's alpha value.</p>
18708     *
18709     * @param paint The paint used to compose the layer. This argument is optional
18710     *        and can be null. It is ignored when the layer type is
18711     *        {@link #LAYER_TYPE_NONE}
18712     *
18713     * @see #setLayerType(int, android.graphics.Paint)
18714     */
18715    public void setLayerPaint(@Nullable Paint paint) {
18716        int layerType = getLayerType();
18717        if (layerType != LAYER_TYPE_NONE) {
18718            mLayerPaint = paint;
18719            if (layerType == LAYER_TYPE_HARDWARE) {
18720                if (mRenderNode.setLayerPaint(paint)) {
18721                    invalidateViewProperty(false, false);
18722                }
18723            } else {
18724                invalidate();
18725            }
18726        }
18727    }
18728
18729    /**
18730     * Indicates what type of layer is currently associated with this view. By default
18731     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
18732     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
18733     * for more information on the different types of layers.
18734     *
18735     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
18736     *         {@link #LAYER_TYPE_HARDWARE}
18737     *
18738     * @see #setLayerType(int, android.graphics.Paint)
18739     * @see #buildLayer()
18740     * @see #LAYER_TYPE_NONE
18741     * @see #LAYER_TYPE_SOFTWARE
18742     * @see #LAYER_TYPE_HARDWARE
18743     */
18744    public int getLayerType() {
18745        return mLayerType;
18746    }
18747
18748    /**
18749     * Forces this view's layer to be created and this view to be rendered
18750     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
18751     * invoking this method will have no effect.
18752     *
18753     * This method can for instance be used to render a view into its layer before
18754     * starting an animation. If this view is complex, rendering into the layer
18755     * before starting the animation will avoid skipping frames.
18756     *
18757     * @throws IllegalStateException If this view is not attached to a window
18758     *
18759     * @see #setLayerType(int, android.graphics.Paint)
18760     */
18761    public void buildLayer() {
18762        if (mLayerType == LAYER_TYPE_NONE) return;
18763
18764        final AttachInfo attachInfo = mAttachInfo;
18765        if (attachInfo == null) {
18766            throw new IllegalStateException("This view must be attached to a window first");
18767        }
18768
18769        if (getWidth() == 0 || getHeight() == 0) {
18770            return;
18771        }
18772
18773        switch (mLayerType) {
18774            case LAYER_TYPE_HARDWARE:
18775                updateDisplayListIfDirty();
18776                if (attachInfo.mThreadedRenderer != null && mRenderNode.isValid()) {
18777                    attachInfo.mThreadedRenderer.buildLayer(mRenderNode);
18778                }
18779                break;
18780            case LAYER_TYPE_SOFTWARE:
18781                buildDrawingCache(true);
18782                break;
18783        }
18784    }
18785
18786    /**
18787     * Destroys all hardware rendering resources. This method is invoked
18788     * when the system needs to reclaim resources. Upon execution of this
18789     * method, you should free any OpenGL resources created by the view.
18790     *
18791     * Note: you <strong>must</strong> call
18792     * <code>super.destroyHardwareResources()</code> when overriding
18793     * this method.
18794     *
18795     * @hide
18796     */
18797    @CallSuper
18798    protected void destroyHardwareResources() {
18799        if (mOverlay != null) {
18800            mOverlay.getOverlayView().destroyHardwareResources();
18801        }
18802        if (mGhostView != null) {
18803            mGhostView.destroyHardwareResources();
18804        }
18805    }
18806
18807    /**
18808     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
18809     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
18810     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
18811     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
18812     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
18813     * null.</p>
18814     *
18815     * <p>Enabling the drawing cache is similar to
18816     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
18817     * acceleration is turned off. When hardware acceleration is turned on, enabling the
18818     * drawing cache has no effect on rendering because the system uses a different mechanism
18819     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
18820     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
18821     * for information on how to enable software and hardware layers.</p>
18822     *
18823     * <p>This API can be used to manually generate
18824     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
18825     * {@link #getDrawingCache()}.</p>
18826     *
18827     * @param enabled true to enable the drawing cache, false otherwise
18828     *
18829     * @see #isDrawingCacheEnabled()
18830     * @see #getDrawingCache()
18831     * @see #buildDrawingCache()
18832     * @see #setLayerType(int, android.graphics.Paint)
18833     *
18834     * @deprecated The view drawing cache was largely made obsolete with the introduction of
18835     * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
18836     * layers are largely unnecessary and can easily result in a net loss in performance due to the
18837     * cost of creating and updating the layer. In the rare cases where caching layers are useful,
18838     * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
18839     * rendering. For software-rendered snapshots of a small part of the View hierarchy or
18840     * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
18841     * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
18842     * software-rendered usages are discouraged and have compatibility issues with hardware-only
18843     * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
18844     * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
18845     * reports or unit testing the {@link PixelCopy} API is recommended.
18846     */
18847    @Deprecated
18848    public void setDrawingCacheEnabled(boolean enabled) {
18849        mCachingFailed = false;
18850        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
18851    }
18852
18853    /**
18854     * <p>Indicates whether the drawing cache is enabled for this view.</p>
18855     *
18856     * @return true if the drawing cache is enabled
18857     *
18858     * @see #setDrawingCacheEnabled(boolean)
18859     * @see #getDrawingCache()
18860     *
18861     * @deprecated The view drawing cache was largely made obsolete with the introduction of
18862     * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
18863     * layers are largely unnecessary and can easily result in a net loss in performance due to the
18864     * cost of creating and updating the layer. In the rare cases where caching layers are useful,
18865     * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
18866     * rendering. For software-rendered snapshots of a small part of the View hierarchy or
18867     * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
18868     * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
18869     * software-rendered usages are discouraged and have compatibility issues with hardware-only
18870     * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
18871     * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
18872     * reports or unit testing the {@link PixelCopy} API is recommended.
18873     */
18874    @Deprecated
18875    @ViewDebug.ExportedProperty(category = "drawing")
18876    public boolean isDrawingCacheEnabled() {
18877        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
18878    }
18879
18880    /**
18881     * Debugging utility which recursively outputs the dirty state of a view and its
18882     * descendants.
18883     *
18884     * @hide
18885     */
18886    @SuppressWarnings({"UnusedDeclaration"})
18887    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
18888        Log.d(VIEW_LOG_TAG, indent + this + "             DIRTY("
18889                + (mPrivateFlags & View.PFLAG_DIRTY_MASK)
18890                + ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID("
18891                + (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID)
18892                + ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
18893        if (clear) {
18894            mPrivateFlags &= clearMask;
18895        }
18896        if (this instanceof ViewGroup) {
18897            ViewGroup parent = (ViewGroup) this;
18898            final int count = parent.getChildCount();
18899            for (int i = 0; i < count; i++) {
18900                final View child = parent.getChildAt(i);
18901                child.outputDirtyFlags(indent + "  ", clear, clearMask);
18902            }
18903        }
18904    }
18905
18906    /**
18907     * This method is used by ViewGroup to cause its children to restore or recreate their
18908     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
18909     * to recreate its own display list, which would happen if it went through the normal
18910     * draw/dispatchDraw mechanisms.
18911     *
18912     * @hide
18913     */
18914    protected void dispatchGetDisplayList() {}
18915
18916    /**
18917     * A view that is not attached or hardware accelerated cannot create a display list.
18918     * This method checks these conditions and returns the appropriate result.
18919     *
18920     * @return true if view has the ability to create a display list, false otherwise.
18921     *
18922     * @hide
18923     */
18924    public boolean canHaveDisplayList() {
18925        return !(mAttachInfo == null || mAttachInfo.mThreadedRenderer == null);
18926    }
18927
18928    /**
18929     * Gets the RenderNode for the view, and updates its DisplayList (if needed and supported)
18930     * @hide
18931     */
18932    @NonNull
18933    public RenderNode updateDisplayListIfDirty() {
18934        final RenderNode renderNode = mRenderNode;
18935        if (!canHaveDisplayList()) {
18936            // can't populate RenderNode, don't try
18937            return renderNode;
18938        }
18939
18940        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0
18941                || !renderNode.isValid()
18942                || (mRecreateDisplayList)) {
18943            // Don't need to recreate the display list, just need to tell our
18944            // children to restore/recreate theirs
18945            if (renderNode.isValid()
18946                    && !mRecreateDisplayList) {
18947                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
18948                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
18949                dispatchGetDisplayList();
18950
18951                return renderNode; // no work needed
18952            }
18953
18954            // If we got here, we're recreating it. Mark it as such to ensure that
18955            // we copy in child display lists into ours in drawChild()
18956            mRecreateDisplayList = true;
18957
18958            int width = mRight - mLeft;
18959            int height = mBottom - mTop;
18960            int layerType = getLayerType();
18961
18962            final DisplayListCanvas canvas = renderNode.start(width, height);
18963
18964            try {
18965                if (layerType == LAYER_TYPE_SOFTWARE) {
18966                    buildDrawingCache(true);
18967                    Bitmap cache = getDrawingCache(true);
18968                    if (cache != null) {
18969                        canvas.drawBitmap(cache, 0, 0, mLayerPaint);
18970                    }
18971                } else {
18972                    computeScroll();
18973
18974                    canvas.translate(-mScrollX, -mScrollY);
18975                    mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
18976                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
18977
18978                    // Fast path for layouts with no backgrounds
18979                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
18980                        dispatchDraw(canvas);
18981                        drawAutofilledHighlight(canvas);
18982                        if (mOverlay != null && !mOverlay.isEmpty()) {
18983                            mOverlay.getOverlayView().draw(canvas);
18984                        }
18985                        if (debugDraw()) {
18986                            debugDrawFocus(canvas);
18987                        }
18988                    } else {
18989                        draw(canvas);
18990                    }
18991                }
18992            } finally {
18993                renderNode.end(canvas);
18994                setDisplayListProperties(renderNode);
18995            }
18996        } else {
18997            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
18998            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
18999        }
19000        return renderNode;
19001    }
19002
19003    private void resetDisplayList() {
19004        mRenderNode.discardDisplayList();
19005        if (mBackgroundRenderNode != null) {
19006            mBackgroundRenderNode.discardDisplayList();
19007        }
19008    }
19009
19010    /**
19011     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
19012     *
19013     * @return A non-scaled bitmap representing this view or null if cache is disabled.
19014     *
19015     * @see #getDrawingCache(boolean)
19016     *
19017     * @deprecated The view drawing cache was largely made obsolete with the introduction of
19018     * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
19019     * layers are largely unnecessary and can easily result in a net loss in performance due to the
19020     * cost of creating and updating the layer. In the rare cases where caching layers are useful,
19021     * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
19022     * rendering. For software-rendered snapshots of a small part of the View hierarchy or
19023     * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
19024     * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
19025     * software-rendered usages are discouraged and have compatibility issues with hardware-only
19026     * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
19027     * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
19028     * reports or unit testing the {@link PixelCopy} API is recommended.
19029     */
19030    @Deprecated
19031    public Bitmap getDrawingCache() {
19032        return getDrawingCache(false);
19033    }
19034
19035    /**
19036     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
19037     * is null when caching is disabled. If caching is enabled and the cache is not ready,
19038     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
19039     * draw from the cache when the cache is enabled. To benefit from the cache, you must
19040     * request the drawing cache by calling this method and draw it on screen if the
19041     * returned bitmap is not null.</p>
19042     *
19043     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
19044     * this method will create a bitmap of the same size as this view. Because this bitmap
19045     * will be drawn scaled by the parent ViewGroup, the result on screen might show
19046     * scaling artifacts. To avoid such artifacts, you should call this method by setting
19047     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
19048     * size than the view. This implies that your application must be able to handle this
19049     * size.</p>
19050     *
19051     * @param autoScale Indicates whether the generated bitmap should be scaled based on
19052     *        the current density of the screen when the application is in compatibility
19053     *        mode.
19054     *
19055     * @return A bitmap representing this view or null if cache is disabled.
19056     *
19057     * @see #setDrawingCacheEnabled(boolean)
19058     * @see #isDrawingCacheEnabled()
19059     * @see #buildDrawingCache(boolean)
19060     * @see #destroyDrawingCache()
19061     *
19062     * @deprecated The view drawing cache was largely made obsolete with the introduction of
19063     * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
19064     * layers are largely unnecessary and can easily result in a net loss in performance due to the
19065     * cost of creating and updating the layer. In the rare cases where caching layers are useful,
19066     * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
19067     * rendering. For software-rendered snapshots of a small part of the View hierarchy or
19068     * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
19069     * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
19070     * software-rendered usages are discouraged and have compatibility issues with hardware-only
19071     * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
19072     * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
19073     * reports or unit testing the {@link PixelCopy} API is recommended.
19074     */
19075    @Deprecated
19076    public Bitmap getDrawingCache(boolean autoScale) {
19077        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
19078            return null;
19079        }
19080        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
19081            buildDrawingCache(autoScale);
19082        }
19083        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
19084    }
19085
19086    /**
19087     * <p>Frees the resources used by the drawing cache. If you call
19088     * {@link #buildDrawingCache()} manually without calling
19089     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
19090     * should cleanup the cache with this method afterwards.</p>
19091     *
19092     * @see #setDrawingCacheEnabled(boolean)
19093     * @see #buildDrawingCache()
19094     * @see #getDrawingCache()
19095     *
19096     * @deprecated The view drawing cache was largely made obsolete with the introduction of
19097     * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
19098     * layers are largely unnecessary and can easily result in a net loss in performance due to the
19099     * cost of creating and updating the layer. In the rare cases where caching layers are useful,
19100     * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
19101     * rendering. For software-rendered snapshots of a small part of the View hierarchy or
19102     * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
19103     * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
19104     * software-rendered usages are discouraged and have compatibility issues with hardware-only
19105     * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
19106     * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
19107     * reports or unit testing the {@link PixelCopy} API is recommended.
19108     */
19109    @Deprecated
19110    public void destroyDrawingCache() {
19111        if (mDrawingCache != null) {
19112            mDrawingCache.recycle();
19113            mDrawingCache = null;
19114        }
19115        if (mUnscaledDrawingCache != null) {
19116            mUnscaledDrawingCache.recycle();
19117            mUnscaledDrawingCache = null;
19118        }
19119    }
19120
19121    /**
19122     * Setting a solid background color for the drawing cache's bitmaps will improve
19123     * performance and memory usage. Note, though that this should only be used if this
19124     * view will always be drawn on top of a solid color.
19125     *
19126     * @param color The background color to use for the drawing cache's bitmap
19127     *
19128     * @see #setDrawingCacheEnabled(boolean)
19129     * @see #buildDrawingCache()
19130     * @see #getDrawingCache()
19131     *
19132     * @deprecated The view drawing cache was largely made obsolete with the introduction of
19133     * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
19134     * layers are largely unnecessary and can easily result in a net loss in performance due to the
19135     * cost of creating and updating the layer. In the rare cases where caching layers are useful,
19136     * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
19137     * rendering. For software-rendered snapshots of a small part of the View hierarchy or
19138     * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
19139     * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
19140     * software-rendered usages are discouraged and have compatibility issues with hardware-only
19141     * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
19142     * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
19143     * reports or unit testing the {@link PixelCopy} API is recommended.
19144     */
19145    @Deprecated
19146    public void setDrawingCacheBackgroundColor(@ColorInt int color) {
19147        if (color != mDrawingCacheBackgroundColor) {
19148            mDrawingCacheBackgroundColor = color;
19149            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
19150        }
19151    }
19152
19153    /**
19154     * @see #setDrawingCacheBackgroundColor(int)
19155     *
19156     * @return The background color to used for the drawing cache's bitmap
19157     *
19158     * @deprecated The view drawing cache was largely made obsolete with the introduction of
19159     * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
19160     * layers are largely unnecessary and can easily result in a net loss in performance due to the
19161     * cost of creating and updating the layer. In the rare cases where caching layers are useful,
19162     * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
19163     * rendering. For software-rendered snapshots of a small part of the View hierarchy or
19164     * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
19165     * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
19166     * software-rendered usages are discouraged and have compatibility issues with hardware-only
19167     * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
19168     * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
19169     * reports or unit testing the {@link PixelCopy} API is recommended.
19170     */
19171    @Deprecated
19172    @ColorInt
19173    public int getDrawingCacheBackgroundColor() {
19174        return mDrawingCacheBackgroundColor;
19175    }
19176
19177    /**
19178     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
19179     *
19180     * @see #buildDrawingCache(boolean)
19181     *
19182     * @deprecated The view drawing cache was largely made obsolete with the introduction of
19183     * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
19184     * layers are largely unnecessary and can easily result in a net loss in performance due to the
19185     * cost of creating and updating the layer. In the rare cases where caching layers are useful,
19186     * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
19187     * rendering. For software-rendered snapshots of a small part of the View hierarchy or
19188     * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
19189     * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
19190     * software-rendered usages are discouraged and have compatibility issues with hardware-only
19191     * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
19192     * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
19193     * reports or unit testing the {@link PixelCopy} API is recommended.
19194     */
19195    @Deprecated
19196    public void buildDrawingCache() {
19197        buildDrawingCache(false);
19198    }
19199
19200    /**
19201     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
19202     *
19203     * <p>If you call {@link #buildDrawingCache()} manually without calling
19204     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
19205     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
19206     *
19207     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
19208     * this method will create a bitmap of the same size as this view. Because this bitmap
19209     * will be drawn scaled by the parent ViewGroup, the result on screen might show
19210     * scaling artifacts. To avoid such artifacts, you should call this method by setting
19211     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
19212     * size than the view. This implies that your application must be able to handle this
19213     * size.</p>
19214     *
19215     * <p>You should avoid calling this method when hardware acceleration is enabled. If
19216     * you do not need the drawing cache bitmap, calling this method will increase memory
19217     * usage and cause the view to be rendered in software once, thus negatively impacting
19218     * performance.</p>
19219     *
19220     * @see #getDrawingCache()
19221     * @see #destroyDrawingCache()
19222     *
19223     * @deprecated The view drawing cache was largely made obsolete with the introduction of
19224     * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
19225     * layers are largely unnecessary and can easily result in a net loss in performance due to the
19226     * cost of creating and updating the layer. In the rare cases where caching layers are useful,
19227     * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
19228     * rendering. For software-rendered snapshots of a small part of the View hierarchy or
19229     * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
19230     * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
19231     * software-rendered usages are discouraged and have compatibility issues with hardware-only
19232     * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
19233     * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
19234     * reports or unit testing the {@link PixelCopy} API is recommended.
19235     */
19236    @Deprecated
19237    public void buildDrawingCache(boolean autoScale) {
19238        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
19239                mDrawingCache == null : mUnscaledDrawingCache == null)) {
19240            if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) {
19241                Trace.traceBegin(Trace.TRACE_TAG_VIEW,
19242                        "buildDrawingCache/SW Layer for " + getClass().getSimpleName());
19243            }
19244            try {
19245                buildDrawingCacheImpl(autoScale);
19246            } finally {
19247                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
19248            }
19249        }
19250    }
19251
19252    /**
19253     * private, internal implementation of buildDrawingCache, used to enable tracing
19254     */
19255    private void buildDrawingCacheImpl(boolean autoScale) {
19256        mCachingFailed = false;
19257
19258        int width = mRight - mLeft;
19259        int height = mBottom - mTop;
19260
19261        final AttachInfo attachInfo = mAttachInfo;
19262        final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
19263
19264        if (autoScale && scalingRequired) {
19265            width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
19266            height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
19267        }
19268
19269        final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
19270        final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
19271        final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
19272
19273        final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
19274        final long drawingCacheSize =
19275                ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
19276        if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
19277            if (width > 0 && height > 0) {
19278                Log.w(VIEW_LOG_TAG, getClass().getSimpleName() + " not displayed because it is"
19279                        + " too large to fit into a software layer (or drawing cache), needs "
19280                        + projectedBitmapSize + " bytes, only "
19281                        + drawingCacheSize + " available");
19282            }
19283            destroyDrawingCache();
19284            mCachingFailed = true;
19285            return;
19286        }
19287
19288        boolean clear = true;
19289        Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
19290
19291        if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
19292            Bitmap.Config quality;
19293            if (!opaque) {
19294                // Never pick ARGB_4444 because it looks awful
19295                // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
19296                switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
19297                    case DRAWING_CACHE_QUALITY_AUTO:
19298                    case DRAWING_CACHE_QUALITY_LOW:
19299                    case DRAWING_CACHE_QUALITY_HIGH:
19300                    default:
19301                        quality = Bitmap.Config.ARGB_8888;
19302                        break;
19303                }
19304            } else {
19305                // Optimization for translucent windows
19306                // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
19307                quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
19308            }
19309
19310            // Try to cleanup memory
19311            if (bitmap != null) bitmap.recycle();
19312
19313            try {
19314                bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
19315                        width, height, quality);
19316                bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
19317                if (autoScale) {
19318                    mDrawingCache = bitmap;
19319                } else {
19320                    mUnscaledDrawingCache = bitmap;
19321                }
19322                if (opaque && use32BitCache) bitmap.setHasAlpha(false);
19323            } catch (OutOfMemoryError e) {
19324                // If there is not enough memory to create the bitmap cache, just
19325                // ignore the issue as bitmap caches are not required to draw the
19326                // view hierarchy
19327                if (autoScale) {
19328                    mDrawingCache = null;
19329                } else {
19330                    mUnscaledDrawingCache = null;
19331                }
19332                mCachingFailed = true;
19333                return;
19334            }
19335
19336            clear = drawingCacheBackgroundColor != 0;
19337        }
19338
19339        Canvas canvas;
19340        if (attachInfo != null) {
19341            canvas = attachInfo.mCanvas;
19342            if (canvas == null) {
19343                canvas = new Canvas();
19344            }
19345            canvas.setBitmap(bitmap);
19346            // Temporarily clobber the cached Canvas in case one of our children
19347            // is also using a drawing cache. Without this, the children would
19348            // steal the canvas by attaching their own bitmap to it and bad, bad
19349            // thing would happen (invisible views, corrupted drawings, etc.)
19350            attachInfo.mCanvas = null;
19351        } else {
19352            // This case should hopefully never or seldom happen
19353            canvas = new Canvas(bitmap);
19354        }
19355
19356        if (clear) {
19357            bitmap.eraseColor(drawingCacheBackgroundColor);
19358        }
19359
19360        computeScroll();
19361        final int restoreCount = canvas.save();
19362
19363        if (autoScale && scalingRequired) {
19364            final float scale = attachInfo.mApplicationScale;
19365            canvas.scale(scale, scale);
19366        }
19367
19368        canvas.translate(-mScrollX, -mScrollY);
19369
19370        mPrivateFlags |= PFLAG_DRAWN;
19371        if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
19372                mLayerType != LAYER_TYPE_NONE) {
19373            mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
19374        }
19375
19376        // Fast path for layouts with no backgrounds
19377        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
19378            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
19379            dispatchDraw(canvas);
19380            drawAutofilledHighlight(canvas);
19381            if (mOverlay != null && !mOverlay.isEmpty()) {
19382                mOverlay.getOverlayView().draw(canvas);
19383            }
19384        } else {
19385            draw(canvas);
19386        }
19387
19388        canvas.restoreToCount(restoreCount);
19389        canvas.setBitmap(null);
19390
19391        if (attachInfo != null) {
19392            // Restore the cached Canvas for our siblings
19393            attachInfo.mCanvas = canvas;
19394        }
19395    }
19396
19397    /**
19398     * Create a snapshot of the view into a bitmap.  We should probably make
19399     * some form of this public, but should think about the API.
19400     *
19401     * @hide
19402     */
19403    public Bitmap createSnapshot(ViewDebug.CanvasProvider canvasProvider, boolean skipChildren) {
19404        int width = mRight - mLeft;
19405        int height = mBottom - mTop;
19406
19407        final AttachInfo attachInfo = mAttachInfo;
19408        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
19409        width = (int) ((width * scale) + 0.5f);
19410        height = (int) ((height * scale) + 0.5f);
19411
19412        Canvas oldCanvas = null;
19413        try {
19414            Canvas canvas = canvasProvider.getCanvas(this,
19415                    width > 0 ? width : 1, height > 0 ? height : 1);
19416
19417            if (attachInfo != null) {
19418                oldCanvas = attachInfo.mCanvas;
19419                // Temporarily clobber the cached Canvas in case one of our children
19420                // is also using a drawing cache. Without this, the children would
19421                // steal the canvas by attaching their own bitmap to it and bad, bad
19422                // things would happen (invisible views, corrupted drawings, etc.)
19423                attachInfo.mCanvas = null;
19424            }
19425
19426            computeScroll();
19427            final int restoreCount = canvas.save();
19428            canvas.scale(scale, scale);
19429            canvas.translate(-mScrollX, -mScrollY);
19430
19431            // Temporarily remove the dirty mask
19432            int flags = mPrivateFlags;
19433            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
19434
19435            // Fast path for layouts with no backgrounds
19436            if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
19437                dispatchDraw(canvas);
19438                drawAutofilledHighlight(canvas);
19439                if (mOverlay != null && !mOverlay.isEmpty()) {
19440                    mOverlay.getOverlayView().draw(canvas);
19441                }
19442            } else {
19443                draw(canvas);
19444            }
19445
19446            mPrivateFlags = flags;
19447            canvas.restoreToCount(restoreCount);
19448            return canvasProvider.createBitmap();
19449        } finally {
19450            if (oldCanvas != null) {
19451                attachInfo.mCanvas = oldCanvas;
19452            }
19453        }
19454    }
19455
19456    /**
19457     * Indicates whether this View is currently in edit mode. A View is usually
19458     * in edit mode when displayed within a developer tool. For instance, if
19459     * this View is being drawn by a visual user interface builder, this method
19460     * should return true.
19461     *
19462     * Subclasses should check the return value of this method to provide
19463     * different behaviors if their normal behavior might interfere with the
19464     * host environment. For instance: the class spawns a thread in its
19465     * constructor, the drawing code relies on device-specific features, etc.
19466     *
19467     * This method is usually checked in the drawing code of custom widgets.
19468     *
19469     * @return True if this View is in edit mode, false otherwise.
19470     */
19471    public boolean isInEditMode() {
19472        return false;
19473    }
19474
19475    /**
19476     * If the View draws content inside its padding and enables fading edges,
19477     * it needs to support padding offsets. Padding offsets are added to the
19478     * fading edges to extend the length of the fade so that it covers pixels
19479     * drawn inside the padding.
19480     *
19481     * Subclasses of this class should override this method if they need
19482     * to draw content inside the padding.
19483     *
19484     * @return True if padding offset must be applied, false otherwise.
19485     *
19486     * @see #getLeftPaddingOffset()
19487     * @see #getRightPaddingOffset()
19488     * @see #getTopPaddingOffset()
19489     * @see #getBottomPaddingOffset()
19490     *
19491     * @since CURRENT
19492     */
19493    protected boolean isPaddingOffsetRequired() {
19494        return false;
19495    }
19496
19497    /**
19498     * Amount by which to extend the left fading region. Called only when
19499     * {@link #isPaddingOffsetRequired()} returns true.
19500     *
19501     * @return The left padding offset in pixels.
19502     *
19503     * @see #isPaddingOffsetRequired()
19504     *
19505     * @since CURRENT
19506     */
19507    protected int getLeftPaddingOffset() {
19508        return 0;
19509    }
19510
19511    /**
19512     * Amount by which to extend the right fading region. Called only when
19513     * {@link #isPaddingOffsetRequired()} returns true.
19514     *
19515     * @return The right padding offset in pixels.
19516     *
19517     * @see #isPaddingOffsetRequired()
19518     *
19519     * @since CURRENT
19520     */
19521    protected int getRightPaddingOffset() {
19522        return 0;
19523    }
19524
19525    /**
19526     * Amount by which to extend the top fading region. Called only when
19527     * {@link #isPaddingOffsetRequired()} returns true.
19528     *
19529     * @return The top padding offset in pixels.
19530     *
19531     * @see #isPaddingOffsetRequired()
19532     *
19533     * @since CURRENT
19534     */
19535    protected int getTopPaddingOffset() {
19536        return 0;
19537    }
19538
19539    /**
19540     * Amount by which to extend the bottom fading region. Called only when
19541     * {@link #isPaddingOffsetRequired()} returns true.
19542     *
19543     * @return The bottom padding offset in pixels.
19544     *
19545     * @see #isPaddingOffsetRequired()
19546     *
19547     * @since CURRENT
19548     */
19549    protected int getBottomPaddingOffset() {
19550        return 0;
19551    }
19552
19553    /**
19554     * @hide
19555     * @param offsetRequired
19556     */
19557    protected int getFadeTop(boolean offsetRequired) {
19558        int top = mPaddingTop;
19559        if (offsetRequired) top += getTopPaddingOffset();
19560        return top;
19561    }
19562
19563    /**
19564     * @hide
19565     * @param offsetRequired
19566     */
19567    protected int getFadeHeight(boolean offsetRequired) {
19568        int padding = mPaddingTop;
19569        if (offsetRequired) padding += getTopPaddingOffset();
19570        return mBottom - mTop - mPaddingBottom - padding;
19571    }
19572
19573    /**
19574     * <p>Indicates whether this view is attached to a hardware accelerated
19575     * window or not.</p>
19576     *
19577     * <p>Even if this method returns true, it does not mean that every call
19578     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
19579     * accelerated {@link android.graphics.Canvas}. For instance, if this view
19580     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
19581     * window is hardware accelerated,
19582     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
19583     * return false, and this method will return true.</p>
19584     *
19585     * @return True if the view is attached to a window and the window is
19586     *         hardware accelerated; false in any other case.
19587     */
19588    @ViewDebug.ExportedProperty(category = "drawing")
19589    public boolean isHardwareAccelerated() {
19590        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
19591    }
19592
19593    /**
19594     * Sets a rectangular area on this view to which the view will be clipped
19595     * when it is drawn. Setting the value to null will remove the clip bounds
19596     * and the view will draw normally, using its full bounds.
19597     *
19598     * @param clipBounds The rectangular area, in the local coordinates of
19599     * this view, to which future drawing operations will be clipped.
19600     */
19601    public void setClipBounds(Rect clipBounds) {
19602        if (clipBounds == mClipBounds
19603                || (clipBounds != null && clipBounds.equals(mClipBounds))) {
19604            return;
19605        }
19606        if (clipBounds != null) {
19607            if (mClipBounds == null) {
19608                mClipBounds = new Rect(clipBounds);
19609            } else {
19610                mClipBounds.set(clipBounds);
19611            }
19612        } else {
19613            mClipBounds = null;
19614        }
19615        mRenderNode.setClipBounds(mClipBounds);
19616        invalidateViewProperty(false, false);
19617    }
19618
19619    /**
19620     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
19621     *
19622     * @return A copy of the current clip bounds if clip bounds are set,
19623     * otherwise null.
19624     */
19625    public Rect getClipBounds() {
19626        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
19627    }
19628
19629
19630    /**
19631     * Populates an output rectangle with the clip bounds of the view,
19632     * returning {@code true} if successful or {@code false} if the view's
19633     * clip bounds are {@code null}.
19634     *
19635     * @param outRect rectangle in which to place the clip bounds of the view
19636     * @return {@code true} if successful or {@code false} if the view's
19637     *         clip bounds are {@code null}
19638     */
19639    public boolean getClipBounds(Rect outRect) {
19640        if (mClipBounds != null) {
19641            outRect.set(mClipBounds);
19642            return true;
19643        }
19644        return false;
19645    }
19646
19647    /**
19648     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
19649     * case of an active Animation being run on the view.
19650     */
19651    private boolean applyLegacyAnimation(ViewGroup parent, long drawingTime,
19652            Animation a, boolean scalingRequired) {
19653        Transformation invalidationTransform;
19654        final int flags = parent.mGroupFlags;
19655        final boolean initialized = a.isInitialized();
19656        if (!initialized) {
19657            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
19658            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
19659            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
19660            onAnimationStart();
19661        }
19662
19663        final Transformation t = parent.getChildTransformation();
19664        boolean more = a.getTransformation(drawingTime, t, 1f);
19665        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
19666            if (parent.mInvalidationTransformation == null) {
19667                parent.mInvalidationTransformation = new Transformation();
19668            }
19669            invalidationTransform = parent.mInvalidationTransformation;
19670            a.getTransformation(drawingTime, invalidationTransform, 1f);
19671        } else {
19672            invalidationTransform = t;
19673        }
19674
19675        if (more) {
19676            if (!a.willChangeBounds()) {
19677                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
19678                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
19679                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
19680                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
19681                    // The child need to draw an animation, potentially offscreen, so
19682                    // make sure we do not cancel invalidate requests
19683                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
19684                    parent.invalidate(mLeft, mTop, mRight, mBottom);
19685                }
19686            } else {
19687                if (parent.mInvalidateRegion == null) {
19688                    parent.mInvalidateRegion = new RectF();
19689                }
19690                final RectF region = parent.mInvalidateRegion;
19691                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
19692                        invalidationTransform);
19693
19694                // The child need to draw an animation, potentially offscreen, so
19695                // make sure we do not cancel invalidate requests
19696                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
19697
19698                final int left = mLeft + (int) region.left;
19699                final int top = mTop + (int) region.top;
19700                parent.invalidate(left, top, left + (int) (region.width() + .5f),
19701                        top + (int) (region.height() + .5f));
19702            }
19703        }
19704        return more;
19705    }
19706
19707    /**
19708     * This method is called by getDisplayList() when a display list is recorded for a View.
19709     * It pushes any properties to the RenderNode that aren't managed by the RenderNode.
19710     */
19711    void setDisplayListProperties(RenderNode renderNode) {
19712        if (renderNode != null) {
19713            renderNode.setHasOverlappingRendering(getHasOverlappingRendering());
19714            renderNode.setClipToBounds(mParent instanceof ViewGroup
19715                    && ((ViewGroup) mParent).getClipChildren());
19716
19717            float alpha = 1;
19718            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
19719                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
19720                ViewGroup parentVG = (ViewGroup) mParent;
19721                final Transformation t = parentVG.getChildTransformation();
19722                if (parentVG.getChildStaticTransformation(this, t)) {
19723                    final int transformType = t.getTransformationType();
19724                    if (transformType != Transformation.TYPE_IDENTITY) {
19725                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
19726                            alpha = t.getAlpha();
19727                        }
19728                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
19729                            renderNode.setStaticMatrix(t.getMatrix());
19730                        }
19731                    }
19732                }
19733            }
19734            if (mTransformationInfo != null) {
19735                alpha *= getFinalAlpha();
19736                if (alpha < 1) {
19737                    final int multipliedAlpha = (int) (255 * alpha);
19738                    if (onSetAlpha(multipliedAlpha)) {
19739                        alpha = 1;
19740                    }
19741                }
19742                renderNode.setAlpha(alpha);
19743            } else if (alpha < 1) {
19744                renderNode.setAlpha(alpha);
19745            }
19746        }
19747    }
19748
19749    /**
19750     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
19751     *
19752     * This is where the View specializes rendering behavior based on layer type,
19753     * and hardware acceleration.
19754     */
19755    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
19756        final boolean hardwareAcceleratedCanvas = canvas.isHardwareAccelerated();
19757        /* If an attached view draws to a HW canvas, it may use its RenderNode + DisplayList.
19758         *
19759         * If a view is dettached, its DisplayList shouldn't exist. If the canvas isn't
19760         * HW accelerated, it can't handle drawing RenderNodes.
19761         */
19762        boolean drawingWithRenderNode = mAttachInfo != null
19763                && mAttachInfo.mHardwareAccelerated
19764                && hardwareAcceleratedCanvas;
19765
19766        boolean more = false;
19767        final boolean childHasIdentityMatrix = hasIdentityMatrix();
19768        final int parentFlags = parent.mGroupFlags;
19769
19770        if ((parentFlags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) != 0) {
19771            parent.getChildTransformation().clear();
19772            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
19773        }
19774
19775        Transformation transformToApply = null;
19776        boolean concatMatrix = false;
19777        final boolean scalingRequired = mAttachInfo != null && mAttachInfo.mScalingRequired;
19778        final Animation a = getAnimation();
19779        if (a != null) {
19780            more = applyLegacyAnimation(parent, drawingTime, a, scalingRequired);
19781            concatMatrix = a.willChangeTransformationMatrix();
19782            if (concatMatrix) {
19783                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
19784            }
19785            transformToApply = parent.getChildTransformation();
19786        } else {
19787            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) {
19788                // No longer animating: clear out old animation matrix
19789                mRenderNode.setAnimationMatrix(null);
19790                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
19791            }
19792            if (!drawingWithRenderNode
19793                    && (parentFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
19794                final Transformation t = parent.getChildTransformation();
19795                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
19796                if (hasTransform) {
19797                    final int transformType = t.getTransformationType();
19798                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
19799                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
19800                }
19801            }
19802        }
19803
19804        concatMatrix |= !childHasIdentityMatrix;
19805
19806        // Sets the flag as early as possible to allow draw() implementations
19807        // to call invalidate() successfully when doing animations
19808        mPrivateFlags |= PFLAG_DRAWN;
19809
19810        if (!concatMatrix &&
19811                (parentFlags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
19812                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
19813                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
19814                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
19815            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
19816            return more;
19817        }
19818        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
19819
19820        if (hardwareAcceleratedCanvas) {
19821            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
19822            // retain the flag's value temporarily in the mRecreateDisplayList flag
19823            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) != 0;
19824            mPrivateFlags &= ~PFLAG_INVALIDATED;
19825        }
19826
19827        RenderNode renderNode = null;
19828        Bitmap cache = null;
19829        int layerType = getLayerType(); // TODO: signify cache state with just 'cache' local
19830        if (layerType == LAYER_TYPE_SOFTWARE || !drawingWithRenderNode) {
19831             if (layerType != LAYER_TYPE_NONE) {
19832                 // If not drawing with RenderNode, treat HW layers as SW
19833                 layerType = LAYER_TYPE_SOFTWARE;
19834                 buildDrawingCache(true);
19835            }
19836            cache = getDrawingCache(true);
19837        }
19838
19839        if (drawingWithRenderNode) {
19840            // Delay getting the display list until animation-driven alpha values are
19841            // set up and possibly passed on to the view
19842            renderNode = updateDisplayListIfDirty();
19843            if (!renderNode.isValid()) {
19844                // Uncommon, but possible. If a view is removed from the hierarchy during the call
19845                // to getDisplayList(), the display list will be marked invalid and we should not
19846                // try to use it again.
19847                renderNode = null;
19848                drawingWithRenderNode = false;
19849            }
19850        }
19851
19852        int sx = 0;
19853        int sy = 0;
19854        if (!drawingWithRenderNode) {
19855            computeScroll();
19856            sx = mScrollX;
19857            sy = mScrollY;
19858        }
19859
19860        final boolean drawingWithDrawingCache = cache != null && !drawingWithRenderNode;
19861        final boolean offsetForScroll = cache == null && !drawingWithRenderNode;
19862
19863        int restoreTo = -1;
19864        if (!drawingWithRenderNode || transformToApply != null) {
19865            restoreTo = canvas.save();
19866        }
19867        if (offsetForScroll) {
19868            canvas.translate(mLeft - sx, mTop - sy);
19869        } else {
19870            if (!drawingWithRenderNode) {
19871                canvas.translate(mLeft, mTop);
19872            }
19873            if (scalingRequired) {
19874                if (drawingWithRenderNode) {
19875                    // TODO: Might not need this if we put everything inside the DL
19876                    restoreTo = canvas.save();
19877                }
19878                // mAttachInfo cannot be null, otherwise scalingRequired == false
19879                final float scale = 1.0f / mAttachInfo.mApplicationScale;
19880                canvas.scale(scale, scale);
19881            }
19882        }
19883
19884        float alpha = drawingWithRenderNode ? 1 : (getAlpha() * getTransitionAlpha());
19885        if (transformToApply != null
19886                || alpha < 1
19887                || !hasIdentityMatrix()
19888                || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
19889            if (transformToApply != null || !childHasIdentityMatrix) {
19890                int transX = 0;
19891                int transY = 0;
19892
19893                if (offsetForScroll) {
19894                    transX = -sx;
19895                    transY = -sy;
19896                }
19897
19898                if (transformToApply != null) {
19899                    if (concatMatrix) {
19900                        if (drawingWithRenderNode) {
19901                            renderNode.setAnimationMatrix(transformToApply.getMatrix());
19902                        } else {
19903                            // Undo the scroll translation, apply the transformation matrix,
19904                            // then redo the scroll translate to get the correct result.
19905                            canvas.translate(-transX, -transY);
19906                            canvas.concat(transformToApply.getMatrix());
19907                            canvas.translate(transX, transY);
19908                        }
19909                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
19910                    }
19911
19912                    float transformAlpha = transformToApply.getAlpha();
19913                    if (transformAlpha < 1) {
19914                        alpha *= transformAlpha;
19915                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
19916                    }
19917                }
19918
19919                if (!childHasIdentityMatrix && !drawingWithRenderNode) {
19920                    canvas.translate(-transX, -transY);
19921                    canvas.concat(getMatrix());
19922                    canvas.translate(transX, transY);
19923                }
19924            }
19925
19926            // Deal with alpha if it is or used to be <1
19927            if (alpha < 1 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
19928                if (alpha < 1) {
19929                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
19930                } else {
19931                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
19932                }
19933                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
19934                if (!drawingWithDrawingCache) {
19935                    final int multipliedAlpha = (int) (255 * alpha);
19936                    if (!onSetAlpha(multipliedAlpha)) {
19937                        if (drawingWithRenderNode) {
19938                            renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha());
19939                        } else if (layerType == LAYER_TYPE_NONE) {
19940                            canvas.saveLayerAlpha(sx, sy, sx + getWidth(), sy + getHeight(),
19941                                    multipliedAlpha);
19942                        }
19943                    } else {
19944                        // Alpha is handled by the child directly, clobber the layer's alpha
19945                        mPrivateFlags |= PFLAG_ALPHA_SET;
19946                    }
19947                }
19948            }
19949        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
19950            onSetAlpha(255);
19951            mPrivateFlags &= ~PFLAG_ALPHA_SET;
19952        }
19953
19954        if (!drawingWithRenderNode) {
19955            // apply clips directly, since RenderNode won't do it for this draw
19956            if ((parentFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 && cache == null) {
19957                if (offsetForScroll) {
19958                    canvas.clipRect(sx, sy, sx + getWidth(), sy + getHeight());
19959                } else {
19960                    if (!scalingRequired || cache == null) {
19961                        canvas.clipRect(0, 0, getWidth(), getHeight());
19962                    } else {
19963                        canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
19964                    }
19965                }
19966            }
19967
19968            if (mClipBounds != null) {
19969                // clip bounds ignore scroll
19970                canvas.clipRect(mClipBounds);
19971            }
19972        }
19973
19974        if (!drawingWithDrawingCache) {
19975            if (drawingWithRenderNode) {
19976                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
19977                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
19978            } else {
19979                // Fast path for layouts with no backgrounds
19980                if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
19981                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
19982                    dispatchDraw(canvas);
19983                } else {
19984                    draw(canvas);
19985                }
19986            }
19987        } else if (cache != null) {
19988            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
19989            if (layerType == LAYER_TYPE_NONE || mLayerPaint == null) {
19990                // no layer paint, use temporary paint to draw bitmap
19991                Paint cachePaint = parent.mCachePaint;
19992                if (cachePaint == null) {
19993                    cachePaint = new Paint();
19994                    cachePaint.setDither(false);
19995                    parent.mCachePaint = cachePaint;
19996                }
19997                cachePaint.setAlpha((int) (alpha * 255));
19998                canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
19999            } else {
20000                // use layer paint to draw the bitmap, merging the two alphas, but also restore
20001                int layerPaintAlpha = mLayerPaint.getAlpha();
20002                if (alpha < 1) {
20003                    mLayerPaint.setAlpha((int) (alpha * layerPaintAlpha));
20004                }
20005                canvas.drawBitmap(cache, 0.0f, 0.0f, mLayerPaint);
20006                if (alpha < 1) {
20007                    mLayerPaint.setAlpha(layerPaintAlpha);
20008                }
20009            }
20010        }
20011
20012        if (restoreTo >= 0) {
20013            canvas.restoreToCount(restoreTo);
20014        }
20015
20016        if (a != null && !more) {
20017            if (!hardwareAcceleratedCanvas && !a.getFillAfter()) {
20018                onSetAlpha(255);
20019            }
20020            parent.finishAnimatingView(this, a);
20021        }
20022
20023        if (more && hardwareAcceleratedCanvas) {
20024            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
20025                // alpha animations should cause the child to recreate its display list
20026                invalidate(true);
20027            }
20028        }
20029
20030        mRecreateDisplayList = false;
20031
20032        return more;
20033    }
20034
20035    static Paint getDebugPaint() {
20036        if (sDebugPaint == null) {
20037            sDebugPaint = new Paint();
20038            sDebugPaint.setAntiAlias(false);
20039        }
20040        return sDebugPaint;
20041    }
20042
20043    final int dipsToPixels(int dips) {
20044        float scale = getContext().getResources().getDisplayMetrics().density;
20045        return (int) (dips * scale + 0.5f);
20046    }
20047
20048    final private void debugDrawFocus(Canvas canvas) {
20049        if (isFocused()) {
20050            final int cornerSquareSize = dipsToPixels(DEBUG_CORNERS_SIZE_DIP);
20051            final int l = mScrollX;
20052            final int r = l + mRight - mLeft;
20053            final int t = mScrollY;
20054            final int b = t + mBottom - mTop;
20055
20056            final Paint paint = getDebugPaint();
20057            paint.setColor(DEBUG_CORNERS_COLOR);
20058
20059            // Draw squares in corners.
20060            paint.setStyle(Paint.Style.FILL);
20061            canvas.drawRect(l, t, l + cornerSquareSize, t + cornerSquareSize, paint);
20062            canvas.drawRect(r - cornerSquareSize, t, r, t + cornerSquareSize, paint);
20063            canvas.drawRect(l, b - cornerSquareSize, l + cornerSquareSize, b, paint);
20064            canvas.drawRect(r - cornerSquareSize, b - cornerSquareSize, r, b, paint);
20065
20066            // Draw big X across the view.
20067            paint.setStyle(Paint.Style.STROKE);
20068            canvas.drawLine(l, t, r, b, paint);
20069            canvas.drawLine(l, b, r, t, paint);
20070        }
20071    }
20072
20073    /**
20074     * Manually render this view (and all of its children) to the given Canvas.
20075     * The view must have already done a full layout before this function is
20076     * called.  When implementing a view, implement
20077     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
20078     * If you do need to override this method, call the superclass version.
20079     *
20080     * @param canvas The Canvas to which the View is rendered.
20081     */
20082    @CallSuper
20083    public void draw(Canvas canvas) {
20084        final int privateFlags = mPrivateFlags;
20085        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
20086                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
20087        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
20088
20089        /*
20090         * Draw traversal performs several drawing steps which must be executed
20091         * in the appropriate order:
20092         *
20093         *      1. Draw the background
20094         *      2. If necessary, save the canvas' layers to prepare for fading
20095         *      3. Draw view's content
20096         *      4. Draw children
20097         *      5. If necessary, draw the fading edges and restore layers
20098         *      6. Draw decorations (scrollbars for instance)
20099         */
20100
20101        // Step 1, draw the background, if needed
20102        int saveCount;
20103
20104        if (!dirtyOpaque) {
20105            drawBackground(canvas);
20106        }
20107
20108        // skip step 2 & 5 if possible (common case)
20109        final int viewFlags = mViewFlags;
20110        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
20111        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
20112        if (!verticalEdges && !horizontalEdges) {
20113            // Step 3, draw the content
20114            if (!dirtyOpaque) onDraw(canvas);
20115
20116            // Step 4, draw the children
20117            dispatchDraw(canvas);
20118
20119            drawAutofilledHighlight(canvas);
20120
20121            // Overlay is part of the content and draws beneath Foreground
20122            if (mOverlay != null && !mOverlay.isEmpty()) {
20123                mOverlay.getOverlayView().dispatchDraw(canvas);
20124            }
20125
20126            // Step 6, draw decorations (foreground, scrollbars)
20127            onDrawForeground(canvas);
20128
20129            // Step 7, draw the default focus highlight
20130            drawDefaultFocusHighlight(canvas);
20131
20132            if (debugDraw()) {
20133                debugDrawFocus(canvas);
20134            }
20135
20136            // we're done...
20137            return;
20138        }
20139
20140        /*
20141         * Here we do the full fledged routine...
20142         * (this is an uncommon case where speed matters less,
20143         * this is why we repeat some of the tests that have been
20144         * done above)
20145         */
20146
20147        boolean drawTop = false;
20148        boolean drawBottom = false;
20149        boolean drawLeft = false;
20150        boolean drawRight = false;
20151
20152        float topFadeStrength = 0.0f;
20153        float bottomFadeStrength = 0.0f;
20154        float leftFadeStrength = 0.0f;
20155        float rightFadeStrength = 0.0f;
20156
20157        // Step 2, save the canvas' layers
20158        int paddingLeft = mPaddingLeft;
20159
20160        final boolean offsetRequired = isPaddingOffsetRequired();
20161        if (offsetRequired) {
20162            paddingLeft += getLeftPaddingOffset();
20163        }
20164
20165        int left = mScrollX + paddingLeft;
20166        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
20167        int top = mScrollY + getFadeTop(offsetRequired);
20168        int bottom = top + getFadeHeight(offsetRequired);
20169
20170        if (offsetRequired) {
20171            right += getRightPaddingOffset();
20172            bottom += getBottomPaddingOffset();
20173        }
20174
20175        final ScrollabilityCache scrollabilityCache = mScrollCache;
20176        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
20177        int length = (int) fadeHeight;
20178
20179        // clip the fade length if top and bottom fades overlap
20180        // overlapping fades produce odd-looking artifacts
20181        if (verticalEdges && (top + length > bottom - length)) {
20182            length = (bottom - top) / 2;
20183        }
20184
20185        // also clip horizontal fades if necessary
20186        if (horizontalEdges && (left + length > right - length)) {
20187            length = (right - left) / 2;
20188        }
20189
20190        if (verticalEdges) {
20191            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
20192            drawTop = topFadeStrength * fadeHeight > 1.0f;
20193            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
20194            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
20195        }
20196
20197        if (horizontalEdges) {
20198            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
20199            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
20200            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
20201            drawRight = rightFadeStrength * fadeHeight > 1.0f;
20202        }
20203
20204        saveCount = canvas.getSaveCount();
20205
20206        int solidColor = getSolidColor();
20207        if (solidColor == 0) {
20208            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
20209
20210            if (drawTop) {
20211                canvas.saveLayer(left, top, right, top + length, null, flags);
20212            }
20213
20214            if (drawBottom) {
20215                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
20216            }
20217
20218            if (drawLeft) {
20219                canvas.saveLayer(left, top, left + length, bottom, null, flags);
20220            }
20221
20222            if (drawRight) {
20223                canvas.saveLayer(right - length, top, right, bottom, null, flags);
20224            }
20225        } else {
20226            scrollabilityCache.setFadeColor(solidColor);
20227        }
20228
20229        // Step 3, draw the content
20230        if (!dirtyOpaque) onDraw(canvas);
20231
20232        // Step 4, draw the children
20233        dispatchDraw(canvas);
20234
20235        // Step 5, draw the fade effect and restore layers
20236        final Paint p = scrollabilityCache.paint;
20237        final Matrix matrix = scrollabilityCache.matrix;
20238        final Shader fade = scrollabilityCache.shader;
20239
20240        if (drawTop) {
20241            matrix.setScale(1, fadeHeight * topFadeStrength);
20242            matrix.postTranslate(left, top);
20243            fade.setLocalMatrix(matrix);
20244            p.setShader(fade);
20245            canvas.drawRect(left, top, right, top + length, p);
20246        }
20247
20248        if (drawBottom) {
20249            matrix.setScale(1, fadeHeight * bottomFadeStrength);
20250            matrix.postRotate(180);
20251            matrix.postTranslate(left, bottom);
20252            fade.setLocalMatrix(matrix);
20253            p.setShader(fade);
20254            canvas.drawRect(left, bottom - length, right, bottom, p);
20255        }
20256
20257        if (drawLeft) {
20258            matrix.setScale(1, fadeHeight * leftFadeStrength);
20259            matrix.postRotate(-90);
20260            matrix.postTranslate(left, top);
20261            fade.setLocalMatrix(matrix);
20262            p.setShader(fade);
20263            canvas.drawRect(left, top, left + length, bottom, p);
20264        }
20265
20266        if (drawRight) {
20267            matrix.setScale(1, fadeHeight * rightFadeStrength);
20268            matrix.postRotate(90);
20269            matrix.postTranslate(right, top);
20270            fade.setLocalMatrix(matrix);
20271            p.setShader(fade);
20272            canvas.drawRect(right - length, top, right, bottom, p);
20273        }
20274
20275        canvas.restoreToCount(saveCount);
20276
20277        drawAutofilledHighlight(canvas);
20278
20279        // Overlay is part of the content and draws beneath Foreground
20280        if (mOverlay != null && !mOverlay.isEmpty()) {
20281            mOverlay.getOverlayView().dispatchDraw(canvas);
20282        }
20283
20284        // Step 6, draw decorations (foreground, scrollbars)
20285        onDrawForeground(canvas);
20286
20287        if (debugDraw()) {
20288            debugDrawFocus(canvas);
20289        }
20290    }
20291
20292    /**
20293     * Draws the background onto the specified canvas.
20294     *
20295     * @param canvas Canvas on which to draw the background
20296     */
20297    private void drawBackground(Canvas canvas) {
20298        final Drawable background = mBackground;
20299        if (background == null) {
20300            return;
20301        }
20302
20303        setBackgroundBounds();
20304
20305        // Attempt to use a display list if requested.
20306        if (canvas.isHardwareAccelerated() && mAttachInfo != null
20307                && mAttachInfo.mThreadedRenderer != null) {
20308            mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode);
20309
20310            final RenderNode renderNode = mBackgroundRenderNode;
20311            if (renderNode != null && renderNode.isValid()) {
20312                setBackgroundRenderNodeProperties(renderNode);
20313                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
20314                return;
20315            }
20316        }
20317
20318        final int scrollX = mScrollX;
20319        final int scrollY = mScrollY;
20320        if ((scrollX | scrollY) == 0) {
20321            background.draw(canvas);
20322        } else {
20323            canvas.translate(scrollX, scrollY);
20324            background.draw(canvas);
20325            canvas.translate(-scrollX, -scrollY);
20326        }
20327    }
20328
20329    /**
20330     * Sets the correct background bounds and rebuilds the outline, if needed.
20331     * <p/>
20332     * This is called by LayoutLib.
20333     */
20334    void setBackgroundBounds() {
20335        if (mBackgroundSizeChanged && mBackground != null) {
20336            mBackground.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
20337            mBackgroundSizeChanged = false;
20338            rebuildOutline();
20339        }
20340    }
20341
20342    private void setBackgroundRenderNodeProperties(RenderNode renderNode) {
20343        renderNode.setTranslationX(mScrollX);
20344        renderNode.setTranslationY(mScrollY);
20345    }
20346
20347    /**
20348     * Creates a new display list or updates the existing display list for the
20349     * specified Drawable.
20350     *
20351     * @param drawable Drawable for which to create a display list
20352     * @param renderNode Existing RenderNode, or {@code null}
20353     * @return A valid display list for the specified drawable
20354     */
20355    private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) {
20356        if (renderNode == null) {
20357            renderNode = RenderNode.create(drawable.getClass().getName(), this);
20358        }
20359
20360        final Rect bounds = drawable.getBounds();
20361        final int width = bounds.width();
20362        final int height = bounds.height();
20363        final DisplayListCanvas canvas = renderNode.start(width, height);
20364
20365        // Reverse left/top translation done by drawable canvas, which will
20366        // instead be applied by rendernode's LTRB bounds below. This way, the
20367        // drawable's bounds match with its rendernode bounds and its content
20368        // will lie within those bounds in the rendernode tree.
20369        canvas.translate(-bounds.left, -bounds.top);
20370
20371        try {
20372            drawable.draw(canvas);
20373        } finally {
20374            renderNode.end(canvas);
20375        }
20376
20377        // Set up drawable properties that are view-independent.
20378        renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
20379        renderNode.setProjectBackwards(drawable.isProjected());
20380        renderNode.setProjectionReceiver(true);
20381        renderNode.setClipToBounds(false);
20382        return renderNode;
20383    }
20384
20385    /**
20386     * Returns the overlay for this view, creating it if it does not yet exist.
20387     * Adding drawables to the overlay will cause them to be displayed whenever
20388     * the view itself is redrawn. Objects in the overlay should be actively
20389     * managed: remove them when they should not be displayed anymore. The
20390     * overlay will always have the same size as its host view.
20391     *
20392     * <p>Note: Overlays do not currently work correctly with {@link
20393     * SurfaceView} or {@link TextureView}; contents in overlays for these
20394     * types of views may not display correctly.</p>
20395     *
20396     * @return The ViewOverlay object for this view.
20397     * @see ViewOverlay
20398     */
20399    public ViewOverlay getOverlay() {
20400        if (mOverlay == null) {
20401            mOverlay = new ViewOverlay(mContext, this);
20402        }
20403        return mOverlay;
20404    }
20405
20406    /**
20407     * Override this if your view is known to always be drawn on top of a solid color background,
20408     * and needs to draw fading edges. Returning a non-zero color enables the view system to
20409     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
20410     * should be set to 0xFF.
20411     *
20412     * @see #setVerticalFadingEdgeEnabled(boolean)
20413     * @see #setHorizontalFadingEdgeEnabled(boolean)
20414     *
20415     * @return The known solid color background for this view, or 0 if the color may vary
20416     */
20417    @ViewDebug.ExportedProperty(category = "drawing")
20418    @ColorInt
20419    public int getSolidColor() {
20420        return 0;
20421    }
20422
20423    /**
20424     * Build a human readable string representation of the specified view flags.
20425     *
20426     * @param flags the view flags to convert to a string
20427     * @return a String representing the supplied flags
20428     */
20429    private static String printFlags(int flags) {
20430        String output = "";
20431        int numFlags = 0;
20432        if ((flags & FOCUSABLE) == FOCUSABLE) {
20433            output += "TAKES_FOCUS";
20434            numFlags++;
20435        }
20436
20437        switch (flags & VISIBILITY_MASK) {
20438        case INVISIBLE:
20439            if (numFlags > 0) {
20440                output += " ";
20441            }
20442            output += "INVISIBLE";
20443            // USELESS HERE numFlags++;
20444            break;
20445        case GONE:
20446            if (numFlags > 0) {
20447                output += " ";
20448            }
20449            output += "GONE";
20450            // USELESS HERE numFlags++;
20451            break;
20452        default:
20453            break;
20454        }
20455        return output;
20456    }
20457
20458    /**
20459     * Build a human readable string representation of the specified private
20460     * view flags.
20461     *
20462     * @param privateFlags the private view flags to convert to a string
20463     * @return a String representing the supplied flags
20464     */
20465    private static String printPrivateFlags(int privateFlags) {
20466        String output = "";
20467        int numFlags = 0;
20468
20469        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
20470            output += "WANTS_FOCUS";
20471            numFlags++;
20472        }
20473
20474        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
20475            if (numFlags > 0) {
20476                output += " ";
20477            }
20478            output += "FOCUSED";
20479            numFlags++;
20480        }
20481
20482        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
20483            if (numFlags > 0) {
20484                output += " ";
20485            }
20486            output += "SELECTED";
20487            numFlags++;
20488        }
20489
20490        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
20491            if (numFlags > 0) {
20492                output += " ";
20493            }
20494            output += "IS_ROOT_NAMESPACE";
20495            numFlags++;
20496        }
20497
20498        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
20499            if (numFlags > 0) {
20500                output += " ";
20501            }
20502            output += "HAS_BOUNDS";
20503            numFlags++;
20504        }
20505
20506        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
20507            if (numFlags > 0) {
20508                output += " ";
20509            }
20510            output += "DRAWN";
20511            // USELESS HERE numFlags++;
20512        }
20513        return output;
20514    }
20515
20516    /**
20517     * <p>Indicates whether or not this view's layout will be requested during
20518     * the next hierarchy layout pass.</p>
20519     *
20520     * @return true if the layout will be forced during next layout pass
20521     */
20522    public boolean isLayoutRequested() {
20523        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
20524    }
20525
20526    /**
20527     * Return true if o is a ViewGroup that is laying out using optical bounds.
20528     * @hide
20529     */
20530    public static boolean isLayoutModeOptical(Object o) {
20531        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
20532    }
20533
20534    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
20535        Insets parentInsets = mParent instanceof View ?
20536                ((View) mParent).getOpticalInsets() : Insets.NONE;
20537        Insets childInsets = getOpticalInsets();
20538        return setFrame(
20539                left   + parentInsets.left - childInsets.left,
20540                top    + parentInsets.top  - childInsets.top,
20541                right  + parentInsets.left + childInsets.right,
20542                bottom + parentInsets.top  + childInsets.bottom);
20543    }
20544
20545    /**
20546     * Assign a size and position to a view and all of its
20547     * descendants
20548     *
20549     * <p>This is the second phase of the layout mechanism.
20550     * (The first is measuring). In this phase, each parent calls
20551     * layout on all of its children to position them.
20552     * This is typically done using the child measurements
20553     * that were stored in the measure pass().</p>
20554     *
20555     * <p>Derived classes should not override this method.
20556     * Derived classes with children should override
20557     * onLayout. In that method, they should
20558     * call layout on each of their children.</p>
20559     *
20560     * @param l Left position, relative to parent
20561     * @param t Top position, relative to parent
20562     * @param r Right position, relative to parent
20563     * @param b Bottom position, relative to parent
20564     */
20565    @SuppressWarnings({"unchecked"})
20566    public void layout(int l, int t, int r, int b) {
20567        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
20568            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
20569            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
20570        }
20571
20572        int oldL = mLeft;
20573        int oldT = mTop;
20574        int oldB = mBottom;
20575        int oldR = mRight;
20576
20577        boolean changed = isLayoutModeOptical(mParent) ?
20578                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
20579
20580        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
20581            onLayout(changed, l, t, r, b);
20582
20583            if (shouldDrawRoundScrollbar()) {
20584                if(mRoundScrollbarRenderer == null) {
20585                    mRoundScrollbarRenderer = new RoundScrollbarRenderer(this);
20586                }
20587            } else {
20588                mRoundScrollbarRenderer = null;
20589            }
20590
20591            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
20592
20593            ListenerInfo li = mListenerInfo;
20594            if (li != null && li.mOnLayoutChangeListeners != null) {
20595                ArrayList<OnLayoutChangeListener> listenersCopy =
20596                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
20597                int numListeners = listenersCopy.size();
20598                for (int i = 0; i < numListeners; ++i) {
20599                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
20600                }
20601            }
20602        }
20603
20604        final boolean wasLayoutValid = isLayoutValid();
20605
20606        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
20607        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
20608
20609        if (!wasLayoutValid && isFocused()) {
20610            mPrivateFlags &= ~PFLAG_WANTS_FOCUS;
20611            if (canTakeFocus()) {
20612                // We have a robust focus, so parents should no longer be wanting focus.
20613                clearParentsWantFocus();
20614            } else if (!getViewRootImpl().isInLayout()) {
20615                // This is a weird case. Most-likely the user, rather than ViewRootImpl, called
20616                // layout. In this case, there's no guarantee that parent layouts will be evaluated
20617                // and thus the safest action is to clear focus here.
20618                clearFocusInternal(null, /* propagate */ true, /* refocus */ false);
20619                clearParentsWantFocus();
20620            } else if (!hasParentWantsFocus()) {
20621                // original requestFocus was likely on this view directly, so just clear focus
20622                clearFocusInternal(null, /* propagate */ true, /* refocus */ false);
20623            }
20624            // otherwise, we let parents handle re-assigning focus during their layout passes.
20625        } else if ((mPrivateFlags & PFLAG_WANTS_FOCUS) != 0) {
20626            mPrivateFlags &= ~PFLAG_WANTS_FOCUS;
20627            View focused = findFocus();
20628            if (focused != null) {
20629                // Try to restore focus as close as possible to our starting focus.
20630                if (!restoreDefaultFocus() && !hasParentWantsFocus()) {
20631                    // Give up and clear focus once we've reached the top-most parent which wants
20632                    // focus.
20633                    focused.clearFocusInternal(null, /* propagate */ true, /* refocus */ false);
20634                }
20635            }
20636        }
20637
20638        if ((mPrivateFlags3 & PFLAG3_NOTIFY_AUTOFILL_ENTER_ON_LAYOUT) != 0) {
20639            mPrivateFlags3 &= ~PFLAG3_NOTIFY_AUTOFILL_ENTER_ON_LAYOUT;
20640            notifyEnterOrExitForAutoFillIfNeeded(true);
20641        }
20642    }
20643
20644    private boolean hasParentWantsFocus() {
20645        ViewParent parent = mParent;
20646        while (parent instanceof ViewGroup) {
20647            ViewGroup pv = (ViewGroup) parent;
20648            if ((pv.mPrivateFlags & PFLAG_WANTS_FOCUS) != 0) {
20649                return true;
20650            }
20651            parent = pv.mParent;
20652        }
20653        return false;
20654    }
20655
20656    /**
20657     * Called from layout when this view should
20658     * assign a size and position to each of its children.
20659     *
20660     * Derived classes with children should override
20661     * this method and call layout on each of
20662     * their children.
20663     * @param changed This is a new size or position for this view
20664     * @param left Left position, relative to parent
20665     * @param top Top position, relative to parent
20666     * @param right Right position, relative to parent
20667     * @param bottom Bottom position, relative to parent
20668     */
20669    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
20670    }
20671
20672    /**
20673     * Assign a size and position to this view.
20674     *
20675     * This is called from layout.
20676     *
20677     * @param left Left position, relative to parent
20678     * @param top Top position, relative to parent
20679     * @param right Right position, relative to parent
20680     * @param bottom Bottom position, relative to parent
20681     * @return true if the new size and position are different than the
20682     *         previous ones
20683     * {@hide}
20684     */
20685    protected boolean setFrame(int left, int top, int right, int bottom) {
20686        boolean changed = false;
20687
20688        if (DBG) {
20689            Log.d(VIEW_LOG_TAG, this + " View.setFrame(" + left + "," + top + ","
20690                    + right + "," + bottom + ")");
20691        }
20692
20693        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
20694            changed = true;
20695
20696            // Remember our drawn bit
20697            int drawn = mPrivateFlags & PFLAG_DRAWN;
20698
20699            int oldWidth = mRight - mLeft;
20700            int oldHeight = mBottom - mTop;
20701            int newWidth = right - left;
20702            int newHeight = bottom - top;
20703            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
20704
20705            // Invalidate our old position
20706            invalidate(sizeChanged);
20707
20708            mLeft = left;
20709            mTop = top;
20710            mRight = right;
20711            mBottom = bottom;
20712            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
20713
20714            mPrivateFlags |= PFLAG_HAS_BOUNDS;
20715
20716
20717            if (sizeChanged) {
20718                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
20719            }
20720
20721            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) {
20722                // If we are visible, force the DRAWN bit to on so that
20723                // this invalidate will go through (at least to our parent).
20724                // This is because someone may have invalidated this view
20725                // before this call to setFrame came in, thereby clearing
20726                // the DRAWN bit.
20727                mPrivateFlags |= PFLAG_DRAWN;
20728                invalidate(sizeChanged);
20729                // parent display list may need to be recreated based on a change in the bounds
20730                // of any child
20731                invalidateParentCaches();
20732            }
20733
20734            // Reset drawn bit to original value (invalidate turns it off)
20735            mPrivateFlags |= drawn;
20736
20737            mBackgroundSizeChanged = true;
20738            mDefaultFocusHighlightSizeChanged = true;
20739            if (mForegroundInfo != null) {
20740                mForegroundInfo.mBoundsChanged = true;
20741            }
20742
20743            notifySubtreeAccessibilityStateChangedIfNeeded();
20744        }
20745        return changed;
20746    }
20747
20748    /**
20749     * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}.
20750     * @hide
20751     */
20752    public void setLeftTopRightBottom(int left, int top, int right, int bottom) {
20753        setFrame(left, top, right, bottom);
20754    }
20755
20756    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
20757        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
20758        if (mOverlay != null) {
20759            mOverlay.getOverlayView().setRight(newWidth);
20760            mOverlay.getOverlayView().setBottom(newHeight);
20761        }
20762        // If this isn't laid out yet, focus assignment will be handled during the "deferment/
20763        // backtracking" of requestFocus during layout, so don't touch focus here.
20764        if (!sCanFocusZeroSized && isLayoutValid()) {
20765            if (newWidth <= 0 || newHeight <= 0) {
20766                if (hasFocus()) {
20767                    clearFocus();
20768                    if (mParent instanceof ViewGroup) {
20769                        ((ViewGroup) mParent).clearFocusedInCluster();
20770                    }
20771                }
20772                clearAccessibilityFocus();
20773            } else if (oldWidth <= 0 || oldHeight <= 0) {
20774                if (mParent != null && canTakeFocus()) {
20775                    mParent.focusableViewAvailable(this);
20776                }
20777            }
20778        }
20779        rebuildOutline();
20780    }
20781
20782    /**
20783     * Finalize inflating a view from XML.  This is called as the last phase
20784     * of inflation, after all child views have been added.
20785     *
20786     * <p>Even if the subclass overrides onFinishInflate, they should always be
20787     * sure to call the super method, so that we get called.
20788     */
20789    @CallSuper
20790    protected void onFinishInflate() {
20791    }
20792
20793    /**
20794     * Returns the resources associated with this view.
20795     *
20796     * @return Resources object.
20797     */
20798    public Resources getResources() {
20799        return mResources;
20800    }
20801
20802    /**
20803     * Invalidates the specified Drawable.
20804     *
20805     * @param drawable the drawable to invalidate
20806     */
20807    @Override
20808    public void invalidateDrawable(@NonNull Drawable drawable) {
20809        if (verifyDrawable(drawable)) {
20810            final Rect dirty = drawable.getDirtyBounds();
20811            final int scrollX = mScrollX;
20812            final int scrollY = mScrollY;
20813
20814            invalidate(dirty.left + scrollX, dirty.top + scrollY,
20815                    dirty.right + scrollX, dirty.bottom + scrollY);
20816            rebuildOutline();
20817        }
20818    }
20819
20820    /**
20821     * Schedules an action on a drawable to occur at a specified time.
20822     *
20823     * @param who the recipient of the action
20824     * @param what the action to run on the drawable
20825     * @param when the time at which the action must occur. Uses the
20826     *        {@link SystemClock#uptimeMillis} timebase.
20827     */
20828    @Override
20829    public void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when) {
20830        if (verifyDrawable(who) && what != null) {
20831            final long delay = when - SystemClock.uptimeMillis();
20832            if (mAttachInfo != null) {
20833                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
20834                        Choreographer.CALLBACK_ANIMATION, what, who,
20835                        Choreographer.subtractFrameDelay(delay));
20836            } else {
20837                // Postpone the runnable until we know
20838                // on which thread it needs to run.
20839                getRunQueue().postDelayed(what, delay);
20840            }
20841        }
20842    }
20843
20844    /**
20845     * Cancels a scheduled action on a drawable.
20846     *
20847     * @param who the recipient of the action
20848     * @param what the action to cancel
20849     */
20850    @Override
20851    public void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what) {
20852        if (verifyDrawable(who) && what != null) {
20853            if (mAttachInfo != null) {
20854                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
20855                        Choreographer.CALLBACK_ANIMATION, what, who);
20856            }
20857            getRunQueue().removeCallbacks(what);
20858        }
20859    }
20860
20861    /**
20862     * Unschedule any events associated with the given Drawable.  This can be
20863     * used when selecting a new Drawable into a view, so that the previous
20864     * one is completely unscheduled.
20865     *
20866     * @param who The Drawable to unschedule.
20867     *
20868     * @see #drawableStateChanged
20869     */
20870    public void unscheduleDrawable(Drawable who) {
20871        if (mAttachInfo != null && who != null) {
20872            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
20873                    Choreographer.CALLBACK_ANIMATION, null, who);
20874        }
20875    }
20876
20877    /**
20878     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
20879     * that the View directionality can and will be resolved before its Drawables.
20880     *
20881     * Will call {@link View#onResolveDrawables} when resolution is done.
20882     *
20883     * @hide
20884     */
20885    protected void resolveDrawables() {
20886        // Drawables resolution may need to happen before resolving the layout direction (which is
20887        // done only during the measure() call).
20888        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
20889        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
20890        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
20891        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
20892        // direction to be resolved as its resolved value will be the same as its raw value.
20893        if (!isLayoutDirectionResolved() &&
20894                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
20895            return;
20896        }
20897
20898        final int layoutDirection = isLayoutDirectionResolved() ?
20899                getLayoutDirection() : getRawLayoutDirection();
20900
20901        if (mBackground != null) {
20902            mBackground.setLayoutDirection(layoutDirection);
20903        }
20904        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
20905            mForegroundInfo.mDrawable.setLayoutDirection(layoutDirection);
20906        }
20907        if (mDefaultFocusHighlight != null) {
20908            mDefaultFocusHighlight.setLayoutDirection(layoutDirection);
20909        }
20910        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
20911        onResolveDrawables(layoutDirection);
20912    }
20913
20914    boolean areDrawablesResolved() {
20915        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
20916    }
20917
20918    /**
20919     * Called when layout direction has been resolved.
20920     *
20921     * The default implementation does nothing.
20922     *
20923     * @param layoutDirection The resolved layout direction.
20924     *
20925     * @see #LAYOUT_DIRECTION_LTR
20926     * @see #LAYOUT_DIRECTION_RTL
20927     *
20928     * @hide
20929     */
20930    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
20931    }
20932
20933    /**
20934     * @hide
20935     */
20936    protected void resetResolvedDrawables() {
20937        resetResolvedDrawablesInternal();
20938    }
20939
20940    void resetResolvedDrawablesInternal() {
20941        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
20942    }
20943
20944    /**
20945     * If your view subclass is displaying its own Drawable objects, it should
20946     * override this function and return true for any Drawable it is
20947     * displaying.  This allows animations for those drawables to be
20948     * scheduled.
20949     *
20950     * <p>Be sure to call through to the super class when overriding this
20951     * function.
20952     *
20953     * @param who The Drawable to verify.  Return true if it is one you are
20954     *            displaying, else return the result of calling through to the
20955     *            super class.
20956     *
20957     * @return boolean If true than the Drawable is being displayed in the
20958     *         view; else false and it is not allowed to animate.
20959     *
20960     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
20961     * @see #drawableStateChanged()
20962     */
20963    @CallSuper
20964    protected boolean verifyDrawable(@NonNull Drawable who) {
20965        // Avoid verifying the scroll bar drawable so that we don't end up in
20966        // an invalidation loop. This effectively prevents the scroll bar
20967        // drawable from triggering invalidations and scheduling runnables.
20968        return who == mBackground || (mForegroundInfo != null && mForegroundInfo.mDrawable == who)
20969                || (mDefaultFocusHighlight == who);
20970    }
20971
20972    /**
20973     * This function is called whenever the state of the view changes in such
20974     * a way that it impacts the state of drawables being shown.
20975     * <p>
20976     * If the View has a StateListAnimator, it will also be called to run necessary state
20977     * change animations.
20978     * <p>
20979     * Be sure to call through to the superclass when overriding this function.
20980     *
20981     * @see Drawable#setState(int[])
20982     */
20983    @CallSuper
20984    protected void drawableStateChanged() {
20985        final int[] state = getDrawableState();
20986        boolean changed = false;
20987
20988        final Drawable bg = mBackground;
20989        if (bg != null && bg.isStateful()) {
20990            changed |= bg.setState(state);
20991        }
20992
20993        final Drawable hl = mDefaultFocusHighlight;
20994        if (hl != null && hl.isStateful()) {
20995            changed |= hl.setState(state);
20996        }
20997
20998        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
20999        if (fg != null && fg.isStateful()) {
21000            changed |= fg.setState(state);
21001        }
21002
21003        if (mScrollCache != null) {
21004            final Drawable scrollBar = mScrollCache.scrollBar;
21005            if (scrollBar != null && scrollBar.isStateful()) {
21006                changed |= scrollBar.setState(state)
21007                        && mScrollCache.state != ScrollabilityCache.OFF;
21008            }
21009        }
21010
21011        if (mStateListAnimator != null) {
21012            mStateListAnimator.setState(state);
21013        }
21014
21015        if (changed) {
21016            invalidate();
21017        }
21018    }
21019
21020    /**
21021     * This function is called whenever the view hotspot changes and needs to
21022     * be propagated to drawables or child views managed by the view.
21023     * <p>
21024     * Dispatching to child views is handled by
21025     * {@link #dispatchDrawableHotspotChanged(float, float)}.
21026     * <p>
21027     * Be sure to call through to the superclass when overriding this function.
21028     *
21029     * @param x hotspot x coordinate
21030     * @param y hotspot y coordinate
21031     */
21032    @CallSuper
21033    public void drawableHotspotChanged(float x, float y) {
21034        if (mBackground != null) {
21035            mBackground.setHotspot(x, y);
21036        }
21037        if (mDefaultFocusHighlight != null) {
21038            mDefaultFocusHighlight.setHotspot(x, y);
21039        }
21040        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
21041            mForegroundInfo.mDrawable.setHotspot(x, y);
21042        }
21043
21044        dispatchDrawableHotspotChanged(x, y);
21045    }
21046
21047    /**
21048     * Dispatches drawableHotspotChanged to all of this View's children.
21049     *
21050     * @param x hotspot x coordinate
21051     * @param y hotspot y coordinate
21052     * @see #drawableHotspotChanged(float, float)
21053     */
21054    public void dispatchDrawableHotspotChanged(float x, float y) {
21055    }
21056
21057    /**
21058     * Call this to force a view to update its drawable state. This will cause
21059     * drawableStateChanged to be called on this view. Views that are interested
21060     * in the new state should call getDrawableState.
21061     *
21062     * @see #drawableStateChanged
21063     * @see #getDrawableState
21064     */
21065    public void refreshDrawableState() {
21066        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
21067        drawableStateChanged();
21068
21069        ViewParent parent = mParent;
21070        if (parent != null) {
21071            parent.childDrawableStateChanged(this);
21072        }
21073    }
21074
21075    /**
21076     * Create a default focus highlight if it doesn't exist.
21077     * @return a default focus highlight.
21078     */
21079    private Drawable getDefaultFocusHighlightDrawable() {
21080        if (mDefaultFocusHighlightCache == null) {
21081            if (mContext != null) {
21082                final int[] attrs = new int[] { android.R.attr.selectableItemBackground };
21083                final TypedArray ta = mContext.obtainStyledAttributes(attrs);
21084                mDefaultFocusHighlightCache = ta.getDrawable(0);
21085                ta.recycle();
21086            }
21087        }
21088        return mDefaultFocusHighlightCache;
21089    }
21090
21091    /**
21092     * Set the current default focus highlight.
21093     * @param highlight the highlight drawable, or {@code null} if it's no longer needed.
21094     */
21095    private void setDefaultFocusHighlight(Drawable highlight) {
21096        mDefaultFocusHighlight = highlight;
21097        mDefaultFocusHighlightSizeChanged = true;
21098        if (highlight != null) {
21099            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
21100                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
21101            }
21102            highlight.setLayoutDirection(getLayoutDirection());
21103            if (highlight.isStateful()) {
21104                highlight.setState(getDrawableState());
21105            }
21106            if (isAttachedToWindow()) {
21107                highlight.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
21108            }
21109            // Set callback last, since the view may still be initializing.
21110            highlight.setCallback(this);
21111        } else if ((mViewFlags & WILL_NOT_DRAW) != 0 && mBackground == null
21112                && (mForegroundInfo == null || mForegroundInfo.mDrawable == null)) {
21113            mPrivateFlags |= PFLAG_SKIP_DRAW;
21114        }
21115        invalidate();
21116    }
21117
21118    /**
21119     * Check whether we need to draw a default focus highlight when this view gets focused,
21120     * which requires:
21121     * <ul>
21122     *     <li>In both background and foreground, {@link android.R.attr#state_focused}
21123     *         is not defined.</li>
21124     *     <li>This view is not in touch mode.</li>
21125     *     <li>This view doesn't opt out for a default focus highlight, via
21126     *         {@link #setDefaultFocusHighlightEnabled(boolean)}.</li>
21127     *     <li>This view is attached to window.</li>
21128     * </ul>
21129     * @return {@code true} if a default focus highlight is needed.
21130     * @hide
21131     */
21132    @TestApi
21133    public boolean isDefaultFocusHighlightNeeded(Drawable background, Drawable foreground) {
21134        final boolean lackFocusState = (background == null || !background.isStateful()
21135                || !background.hasFocusStateSpecified())
21136                && (foreground == null || !foreground.isStateful()
21137                || !foreground.hasFocusStateSpecified());
21138        return !isInTouchMode() && getDefaultFocusHighlightEnabled() && lackFocusState
21139                && isAttachedToWindow() && sUseDefaultFocusHighlight;
21140    }
21141
21142    /**
21143     * When this view is focused, switches on/off the default focused highlight.
21144     * <p>
21145     * This always happens when this view is focused, and only at this moment the default focus
21146     * highlight can be visible.
21147     */
21148    private void switchDefaultFocusHighlight() {
21149        if (isFocused()) {
21150            final boolean needed = isDefaultFocusHighlightNeeded(mBackground,
21151                    mForegroundInfo == null ? null : mForegroundInfo.mDrawable);
21152            final boolean active = mDefaultFocusHighlight != null;
21153            if (needed && !active) {
21154                setDefaultFocusHighlight(getDefaultFocusHighlightDrawable());
21155            } else if (!needed && active) {
21156                // The highlight is no longer needed, so tear it down.
21157                setDefaultFocusHighlight(null);
21158            }
21159        }
21160    }
21161
21162    /**
21163     * Draw the default focus highlight onto the canvas.
21164     * @param canvas the canvas where we're drawing the highlight.
21165     */
21166    private void drawDefaultFocusHighlight(Canvas canvas) {
21167        if (mDefaultFocusHighlight != null) {
21168            if (mDefaultFocusHighlightSizeChanged) {
21169                mDefaultFocusHighlightSizeChanged = false;
21170                final int l = mScrollX;
21171                final int r = l + mRight - mLeft;
21172                final int t = mScrollY;
21173                final int b = t + mBottom - mTop;
21174                mDefaultFocusHighlight.setBounds(l, t, r, b);
21175            }
21176            mDefaultFocusHighlight.draw(canvas);
21177        }
21178    }
21179
21180    /**
21181     * Return an array of resource IDs of the drawable states representing the
21182     * current state of the view.
21183     *
21184     * @return The current drawable state
21185     *
21186     * @see Drawable#setState(int[])
21187     * @see #drawableStateChanged()
21188     * @see #onCreateDrawableState(int)
21189     */
21190    public final int[] getDrawableState() {
21191        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
21192            return mDrawableState;
21193        } else {
21194            mDrawableState = onCreateDrawableState(0);
21195            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
21196            return mDrawableState;
21197        }
21198    }
21199
21200    /**
21201     * Generate the new {@link android.graphics.drawable.Drawable} state for
21202     * this view. This is called by the view
21203     * system when the cached Drawable state is determined to be invalid.  To
21204     * retrieve the current state, you should use {@link #getDrawableState}.
21205     *
21206     * @param extraSpace if non-zero, this is the number of extra entries you
21207     * would like in the returned array in which you can place your own
21208     * states.
21209     *
21210     * @return Returns an array holding the current {@link Drawable} state of
21211     * the view.
21212     *
21213     * @see #mergeDrawableStates(int[], int[])
21214     */
21215    protected int[] onCreateDrawableState(int extraSpace) {
21216        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
21217                mParent instanceof View) {
21218            return ((View) mParent).onCreateDrawableState(extraSpace);
21219        }
21220
21221        int[] drawableState;
21222
21223        int privateFlags = mPrivateFlags;
21224
21225        int viewStateIndex = 0;
21226        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= StateSet.VIEW_STATE_PRESSED;
21227        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= StateSet.VIEW_STATE_ENABLED;
21228        if (isFocused()) viewStateIndex |= StateSet.VIEW_STATE_FOCUSED;
21229        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= StateSet.VIEW_STATE_SELECTED;
21230        if (hasWindowFocus()) viewStateIndex |= StateSet.VIEW_STATE_WINDOW_FOCUSED;
21231        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= StateSet.VIEW_STATE_ACTIVATED;
21232        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
21233                ThreadedRenderer.isAvailable()) {
21234            // This is set if HW acceleration is requested, even if the current
21235            // process doesn't allow it.  This is just to allow app preview
21236            // windows to better match their app.
21237            viewStateIndex |= StateSet.VIEW_STATE_ACCELERATED;
21238        }
21239        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= StateSet.VIEW_STATE_HOVERED;
21240
21241        final int privateFlags2 = mPrivateFlags2;
21242        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) {
21243            viewStateIndex |= StateSet.VIEW_STATE_DRAG_CAN_ACCEPT;
21244        }
21245        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) {
21246            viewStateIndex |= StateSet.VIEW_STATE_DRAG_HOVERED;
21247        }
21248
21249        drawableState = StateSet.get(viewStateIndex);
21250
21251        //noinspection ConstantIfStatement
21252        if (false) {
21253            Log.i("View", "drawableStateIndex=" + viewStateIndex);
21254            Log.i("View", toString()
21255                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
21256                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
21257                    + " fo=" + hasFocus()
21258                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
21259                    + " wf=" + hasWindowFocus()
21260                    + ": " + Arrays.toString(drawableState));
21261        }
21262
21263        if (extraSpace == 0) {
21264            return drawableState;
21265        }
21266
21267        final int[] fullState;
21268        if (drawableState != null) {
21269            fullState = new int[drawableState.length + extraSpace];
21270            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
21271        } else {
21272            fullState = new int[extraSpace];
21273        }
21274
21275        return fullState;
21276    }
21277
21278    /**
21279     * Merge your own state values in <var>additionalState</var> into the base
21280     * state values <var>baseState</var> that were returned by
21281     * {@link #onCreateDrawableState(int)}.
21282     *
21283     * @param baseState The base state values returned by
21284     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
21285     * own additional state values.
21286     *
21287     * @param additionalState The additional state values you would like
21288     * added to <var>baseState</var>; this array is not modified.
21289     *
21290     * @return As a convenience, the <var>baseState</var> array you originally
21291     * passed into the function is returned.
21292     *
21293     * @see #onCreateDrawableState(int)
21294     */
21295    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
21296        final int N = baseState.length;
21297        int i = N - 1;
21298        while (i >= 0 && baseState[i] == 0) {
21299            i--;
21300        }
21301        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
21302        return baseState;
21303    }
21304
21305    /**
21306     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
21307     * on all Drawable objects associated with this view.
21308     * <p>
21309     * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator
21310     * attached to this view.
21311     */
21312    @CallSuper
21313    public void jumpDrawablesToCurrentState() {
21314        if (mBackground != null) {
21315            mBackground.jumpToCurrentState();
21316        }
21317        if (mStateListAnimator != null) {
21318            mStateListAnimator.jumpToCurrentState();
21319        }
21320        if (mDefaultFocusHighlight != null) {
21321            mDefaultFocusHighlight.jumpToCurrentState();
21322        }
21323        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
21324            mForegroundInfo.mDrawable.jumpToCurrentState();
21325        }
21326    }
21327
21328    /**
21329     * Sets the background color for this view.
21330     * @param color the color of the background
21331     */
21332    @RemotableViewMethod
21333    public void setBackgroundColor(@ColorInt int color) {
21334        if (mBackground instanceof ColorDrawable) {
21335            ((ColorDrawable) mBackground.mutate()).setColor(color);
21336            computeOpaqueFlags();
21337            mBackgroundResource = 0;
21338        } else {
21339            setBackground(new ColorDrawable(color));
21340        }
21341    }
21342
21343    /**
21344     * Set the background to a given resource. The resource should refer to
21345     * a Drawable object or 0 to remove the background.
21346     * @param resid The identifier of the resource.
21347     *
21348     * @attr ref android.R.styleable#View_background
21349     */
21350    @RemotableViewMethod
21351    public void setBackgroundResource(@DrawableRes int resid) {
21352        if (resid != 0 && resid == mBackgroundResource) {
21353            return;
21354        }
21355
21356        Drawable d = null;
21357        if (resid != 0) {
21358            d = mContext.getDrawable(resid);
21359        }
21360        setBackground(d);
21361
21362        mBackgroundResource = resid;
21363    }
21364
21365    /**
21366     * Set the background to a given Drawable, or remove the background. If the
21367     * background has padding, this View's padding is set to the background's
21368     * padding. However, when a background is removed, this View's padding isn't
21369     * touched. If setting the padding is desired, please use
21370     * {@link #setPadding(int, int, int, int)}.
21371     *
21372     * @param background The Drawable to use as the background, or null to remove the
21373     *        background
21374     */
21375    public void setBackground(Drawable background) {
21376        //noinspection deprecation
21377        setBackgroundDrawable(background);
21378    }
21379
21380    /**
21381     * @deprecated use {@link #setBackground(Drawable)} instead
21382     */
21383    @Deprecated
21384    public void setBackgroundDrawable(Drawable background) {
21385        computeOpaqueFlags();
21386
21387        if (background == mBackground) {
21388            return;
21389        }
21390
21391        boolean requestLayout = false;
21392
21393        mBackgroundResource = 0;
21394
21395        /*
21396         * Regardless of whether we're setting a new background or not, we want
21397         * to clear the previous drawable. setVisible first while we still have the callback set.
21398         */
21399        if (mBackground != null) {
21400            if (isAttachedToWindow()) {
21401                mBackground.setVisible(false, false);
21402            }
21403            mBackground.setCallback(null);
21404            unscheduleDrawable(mBackground);
21405        }
21406
21407        if (background != null) {
21408            Rect padding = sThreadLocal.get();
21409            if (padding == null) {
21410                padding = new Rect();
21411                sThreadLocal.set(padding);
21412            }
21413            resetResolvedDrawablesInternal();
21414            background.setLayoutDirection(getLayoutDirection());
21415            if (background.getPadding(padding)) {
21416                resetResolvedPaddingInternal();
21417                switch (background.getLayoutDirection()) {
21418                    case LAYOUT_DIRECTION_RTL:
21419                        mUserPaddingLeftInitial = padding.right;
21420                        mUserPaddingRightInitial = padding.left;
21421                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
21422                        break;
21423                    case LAYOUT_DIRECTION_LTR:
21424                    default:
21425                        mUserPaddingLeftInitial = padding.left;
21426                        mUserPaddingRightInitial = padding.right;
21427                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
21428                }
21429                mLeftPaddingDefined = false;
21430                mRightPaddingDefined = false;
21431            }
21432
21433            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
21434            // if it has a different minimum size, we should layout again
21435            if (mBackground == null
21436                    || mBackground.getMinimumHeight() != background.getMinimumHeight()
21437                    || mBackground.getMinimumWidth() != background.getMinimumWidth()) {
21438                requestLayout = true;
21439            }
21440
21441            // Set mBackground before we set this as the callback and start making other
21442            // background drawable state change calls. In particular, the setVisible call below
21443            // can result in drawables attempting to start animations or otherwise invalidate,
21444            // which requires the view set as the callback (us) to recognize the drawable as
21445            // belonging to it as per verifyDrawable.
21446            mBackground = background;
21447            if (background.isStateful()) {
21448                background.setState(getDrawableState());
21449            }
21450            if (isAttachedToWindow()) {
21451                background.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
21452            }
21453
21454            applyBackgroundTint();
21455
21456            // Set callback last, since the view may still be initializing.
21457            background.setCallback(this);
21458
21459            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
21460                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
21461                requestLayout = true;
21462            }
21463        } else {
21464            /* Remove the background */
21465            mBackground = null;
21466            if ((mViewFlags & WILL_NOT_DRAW) != 0
21467                    && (mDefaultFocusHighlight == null)
21468                    && (mForegroundInfo == null || mForegroundInfo.mDrawable == null)) {
21469                mPrivateFlags |= PFLAG_SKIP_DRAW;
21470            }
21471
21472            /*
21473             * When the background is set, we try to apply its padding to this
21474             * View. When the background is removed, we don't touch this View's
21475             * padding. This is noted in the Javadocs. Hence, we don't need to
21476             * requestLayout(), the invalidate() below is sufficient.
21477             */
21478
21479            // The old background's minimum size could have affected this
21480            // View's layout, so let's requestLayout
21481            requestLayout = true;
21482        }
21483
21484        computeOpaqueFlags();
21485
21486        if (requestLayout) {
21487            requestLayout();
21488        }
21489
21490        mBackgroundSizeChanged = true;
21491        invalidate(true);
21492        invalidateOutline();
21493    }
21494
21495    /**
21496     * Gets the background drawable
21497     *
21498     * @return The drawable used as the background for this view, if any.
21499     *
21500     * @see #setBackground(Drawable)
21501     *
21502     * @attr ref android.R.styleable#View_background
21503     */
21504    public Drawable getBackground() {
21505        return mBackground;
21506    }
21507
21508    /**
21509     * Applies a tint to the background drawable. Does not modify the current tint
21510     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
21511     * <p>
21512     * Subsequent calls to {@link #setBackground(Drawable)} will automatically
21513     * mutate the drawable and apply the specified tint and tint mode using
21514     * {@link Drawable#setTintList(ColorStateList)}.
21515     *
21516     * @param tint the tint to apply, may be {@code null} to clear tint
21517     *
21518     * @attr ref android.R.styleable#View_backgroundTint
21519     * @see #getBackgroundTintList()
21520     * @see Drawable#setTintList(ColorStateList)
21521     */
21522    public void setBackgroundTintList(@Nullable ColorStateList tint) {
21523        if (mBackgroundTint == null) {
21524            mBackgroundTint = new TintInfo();
21525        }
21526        mBackgroundTint.mTintList = tint;
21527        mBackgroundTint.mHasTintList = true;
21528
21529        applyBackgroundTint();
21530    }
21531
21532    /**
21533     * Return the tint applied to the background drawable, if specified.
21534     *
21535     * @return the tint applied to the background drawable
21536     * @attr ref android.R.styleable#View_backgroundTint
21537     * @see #setBackgroundTintList(ColorStateList)
21538     */
21539    @Nullable
21540    public ColorStateList getBackgroundTintList() {
21541        return mBackgroundTint != null ? mBackgroundTint.mTintList : null;
21542    }
21543
21544    /**
21545     * Specifies the blending mode used to apply the tint specified by
21546     * {@link #setBackgroundTintList(ColorStateList)}} to the background
21547     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
21548     *
21549     * @param tintMode the blending mode used to apply the tint, may be
21550     *                 {@code null} to clear tint
21551     * @attr ref android.R.styleable#View_backgroundTintMode
21552     * @see #getBackgroundTintMode()
21553     * @see Drawable#setTintMode(PorterDuff.Mode)
21554     */
21555    public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) {
21556        if (mBackgroundTint == null) {
21557            mBackgroundTint = new TintInfo();
21558        }
21559        mBackgroundTint.mTintMode = tintMode;
21560        mBackgroundTint.mHasTintMode = true;
21561
21562        applyBackgroundTint();
21563    }
21564
21565    /**
21566     * Return the blending mode used to apply the tint to the background
21567     * drawable, if specified.
21568     *
21569     * @return the blending mode used to apply the tint to the background
21570     *         drawable
21571     * @attr ref android.R.styleable#View_backgroundTintMode
21572     * @see #setBackgroundTintMode(PorterDuff.Mode)
21573     */
21574    @Nullable
21575    public PorterDuff.Mode getBackgroundTintMode() {
21576        return mBackgroundTint != null ? mBackgroundTint.mTintMode : null;
21577    }
21578
21579    private void applyBackgroundTint() {
21580        if (mBackground != null && mBackgroundTint != null) {
21581            final TintInfo tintInfo = mBackgroundTint;
21582            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
21583                mBackground = mBackground.mutate();
21584
21585                if (tintInfo.mHasTintList) {
21586                    mBackground.setTintList(tintInfo.mTintList);
21587                }
21588
21589                if (tintInfo.mHasTintMode) {
21590                    mBackground.setTintMode(tintInfo.mTintMode);
21591                }
21592
21593                // The drawable (or one of its children) may not have been
21594                // stateful before applying the tint, so let's try again.
21595                if (mBackground.isStateful()) {
21596                    mBackground.setState(getDrawableState());
21597                }
21598            }
21599        }
21600    }
21601
21602    /**
21603     * Returns the drawable used as the foreground of this View. The
21604     * foreground drawable, if non-null, is always drawn on top of the view's content.
21605     *
21606     * @return a Drawable or null if no foreground was set
21607     *
21608     * @see #onDrawForeground(Canvas)
21609     */
21610    public Drawable getForeground() {
21611        return mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
21612    }
21613
21614    /**
21615     * Supply a Drawable that is to be rendered on top of all of the content in the view.
21616     *
21617     * @param foreground the Drawable to be drawn on top of the children
21618     *
21619     * @attr ref android.R.styleable#View_foreground
21620     */
21621    public void setForeground(Drawable foreground) {
21622        if (mForegroundInfo == null) {
21623            if (foreground == null) {
21624                // Nothing to do.
21625                return;
21626            }
21627            mForegroundInfo = new ForegroundInfo();
21628        }
21629
21630        if (foreground == mForegroundInfo.mDrawable) {
21631            // Nothing to do
21632            return;
21633        }
21634
21635        if (mForegroundInfo.mDrawable != null) {
21636            if (isAttachedToWindow()) {
21637                mForegroundInfo.mDrawable.setVisible(false, false);
21638            }
21639            mForegroundInfo.mDrawable.setCallback(null);
21640            unscheduleDrawable(mForegroundInfo.mDrawable);
21641        }
21642
21643        mForegroundInfo.mDrawable = foreground;
21644        mForegroundInfo.mBoundsChanged = true;
21645        if (foreground != null) {
21646            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
21647                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
21648            }
21649            foreground.setLayoutDirection(getLayoutDirection());
21650            if (foreground.isStateful()) {
21651                foreground.setState(getDrawableState());
21652            }
21653            applyForegroundTint();
21654            if (isAttachedToWindow()) {
21655                foreground.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
21656            }
21657            // Set callback last, since the view may still be initializing.
21658            foreground.setCallback(this);
21659        } else if ((mViewFlags & WILL_NOT_DRAW) != 0 && mBackground == null
21660                && (mDefaultFocusHighlight == null)) {
21661            mPrivateFlags |= PFLAG_SKIP_DRAW;
21662        }
21663        requestLayout();
21664        invalidate();
21665    }
21666
21667    /**
21668     * Magic bit used to support features of framework-internal window decor implementation details.
21669     * This used to live exclusively in FrameLayout.
21670     *
21671     * @return true if the foreground should draw inside the padding region or false
21672     *         if it should draw inset by the view's padding
21673     * @hide internal use only; only used by FrameLayout and internal screen layouts.
21674     */
21675    public boolean isForegroundInsidePadding() {
21676        return mForegroundInfo != null ? mForegroundInfo.mInsidePadding : true;
21677    }
21678
21679    /**
21680     * Describes how the foreground is positioned.
21681     *
21682     * @return foreground gravity.
21683     *
21684     * @see #setForegroundGravity(int)
21685     *
21686     * @attr ref android.R.styleable#View_foregroundGravity
21687     */
21688    public int getForegroundGravity() {
21689        return mForegroundInfo != null ? mForegroundInfo.mGravity
21690                : Gravity.START | Gravity.TOP;
21691    }
21692
21693    /**
21694     * Describes how the foreground is positioned. Defaults to START and TOP.
21695     *
21696     * @param gravity see {@link android.view.Gravity}
21697     *
21698     * @see #getForegroundGravity()
21699     *
21700     * @attr ref android.R.styleable#View_foregroundGravity
21701     */
21702    public void setForegroundGravity(int gravity) {
21703        if (mForegroundInfo == null) {
21704            mForegroundInfo = new ForegroundInfo();
21705        }
21706
21707        if (mForegroundInfo.mGravity != gravity) {
21708            if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) {
21709                gravity |= Gravity.START;
21710            }
21711
21712            if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) {
21713                gravity |= Gravity.TOP;
21714            }
21715
21716            mForegroundInfo.mGravity = gravity;
21717            requestLayout();
21718        }
21719    }
21720
21721    /**
21722     * Applies a tint to the foreground drawable. Does not modify the current tint
21723     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
21724     * <p>
21725     * Subsequent calls to {@link #setForeground(Drawable)} will automatically
21726     * mutate the drawable and apply the specified tint and tint mode using
21727     * {@link Drawable#setTintList(ColorStateList)}.
21728     *
21729     * @param tint the tint to apply, may be {@code null} to clear tint
21730     *
21731     * @attr ref android.R.styleable#View_foregroundTint
21732     * @see #getForegroundTintList()
21733     * @see Drawable#setTintList(ColorStateList)
21734     */
21735    public void setForegroundTintList(@Nullable ColorStateList tint) {
21736        if (mForegroundInfo == null) {
21737            mForegroundInfo = new ForegroundInfo();
21738        }
21739        if (mForegroundInfo.mTintInfo == null) {
21740            mForegroundInfo.mTintInfo = new TintInfo();
21741        }
21742        mForegroundInfo.mTintInfo.mTintList = tint;
21743        mForegroundInfo.mTintInfo.mHasTintList = true;
21744
21745        applyForegroundTint();
21746    }
21747
21748    /**
21749     * Return the tint applied to the foreground drawable, if specified.
21750     *
21751     * @return the tint applied to the foreground drawable
21752     * @attr ref android.R.styleable#View_foregroundTint
21753     * @see #setForegroundTintList(ColorStateList)
21754     */
21755    @Nullable
21756    public ColorStateList getForegroundTintList() {
21757        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
21758                ? mForegroundInfo.mTintInfo.mTintList : null;
21759    }
21760
21761    /**
21762     * Specifies the blending mode used to apply the tint specified by
21763     * {@link #setForegroundTintList(ColorStateList)}} to the background
21764     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
21765     *
21766     * @param tintMode the blending mode used to apply the tint, may be
21767     *                 {@code null} to clear tint
21768     * @attr ref android.R.styleable#View_foregroundTintMode
21769     * @see #getForegroundTintMode()
21770     * @see Drawable#setTintMode(PorterDuff.Mode)
21771     */
21772    public void setForegroundTintMode(@Nullable PorterDuff.Mode tintMode) {
21773        if (mForegroundInfo == null) {
21774            mForegroundInfo = new ForegroundInfo();
21775        }
21776        if (mForegroundInfo.mTintInfo == null) {
21777            mForegroundInfo.mTintInfo = new TintInfo();
21778        }
21779        mForegroundInfo.mTintInfo.mTintMode = tintMode;
21780        mForegroundInfo.mTintInfo.mHasTintMode = true;
21781
21782        applyForegroundTint();
21783    }
21784
21785    /**
21786     * Return the blending mode used to apply the tint to the foreground
21787     * drawable, if specified.
21788     *
21789     * @return the blending mode used to apply the tint to the foreground
21790     *         drawable
21791     * @attr ref android.R.styleable#View_foregroundTintMode
21792     * @see #setForegroundTintMode(PorterDuff.Mode)
21793     */
21794    @Nullable
21795    public PorterDuff.Mode getForegroundTintMode() {
21796        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
21797                ? mForegroundInfo.mTintInfo.mTintMode : null;
21798    }
21799
21800    private void applyForegroundTint() {
21801        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
21802                && mForegroundInfo.mTintInfo != null) {
21803            final TintInfo tintInfo = mForegroundInfo.mTintInfo;
21804            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
21805                mForegroundInfo.mDrawable = mForegroundInfo.mDrawable.mutate();
21806
21807                if (tintInfo.mHasTintList) {
21808                    mForegroundInfo.mDrawable.setTintList(tintInfo.mTintList);
21809                }
21810
21811                if (tintInfo.mHasTintMode) {
21812                    mForegroundInfo.mDrawable.setTintMode(tintInfo.mTintMode);
21813                }
21814
21815                // The drawable (or one of its children) may not have been
21816                // stateful before applying the tint, so let's try again.
21817                if (mForegroundInfo.mDrawable.isStateful()) {
21818                    mForegroundInfo.mDrawable.setState(getDrawableState());
21819                }
21820            }
21821        }
21822    }
21823
21824    /**
21825     * Get the drawable to be overlayed when a view is autofilled
21826     *
21827     * @return The drawable
21828     *
21829     * @throws IllegalStateException if the drawable could not be found.
21830     */
21831    @Nullable private Drawable getAutofilledDrawable() {
21832        if (mAttachInfo == null) {
21833            return null;
21834        }
21835        // Lazily load the isAutofilled drawable.
21836        if (mAttachInfo.mAutofilledDrawable == null) {
21837            Context rootContext = getRootView().getContext();
21838            TypedArray a = rootContext.getTheme().obtainStyledAttributes(AUTOFILL_HIGHLIGHT_ATTR);
21839            int attributeResourceId = a.getResourceId(0, 0);
21840            mAttachInfo.mAutofilledDrawable = rootContext.getDrawable(attributeResourceId);
21841            a.recycle();
21842        }
21843
21844        return mAttachInfo.mAutofilledDrawable;
21845    }
21846
21847    /**
21848     * Draw {@link View#isAutofilled()} highlight over view if the view is autofilled.
21849     *
21850     * @param canvas The canvas to draw on
21851     */
21852    private void drawAutofilledHighlight(@NonNull Canvas canvas) {
21853        if (isAutofilled()) {
21854            Drawable autofilledHighlight = getAutofilledDrawable();
21855
21856            if (autofilledHighlight != null) {
21857                autofilledHighlight.setBounds(0, 0, getWidth(), getHeight());
21858                autofilledHighlight.draw(canvas);
21859            }
21860        }
21861    }
21862
21863    /**
21864     * Draw any foreground content for this view.
21865     *
21866     * <p>Foreground content may consist of scroll bars, a {@link #setForeground foreground}
21867     * drawable or other view-specific decorations. The foreground is drawn on top of the
21868     * primary view content.</p>
21869     *
21870     * @param canvas canvas to draw into
21871     */
21872    public void onDrawForeground(Canvas canvas) {
21873        onDrawScrollIndicators(canvas);
21874        onDrawScrollBars(canvas);
21875
21876        final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
21877        if (foreground != null) {
21878            if (mForegroundInfo.mBoundsChanged) {
21879                mForegroundInfo.mBoundsChanged = false;
21880                final Rect selfBounds = mForegroundInfo.mSelfBounds;
21881                final Rect overlayBounds = mForegroundInfo.mOverlayBounds;
21882
21883                if (mForegroundInfo.mInsidePadding) {
21884                    selfBounds.set(0, 0, getWidth(), getHeight());
21885                } else {
21886                    selfBounds.set(getPaddingLeft(), getPaddingTop(),
21887                            getWidth() - getPaddingRight(), getHeight() - getPaddingBottom());
21888                }
21889
21890                final int ld = getLayoutDirection();
21891                Gravity.apply(mForegroundInfo.mGravity, foreground.getIntrinsicWidth(),
21892                        foreground.getIntrinsicHeight(), selfBounds, overlayBounds, ld);
21893                foreground.setBounds(overlayBounds);
21894            }
21895
21896            foreground.draw(canvas);
21897        }
21898    }
21899
21900    /**
21901     * Sets the padding. The view may add on the space required to display
21902     * the scrollbars, depending on the style and visibility of the scrollbars.
21903     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
21904     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
21905     * from the values set in this call.
21906     *
21907     * @attr ref android.R.styleable#View_padding
21908     * @attr ref android.R.styleable#View_paddingBottom
21909     * @attr ref android.R.styleable#View_paddingLeft
21910     * @attr ref android.R.styleable#View_paddingRight
21911     * @attr ref android.R.styleable#View_paddingTop
21912     * @param left the left padding in pixels
21913     * @param top the top padding in pixels
21914     * @param right the right padding in pixels
21915     * @param bottom the bottom padding in pixels
21916     */
21917    public void setPadding(int left, int top, int right, int bottom) {
21918        resetResolvedPaddingInternal();
21919
21920        mUserPaddingStart = UNDEFINED_PADDING;
21921        mUserPaddingEnd = UNDEFINED_PADDING;
21922
21923        mUserPaddingLeftInitial = left;
21924        mUserPaddingRightInitial = right;
21925
21926        mLeftPaddingDefined = true;
21927        mRightPaddingDefined = true;
21928
21929        internalSetPadding(left, top, right, bottom);
21930    }
21931
21932    /**
21933     * @hide
21934     */
21935    protected void internalSetPadding(int left, int top, int right, int bottom) {
21936        mUserPaddingLeft = left;
21937        mUserPaddingRight = right;
21938        mUserPaddingBottom = bottom;
21939
21940        final int viewFlags = mViewFlags;
21941        boolean changed = false;
21942
21943        // Common case is there are no scroll bars.
21944        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
21945            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
21946                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
21947                        ? 0 : getVerticalScrollbarWidth();
21948                switch (mVerticalScrollbarPosition) {
21949                    case SCROLLBAR_POSITION_DEFAULT:
21950                        if (isLayoutRtl()) {
21951                            left += offset;
21952                        } else {
21953                            right += offset;
21954                        }
21955                        break;
21956                    case SCROLLBAR_POSITION_RIGHT:
21957                        right += offset;
21958                        break;
21959                    case SCROLLBAR_POSITION_LEFT:
21960                        left += offset;
21961                        break;
21962                }
21963            }
21964            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
21965                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
21966                        ? 0 : getHorizontalScrollbarHeight();
21967            }
21968        }
21969
21970        if (mPaddingLeft != left) {
21971            changed = true;
21972            mPaddingLeft = left;
21973        }
21974        if (mPaddingTop != top) {
21975            changed = true;
21976            mPaddingTop = top;
21977        }
21978        if (mPaddingRight != right) {
21979            changed = true;
21980            mPaddingRight = right;
21981        }
21982        if (mPaddingBottom != bottom) {
21983            changed = true;
21984            mPaddingBottom = bottom;
21985        }
21986
21987        if (changed) {
21988            requestLayout();
21989            invalidateOutline();
21990        }
21991    }
21992
21993    /**
21994     * Sets the relative padding. The view may add on the space required to display
21995     * the scrollbars, depending on the style and visibility of the scrollbars.
21996     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
21997     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
21998     * from the values set in this call.
21999     *
22000     * @attr ref android.R.styleable#View_padding
22001     * @attr ref android.R.styleable#View_paddingBottom
22002     * @attr ref android.R.styleable#View_paddingStart
22003     * @attr ref android.R.styleable#View_paddingEnd
22004     * @attr ref android.R.styleable#View_paddingTop
22005     * @param start the start padding in pixels
22006     * @param top the top padding in pixels
22007     * @param end the end padding in pixels
22008     * @param bottom the bottom padding in pixels
22009     */
22010    public void setPaddingRelative(int start, int top, int end, int bottom) {
22011        resetResolvedPaddingInternal();
22012
22013        mUserPaddingStart = start;
22014        mUserPaddingEnd = end;
22015        mLeftPaddingDefined = true;
22016        mRightPaddingDefined = true;
22017
22018        switch(getLayoutDirection()) {
22019            case LAYOUT_DIRECTION_RTL:
22020                mUserPaddingLeftInitial = end;
22021                mUserPaddingRightInitial = start;
22022                internalSetPadding(end, top, start, bottom);
22023                break;
22024            case LAYOUT_DIRECTION_LTR:
22025            default:
22026                mUserPaddingLeftInitial = start;
22027                mUserPaddingRightInitial = end;
22028                internalSetPadding(start, top, end, bottom);
22029        }
22030    }
22031
22032    /**
22033     * Returns the top padding of this view.
22034     *
22035     * @return the top padding in pixels
22036     */
22037    public int getPaddingTop() {
22038        return mPaddingTop;
22039    }
22040
22041    /**
22042     * Returns the bottom padding of this view. If there are inset and enabled
22043     * scrollbars, this value may include the space required to display the
22044     * scrollbars as well.
22045     *
22046     * @return the bottom padding in pixels
22047     */
22048    public int getPaddingBottom() {
22049        return mPaddingBottom;
22050    }
22051
22052    /**
22053     * Returns the left padding of this view. If there are inset and enabled
22054     * scrollbars, this value may include the space required to display the
22055     * scrollbars as well.
22056     *
22057     * @return the left padding in pixels
22058     */
22059    public int getPaddingLeft() {
22060        if (!isPaddingResolved()) {
22061            resolvePadding();
22062        }
22063        return mPaddingLeft;
22064    }
22065
22066    /**
22067     * Returns the start padding of this view depending on its resolved layout direction.
22068     * If there are inset and enabled scrollbars, this value may include the space
22069     * required to display the scrollbars as well.
22070     *
22071     * @return the start padding in pixels
22072     */
22073    public int getPaddingStart() {
22074        if (!isPaddingResolved()) {
22075            resolvePadding();
22076        }
22077        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
22078                mPaddingRight : mPaddingLeft;
22079    }
22080
22081    /**
22082     * Returns the right padding of this view. If there are inset and enabled
22083     * scrollbars, this value may include the space required to display the
22084     * scrollbars as well.
22085     *
22086     * @return the right padding in pixels
22087     */
22088    public int getPaddingRight() {
22089        if (!isPaddingResolved()) {
22090            resolvePadding();
22091        }
22092        return mPaddingRight;
22093    }
22094
22095    /**
22096     * Returns the end padding of this view depending on its resolved layout direction.
22097     * If there are inset and enabled scrollbars, this value may include the space
22098     * required to display the scrollbars as well.
22099     *
22100     * @return the end padding in pixels
22101     */
22102    public int getPaddingEnd() {
22103        if (!isPaddingResolved()) {
22104            resolvePadding();
22105        }
22106        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
22107                mPaddingLeft : mPaddingRight;
22108    }
22109
22110    /**
22111     * Return if the padding has been set through relative values
22112     * {@link #setPaddingRelative(int, int, int, int)} or through
22113     * @attr ref android.R.styleable#View_paddingStart or
22114     * @attr ref android.R.styleable#View_paddingEnd
22115     *
22116     * @return true if the padding is relative or false if it is not.
22117     */
22118    public boolean isPaddingRelative() {
22119        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
22120    }
22121
22122    Insets computeOpticalInsets() {
22123        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
22124    }
22125
22126    /**
22127     * @hide
22128     */
22129    public void resetPaddingToInitialValues() {
22130        if (isRtlCompatibilityMode()) {
22131            mPaddingLeft = mUserPaddingLeftInitial;
22132            mPaddingRight = mUserPaddingRightInitial;
22133            return;
22134        }
22135        if (isLayoutRtl()) {
22136            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
22137            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
22138        } else {
22139            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
22140            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
22141        }
22142    }
22143
22144    /**
22145     * @hide
22146     */
22147    public Insets getOpticalInsets() {
22148        if (mLayoutInsets == null) {
22149            mLayoutInsets = computeOpticalInsets();
22150        }
22151        return mLayoutInsets;
22152    }
22153
22154    /**
22155     * Set this view's optical insets.
22156     *
22157     * <p>This method should be treated similarly to setMeasuredDimension and not as a general
22158     * property. Views that compute their own optical insets should call it as part of measurement.
22159     * This method does not request layout. If you are setting optical insets outside of
22160     * measure/layout itself you will want to call requestLayout() yourself.
22161     * </p>
22162     * @hide
22163     */
22164    public void setOpticalInsets(Insets insets) {
22165        mLayoutInsets = insets;
22166    }
22167
22168    /**
22169     * Changes the selection state of this view. A view can be selected or not.
22170     * Note that selection is not the same as focus. Views are typically
22171     * selected in the context of an AdapterView like ListView or GridView;
22172     * the selected view is the view that is highlighted.
22173     *
22174     * @param selected true if the view must be selected, false otherwise
22175     */
22176    public void setSelected(boolean selected) {
22177        //noinspection DoubleNegation
22178        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
22179            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
22180            if (!selected) resetPressedState();
22181            invalidate(true);
22182            refreshDrawableState();
22183            dispatchSetSelected(selected);
22184            if (selected) {
22185                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
22186            } else {
22187                notifyViewAccessibilityStateChangedIfNeeded(
22188                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
22189            }
22190        }
22191    }
22192
22193    /**
22194     * Dispatch setSelected to all of this View's children.
22195     *
22196     * @see #setSelected(boolean)
22197     *
22198     * @param selected The new selected state
22199     */
22200    protected void dispatchSetSelected(boolean selected) {
22201    }
22202
22203    /**
22204     * Indicates the selection state of this view.
22205     *
22206     * @return true if the view is selected, false otherwise
22207     */
22208    @ViewDebug.ExportedProperty
22209    public boolean isSelected() {
22210        return (mPrivateFlags & PFLAG_SELECTED) != 0;
22211    }
22212
22213    /**
22214     * Changes the activated state of this view. A view can be activated or not.
22215     * Note that activation is not the same as selection.  Selection is
22216     * a transient property, representing the view (hierarchy) the user is
22217     * currently interacting with.  Activation is a longer-term state that the
22218     * user can move views in and out of.  For example, in a list view with
22219     * single or multiple selection enabled, the views in the current selection
22220     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
22221     * here.)  The activated state is propagated down to children of the view it
22222     * is set on.
22223     *
22224     * @param activated true if the view must be activated, false otherwise
22225     */
22226    public void setActivated(boolean activated) {
22227        //noinspection DoubleNegation
22228        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
22229            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
22230            invalidate(true);
22231            refreshDrawableState();
22232            dispatchSetActivated(activated);
22233        }
22234    }
22235
22236    /**
22237     * Dispatch setActivated to all of this View's children.
22238     *
22239     * @see #setActivated(boolean)
22240     *
22241     * @param activated The new activated state
22242     */
22243    protected void dispatchSetActivated(boolean activated) {
22244    }
22245
22246    /**
22247     * Indicates the activation state of this view.
22248     *
22249     * @return true if the view is activated, false otherwise
22250     */
22251    @ViewDebug.ExportedProperty
22252    public boolean isActivated() {
22253        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
22254    }
22255
22256    /**
22257     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
22258     * observer can be used to get notifications when global events, like
22259     * layout, happen.
22260     *
22261     * The returned ViewTreeObserver observer is not guaranteed to remain
22262     * valid for the lifetime of this View. If the caller of this method keeps
22263     * a long-lived reference to ViewTreeObserver, it should always check for
22264     * the return value of {@link ViewTreeObserver#isAlive()}.
22265     *
22266     * @return The ViewTreeObserver for this view's hierarchy.
22267     */
22268    public ViewTreeObserver getViewTreeObserver() {
22269        if (mAttachInfo != null) {
22270            return mAttachInfo.mTreeObserver;
22271        }
22272        if (mFloatingTreeObserver == null) {
22273            mFloatingTreeObserver = new ViewTreeObserver(mContext);
22274        }
22275        return mFloatingTreeObserver;
22276    }
22277
22278    /**
22279     * <p>Finds the topmost view in the current view hierarchy.</p>
22280     *
22281     * @return the topmost view containing this view
22282     */
22283    public View getRootView() {
22284        if (mAttachInfo != null) {
22285            final View v = mAttachInfo.mRootView;
22286            if (v != null) {
22287                return v;
22288            }
22289        }
22290
22291        View parent = this;
22292
22293        while (parent.mParent != null && parent.mParent instanceof View) {
22294            parent = (View) parent.mParent;
22295        }
22296
22297        return parent;
22298    }
22299
22300    /**
22301     * Transforms a motion event from view-local coordinates to on-screen
22302     * coordinates.
22303     *
22304     * @param ev the view-local motion event
22305     * @return false if the transformation could not be applied
22306     * @hide
22307     */
22308    public boolean toGlobalMotionEvent(MotionEvent ev) {
22309        final AttachInfo info = mAttachInfo;
22310        if (info == null) {
22311            return false;
22312        }
22313
22314        final Matrix m = info.mTmpMatrix;
22315        m.set(Matrix.IDENTITY_MATRIX);
22316        transformMatrixToGlobal(m);
22317        ev.transform(m);
22318        return true;
22319    }
22320
22321    /**
22322     * Transforms a motion event from on-screen coordinates to view-local
22323     * coordinates.
22324     *
22325     * @param ev the on-screen motion event
22326     * @return false if the transformation could not be applied
22327     * @hide
22328     */
22329    public boolean toLocalMotionEvent(MotionEvent ev) {
22330        final AttachInfo info = mAttachInfo;
22331        if (info == null) {
22332            return false;
22333        }
22334
22335        final Matrix m = info.mTmpMatrix;
22336        m.set(Matrix.IDENTITY_MATRIX);
22337        transformMatrixToLocal(m);
22338        ev.transform(m);
22339        return true;
22340    }
22341
22342    /**
22343     * Modifies the input matrix such that it maps view-local coordinates to
22344     * on-screen coordinates.
22345     *
22346     * @param m input matrix to modify
22347     * @hide
22348     */
22349    public void transformMatrixToGlobal(Matrix m) {
22350        final ViewParent parent = mParent;
22351        if (parent instanceof View) {
22352            final View vp = (View) parent;
22353            vp.transformMatrixToGlobal(m);
22354            m.preTranslate(-vp.mScrollX, -vp.mScrollY);
22355        } else if (parent instanceof ViewRootImpl) {
22356            final ViewRootImpl vr = (ViewRootImpl) parent;
22357            vr.transformMatrixToGlobal(m);
22358            m.preTranslate(0, -vr.mCurScrollY);
22359        }
22360
22361        m.preTranslate(mLeft, mTop);
22362
22363        if (!hasIdentityMatrix()) {
22364            m.preConcat(getMatrix());
22365        }
22366    }
22367
22368    /**
22369     * Modifies the input matrix such that it maps on-screen coordinates to
22370     * view-local coordinates.
22371     *
22372     * @param m input matrix to modify
22373     * @hide
22374     */
22375    public void transformMatrixToLocal(Matrix m) {
22376        final ViewParent parent = mParent;
22377        if (parent instanceof View) {
22378            final View vp = (View) parent;
22379            vp.transformMatrixToLocal(m);
22380            m.postTranslate(vp.mScrollX, vp.mScrollY);
22381        } else if (parent instanceof ViewRootImpl) {
22382            final ViewRootImpl vr = (ViewRootImpl) parent;
22383            vr.transformMatrixToLocal(m);
22384            m.postTranslate(0, vr.mCurScrollY);
22385        }
22386
22387        m.postTranslate(-mLeft, -mTop);
22388
22389        if (!hasIdentityMatrix()) {
22390            m.postConcat(getInverseMatrix());
22391        }
22392    }
22393
22394    /**
22395     * @hide
22396     */
22397    @ViewDebug.ExportedProperty(category = "layout", indexMapping = {
22398            @ViewDebug.IntToString(from = 0, to = "x"),
22399            @ViewDebug.IntToString(from = 1, to = "y")
22400    })
22401    public int[] getLocationOnScreen() {
22402        int[] location = new int[2];
22403        getLocationOnScreen(location);
22404        return location;
22405    }
22406
22407    /**
22408     * <p>Computes the coordinates of this view on the screen. The argument
22409     * must be an array of two integers. After the method returns, the array
22410     * contains the x and y location in that order.</p>
22411     *
22412     * @param outLocation an array of two integers in which to hold the coordinates
22413     */
22414    public void getLocationOnScreen(@Size(2) int[] outLocation) {
22415        getLocationInWindow(outLocation);
22416
22417        final AttachInfo info = mAttachInfo;
22418        if (info != null) {
22419            outLocation[0] += info.mWindowLeft;
22420            outLocation[1] += info.mWindowTop;
22421        }
22422    }
22423
22424    /**
22425     * <p>Computes the coordinates of this view in its window. The argument
22426     * must be an array of two integers. After the method returns, the array
22427     * contains the x and y location in that order.</p>
22428     *
22429     * @param outLocation an array of two integers in which to hold the coordinates
22430     */
22431    public void getLocationInWindow(@Size(2) int[] outLocation) {
22432        if (outLocation == null || outLocation.length < 2) {
22433            throw new IllegalArgumentException("outLocation must be an array of two integers");
22434        }
22435
22436        outLocation[0] = 0;
22437        outLocation[1] = 0;
22438
22439        transformFromViewToWindowSpace(outLocation);
22440    }
22441
22442    /** @hide */
22443    public void transformFromViewToWindowSpace(@Size(2) int[] inOutLocation) {
22444        if (inOutLocation == null || inOutLocation.length < 2) {
22445            throw new IllegalArgumentException("inOutLocation must be an array of two integers");
22446        }
22447
22448        if (mAttachInfo == null) {
22449            // When the view is not attached to a window, this method does not make sense
22450            inOutLocation[0] = inOutLocation[1] = 0;
22451            return;
22452        }
22453
22454        float position[] = mAttachInfo.mTmpTransformLocation;
22455        position[0] = inOutLocation[0];
22456        position[1] = inOutLocation[1];
22457
22458        if (!hasIdentityMatrix()) {
22459            getMatrix().mapPoints(position);
22460        }
22461
22462        position[0] += mLeft;
22463        position[1] += mTop;
22464
22465        ViewParent viewParent = mParent;
22466        while (viewParent instanceof View) {
22467            final View view = (View) viewParent;
22468
22469            position[0] -= view.mScrollX;
22470            position[1] -= view.mScrollY;
22471
22472            if (!view.hasIdentityMatrix()) {
22473                view.getMatrix().mapPoints(position);
22474            }
22475
22476            position[0] += view.mLeft;
22477            position[1] += view.mTop;
22478
22479            viewParent = view.mParent;
22480         }
22481
22482        if (viewParent instanceof ViewRootImpl) {
22483            // *cough*
22484            final ViewRootImpl vr = (ViewRootImpl) viewParent;
22485            position[1] -= vr.mCurScrollY;
22486        }
22487
22488        inOutLocation[0] = Math.round(position[0]);
22489        inOutLocation[1] = Math.round(position[1]);
22490    }
22491
22492    /**
22493     * @param id the id of the view to be found
22494     * @return the view of the specified id, null if cannot be found
22495     * @hide
22496     */
22497    protected <T extends View> T findViewTraversal(@IdRes int id) {
22498        if (id == mID) {
22499            return (T) this;
22500        }
22501        return null;
22502    }
22503
22504    /**
22505     * @param tag the tag of the view to be found
22506     * @return the view of specified tag, null if cannot be found
22507     * @hide
22508     */
22509    protected <T extends View> T findViewWithTagTraversal(Object tag) {
22510        if (tag != null && tag.equals(mTag)) {
22511            return (T) this;
22512        }
22513        return null;
22514    }
22515
22516    /**
22517     * @param predicate The predicate to evaluate.
22518     * @param childToSkip If not null, ignores this child during the recursive traversal.
22519     * @return The first view that matches the predicate or null.
22520     * @hide
22521     */
22522    protected <T extends View> T findViewByPredicateTraversal(Predicate<View> predicate,
22523            View childToSkip) {
22524        if (predicate.test(this)) {
22525            return (T) this;
22526        }
22527        return null;
22528    }
22529
22530    /**
22531     * Finds the first descendant view with the given ID, the view itself if
22532     * the ID matches {@link #getId()}, or {@code null} if the ID is invalid
22533     * (< 0) or there is no matching view in the hierarchy.
22534     * <p>
22535     * <strong>Note:</strong> In most cases -- depending on compiler support --
22536     * the resulting view is automatically cast to the target class type. If
22537     * the target class type is unconstrained, an explicit cast may be
22538     * necessary.
22539     *
22540     * @param id the ID to search for
22541     * @return a view with given ID if found, or {@code null} otherwise
22542     * @see View#requireViewById(int)
22543     */
22544    @Nullable
22545    public final <T extends View> T findViewById(@IdRes int id) {
22546        if (id == NO_ID) {
22547            return null;
22548        }
22549        return findViewTraversal(id);
22550    }
22551
22552    /**
22553     * Finds the first descendant view with the given ID, the view itself if the ID matches
22554     * {@link #getId()}, or throws an IllegalArgumentException if the ID is invalid or there is no
22555     * matching view in the hierarchy.
22556     * <p>
22557     * <strong>Note:</strong> In most cases -- depending on compiler support --
22558     * the resulting view is automatically cast to the target class type. If
22559     * the target class type is unconstrained, an explicit cast may be
22560     * necessary.
22561     *
22562     * @param id the ID to search for
22563     * @return a view with given ID
22564     * @see View#findViewById(int)
22565     */
22566    @NonNull
22567    public final <T extends View> T requireViewById(@IdRes int id) {
22568        T view = findViewById(id);
22569        if (view == null) {
22570            throw new IllegalArgumentException("ID does not reference a View inside this View");
22571        }
22572        return view;
22573    }
22574
22575    /**
22576     * Finds a view by its unuque and stable accessibility id.
22577     *
22578     * @param accessibilityId The searched accessibility id.
22579     * @return The found view.
22580     */
22581    final <T extends View> T findViewByAccessibilityId(int accessibilityId) {
22582        if (accessibilityId < 0) {
22583            return null;
22584        }
22585        T view = findViewByAccessibilityIdTraversal(accessibilityId);
22586        if (view != null) {
22587            return view.includeForAccessibility() ? view : null;
22588        }
22589        return null;
22590    }
22591
22592    /**
22593     * Performs the traversal to find a view by its unique and stable accessibility id.
22594     *
22595     * <strong>Note:</strong>This method does not stop at the root namespace
22596     * boundary since the user can touch the screen at an arbitrary location
22597     * potentially crossing the root namespace boundary which will send an
22598     * accessibility event to accessibility services and they should be able
22599     * to obtain the event source. Also accessibility ids are guaranteed to be
22600     * unique in the window.
22601     *
22602     * @param accessibilityId The accessibility id.
22603     * @return The found view.
22604     * @hide
22605     */
22606    public <T extends View> T findViewByAccessibilityIdTraversal(int accessibilityId) {
22607        if (getAccessibilityViewId() == accessibilityId) {
22608            return (T) this;
22609        }
22610        return null;
22611    }
22612
22613    /**
22614     * Performs the traversal to find a view by its autofill id.
22615     *
22616     * <strong>Note:</strong>This method does not stop at the root namespace
22617     * boundary.
22618     *
22619     * @param autofillId The autofill id.
22620     * @return The found view.
22621     * @hide
22622     */
22623    public <T extends View> T findViewByAutofillIdTraversal(int autofillId) {
22624        if (getAutofillViewId() == autofillId) {
22625            return (T) this;
22626        }
22627        return null;
22628    }
22629
22630    /**
22631     * Look for a child view with the given tag.  If this view has the given
22632     * tag, return this view.
22633     *
22634     * @param tag The tag to search for, using "tag.equals(getTag())".
22635     * @return The View that has the given tag in the hierarchy or null
22636     */
22637    public final <T extends View> T findViewWithTag(Object tag) {
22638        if (tag == null) {
22639            return null;
22640        }
22641        return findViewWithTagTraversal(tag);
22642    }
22643
22644    /**
22645     * Look for a child view that matches the specified predicate.
22646     * If this view matches the predicate, return this view.
22647     *
22648     * @param predicate The predicate to evaluate.
22649     * @return The first view that matches the predicate or null.
22650     * @hide
22651     */
22652    public final <T extends View> T findViewByPredicate(Predicate<View> predicate) {
22653        return findViewByPredicateTraversal(predicate, null);
22654    }
22655
22656    /**
22657     * Look for a child view that matches the specified predicate,
22658     * starting with the specified view and its descendents and then
22659     * recusively searching the ancestors and siblings of that view
22660     * until this view is reached.
22661     *
22662     * This method is useful in cases where the predicate does not match
22663     * a single unique view (perhaps multiple views use the same id)
22664     * and we are trying to find the view that is "closest" in scope to the
22665     * starting view.
22666     *
22667     * @param start The view to start from.
22668     * @param predicate The predicate to evaluate.
22669     * @return The first view that matches the predicate or null.
22670     * @hide
22671     */
22672    public final <T extends View> T findViewByPredicateInsideOut(
22673            View start, Predicate<View> predicate) {
22674        View childToSkip = null;
22675        for (;;) {
22676            T view = start.findViewByPredicateTraversal(predicate, childToSkip);
22677            if (view != null || start == this) {
22678                return view;
22679            }
22680
22681            ViewParent parent = start.getParent();
22682            if (parent == null || !(parent instanceof View)) {
22683                return null;
22684            }
22685
22686            childToSkip = start;
22687            start = (View) parent;
22688        }
22689    }
22690
22691    /**
22692     * Sets the identifier for this view. The identifier does not have to be
22693     * unique in this view's hierarchy. The identifier should be a positive
22694     * number.
22695     *
22696     * @see #NO_ID
22697     * @see #getId()
22698     * @see #findViewById(int)
22699     *
22700     * @param id a number used to identify the view
22701     *
22702     * @attr ref android.R.styleable#View_id
22703     */
22704    public void setId(@IdRes int id) {
22705        mID = id;
22706        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
22707            mID = generateViewId();
22708        }
22709    }
22710
22711    /**
22712     * {@hide}
22713     *
22714     * @param isRoot true if the view belongs to the root namespace, false
22715     *        otherwise
22716     */
22717    public void setIsRootNamespace(boolean isRoot) {
22718        if (isRoot) {
22719            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
22720        } else {
22721            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
22722        }
22723    }
22724
22725    /**
22726     * {@hide}
22727     *
22728     * @return true if the view belongs to the root namespace, false otherwise
22729     */
22730    public boolean isRootNamespace() {
22731        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
22732    }
22733
22734    /**
22735     * Returns this view's identifier.
22736     *
22737     * @return a positive integer used to identify the view or {@link #NO_ID}
22738     *         if the view has no ID
22739     *
22740     * @see #setId(int)
22741     * @see #findViewById(int)
22742     * @attr ref android.R.styleable#View_id
22743     */
22744    @IdRes
22745    @ViewDebug.CapturedViewProperty
22746    public int getId() {
22747        return mID;
22748    }
22749
22750    /**
22751     * Returns this view's tag.
22752     *
22753     * @return the Object stored in this view as a tag, or {@code null} if not
22754     *         set
22755     *
22756     * @see #setTag(Object)
22757     * @see #getTag(int)
22758     */
22759    @ViewDebug.ExportedProperty
22760    public Object getTag() {
22761        return mTag;
22762    }
22763
22764    /**
22765     * Sets the tag associated with this view. A tag can be used to mark
22766     * a view in its hierarchy and does not have to be unique within the
22767     * hierarchy. Tags can also be used to store data within a view without
22768     * resorting to another data structure.
22769     *
22770     * @param tag an Object to tag the view with
22771     *
22772     * @see #getTag()
22773     * @see #setTag(int, Object)
22774     */
22775    public void setTag(final Object tag) {
22776        mTag = tag;
22777    }
22778
22779    /**
22780     * Returns the tag associated with this view and the specified key.
22781     *
22782     * @param key The key identifying the tag
22783     *
22784     * @return the Object stored in this view as a tag, or {@code null} if not
22785     *         set
22786     *
22787     * @see #setTag(int, Object)
22788     * @see #getTag()
22789     */
22790    public Object getTag(int key) {
22791        if (mKeyedTags != null) return mKeyedTags.get(key);
22792        return null;
22793    }
22794
22795    /**
22796     * Sets a tag associated with this view and a key. A tag can be used
22797     * to mark a view in its hierarchy and does not have to be unique within
22798     * the hierarchy. Tags can also be used to store data within a view
22799     * without resorting to another data structure.
22800     *
22801     * The specified key should be an id declared in the resources of the
22802     * application to ensure it is unique (see the <a
22803     * href="{@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
22804     * Keys identified as belonging to
22805     * the Android framework or not associated with any package will cause
22806     * an {@link IllegalArgumentException} to be thrown.
22807     *
22808     * @param key The key identifying the tag
22809     * @param tag An Object to tag the view with
22810     *
22811     * @throws IllegalArgumentException If they specified key is not valid
22812     *
22813     * @see #setTag(Object)
22814     * @see #getTag(int)
22815     */
22816    public void setTag(int key, final Object tag) {
22817        // If the package id is 0x00 or 0x01, it's either an undefined package
22818        // or a framework id
22819        if ((key >>> 24) < 2) {
22820            throw new IllegalArgumentException("The key must be an application-specific "
22821                    + "resource id.");
22822        }
22823
22824        setKeyedTag(key, tag);
22825    }
22826
22827    /**
22828     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
22829     * framework id.
22830     *
22831     * @hide
22832     */
22833    public void setTagInternal(int key, Object tag) {
22834        if ((key >>> 24) != 0x1) {
22835            throw new IllegalArgumentException("The key must be a framework-specific "
22836                    + "resource id.");
22837        }
22838
22839        setKeyedTag(key, tag);
22840    }
22841
22842    private void setKeyedTag(int key, Object tag) {
22843        if (mKeyedTags == null) {
22844            mKeyedTags = new SparseArray<Object>(2);
22845        }
22846
22847        mKeyedTags.put(key, tag);
22848    }
22849
22850    /**
22851     * Prints information about this view in the log output, with the tag
22852     * {@link #VIEW_LOG_TAG}.
22853     *
22854     * @hide
22855     */
22856    public void debug() {
22857        debug(0);
22858    }
22859
22860    /**
22861     * Prints information about this view in the log output, with the tag
22862     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
22863     * indentation defined by the <code>depth</code>.
22864     *
22865     * @param depth the indentation level
22866     *
22867     * @hide
22868     */
22869    protected void debug(int depth) {
22870        String output = debugIndent(depth - 1);
22871
22872        output += "+ " + this;
22873        int id = getId();
22874        if (id != -1) {
22875            output += " (id=" + id + ")";
22876        }
22877        Object tag = getTag();
22878        if (tag != null) {
22879            output += " (tag=" + tag + ")";
22880        }
22881        Log.d(VIEW_LOG_TAG, output);
22882
22883        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
22884            output = debugIndent(depth) + " FOCUSED";
22885            Log.d(VIEW_LOG_TAG, output);
22886        }
22887
22888        output = debugIndent(depth);
22889        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
22890                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
22891                + "} ";
22892        Log.d(VIEW_LOG_TAG, output);
22893
22894        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
22895                || mPaddingBottom != 0) {
22896            output = debugIndent(depth);
22897            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
22898                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
22899            Log.d(VIEW_LOG_TAG, output);
22900        }
22901
22902        output = debugIndent(depth);
22903        output += "mMeasureWidth=" + mMeasuredWidth +
22904                " mMeasureHeight=" + mMeasuredHeight;
22905        Log.d(VIEW_LOG_TAG, output);
22906
22907        output = debugIndent(depth);
22908        if (mLayoutParams == null) {
22909            output += "BAD! no layout params";
22910        } else {
22911            output = mLayoutParams.debug(output);
22912        }
22913        Log.d(VIEW_LOG_TAG, output);
22914
22915        output = debugIndent(depth);
22916        output += "flags={";
22917        output += View.printFlags(mViewFlags);
22918        output += "}";
22919        Log.d(VIEW_LOG_TAG, output);
22920
22921        output = debugIndent(depth);
22922        output += "privateFlags={";
22923        output += View.printPrivateFlags(mPrivateFlags);
22924        output += "}";
22925        Log.d(VIEW_LOG_TAG, output);
22926    }
22927
22928    /**
22929     * Creates a string of whitespaces used for indentation.
22930     *
22931     * @param depth the indentation level
22932     * @return a String containing (depth * 2 + 3) * 2 white spaces
22933     *
22934     * @hide
22935     */
22936    protected static String debugIndent(int depth) {
22937        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
22938        for (int i = 0; i < (depth * 2) + 3; i++) {
22939            spaces.append(' ').append(' ');
22940        }
22941        return spaces.toString();
22942    }
22943
22944    /**
22945     * <p>Return the offset of the widget's text baseline from the widget's top
22946     * boundary. If this widget does not support baseline alignment, this
22947     * method returns -1. </p>
22948     *
22949     * @return the offset of the baseline within the widget's bounds or -1
22950     *         if baseline alignment is not supported
22951     */
22952    @ViewDebug.ExportedProperty(category = "layout")
22953    public int getBaseline() {
22954        return -1;
22955    }
22956
22957    /**
22958     * Returns whether the view hierarchy is currently undergoing a layout pass. This
22959     * information is useful to avoid situations such as calling {@link #requestLayout()} during
22960     * a layout pass.
22961     *
22962     * @return whether the view hierarchy is currently undergoing a layout pass
22963     */
22964    public boolean isInLayout() {
22965        ViewRootImpl viewRoot = getViewRootImpl();
22966        return (viewRoot != null && viewRoot.isInLayout());
22967    }
22968
22969    /**
22970     * Call this when something has changed which has invalidated the
22971     * layout of this view. This will schedule a layout pass of the view
22972     * tree. This should not be called while the view hierarchy is currently in a layout
22973     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
22974     * end of the current layout pass (and then layout will run again) or after the current
22975     * frame is drawn and the next layout occurs.
22976     *
22977     * <p>Subclasses which override this method should call the superclass method to
22978     * handle possible request-during-layout errors correctly.</p>
22979     */
22980    @CallSuper
22981    public void requestLayout() {
22982        if (mMeasureCache != null) mMeasureCache.clear();
22983
22984        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
22985            // Only trigger request-during-layout logic if this is the view requesting it,
22986            // not the views in its parent hierarchy
22987            ViewRootImpl viewRoot = getViewRootImpl();
22988            if (viewRoot != null && viewRoot.isInLayout()) {
22989                if (!viewRoot.requestLayoutDuringLayout(this)) {
22990                    return;
22991                }
22992            }
22993            mAttachInfo.mViewRequestingLayout = this;
22994        }
22995
22996        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
22997        mPrivateFlags |= PFLAG_INVALIDATED;
22998
22999        if (mParent != null && !mParent.isLayoutRequested()) {
23000            mParent.requestLayout();
23001        }
23002        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
23003            mAttachInfo.mViewRequestingLayout = null;
23004        }
23005    }
23006
23007    /**
23008     * Forces this view to be laid out during the next layout pass.
23009     * This method does not call requestLayout() or forceLayout()
23010     * on the parent.
23011     */
23012    public void forceLayout() {
23013        if (mMeasureCache != null) mMeasureCache.clear();
23014
23015        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
23016        mPrivateFlags |= PFLAG_INVALIDATED;
23017    }
23018
23019    /**
23020     * <p>
23021     * This is called to find out how big a view should be. The parent
23022     * supplies constraint information in the width and height parameters.
23023     * </p>
23024     *
23025     * <p>
23026     * The actual measurement work of a view is performed in
23027     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
23028     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
23029     * </p>
23030     *
23031     *
23032     * @param widthMeasureSpec Horizontal space requirements as imposed by the
23033     *        parent
23034     * @param heightMeasureSpec Vertical space requirements as imposed by the
23035     *        parent
23036     *
23037     * @see #onMeasure(int, int)
23038     */
23039    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
23040        boolean optical = isLayoutModeOptical(this);
23041        if (optical != isLayoutModeOptical(mParent)) {
23042            Insets insets = getOpticalInsets();
23043            int oWidth  = insets.left + insets.right;
23044            int oHeight = insets.top  + insets.bottom;
23045            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
23046            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
23047        }
23048
23049        // Suppress sign extension for the low bytes
23050        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
23051        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
23052
23053        final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
23054
23055        // Optimize layout by avoiding an extra EXACTLY pass when the view is
23056        // already measured as the correct size. In API 23 and below, this
23057        // extra pass is required to make LinearLayout re-distribute weight.
23058        final boolean specChanged = widthMeasureSpec != mOldWidthMeasureSpec
23059                || heightMeasureSpec != mOldHeightMeasureSpec;
23060        final boolean isSpecExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY
23061                && MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY;
23062        final boolean matchesSpecSize = getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec)
23063                && getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec);
23064        final boolean needsLayout = specChanged
23065                && (sAlwaysRemeasureExactly || !isSpecExactly || !matchesSpecSize);
23066
23067        if (forceLayout || needsLayout) {
23068            // first clears the measured dimension flag
23069            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
23070
23071            resolveRtlPropertiesIfNeeded();
23072
23073            int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key);
23074            if (cacheIndex < 0 || sIgnoreMeasureCache) {
23075                // measure ourselves, this should set the measured dimension flag back
23076                onMeasure(widthMeasureSpec, heightMeasureSpec);
23077                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
23078            } else {
23079                long value = mMeasureCache.valueAt(cacheIndex);
23080                // Casting a long to int drops the high 32 bits, no mask needed
23081                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
23082                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
23083            }
23084
23085            // flag not set, setMeasuredDimension() was not invoked, we raise
23086            // an exception to warn the developer
23087            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
23088                throw new IllegalStateException("View with id " + getId() + ": "
23089                        + getClass().getName() + "#onMeasure() did not set the"
23090                        + " measured dimension by calling"
23091                        + " setMeasuredDimension()");
23092            }
23093
23094            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
23095        }
23096
23097        mOldWidthMeasureSpec = widthMeasureSpec;
23098        mOldHeightMeasureSpec = heightMeasureSpec;
23099
23100        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
23101                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
23102    }
23103
23104    /**
23105     * <p>
23106     * Measure the view and its content to determine the measured width and the
23107     * measured height. This method is invoked by {@link #measure(int, int)} and
23108     * should be overridden by subclasses to provide accurate and efficient
23109     * measurement of their contents.
23110     * </p>
23111     *
23112     * <p>
23113     * <strong>CONTRACT:</strong> When overriding this method, you
23114     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
23115     * measured width and height of this view. Failure to do so will trigger an
23116     * <code>IllegalStateException</code>, thrown by
23117     * {@link #measure(int, int)}. Calling the superclass'
23118     * {@link #onMeasure(int, int)} is a valid use.
23119     * </p>
23120     *
23121     * <p>
23122     * The base class implementation of measure defaults to the background size,
23123     * unless a larger size is allowed by the MeasureSpec. Subclasses should
23124     * override {@link #onMeasure(int, int)} to provide better measurements of
23125     * their content.
23126     * </p>
23127     *
23128     * <p>
23129     * If this method is overridden, it is the subclass's responsibility to make
23130     * sure the measured height and width are at least the view's minimum height
23131     * and width ({@link #getSuggestedMinimumHeight()} and
23132     * {@link #getSuggestedMinimumWidth()}).
23133     * </p>
23134     *
23135     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
23136     *                         The requirements are encoded with
23137     *                         {@link android.view.View.MeasureSpec}.
23138     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
23139     *                         The requirements are encoded with
23140     *                         {@link android.view.View.MeasureSpec}.
23141     *
23142     * @see #getMeasuredWidth()
23143     * @see #getMeasuredHeight()
23144     * @see #setMeasuredDimension(int, int)
23145     * @see #getSuggestedMinimumHeight()
23146     * @see #getSuggestedMinimumWidth()
23147     * @see android.view.View.MeasureSpec#getMode(int)
23148     * @see android.view.View.MeasureSpec#getSize(int)
23149     */
23150    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
23151        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
23152                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
23153    }
23154
23155    /**
23156     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
23157     * measured width and measured height. Failing to do so will trigger an
23158     * exception at measurement time.</p>
23159     *
23160     * @param measuredWidth The measured width of this view.  May be a complex
23161     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
23162     * {@link #MEASURED_STATE_TOO_SMALL}.
23163     * @param measuredHeight The measured height of this view.  May be a complex
23164     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
23165     * {@link #MEASURED_STATE_TOO_SMALL}.
23166     */
23167    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
23168        boolean optical = isLayoutModeOptical(this);
23169        if (optical != isLayoutModeOptical(mParent)) {
23170            Insets insets = getOpticalInsets();
23171            int opticalWidth  = insets.left + insets.right;
23172            int opticalHeight = insets.top  + insets.bottom;
23173
23174            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
23175            measuredHeight += optical ? opticalHeight : -opticalHeight;
23176        }
23177        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
23178    }
23179
23180    /**
23181     * Sets the measured dimension without extra processing for things like optical bounds.
23182     * Useful for reapplying consistent values that have already been cooked with adjustments
23183     * for optical bounds, etc. such as those from the measurement cache.
23184     *
23185     * @param measuredWidth The measured width of this view.  May be a complex
23186     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
23187     * {@link #MEASURED_STATE_TOO_SMALL}.
23188     * @param measuredHeight The measured height of this view.  May be a complex
23189     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
23190     * {@link #MEASURED_STATE_TOO_SMALL}.
23191     */
23192    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
23193        mMeasuredWidth = measuredWidth;
23194        mMeasuredHeight = measuredHeight;
23195
23196        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
23197    }
23198
23199    /**
23200     * Merge two states as returned by {@link #getMeasuredState()}.
23201     * @param curState The current state as returned from a view or the result
23202     * of combining multiple views.
23203     * @param newState The new view state to combine.
23204     * @return Returns a new integer reflecting the combination of the two
23205     * states.
23206     */
23207    public static int combineMeasuredStates(int curState, int newState) {
23208        return curState | newState;
23209    }
23210
23211    /**
23212     * Version of {@link #resolveSizeAndState(int, int, int)}
23213     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
23214     */
23215    public static int resolveSize(int size, int measureSpec) {
23216        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
23217    }
23218
23219    /**
23220     * Utility to reconcile a desired size and state, with constraints imposed
23221     * by a MeasureSpec. Will take the desired size, unless a different size
23222     * is imposed by the constraints. The returned value is a compound integer,
23223     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
23224     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the
23225     * resulting size is smaller than the size the view wants to be.
23226     *
23227     * @param size How big the view wants to be.
23228     * @param measureSpec Constraints imposed by the parent.
23229     * @param childMeasuredState Size information bit mask for the view's
23230     *                           children.
23231     * @return Size information bit mask as defined by
23232     *         {@link #MEASURED_SIZE_MASK} and
23233     *         {@link #MEASURED_STATE_TOO_SMALL}.
23234     */
23235    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
23236        final int specMode = MeasureSpec.getMode(measureSpec);
23237        final int specSize = MeasureSpec.getSize(measureSpec);
23238        final int result;
23239        switch (specMode) {
23240            case MeasureSpec.AT_MOST:
23241                if (specSize < size) {
23242                    result = specSize | MEASURED_STATE_TOO_SMALL;
23243                } else {
23244                    result = size;
23245                }
23246                break;
23247            case MeasureSpec.EXACTLY:
23248                result = specSize;
23249                break;
23250            case MeasureSpec.UNSPECIFIED:
23251            default:
23252                result = size;
23253        }
23254        return result | (childMeasuredState & MEASURED_STATE_MASK);
23255    }
23256
23257    /**
23258     * Utility to return a default size. Uses the supplied size if the
23259     * MeasureSpec imposed no constraints. Will get larger if allowed
23260     * by the MeasureSpec.
23261     *
23262     * @param size Default size for this view
23263     * @param measureSpec Constraints imposed by the parent
23264     * @return The size this view should be.
23265     */
23266    public static int getDefaultSize(int size, int measureSpec) {
23267        int result = size;
23268        int specMode = MeasureSpec.getMode(measureSpec);
23269        int specSize = MeasureSpec.getSize(measureSpec);
23270
23271        switch (specMode) {
23272        case MeasureSpec.UNSPECIFIED:
23273            result = size;
23274            break;
23275        case MeasureSpec.AT_MOST:
23276        case MeasureSpec.EXACTLY:
23277            result = specSize;
23278            break;
23279        }
23280        return result;
23281    }
23282
23283    /**
23284     * Returns the suggested minimum height that the view should use. This
23285     * returns the maximum of the view's minimum height
23286     * and the background's minimum height
23287     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
23288     * <p>
23289     * When being used in {@link #onMeasure(int, int)}, the caller should still
23290     * ensure the returned height is within the requirements of the parent.
23291     *
23292     * @return The suggested minimum height of the view.
23293     */
23294    protected int getSuggestedMinimumHeight() {
23295        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
23296
23297    }
23298
23299    /**
23300     * Returns the suggested minimum width that the view should use. This
23301     * returns the maximum of the view's minimum width
23302     * and the background's minimum width
23303     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
23304     * <p>
23305     * When being used in {@link #onMeasure(int, int)}, the caller should still
23306     * ensure the returned width is within the requirements of the parent.
23307     *
23308     * @return The suggested minimum width of the view.
23309     */
23310    protected int getSuggestedMinimumWidth() {
23311        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
23312    }
23313
23314    /**
23315     * Returns the minimum height of the view.
23316     *
23317     * @return the minimum height the view will try to be, in pixels
23318     *
23319     * @see #setMinimumHeight(int)
23320     *
23321     * @attr ref android.R.styleable#View_minHeight
23322     */
23323    public int getMinimumHeight() {
23324        return mMinHeight;
23325    }
23326
23327    /**
23328     * Sets the minimum height of the view. It is not guaranteed the view will
23329     * be able to achieve this minimum height (for example, if its parent layout
23330     * constrains it with less available height).
23331     *
23332     * @param minHeight The minimum height the view will try to be, in pixels
23333     *
23334     * @see #getMinimumHeight()
23335     *
23336     * @attr ref android.R.styleable#View_minHeight
23337     */
23338    @RemotableViewMethod
23339    public void setMinimumHeight(int minHeight) {
23340        mMinHeight = minHeight;
23341        requestLayout();
23342    }
23343
23344    /**
23345     * Returns the minimum width of the view.
23346     *
23347     * @return the minimum width the view will try to be, in pixels
23348     *
23349     * @see #setMinimumWidth(int)
23350     *
23351     * @attr ref android.R.styleable#View_minWidth
23352     */
23353    public int getMinimumWidth() {
23354        return mMinWidth;
23355    }
23356
23357    /**
23358     * Sets the minimum width of the view. It is not guaranteed the view will
23359     * be able to achieve this minimum width (for example, if its parent layout
23360     * constrains it with less available width).
23361     *
23362     * @param minWidth The minimum width the view will try to be, in pixels
23363     *
23364     * @see #getMinimumWidth()
23365     *
23366     * @attr ref android.R.styleable#View_minWidth
23367     */
23368    public void setMinimumWidth(int minWidth) {
23369        mMinWidth = minWidth;
23370        requestLayout();
23371
23372    }
23373
23374    /**
23375     * Get the animation currently associated with this view.
23376     *
23377     * @return The animation that is currently playing or
23378     *         scheduled to play for this view.
23379     */
23380    public Animation getAnimation() {
23381        return mCurrentAnimation;
23382    }
23383
23384    /**
23385     * Start the specified animation now.
23386     *
23387     * @param animation the animation to start now
23388     */
23389    public void startAnimation(Animation animation) {
23390        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
23391        setAnimation(animation);
23392        invalidateParentCaches();
23393        invalidate(true);
23394    }
23395
23396    /**
23397     * Cancels any animations for this view.
23398     */
23399    public void clearAnimation() {
23400        if (mCurrentAnimation != null) {
23401            mCurrentAnimation.detach();
23402        }
23403        mCurrentAnimation = null;
23404        invalidateParentIfNeeded();
23405    }
23406
23407    /**
23408     * Sets the next animation to play for this view.
23409     * If you want the animation to play immediately, use
23410     * {@link #startAnimation(android.view.animation.Animation)} instead.
23411     * This method provides allows fine-grained
23412     * control over the start time and invalidation, but you
23413     * must make sure that 1) the animation has a start time set, and
23414     * 2) the view's parent (which controls animations on its children)
23415     * will be invalidated when the animation is supposed to
23416     * start.
23417     *
23418     * @param animation The next animation, or null.
23419     */
23420    public void setAnimation(Animation animation) {
23421        mCurrentAnimation = animation;
23422
23423        if (animation != null) {
23424            // If the screen is off assume the animation start time is now instead of
23425            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
23426            // would cause the animation to start when the screen turns back on
23427            if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF
23428                    && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
23429                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
23430            }
23431            animation.reset();
23432        }
23433    }
23434
23435    /**
23436     * Invoked by a parent ViewGroup to notify the start of the animation
23437     * currently associated with this view. If you override this method,
23438     * always call super.onAnimationStart();
23439     *
23440     * @see #setAnimation(android.view.animation.Animation)
23441     * @see #getAnimation()
23442     */
23443    @CallSuper
23444    protected void onAnimationStart() {
23445        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
23446    }
23447
23448    /**
23449     * Invoked by a parent ViewGroup to notify the end of the animation
23450     * currently associated with this view. If you override this method,
23451     * always call super.onAnimationEnd();
23452     *
23453     * @see #setAnimation(android.view.animation.Animation)
23454     * @see #getAnimation()
23455     */
23456    @CallSuper
23457    protected void onAnimationEnd() {
23458        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
23459    }
23460
23461    /**
23462     * Invoked if there is a Transform that involves alpha. Subclass that can
23463     * draw themselves with the specified alpha should return true, and then
23464     * respect that alpha when their onDraw() is called. If this returns false
23465     * then the view may be redirected to draw into an offscreen buffer to
23466     * fulfill the request, which will look fine, but may be slower than if the
23467     * subclass handles it internally. The default implementation returns false.
23468     *
23469     * @param alpha The alpha (0..255) to apply to the view's drawing
23470     * @return true if the view can draw with the specified alpha.
23471     */
23472    protected boolean onSetAlpha(int alpha) {
23473        return false;
23474    }
23475
23476    /**
23477     * This is used by the RootView to perform an optimization when
23478     * the view hierarchy contains one or several SurfaceView.
23479     * SurfaceView is always considered transparent, but its children are not,
23480     * therefore all View objects remove themselves from the global transparent
23481     * region (passed as a parameter to this function).
23482     *
23483     * @param region The transparent region for this ViewAncestor (window).
23484     *
23485     * @return Returns true if the effective visibility of the view at this
23486     * point is opaque, regardless of the transparent region; returns false
23487     * if it is possible for underlying windows to be seen behind the view.
23488     *
23489     * {@hide}
23490     */
23491    public boolean gatherTransparentRegion(Region region) {
23492        final AttachInfo attachInfo = mAttachInfo;
23493        if (region != null && attachInfo != null) {
23494            final int pflags = mPrivateFlags;
23495            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
23496                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
23497                // remove it from the transparent region.
23498                final int[] location = attachInfo.mTransparentLocation;
23499                getLocationInWindow(location);
23500                // When a view has Z value, then it will be better to leave some area below the view
23501                // for drawing shadow. The shadow outset is proportional to the Z value. Note that
23502                // the bottom part needs more offset than the left, top and right parts due to the
23503                // spot light effects.
23504                int shadowOffset = getZ() > 0 ? (int) getZ() : 0;
23505                region.op(location[0] - shadowOffset, location[1] - shadowOffset,
23506                        location[0] + mRight - mLeft + shadowOffset,
23507                        location[1] + mBottom - mTop + (shadowOffset * 3), Region.Op.DIFFERENCE);
23508            } else {
23509                if (mBackground != null && mBackground.getOpacity() != PixelFormat.TRANSPARENT) {
23510                    // The SKIP_DRAW flag IS set and the background drawable exists, we remove
23511                    // the background drawable's non-transparent parts from this transparent region.
23512                    applyDrawableToTransparentRegion(mBackground, region);
23513                }
23514                if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
23515                        && mForegroundInfo.mDrawable.getOpacity() != PixelFormat.TRANSPARENT) {
23516                    // Similarly, we remove the foreground drawable's non-transparent parts.
23517                    applyDrawableToTransparentRegion(mForegroundInfo.mDrawable, region);
23518                }
23519                if (mDefaultFocusHighlight != null
23520                        && mDefaultFocusHighlight.getOpacity() != PixelFormat.TRANSPARENT) {
23521                    // Similarly, we remove the default focus highlight's non-transparent parts.
23522                    applyDrawableToTransparentRegion(mDefaultFocusHighlight, region);
23523                }
23524            }
23525        }
23526        return true;
23527    }
23528
23529    /**
23530     * Play a sound effect for this view.
23531     *
23532     * <p>The framework will play sound effects for some built in actions, such as
23533     * clicking, but you may wish to play these effects in your widget,
23534     * for instance, for internal navigation.
23535     *
23536     * <p>The sound effect will only be played if sound effects are enabled by the user, and
23537     * {@link #isSoundEffectsEnabled()} is true.
23538     *
23539     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
23540     */
23541    public void playSoundEffect(int soundConstant) {
23542        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
23543            return;
23544        }
23545        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
23546    }
23547
23548    /**
23549     * BZZZTT!!1!
23550     *
23551     * <p>Provide haptic feedback to the user for this view.
23552     *
23553     * <p>The framework will provide haptic feedback for some built in actions,
23554     * such as long presses, but you may wish to provide feedback for your
23555     * own widget.
23556     *
23557     * <p>The feedback will only be performed if
23558     * {@link #isHapticFeedbackEnabled()} is true.
23559     *
23560     * @param feedbackConstant One of the constants defined in
23561     * {@link HapticFeedbackConstants}
23562     */
23563    public boolean performHapticFeedback(int feedbackConstant) {
23564        return performHapticFeedback(feedbackConstant, 0);
23565    }
23566
23567    /**
23568     * BZZZTT!!1!
23569     *
23570     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
23571     *
23572     * @param feedbackConstant One of the constants defined in
23573     * {@link HapticFeedbackConstants}
23574     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
23575     */
23576    public boolean performHapticFeedback(int feedbackConstant, int flags) {
23577        if (mAttachInfo == null) {
23578            return false;
23579        }
23580        //noinspection SimplifiableIfStatement
23581        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
23582                && !isHapticFeedbackEnabled()) {
23583            return false;
23584        }
23585        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
23586                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
23587    }
23588
23589    /**
23590     * Request that the visibility of the status bar or other screen/window
23591     * decorations be changed.
23592     *
23593     * <p>This method is used to put the over device UI into temporary modes
23594     * where the user's attention is focused more on the application content,
23595     * by dimming or hiding surrounding system affordances.  This is typically
23596     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
23597     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
23598     * to be placed behind the action bar (and with these flags other system
23599     * affordances) so that smooth transitions between hiding and showing them
23600     * can be done.
23601     *
23602     * <p>Two representative examples of the use of system UI visibility is
23603     * implementing a content browsing application (like a magazine reader)
23604     * and a video playing application.
23605     *
23606     * <p>The first code shows a typical implementation of a View in a content
23607     * browsing application.  In this implementation, the application goes
23608     * into a content-oriented mode by hiding the status bar and action bar,
23609     * and putting the navigation elements into lights out mode.  The user can
23610     * then interact with content while in this mode.  Such an application should
23611     * provide an easy way for the user to toggle out of the mode (such as to
23612     * check information in the status bar or access notifications).  In the
23613     * implementation here, this is done simply by tapping on the content.
23614     *
23615     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
23616     *      content}
23617     *
23618     * <p>This second code sample shows a typical implementation of a View
23619     * in a video playing application.  In this situation, while the video is
23620     * playing the application would like to go into a complete full-screen mode,
23621     * to use as much of the display as possible for the video.  When in this state
23622     * the user can not interact with the application; the system intercepts
23623     * touching on the screen to pop the UI out of full screen mode.  See
23624     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
23625     *
23626     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
23627     *      content}
23628     *
23629     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
23630     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
23631     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
23632     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
23633     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
23634     */
23635    public void setSystemUiVisibility(int visibility) {
23636        if (visibility != mSystemUiVisibility) {
23637            mSystemUiVisibility = visibility;
23638            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
23639                mParent.recomputeViewAttributes(this);
23640            }
23641        }
23642    }
23643
23644    /**
23645     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
23646     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
23647     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
23648     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
23649     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
23650     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
23651     */
23652    public int getSystemUiVisibility() {
23653        return mSystemUiVisibility;
23654    }
23655
23656    /**
23657     * Returns the current system UI visibility that is currently set for
23658     * the entire window.  This is the combination of the
23659     * {@link #setSystemUiVisibility(int)} values supplied by all of the
23660     * views in the window.
23661     */
23662    public int getWindowSystemUiVisibility() {
23663        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
23664    }
23665
23666    /**
23667     * Override to find out when the window's requested system UI visibility
23668     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
23669     * This is different from the callbacks received through
23670     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
23671     * in that this is only telling you about the local request of the window,
23672     * not the actual values applied by the system.
23673     */
23674    public void onWindowSystemUiVisibilityChanged(int visible) {
23675    }
23676
23677    /**
23678     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
23679     * the view hierarchy.
23680     */
23681    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
23682        onWindowSystemUiVisibilityChanged(visible);
23683    }
23684
23685    /**
23686     * Set a listener to receive callbacks when the visibility of the system bar changes.
23687     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
23688     */
23689    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
23690        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
23691        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
23692            mParent.recomputeViewAttributes(this);
23693        }
23694    }
23695
23696    /**
23697     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
23698     * the view hierarchy.
23699     */
23700    public void dispatchSystemUiVisibilityChanged(int visibility) {
23701        ListenerInfo li = mListenerInfo;
23702        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
23703            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
23704                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
23705        }
23706    }
23707
23708    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
23709        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
23710        if (val != mSystemUiVisibility) {
23711            setSystemUiVisibility(val);
23712            return true;
23713        }
23714        return false;
23715    }
23716
23717    /** @hide */
23718    public void setDisabledSystemUiVisibility(int flags) {
23719        if (mAttachInfo != null) {
23720            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
23721                mAttachInfo.mDisabledSystemUiVisibility = flags;
23722                if (mParent != null) {
23723                    mParent.recomputeViewAttributes(this);
23724                }
23725            }
23726        }
23727    }
23728
23729    /**
23730     * Creates an image that the system displays during the drag and drop
23731     * operation. This is called a &quot;drag shadow&quot;. The default implementation
23732     * for a DragShadowBuilder based on a View returns an image that has exactly the same
23733     * appearance as the given View. The default also positions the center of the drag shadow
23734     * directly under the touch point. If no View is provided (the constructor with no parameters
23735     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
23736     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overridden, then the
23737     * default is an invisible drag shadow.
23738     * <p>
23739     * You are not required to use the View you provide to the constructor as the basis of the
23740     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
23741     * anything you want as the drag shadow.
23742     * </p>
23743     * <p>
23744     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
23745     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
23746     *  size and position of the drag shadow. It uses this data to construct a
23747     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
23748     *  so that your application can draw the shadow image in the Canvas.
23749     * </p>
23750     *
23751     * <div class="special reference">
23752     * <h3>Developer Guides</h3>
23753     * <p>For a guide to implementing drag and drop features, read the
23754     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
23755     * </div>
23756     */
23757    public static class DragShadowBuilder {
23758        private final WeakReference<View> mView;
23759
23760        /**
23761         * Constructs a shadow image builder based on a View. By default, the resulting drag
23762         * shadow will have the same appearance and dimensions as the View, with the touch point
23763         * over the center of the View.
23764         * @param view A View. Any View in scope can be used.
23765         */
23766        public DragShadowBuilder(View view) {
23767            mView = new WeakReference<View>(view);
23768        }
23769
23770        /**
23771         * Construct a shadow builder object with no associated View.  This
23772         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
23773         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
23774         * to supply the drag shadow's dimensions and appearance without
23775         * reference to any View object.
23776         */
23777        public DragShadowBuilder() {
23778            mView = new WeakReference<View>(null);
23779        }
23780
23781        /**
23782         * Returns the View object that had been passed to the
23783         * {@link #View.DragShadowBuilder(View)}
23784         * constructor.  If that View parameter was {@code null} or if the
23785         * {@link #View.DragShadowBuilder()}
23786         * constructor was used to instantiate the builder object, this method will return
23787         * null.
23788         *
23789         * @return The View object associate with this builder object.
23790         */
23791        @SuppressWarnings({"JavadocReference"})
23792        final public View getView() {
23793            return mView.get();
23794        }
23795
23796        /**
23797         * Provides the metrics for the shadow image. These include the dimensions of
23798         * the shadow image, and the point within that shadow that should
23799         * be centered under the touch location while dragging.
23800         * <p>
23801         * The default implementation sets the dimensions of the shadow to be the
23802         * same as the dimensions of the View itself and centers the shadow under
23803         * the touch point.
23804         * </p>
23805         *
23806         * @param outShadowSize A {@link android.graphics.Point} containing the width and height
23807         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
23808         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
23809         * image.
23810         *
23811         * @param outShadowTouchPoint A {@link android.graphics.Point} for the position within the
23812         * shadow image that should be underneath the touch point during the drag and drop
23813         * operation. Your application must set {@link android.graphics.Point#x} to the
23814         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
23815         */
23816        public void onProvideShadowMetrics(Point outShadowSize, Point outShadowTouchPoint) {
23817            final View view = mView.get();
23818            if (view != null) {
23819                outShadowSize.set(view.getWidth(), view.getHeight());
23820                outShadowTouchPoint.set(outShadowSize.x / 2, outShadowSize.y / 2);
23821            } else {
23822                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
23823            }
23824        }
23825
23826        /**
23827         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
23828         * based on the dimensions it received from the
23829         * {@link #onProvideShadowMetrics(Point, Point)} callback.
23830         *
23831         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
23832         */
23833        public void onDrawShadow(Canvas canvas) {
23834            final View view = mView.get();
23835            if (view != null) {
23836                view.draw(canvas);
23837            } else {
23838                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
23839            }
23840        }
23841    }
23842
23843    /**
23844     * @deprecated Use {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)
23845     * startDragAndDrop()} for newer platform versions.
23846     */
23847    @Deprecated
23848    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
23849                                   Object myLocalState, int flags) {
23850        return startDragAndDrop(data, shadowBuilder, myLocalState, flags);
23851    }
23852
23853    /**
23854     * Starts a drag and drop operation. When your application calls this method, it passes a
23855     * {@link android.view.View.DragShadowBuilder} object to the system. The
23856     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
23857     * to get metrics for the drag shadow, and then calls the object's
23858     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
23859     * <p>
23860     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
23861     *  drag events to all the View objects in your application that are currently visible. It does
23862     *  this either by calling the View object's drag listener (an implementation of
23863     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
23864     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
23865     *  Both are passed a {@link android.view.DragEvent} object that has a
23866     *  {@link android.view.DragEvent#getAction()} value of
23867     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
23868     * </p>
23869     * <p>
23870     * Your application can invoke {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object,
23871     * int) startDragAndDrop()} on any attached View object. The View object does not need to be
23872     * the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to be related
23873     * to the View the user selected for dragging.
23874     * </p>
23875     * @param data A {@link android.content.ClipData} object pointing to the data to be
23876     * transferred by the drag and drop operation.
23877     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
23878     * drag shadow.
23879     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
23880     * drop operation. When dispatching drag events to views in the same activity this object
23881     * will be available through {@link android.view.DragEvent#getLocalState()}. Views in other
23882     * activities will not have access to this data ({@link android.view.DragEvent#getLocalState()}
23883     * will return null).
23884     * <p>
23885     * myLocalState is a lightweight mechanism for the sending information from the dragged View
23886     * to the target Views. For example, it can contain flags that differentiate between a
23887     * a copy operation and a move operation.
23888     * </p>
23889     * @param flags Flags that control the drag and drop operation. This can be set to 0 for no
23890     * flags, or any combination of the following:
23891     *     <ul>
23892     *         <li>{@link #DRAG_FLAG_GLOBAL}</li>
23893     *         <li>{@link #DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION}</li>
23894     *         <li>{@link #DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION}</li>
23895     *         <li>{@link #DRAG_FLAG_GLOBAL_URI_READ}</li>
23896     *         <li>{@link #DRAG_FLAG_GLOBAL_URI_WRITE}</li>
23897     *         <li>{@link #DRAG_FLAG_OPAQUE}</li>
23898     *     </ul>
23899     * @return {@code true} if the method completes successfully, or
23900     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
23901     * do a drag, and so no drag operation is in progress.
23902     */
23903    public final boolean startDragAndDrop(ClipData data, DragShadowBuilder shadowBuilder,
23904            Object myLocalState, int flags) {
23905        if (ViewDebug.DEBUG_DRAG) {
23906            Log.d(VIEW_LOG_TAG, "startDragAndDrop: data=" + data + " flags=" + flags);
23907        }
23908        if (mAttachInfo == null) {
23909            Log.w(VIEW_LOG_TAG, "startDragAndDrop called on a detached view.");
23910            return false;
23911        }
23912
23913        if (data != null) {
23914            data.prepareToLeaveProcess((flags & View.DRAG_FLAG_GLOBAL) != 0);
23915        }
23916
23917        Point shadowSize = new Point();
23918        Point shadowTouchPoint = new Point();
23919        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
23920
23921        if ((shadowSize.x < 0) || (shadowSize.y < 0)
23922                || (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
23923            throw new IllegalStateException("Drag shadow dimensions must not be negative");
23924        }
23925
23926        // Create 1x1 surface when zero surface size is specified because SurfaceControl.Builder
23927        // does not accept zero size surface.
23928        if (shadowSize.x == 0  || shadowSize.y == 0) {
23929            if (!sAcceptZeroSizeDragShadow) {
23930                throw new IllegalStateException("Drag shadow dimensions must be positive");
23931            }
23932            shadowSize.x = 1;
23933            shadowSize.y = 1;
23934        }
23935
23936        if (ViewDebug.DEBUG_DRAG) {
23937            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
23938                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
23939        }
23940        if (mAttachInfo.mDragSurface != null) {
23941            mAttachInfo.mDragSurface.release();
23942        }
23943        mAttachInfo.mDragSurface = new Surface();
23944        mAttachInfo.mDragToken = null;
23945
23946        final ViewRootImpl root = mAttachInfo.mViewRootImpl;
23947        final SurfaceSession session = new SurfaceSession(root.mSurface);
23948        final SurfaceControl surface = new SurfaceControl.Builder(session)
23949                .setName("drag surface")
23950                .setSize(shadowSize.x, shadowSize.y)
23951                .setFormat(PixelFormat.TRANSLUCENT)
23952                .build();
23953        try {
23954            mAttachInfo.mDragSurface.copyFrom(surface);
23955            final Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null);
23956            try {
23957                canvas.drawColor(0, PorterDuff.Mode.CLEAR);
23958                shadowBuilder.onDrawShadow(canvas);
23959            } finally {
23960                mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas);
23961            }
23962
23963            // Cache the local state object for delivery with DragEvents
23964            root.setLocalDragState(myLocalState);
23965
23966            // repurpose 'shadowSize' for the last touch point
23967            root.getLastTouchPoint(shadowSize);
23968
23969            mAttachInfo.mDragToken = mAttachInfo.mSession.performDrag(
23970                    mAttachInfo.mWindow, flags, surface, root.getLastTouchSource(),
23971                    shadowSize.x, shadowSize.y, shadowTouchPoint.x, shadowTouchPoint.y, data);
23972            if (ViewDebug.DEBUG_DRAG) {
23973                Log.d(VIEW_LOG_TAG, "performDrag returned " + mAttachInfo.mDragToken);
23974            }
23975
23976            return mAttachInfo.mDragToken != null;
23977        } catch (Exception e) {
23978            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
23979            return false;
23980        } finally {
23981            if (mAttachInfo.mDragToken == null) {
23982                mAttachInfo.mDragSurface.destroy();
23983                mAttachInfo.mDragSurface = null;
23984                root.setLocalDragState(null);
23985            }
23986            session.kill();
23987        }
23988    }
23989
23990    /**
23991     * Cancels an ongoing drag and drop operation.
23992     * <p>
23993     * A {@link android.view.DragEvent} object with
23994     * {@link android.view.DragEvent#getAction()} value of
23995     * {@link android.view.DragEvent#ACTION_DRAG_ENDED} and
23996     * {@link android.view.DragEvent#getResult()} value of {@code false}
23997     * will be sent to every
23998     * View that received {@link android.view.DragEvent#ACTION_DRAG_STARTED}
23999     * even if they are not currently visible.
24000     * </p>
24001     * <p>
24002     * This method can be called on any View in the same window as the View on which
24003     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int) startDragAndDrop}
24004     * was called.
24005     * </p>
24006     */
24007    public final void cancelDragAndDrop() {
24008        if (ViewDebug.DEBUG_DRAG) {
24009            Log.d(VIEW_LOG_TAG, "cancelDragAndDrop");
24010        }
24011        if (mAttachInfo == null) {
24012            Log.w(VIEW_LOG_TAG, "cancelDragAndDrop called on a detached view.");
24013            return;
24014        }
24015        if (mAttachInfo.mDragToken != null) {
24016            try {
24017                mAttachInfo.mSession.cancelDragAndDrop(mAttachInfo.mDragToken);
24018            } catch (Exception e) {
24019                Log.e(VIEW_LOG_TAG, "Unable to cancel drag", e);
24020            }
24021            mAttachInfo.mDragToken = null;
24022        } else {
24023            Log.e(VIEW_LOG_TAG, "No active drag to cancel");
24024        }
24025    }
24026
24027    /**
24028     * Updates the drag shadow for the ongoing drag and drop operation.
24029     *
24030     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
24031     * new drag shadow.
24032     */
24033    public final void updateDragShadow(DragShadowBuilder shadowBuilder) {
24034        if (ViewDebug.DEBUG_DRAG) {
24035            Log.d(VIEW_LOG_TAG, "updateDragShadow");
24036        }
24037        if (mAttachInfo == null) {
24038            Log.w(VIEW_LOG_TAG, "updateDragShadow called on a detached view.");
24039            return;
24040        }
24041        if (mAttachInfo.mDragToken != null) {
24042            try {
24043                Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null);
24044                try {
24045                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
24046                    shadowBuilder.onDrawShadow(canvas);
24047                } finally {
24048                    mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas);
24049                }
24050            } catch (Exception e) {
24051                Log.e(VIEW_LOG_TAG, "Unable to update drag shadow", e);
24052            }
24053        } else {
24054            Log.e(VIEW_LOG_TAG, "No active drag");
24055        }
24056    }
24057
24058    /**
24059     * Starts a move from {startX, startY}, the amount of the movement will be the offset
24060     * between {startX, startY} and the new cursor positon.
24061     * @param startX horizontal coordinate where the move started.
24062     * @param startY vertical coordinate where the move started.
24063     * @return whether moving was started successfully.
24064     * @hide
24065     */
24066    public final boolean startMovingTask(float startX, float startY) {
24067        if (ViewDebug.DEBUG_POSITIONING) {
24068            Log.d(VIEW_LOG_TAG, "startMovingTask: {" + startX + "," + startY + "}");
24069        }
24070        try {
24071            return mAttachInfo.mSession.startMovingTask(mAttachInfo.mWindow, startX, startY);
24072        } catch (RemoteException e) {
24073            Log.e(VIEW_LOG_TAG, "Unable to start moving", e);
24074        }
24075        return false;
24076    }
24077
24078    /**
24079     * Handles drag events sent by the system following a call to
24080     * {@link android.view.View#startDragAndDrop(ClipData,DragShadowBuilder,Object,int)
24081     * startDragAndDrop()}.
24082     *<p>
24083     * When the system calls this method, it passes a
24084     * {@link android.view.DragEvent} object. A call to
24085     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
24086     * in DragEvent. The method uses these to determine what is happening in the drag and drop
24087     * operation.
24088     * @param event The {@link android.view.DragEvent} sent by the system.
24089     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
24090     * in DragEvent, indicating the type of drag event represented by this object.
24091     * @return {@code true} if the method was successful, otherwise {@code false}.
24092     * <p>
24093     *  The method should return {@code true} in response to an action type of
24094     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
24095     *  operation.
24096     * </p>
24097     * <p>
24098     *  The method should also return {@code true} in response to an action type of
24099     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
24100     *  {@code false} if it didn't.
24101     * </p>
24102     * <p>
24103     *  For all other events, the return value is ignored.
24104     * </p>
24105     */
24106    public boolean onDragEvent(DragEvent event) {
24107        return false;
24108    }
24109
24110    // Dispatches ACTION_DRAG_ENTERED and ACTION_DRAG_EXITED events for pre-Nougat apps.
24111    boolean dispatchDragEnterExitInPreN(DragEvent event) {
24112        return callDragEventHandler(event);
24113    }
24114
24115    /**
24116     * Detects if this View is enabled and has a drag event listener.
24117     * If both are true, then it calls the drag event listener with the
24118     * {@link android.view.DragEvent} it received. If the drag event listener returns
24119     * {@code true}, then dispatchDragEvent() returns {@code true}.
24120     * <p>
24121     * For all other cases, the method calls the
24122     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
24123     * method and returns its result.
24124     * </p>
24125     * <p>
24126     * This ensures that a drag event is always consumed, even if the View does not have a drag
24127     * event listener. However, if the View has a listener and the listener returns true, then
24128     * onDragEvent() is not called.
24129     * </p>
24130     */
24131    public boolean dispatchDragEvent(DragEvent event) {
24132        event.mEventHandlerWasCalled = true;
24133        if (event.mAction == DragEvent.ACTION_DRAG_LOCATION ||
24134            event.mAction == DragEvent.ACTION_DROP) {
24135            // About to deliver an event with coordinates to this view. Notify that now this view
24136            // has drag focus. This will send exit/enter events as needed.
24137            getViewRootImpl().setDragFocus(this, event);
24138        }
24139        return callDragEventHandler(event);
24140    }
24141
24142    final boolean callDragEventHandler(DragEvent event) {
24143        final boolean result;
24144
24145        ListenerInfo li = mListenerInfo;
24146        //noinspection SimplifiableIfStatement
24147        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
24148                && li.mOnDragListener.onDrag(this, event)) {
24149            result = true;
24150        } else {
24151            result = onDragEvent(event);
24152        }
24153
24154        switch (event.mAction) {
24155            case DragEvent.ACTION_DRAG_ENTERED: {
24156                mPrivateFlags2 |= View.PFLAG2_DRAG_HOVERED;
24157                refreshDrawableState();
24158            } break;
24159            case DragEvent.ACTION_DRAG_EXITED: {
24160                mPrivateFlags2 &= ~View.PFLAG2_DRAG_HOVERED;
24161                refreshDrawableState();
24162            } break;
24163            case DragEvent.ACTION_DRAG_ENDED: {
24164                mPrivateFlags2 &= ~View.DRAG_MASK;
24165                refreshDrawableState();
24166            } break;
24167        }
24168
24169        return result;
24170    }
24171
24172    boolean canAcceptDrag() {
24173        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
24174    }
24175
24176    /**
24177     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
24178     * it is ever exposed at all.
24179     * @hide
24180     */
24181    public void onCloseSystemDialogs(String reason) {
24182    }
24183
24184    /**
24185     * Given a Drawable whose bounds have been set to draw into this view,
24186     * update a Region being computed for
24187     * {@link #gatherTransparentRegion(android.graphics.Region)} so
24188     * that any non-transparent parts of the Drawable are removed from the
24189     * given transparent region.
24190     *
24191     * @param dr The Drawable whose transparency is to be applied to the region.
24192     * @param region A Region holding the current transparency information,
24193     * where any parts of the region that are set are considered to be
24194     * transparent.  On return, this region will be modified to have the
24195     * transparency information reduced by the corresponding parts of the
24196     * Drawable that are not transparent.
24197     * {@hide}
24198     */
24199    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
24200        if (DBG) {
24201            Log.i("View", "Getting transparent region for: " + this);
24202        }
24203        final Region r = dr.getTransparentRegion();
24204        final Rect db = dr.getBounds();
24205        final AttachInfo attachInfo = mAttachInfo;
24206        if (r != null && attachInfo != null) {
24207            final int w = getRight()-getLeft();
24208            final int h = getBottom()-getTop();
24209            if (db.left > 0) {
24210                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
24211                r.op(0, 0, db.left, h, Region.Op.UNION);
24212            }
24213            if (db.right < w) {
24214                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
24215                r.op(db.right, 0, w, h, Region.Op.UNION);
24216            }
24217            if (db.top > 0) {
24218                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
24219                r.op(0, 0, w, db.top, Region.Op.UNION);
24220            }
24221            if (db.bottom < h) {
24222                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
24223                r.op(0, db.bottom, w, h, Region.Op.UNION);
24224            }
24225            final int[] location = attachInfo.mTransparentLocation;
24226            getLocationInWindow(location);
24227            r.translate(location[0], location[1]);
24228            region.op(r, Region.Op.INTERSECT);
24229        } else {
24230            region.op(db, Region.Op.DIFFERENCE);
24231        }
24232    }
24233
24234    private void checkForLongClick(int delayOffset, float x, float y) {
24235        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE || (mViewFlags & TOOLTIP) == TOOLTIP) {
24236            mHasPerformedLongPress = false;
24237
24238            if (mPendingCheckForLongPress == null) {
24239                mPendingCheckForLongPress = new CheckForLongPress();
24240            }
24241            mPendingCheckForLongPress.setAnchor(x, y);
24242            mPendingCheckForLongPress.rememberWindowAttachCount();
24243            mPendingCheckForLongPress.rememberPressedState();
24244            postDelayed(mPendingCheckForLongPress,
24245                    ViewConfiguration.getLongPressTimeout() - delayOffset);
24246        }
24247    }
24248
24249    /**
24250     * Inflate a view from an XML resource.  This convenience method wraps the {@link
24251     * LayoutInflater} class, which provides a full range of options for view inflation.
24252     *
24253     * @param context The Context object for your activity or application.
24254     * @param resource The resource ID to inflate
24255     * @param root A view group that will be the parent.  Used to properly inflate the
24256     * layout_* parameters.
24257     * @see LayoutInflater
24258     */
24259    public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
24260        LayoutInflater factory = LayoutInflater.from(context);
24261        return factory.inflate(resource, root);
24262    }
24263
24264    /**
24265     * Scroll the view with standard behavior for scrolling beyond the normal
24266     * content boundaries. Views that call this method should override
24267     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
24268     * results of an over-scroll operation.
24269     *
24270     * Views can use this method to handle any touch or fling-based scrolling.
24271     *
24272     * @param deltaX Change in X in pixels
24273     * @param deltaY Change in Y in pixels
24274     * @param scrollX Current X scroll value in pixels before applying deltaX
24275     * @param scrollY Current Y scroll value in pixels before applying deltaY
24276     * @param scrollRangeX Maximum content scroll range along the X axis
24277     * @param scrollRangeY Maximum content scroll range along the Y axis
24278     * @param maxOverScrollX Number of pixels to overscroll by in either direction
24279     *          along the X axis.
24280     * @param maxOverScrollY Number of pixels to overscroll by in either direction
24281     *          along the Y axis.
24282     * @param isTouchEvent true if this scroll operation is the result of a touch event.
24283     * @return true if scrolling was clamped to an over-scroll boundary along either
24284     *          axis, false otherwise.
24285     */
24286    @SuppressWarnings({"UnusedParameters"})
24287    protected boolean overScrollBy(int deltaX, int deltaY,
24288            int scrollX, int scrollY,
24289            int scrollRangeX, int scrollRangeY,
24290            int maxOverScrollX, int maxOverScrollY,
24291            boolean isTouchEvent) {
24292        final int overScrollMode = mOverScrollMode;
24293        final boolean canScrollHorizontal =
24294                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
24295        final boolean canScrollVertical =
24296                computeVerticalScrollRange() > computeVerticalScrollExtent();
24297        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
24298                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
24299        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
24300                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
24301
24302        int newScrollX = scrollX + deltaX;
24303        if (!overScrollHorizontal) {
24304            maxOverScrollX = 0;
24305        }
24306
24307        int newScrollY = scrollY + deltaY;
24308        if (!overScrollVertical) {
24309            maxOverScrollY = 0;
24310        }
24311
24312        // Clamp values if at the limits and record
24313        final int left = -maxOverScrollX;
24314        final int right = maxOverScrollX + scrollRangeX;
24315        final int top = -maxOverScrollY;
24316        final int bottom = maxOverScrollY + scrollRangeY;
24317
24318        boolean clampedX = false;
24319        if (newScrollX > right) {
24320            newScrollX = right;
24321            clampedX = true;
24322        } else if (newScrollX < left) {
24323            newScrollX = left;
24324            clampedX = true;
24325        }
24326
24327        boolean clampedY = false;
24328        if (newScrollY > bottom) {
24329            newScrollY = bottom;
24330            clampedY = true;
24331        } else if (newScrollY < top) {
24332            newScrollY = top;
24333            clampedY = true;
24334        }
24335
24336        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
24337
24338        return clampedX || clampedY;
24339    }
24340
24341    /**
24342     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
24343     * respond to the results of an over-scroll operation.
24344     *
24345     * @param scrollX New X scroll value in pixels
24346     * @param scrollY New Y scroll value in pixels
24347     * @param clampedX True if scrollX was clamped to an over-scroll boundary
24348     * @param clampedY True if scrollY was clamped to an over-scroll boundary
24349     */
24350    protected void onOverScrolled(int scrollX, int scrollY,
24351            boolean clampedX, boolean clampedY) {
24352        // Intentionally empty.
24353    }
24354
24355    /**
24356     * Returns the over-scroll mode for this view. The result will be
24357     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
24358     * (allow over-scrolling only if the view content is larger than the container),
24359     * or {@link #OVER_SCROLL_NEVER}.
24360     *
24361     * @return This view's over-scroll mode.
24362     */
24363    public int getOverScrollMode() {
24364        return mOverScrollMode;
24365    }
24366
24367    /**
24368     * Set the over-scroll mode for this view. Valid over-scroll modes are
24369     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
24370     * (allow over-scrolling only if the view content is larger than the container),
24371     * or {@link #OVER_SCROLL_NEVER}.
24372     *
24373     * Setting the over-scroll mode of a view will have an effect only if the
24374     * view is capable of scrolling.
24375     *
24376     * @param overScrollMode The new over-scroll mode for this view.
24377     */
24378    public void setOverScrollMode(int overScrollMode) {
24379        if (overScrollMode != OVER_SCROLL_ALWAYS &&
24380                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
24381                overScrollMode != OVER_SCROLL_NEVER) {
24382            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
24383        }
24384        mOverScrollMode = overScrollMode;
24385    }
24386
24387    /**
24388     * Enable or disable nested scrolling for this view.
24389     *
24390     * <p>If this property is set to true the view will be permitted to initiate nested
24391     * scrolling operations with a compatible parent view in the current hierarchy. If this
24392     * view does not implement nested scrolling this will have no effect. Disabling nested scrolling
24393     * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping}
24394     * the nested scroll.</p>
24395     *
24396     * @param enabled true to enable nested scrolling, false to disable
24397     *
24398     * @see #isNestedScrollingEnabled()
24399     */
24400    public void setNestedScrollingEnabled(boolean enabled) {
24401        if (enabled) {
24402            mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED;
24403        } else {
24404            stopNestedScroll();
24405            mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED;
24406        }
24407    }
24408
24409    /**
24410     * Returns true if nested scrolling is enabled for this view.
24411     *
24412     * <p>If nested scrolling is enabled and this View class implementation supports it,
24413     * this view will act as a nested scrolling child view when applicable, forwarding data
24414     * about the scroll operation in progress to a compatible and cooperating nested scrolling
24415     * parent.</p>
24416     *
24417     * @return true if nested scrolling is enabled
24418     *
24419     * @see #setNestedScrollingEnabled(boolean)
24420     */
24421    public boolean isNestedScrollingEnabled() {
24422        return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) ==
24423                PFLAG3_NESTED_SCROLLING_ENABLED;
24424    }
24425
24426    /**
24427     * Begin a nestable scroll operation along the given axes.
24428     *
24429     * <p>A view starting a nested scroll promises to abide by the following contract:</p>
24430     *
24431     * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case
24432     * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}.
24433     * In the case of touch scrolling the nested scroll will be terminated automatically in
24434     * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}.
24435     * In the event of programmatic scrolling the caller must explicitly call
24436     * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p>
24437     *
24438     * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found.
24439     * If it returns false the caller may ignore the rest of this contract until the next scroll.
24440     * Calling startNestedScroll while a nested scroll is already in progress will return true.</p>
24441     *
24442     * <p>At each incremental step of the scroll the caller should invoke
24443     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll}
24444     * once it has calculated the requested scrolling delta. If it returns true the nested scrolling
24445     * parent at least partially consumed the scroll and the caller should adjust the amount it
24446     * scrolls by.</p>
24447     *
24448     * <p>After applying the remainder of the scroll delta the caller should invoke
24449     * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing
24450     * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat
24451     * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}.
24452     * </p>
24453     *
24454     * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or
24455     *             {@link #SCROLL_AXIS_VERTICAL}.
24456     * @return true if a cooperative parent was found and nested scrolling has been enabled for
24457     *         the current gesture.
24458     *
24459     * @see #stopNestedScroll()
24460     * @see #dispatchNestedPreScroll(int, int, int[], int[])
24461     * @see #dispatchNestedScroll(int, int, int, int, int[])
24462     */
24463    public boolean startNestedScroll(int axes) {
24464        if (hasNestedScrollingParent()) {
24465            // Already in progress
24466            return true;
24467        }
24468        if (isNestedScrollingEnabled()) {
24469            ViewParent p = getParent();
24470            View child = this;
24471            while (p != null) {
24472                try {
24473                    if (p.onStartNestedScroll(child, this, axes)) {
24474                        mNestedScrollingParent = p;
24475                        p.onNestedScrollAccepted(child, this, axes);
24476                        return true;
24477                    }
24478                } catch (AbstractMethodError e) {
24479                    Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " +
24480                            "method onStartNestedScroll", e);
24481                    // Allow the search upward to continue
24482                }
24483                if (p instanceof View) {
24484                    child = (View) p;
24485                }
24486                p = p.getParent();
24487            }
24488        }
24489        return false;
24490    }
24491
24492    /**
24493     * Stop a nested scroll in progress.
24494     *
24495     * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p>
24496     *
24497     * @see #startNestedScroll(int)
24498     */
24499    public void stopNestedScroll() {
24500        if (mNestedScrollingParent != null) {
24501            mNestedScrollingParent.onStopNestedScroll(this);
24502            mNestedScrollingParent = null;
24503        }
24504    }
24505
24506    /**
24507     * Returns true if this view has a nested scrolling parent.
24508     *
24509     * <p>The presence of a nested scrolling parent indicates that this view has initiated
24510     * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p>
24511     *
24512     * @return whether this view has a nested scrolling parent
24513     */
24514    public boolean hasNestedScrollingParent() {
24515        return mNestedScrollingParent != null;
24516    }
24517
24518    /**
24519     * Dispatch one step of a nested scroll in progress.
24520     *
24521     * <p>Implementations of views that support nested scrolling should call this to report
24522     * info about a scroll in progress to the current nested scrolling parent. If a nested scroll
24523     * is not currently in progress or nested scrolling is not
24524     * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p>
24525     *
24526     * <p>Compatible View implementations should also call
24527     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before
24528     * consuming a component of the scroll event themselves.</p>
24529     *
24530     * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step
24531     * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step
24532     * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view
24533     * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view
24534     * @param offsetInWindow Optional. If not null, on return this will contain the offset
24535     *                       in local view coordinates of this view from before this operation
24536     *                       to after it completes. View implementations may use this to adjust
24537     *                       expected input coordinate tracking.
24538     * @return true if the event was dispatched, false if it could not be dispatched.
24539     * @see #dispatchNestedPreScroll(int, int, int[], int[])
24540     */
24541    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed,
24542            int dxUnconsumed, int dyUnconsumed, @Nullable @Size(2) int[] offsetInWindow) {
24543        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
24544            if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) {
24545                int startX = 0;
24546                int startY = 0;
24547                if (offsetInWindow != null) {
24548                    getLocationInWindow(offsetInWindow);
24549                    startX = offsetInWindow[0];
24550                    startY = offsetInWindow[1];
24551                }
24552
24553                mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed,
24554                        dxUnconsumed, dyUnconsumed);
24555
24556                if (offsetInWindow != null) {
24557                    getLocationInWindow(offsetInWindow);
24558                    offsetInWindow[0] -= startX;
24559                    offsetInWindow[1] -= startY;
24560                }
24561                return true;
24562            } else if (offsetInWindow != null) {
24563                // No motion, no dispatch. Keep offsetInWindow up to date.
24564                offsetInWindow[0] = 0;
24565                offsetInWindow[1] = 0;
24566            }
24567        }
24568        return false;
24569    }
24570
24571    /**
24572     * Dispatch one step of a nested scroll in progress before this view consumes any portion of it.
24573     *
24574     * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch.
24575     * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested
24576     * scrolling operation to consume some or all of the scroll operation before the child view
24577     * consumes it.</p>
24578     *
24579     * @param dx Horizontal scroll distance in pixels
24580     * @param dy Vertical scroll distance in pixels
24581     * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx
24582     *                 and consumed[1] the consumed dy.
24583     * @param offsetInWindow Optional. If not null, on return this will contain the offset
24584     *                       in local view coordinates of this view from before this operation
24585     *                       to after it completes. View implementations may use this to adjust
24586     *                       expected input coordinate tracking.
24587     * @return true if the parent consumed some or all of the scroll delta
24588     * @see #dispatchNestedScroll(int, int, int, int, int[])
24589     */
24590    public boolean dispatchNestedPreScroll(int dx, int dy,
24591            @Nullable @Size(2) int[] consumed, @Nullable @Size(2) int[] offsetInWindow) {
24592        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
24593            if (dx != 0 || dy != 0) {
24594                int startX = 0;
24595                int startY = 0;
24596                if (offsetInWindow != null) {
24597                    getLocationInWindow(offsetInWindow);
24598                    startX = offsetInWindow[0];
24599                    startY = offsetInWindow[1];
24600                }
24601
24602                if (consumed == null) {
24603                    if (mTempNestedScrollConsumed == null) {
24604                        mTempNestedScrollConsumed = new int[2];
24605                    }
24606                    consumed = mTempNestedScrollConsumed;
24607                }
24608                consumed[0] = 0;
24609                consumed[1] = 0;
24610                mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed);
24611
24612                if (offsetInWindow != null) {
24613                    getLocationInWindow(offsetInWindow);
24614                    offsetInWindow[0] -= startX;
24615                    offsetInWindow[1] -= startY;
24616                }
24617                return consumed[0] != 0 || consumed[1] != 0;
24618            } else if (offsetInWindow != null) {
24619                offsetInWindow[0] = 0;
24620                offsetInWindow[1] = 0;
24621            }
24622        }
24623        return false;
24624    }
24625
24626    /**
24627     * Dispatch a fling to a nested scrolling parent.
24628     *
24629     * <p>This method should be used to indicate that a nested scrolling child has detected
24630     * suitable conditions for a fling. Generally this means that a touch scroll has ended with a
24631     * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds
24632     * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity}
24633     * along a scrollable axis.</p>
24634     *
24635     * <p>If a nested scrolling child view would normally fling but it is at the edge of
24636     * its own content, it can use this method to delegate the fling to its nested scrolling
24637     * parent instead. The parent may optionally consume the fling or observe a child fling.</p>
24638     *
24639     * @param velocityX Horizontal fling velocity in pixels per second
24640     * @param velocityY Vertical fling velocity in pixels per second
24641     * @param consumed true if the child consumed the fling, false otherwise
24642     * @return true if the nested scrolling parent consumed or otherwise reacted to the fling
24643     */
24644    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
24645        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
24646            return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed);
24647        }
24648        return false;
24649    }
24650
24651    /**
24652     * Dispatch a fling to a nested scrolling parent before it is processed by this view.
24653     *
24654     * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch
24655     * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code>
24656     * offsets an opportunity for the parent view in a nested fling to fully consume the fling
24657     * before the child view consumes it. If this method returns <code>true</code>, a nested
24658     * parent view consumed the fling and this view should not scroll as a result.</p>
24659     *
24660     * <p>For a better user experience, only one view in a nested scrolling chain should consume
24661     * the fling at a time. If a parent view consumed the fling this method will return false.
24662     * Custom view implementations should account for this in two ways:</p>
24663     *
24664     * <ul>
24665     *     <li>If a custom view is paged and needs to settle to a fixed page-point, do not
24666     *     call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid
24667     *     position regardless.</li>
24668     *     <li>If a nested parent does consume the fling, this view should not scroll at all,
24669     *     even to settle back to a valid idle position.</li>
24670     * </ul>
24671     *
24672     * <p>Views should also not offer fling velocities to nested parent views along an axis
24673     * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView}
24674     * should not offer a horizontal fling velocity to its parents since scrolling along that
24675     * axis is not permitted and carrying velocity along that motion does not make sense.</p>
24676     *
24677     * @param velocityX Horizontal fling velocity in pixels per second
24678     * @param velocityY Vertical fling velocity in pixels per second
24679     * @return true if a nested scrolling parent consumed the fling
24680     */
24681    public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
24682        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
24683            return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY);
24684        }
24685        return false;
24686    }
24687
24688    /**
24689     * Gets a scale factor that determines the distance the view should scroll
24690     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
24691     * @return The vertical scroll scale factor.
24692     * @hide
24693     */
24694    protected float getVerticalScrollFactor() {
24695        if (mVerticalScrollFactor == 0) {
24696            TypedValue outValue = new TypedValue();
24697            if (!mContext.getTheme().resolveAttribute(
24698                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
24699                throw new IllegalStateException(
24700                        "Expected theme to define listPreferredItemHeight.");
24701            }
24702            mVerticalScrollFactor = outValue.getDimension(
24703                    mContext.getResources().getDisplayMetrics());
24704        }
24705        return mVerticalScrollFactor;
24706    }
24707
24708    /**
24709     * Gets a scale factor that determines the distance the view should scroll
24710     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
24711     * @return The horizontal scroll scale factor.
24712     * @hide
24713     */
24714    protected float getHorizontalScrollFactor() {
24715        // TODO: Should use something else.
24716        return getVerticalScrollFactor();
24717    }
24718
24719    /**
24720     * Return the value specifying the text direction or policy that was set with
24721     * {@link #setTextDirection(int)}.
24722     *
24723     * @return the defined text direction. It can be one of:
24724     *
24725     * {@link #TEXT_DIRECTION_INHERIT},
24726     * {@link #TEXT_DIRECTION_FIRST_STRONG},
24727     * {@link #TEXT_DIRECTION_ANY_RTL},
24728     * {@link #TEXT_DIRECTION_LTR},
24729     * {@link #TEXT_DIRECTION_RTL},
24730     * {@link #TEXT_DIRECTION_LOCALE},
24731     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
24732     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
24733     *
24734     * @attr ref android.R.styleable#View_textDirection
24735     *
24736     * @hide
24737     */
24738    @ViewDebug.ExportedProperty(category = "text", mapping = {
24739            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
24740            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
24741            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
24742            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
24743            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
24744            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
24745            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
24746            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
24747    })
24748    public int getRawTextDirection() {
24749        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
24750    }
24751
24752    /**
24753     * Set the text direction.
24754     *
24755     * @param textDirection the direction to set. Should be one of:
24756     *
24757     * {@link #TEXT_DIRECTION_INHERIT},
24758     * {@link #TEXT_DIRECTION_FIRST_STRONG},
24759     * {@link #TEXT_DIRECTION_ANY_RTL},
24760     * {@link #TEXT_DIRECTION_LTR},
24761     * {@link #TEXT_DIRECTION_RTL},
24762     * {@link #TEXT_DIRECTION_LOCALE}
24763     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
24764     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL},
24765     *
24766     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
24767     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
24768     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
24769     *
24770     * @attr ref android.R.styleable#View_textDirection
24771     */
24772    public void setTextDirection(int textDirection) {
24773        if (getRawTextDirection() != textDirection) {
24774            // Reset the current text direction and the resolved one
24775            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
24776            resetResolvedTextDirection();
24777            // Set the new text direction
24778            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
24779            // Do resolution
24780            resolveTextDirection();
24781            // Notify change
24782            onRtlPropertiesChanged(getLayoutDirection());
24783            // Refresh
24784            requestLayout();
24785            invalidate(true);
24786        }
24787    }
24788
24789    /**
24790     * Return the resolved text direction.
24791     *
24792     * @return the resolved text direction. Returns one of:
24793     *
24794     * {@link #TEXT_DIRECTION_FIRST_STRONG},
24795     * {@link #TEXT_DIRECTION_ANY_RTL},
24796     * {@link #TEXT_DIRECTION_LTR},
24797     * {@link #TEXT_DIRECTION_RTL},
24798     * {@link #TEXT_DIRECTION_LOCALE},
24799     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
24800     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
24801     *
24802     * @attr ref android.R.styleable#View_textDirection
24803     */
24804    @ViewDebug.ExportedProperty(category = "text", mapping = {
24805            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
24806            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
24807            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
24808            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
24809            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
24810            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
24811            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
24812            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
24813    })
24814    public int getTextDirection() {
24815        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
24816    }
24817
24818    /**
24819     * Resolve the text direction.
24820     *
24821     * @return true if resolution has been done, false otherwise.
24822     *
24823     * @hide
24824     */
24825    public boolean resolveTextDirection() {
24826        // Reset any previous text direction resolution
24827        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
24828
24829        if (hasRtlSupport()) {
24830            // Set resolved text direction flag depending on text direction flag
24831            final int textDirection = getRawTextDirection();
24832            switch(textDirection) {
24833                case TEXT_DIRECTION_INHERIT:
24834                    if (!canResolveTextDirection()) {
24835                        // We cannot do the resolution if there is no parent, so use the default one
24836                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
24837                        // Resolution will need to happen again later
24838                        return false;
24839                    }
24840
24841                    // Parent has not yet resolved, so we still return the default
24842                    try {
24843                        if (!mParent.isTextDirectionResolved()) {
24844                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
24845                            // Resolution will need to happen again later
24846                            return false;
24847                        }
24848                    } catch (AbstractMethodError e) {
24849                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
24850                                " does not fully implement ViewParent", e);
24851                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
24852                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
24853                        return true;
24854                    }
24855
24856                    // Set current resolved direction to the same value as the parent's one
24857                    int parentResolvedDirection;
24858                    try {
24859                        parentResolvedDirection = mParent.getTextDirection();
24860                    } catch (AbstractMethodError e) {
24861                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
24862                                " does not fully implement ViewParent", e);
24863                        parentResolvedDirection = TEXT_DIRECTION_LTR;
24864                    }
24865                    switch (parentResolvedDirection) {
24866                        case TEXT_DIRECTION_FIRST_STRONG:
24867                        case TEXT_DIRECTION_ANY_RTL:
24868                        case TEXT_DIRECTION_LTR:
24869                        case TEXT_DIRECTION_RTL:
24870                        case TEXT_DIRECTION_LOCALE:
24871                        case TEXT_DIRECTION_FIRST_STRONG_LTR:
24872                        case TEXT_DIRECTION_FIRST_STRONG_RTL:
24873                            mPrivateFlags2 |=
24874                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
24875                            break;
24876                        default:
24877                            // Default resolved direction is "first strong" heuristic
24878                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
24879                    }
24880                    break;
24881                case TEXT_DIRECTION_FIRST_STRONG:
24882                case TEXT_DIRECTION_ANY_RTL:
24883                case TEXT_DIRECTION_LTR:
24884                case TEXT_DIRECTION_RTL:
24885                case TEXT_DIRECTION_LOCALE:
24886                case TEXT_DIRECTION_FIRST_STRONG_LTR:
24887                case TEXT_DIRECTION_FIRST_STRONG_RTL:
24888                    // Resolved direction is the same as text direction
24889                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
24890                    break;
24891                default:
24892                    // Default resolved direction is "first strong" heuristic
24893                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
24894            }
24895        } else {
24896            // Default resolved direction is "first strong" heuristic
24897            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
24898        }
24899
24900        // Set to resolved
24901        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
24902        return true;
24903    }
24904
24905    /**
24906     * Check if text direction resolution can be done.
24907     *
24908     * @return true if text direction resolution can be done otherwise return false.
24909     */
24910    public boolean canResolveTextDirection() {
24911        switch (getRawTextDirection()) {
24912            case TEXT_DIRECTION_INHERIT:
24913                if (mParent != null) {
24914                    try {
24915                        return mParent.canResolveTextDirection();
24916                    } catch (AbstractMethodError e) {
24917                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
24918                                " does not fully implement ViewParent", e);
24919                    }
24920                }
24921                return false;
24922
24923            default:
24924                return true;
24925        }
24926    }
24927
24928    /**
24929     * Reset resolved text direction. Text direction will be resolved during a call to
24930     * {@link #onMeasure(int, int)}.
24931     *
24932     * @hide
24933     */
24934    public void resetResolvedTextDirection() {
24935        // Reset any previous text direction resolution
24936        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
24937        // Set to default value
24938        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
24939    }
24940
24941    /**
24942     * @return true if text direction is inherited.
24943     *
24944     * @hide
24945     */
24946    public boolean isTextDirectionInherited() {
24947        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
24948    }
24949
24950    /**
24951     * @return true if text direction is resolved.
24952     */
24953    public boolean isTextDirectionResolved() {
24954        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
24955    }
24956
24957    /**
24958     * Return the value specifying the text alignment or policy that was set with
24959     * {@link #setTextAlignment(int)}.
24960     *
24961     * @return the defined text alignment. It can be one of:
24962     *
24963     * {@link #TEXT_ALIGNMENT_INHERIT},
24964     * {@link #TEXT_ALIGNMENT_GRAVITY},
24965     * {@link #TEXT_ALIGNMENT_CENTER},
24966     * {@link #TEXT_ALIGNMENT_TEXT_START},
24967     * {@link #TEXT_ALIGNMENT_TEXT_END},
24968     * {@link #TEXT_ALIGNMENT_VIEW_START},
24969     * {@link #TEXT_ALIGNMENT_VIEW_END}
24970     *
24971     * @attr ref android.R.styleable#View_textAlignment
24972     *
24973     * @hide
24974     */
24975    @ViewDebug.ExportedProperty(category = "text", mapping = {
24976            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
24977            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
24978            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
24979            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
24980            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
24981            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
24982            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
24983    })
24984    @TextAlignment
24985    public int getRawTextAlignment() {
24986        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
24987    }
24988
24989    /**
24990     * Set the text alignment.
24991     *
24992     * @param textAlignment The text alignment to set. Should be one of
24993     *
24994     * {@link #TEXT_ALIGNMENT_INHERIT},
24995     * {@link #TEXT_ALIGNMENT_GRAVITY},
24996     * {@link #TEXT_ALIGNMENT_CENTER},
24997     * {@link #TEXT_ALIGNMENT_TEXT_START},
24998     * {@link #TEXT_ALIGNMENT_TEXT_END},
24999     * {@link #TEXT_ALIGNMENT_VIEW_START},
25000     * {@link #TEXT_ALIGNMENT_VIEW_END}
25001     *
25002     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
25003     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
25004     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
25005     *
25006     * @attr ref android.R.styleable#View_textAlignment
25007     */
25008    public void setTextAlignment(@TextAlignment int textAlignment) {
25009        if (textAlignment != getRawTextAlignment()) {
25010            // Reset the current and resolved text alignment
25011            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
25012            resetResolvedTextAlignment();
25013            // Set the new text alignment
25014            mPrivateFlags2 |=
25015                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
25016            // Do resolution
25017            resolveTextAlignment();
25018            // Notify change
25019            onRtlPropertiesChanged(getLayoutDirection());
25020            // Refresh
25021            requestLayout();
25022            invalidate(true);
25023        }
25024    }
25025
25026    /**
25027     * Return the resolved text alignment.
25028     *
25029     * @return the resolved text alignment. Returns one of:
25030     *
25031     * {@link #TEXT_ALIGNMENT_GRAVITY},
25032     * {@link #TEXT_ALIGNMENT_CENTER},
25033     * {@link #TEXT_ALIGNMENT_TEXT_START},
25034     * {@link #TEXT_ALIGNMENT_TEXT_END},
25035     * {@link #TEXT_ALIGNMENT_VIEW_START},
25036     * {@link #TEXT_ALIGNMENT_VIEW_END}
25037     *
25038     * @attr ref android.R.styleable#View_textAlignment
25039     */
25040    @ViewDebug.ExportedProperty(category = "text", mapping = {
25041            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
25042            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
25043            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
25044            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
25045            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
25046            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
25047            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
25048    })
25049    @TextAlignment
25050    public int getTextAlignment() {
25051        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
25052                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
25053    }
25054
25055    /**
25056     * Resolve the text alignment.
25057     *
25058     * @return true if resolution has been done, false otherwise.
25059     *
25060     * @hide
25061     */
25062    public boolean resolveTextAlignment() {
25063        // Reset any previous text alignment resolution
25064        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
25065
25066        if (hasRtlSupport()) {
25067            // Set resolved text alignment flag depending on text alignment flag
25068            final int textAlignment = getRawTextAlignment();
25069            switch (textAlignment) {
25070                case TEXT_ALIGNMENT_INHERIT:
25071                    // Check if we can resolve the text alignment
25072                    if (!canResolveTextAlignment()) {
25073                        // We cannot do the resolution if there is no parent so use the default
25074                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
25075                        // Resolution will need to happen again later
25076                        return false;
25077                    }
25078
25079                    // Parent has not yet resolved, so we still return the default
25080                    try {
25081                        if (!mParent.isTextAlignmentResolved()) {
25082                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
25083                            // Resolution will need to happen again later
25084                            return false;
25085                        }
25086                    } catch (AbstractMethodError e) {
25087                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
25088                                " does not fully implement ViewParent", e);
25089                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
25090                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
25091                        return true;
25092                    }
25093
25094                    int parentResolvedTextAlignment;
25095                    try {
25096                        parentResolvedTextAlignment = mParent.getTextAlignment();
25097                    } catch (AbstractMethodError e) {
25098                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
25099                                " does not fully implement ViewParent", e);
25100                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
25101                    }
25102                    switch (parentResolvedTextAlignment) {
25103                        case TEXT_ALIGNMENT_GRAVITY:
25104                        case TEXT_ALIGNMENT_TEXT_START:
25105                        case TEXT_ALIGNMENT_TEXT_END:
25106                        case TEXT_ALIGNMENT_CENTER:
25107                        case TEXT_ALIGNMENT_VIEW_START:
25108                        case TEXT_ALIGNMENT_VIEW_END:
25109                            // Resolved text alignment is the same as the parent resolved
25110                            // text alignment
25111                            mPrivateFlags2 |=
25112                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
25113                            break;
25114                        default:
25115                            // Use default resolved text alignment
25116                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
25117                    }
25118                    break;
25119                case TEXT_ALIGNMENT_GRAVITY:
25120                case TEXT_ALIGNMENT_TEXT_START:
25121                case TEXT_ALIGNMENT_TEXT_END:
25122                case TEXT_ALIGNMENT_CENTER:
25123                case TEXT_ALIGNMENT_VIEW_START:
25124                case TEXT_ALIGNMENT_VIEW_END:
25125                    // Resolved text alignment is the same as text alignment
25126                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
25127                    break;
25128                default:
25129                    // Use default resolved text alignment
25130                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
25131            }
25132        } else {
25133            // Use default resolved text alignment
25134            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
25135        }
25136
25137        // Set the resolved
25138        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
25139        return true;
25140    }
25141
25142    /**
25143     * Check if text alignment resolution can be done.
25144     *
25145     * @return true if text alignment resolution can be done otherwise return false.
25146     */
25147    public boolean canResolveTextAlignment() {
25148        switch (getRawTextAlignment()) {
25149            case TEXT_DIRECTION_INHERIT:
25150                if (mParent != null) {
25151                    try {
25152                        return mParent.canResolveTextAlignment();
25153                    } catch (AbstractMethodError e) {
25154                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
25155                                " does not fully implement ViewParent", e);
25156                    }
25157                }
25158                return false;
25159
25160            default:
25161                return true;
25162        }
25163    }
25164
25165    /**
25166     * Reset resolved text alignment. Text alignment will be resolved during a call to
25167     * {@link #onMeasure(int, int)}.
25168     *
25169     * @hide
25170     */
25171    public void resetResolvedTextAlignment() {
25172        // Reset any previous text alignment resolution
25173        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
25174        // Set to default
25175        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
25176    }
25177
25178    /**
25179     * @return true if text alignment is inherited.
25180     *
25181     * @hide
25182     */
25183    public boolean isTextAlignmentInherited() {
25184        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
25185    }
25186
25187    /**
25188     * @return true if text alignment is resolved.
25189     */
25190    public boolean isTextAlignmentResolved() {
25191        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
25192    }
25193
25194    /**
25195     * Generate a value suitable for use in {@link #setId(int)}.
25196     * This value will not collide with ID values generated at build time by aapt for R.id.
25197     *
25198     * @return a generated ID value
25199     */
25200    public static int generateViewId() {
25201        for (;;) {
25202            final int result = sNextGeneratedId.get();
25203            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
25204            int newValue = result + 1;
25205            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
25206            if (sNextGeneratedId.compareAndSet(result, newValue)) {
25207                return result;
25208            }
25209        }
25210    }
25211
25212    private static boolean isViewIdGenerated(int id) {
25213        return (id & 0xFF000000) == 0 && (id & 0x00FFFFFF) != 0;
25214    }
25215
25216    /**
25217     * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions.
25218     * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and
25219     *                           a normal View or a ViewGroup with
25220     *                           {@link android.view.ViewGroup#isTransitionGroup()} true.
25221     * @hide
25222     */
25223    public void captureTransitioningViews(List<View> transitioningViews) {
25224        if (getVisibility() == View.VISIBLE) {
25225            transitioningViews.add(this);
25226        }
25227    }
25228
25229    /**
25230     * Adds all Views that have {@link #getTransitionName()} non-null to namedElements.
25231     * @param namedElements Will contain all Views in the hierarchy having a transitionName.
25232     * @hide
25233     */
25234    public void findNamedViews(Map<String, View> namedElements) {
25235        if (getVisibility() == VISIBLE || mGhostView != null) {
25236            String transitionName = getTransitionName();
25237            if (transitionName != null) {
25238                namedElements.put(transitionName, this);
25239            }
25240        }
25241    }
25242
25243    /**
25244     * Returns the pointer icon for the motion event, or null if it doesn't specify the icon.
25245     * The default implementation does not care the location or event types, but some subclasses
25246     * may use it (such as WebViews).
25247     * @param event The MotionEvent from a mouse
25248     * @param pointerIndex The index of the pointer for which to retrieve the {@link PointerIcon}.
25249     *                     This will be between 0 and {@link MotionEvent#getPointerCount()}.
25250     * @see PointerIcon
25251     */
25252    public PointerIcon onResolvePointerIcon(MotionEvent event, int pointerIndex) {
25253        final float x = event.getX(pointerIndex);
25254        final float y = event.getY(pointerIndex);
25255        if (isDraggingScrollBar() || isOnScrollbarThumb(x, y)) {
25256            return PointerIcon.getSystemIcon(mContext, PointerIcon.TYPE_ARROW);
25257        }
25258        return mPointerIcon;
25259    }
25260
25261    /**
25262     * Set the pointer icon for the current view.
25263     * Passing {@code null} will restore the pointer icon to its default value.
25264     * @param pointerIcon A PointerIcon instance which will be shown when the mouse hovers.
25265     */
25266    public void setPointerIcon(PointerIcon pointerIcon) {
25267        mPointerIcon = pointerIcon;
25268        if (mAttachInfo == null || mAttachInfo.mHandlingPointerEvent) {
25269            return;
25270        }
25271        try {
25272            mAttachInfo.mSession.updatePointerIcon(mAttachInfo.mWindow);
25273        } catch (RemoteException e) {
25274        }
25275    }
25276
25277    /**
25278     * Gets the pointer icon for the current view.
25279     */
25280    public PointerIcon getPointerIcon() {
25281        return mPointerIcon;
25282    }
25283
25284    /**
25285     * Checks pointer capture status.
25286     *
25287     * @return true if the view has pointer capture.
25288     * @see #requestPointerCapture()
25289     * @see #hasPointerCapture()
25290     */
25291    public boolean hasPointerCapture() {
25292        final ViewRootImpl viewRootImpl = getViewRootImpl();
25293        if (viewRootImpl == null) {
25294            return false;
25295        }
25296        return viewRootImpl.hasPointerCapture();
25297    }
25298
25299    /**
25300     * Requests pointer capture mode.
25301     * <p>
25302     * When the window has pointer capture, the mouse pointer icon will disappear and will not
25303     * change its position. Further mouse will be dispatched with the source
25304     * {@link InputDevice#SOURCE_MOUSE_RELATIVE}, and relative position changes will be available
25305     * through {@link MotionEvent#getX} and {@link MotionEvent#getY}. Non-mouse events
25306     * (touchscreens, or stylus) will not be affected.
25307     * <p>
25308     * If the window already has pointer capture, this call does nothing.
25309     * <p>
25310     * The capture may be released through {@link #releasePointerCapture()}, or will be lost
25311     * automatically when the window loses focus.
25312     *
25313     * @see #releasePointerCapture()
25314     * @see #hasPointerCapture()
25315     */
25316    public void requestPointerCapture() {
25317        final ViewRootImpl viewRootImpl = getViewRootImpl();
25318        if (viewRootImpl != null) {
25319            viewRootImpl.requestPointerCapture(true);
25320        }
25321    }
25322
25323
25324    /**
25325     * Releases the pointer capture.
25326     * <p>
25327     * If the window does not have pointer capture, this call will do nothing.
25328     * @see #requestPointerCapture()
25329     * @see #hasPointerCapture()
25330     */
25331    public void releasePointerCapture() {
25332        final ViewRootImpl viewRootImpl = getViewRootImpl();
25333        if (viewRootImpl != null) {
25334            viewRootImpl.requestPointerCapture(false);
25335        }
25336    }
25337
25338    /**
25339     * Called when the window has just acquired or lost pointer capture.
25340     *
25341     * @param hasCapture True if the view now has pointerCapture, false otherwise.
25342     */
25343    @CallSuper
25344    public void onPointerCaptureChange(boolean hasCapture) {
25345    }
25346
25347    /**
25348     * @see #onPointerCaptureChange
25349     */
25350    public void dispatchPointerCaptureChanged(boolean hasCapture) {
25351        onPointerCaptureChange(hasCapture);
25352    }
25353
25354    /**
25355     * Implement this method to handle captured pointer events
25356     *
25357     * @param event The captured pointer event.
25358     * @return True if the event was handled, false otherwise.
25359     * @see #requestPointerCapture()
25360     */
25361    public boolean onCapturedPointerEvent(MotionEvent event) {
25362        return false;
25363    }
25364
25365    /**
25366     * Interface definition for a callback to be invoked when a captured pointer event
25367     * is being dispatched this view. The callback will be invoked before the event is
25368     * given to the view.
25369     */
25370    public interface OnCapturedPointerListener {
25371        /**
25372         * Called when a captured pointer event is dispatched to a view.
25373         * @param view The view this event has been dispatched to.
25374         * @param event The captured event.
25375         * @return True if the listener has consumed the event, false otherwise.
25376         */
25377        boolean onCapturedPointer(View view, MotionEvent event);
25378    }
25379
25380    /**
25381     * Set a listener to receive callbacks when the pointer capture state of a view changes.
25382     * @param l  The {@link OnCapturedPointerListener} to receive callbacks.
25383     */
25384    public void setOnCapturedPointerListener(OnCapturedPointerListener l) {
25385        getListenerInfo().mOnCapturedPointerListener = l;
25386    }
25387
25388    // Properties
25389    //
25390    /**
25391     * A Property wrapper around the <code>alpha</code> functionality handled by the
25392     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
25393     */
25394    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
25395        @Override
25396        public void setValue(View object, float value) {
25397            object.setAlpha(value);
25398        }
25399
25400        @Override
25401        public Float get(View object) {
25402            return object.getAlpha();
25403        }
25404    };
25405
25406    /**
25407     * A Property wrapper around the <code>translationX</code> functionality handled by the
25408     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
25409     */
25410    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
25411        @Override
25412        public void setValue(View object, float value) {
25413            object.setTranslationX(value);
25414        }
25415
25416                @Override
25417        public Float get(View object) {
25418            return object.getTranslationX();
25419        }
25420    };
25421
25422    /**
25423     * A Property wrapper around the <code>translationY</code> functionality handled by the
25424     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
25425     */
25426    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
25427        @Override
25428        public void setValue(View object, float value) {
25429            object.setTranslationY(value);
25430        }
25431
25432        @Override
25433        public Float get(View object) {
25434            return object.getTranslationY();
25435        }
25436    };
25437
25438    /**
25439     * A Property wrapper around the <code>translationZ</code> functionality handled by the
25440     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
25441     */
25442    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
25443        @Override
25444        public void setValue(View object, float value) {
25445            object.setTranslationZ(value);
25446        }
25447
25448        @Override
25449        public Float get(View object) {
25450            return object.getTranslationZ();
25451        }
25452    };
25453
25454    /**
25455     * A Property wrapper around the <code>x</code> functionality handled by the
25456     * {@link View#setX(float)} and {@link View#getX()} methods.
25457     */
25458    public static final Property<View, Float> X = new FloatProperty<View>("x") {
25459        @Override
25460        public void setValue(View object, float value) {
25461            object.setX(value);
25462        }
25463
25464        @Override
25465        public Float get(View object) {
25466            return object.getX();
25467        }
25468    };
25469
25470    /**
25471     * A Property wrapper around the <code>y</code> functionality handled by the
25472     * {@link View#setY(float)} and {@link View#getY()} methods.
25473     */
25474    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
25475        @Override
25476        public void setValue(View object, float value) {
25477            object.setY(value);
25478        }
25479
25480        @Override
25481        public Float get(View object) {
25482            return object.getY();
25483        }
25484    };
25485
25486    /**
25487     * A Property wrapper around the <code>z</code> functionality handled by the
25488     * {@link View#setZ(float)} and {@link View#getZ()} methods.
25489     */
25490    public static final Property<View, Float> Z = new FloatProperty<View>("z") {
25491        @Override
25492        public void setValue(View object, float value) {
25493            object.setZ(value);
25494        }
25495
25496        @Override
25497        public Float get(View object) {
25498            return object.getZ();
25499        }
25500    };
25501
25502    /**
25503     * A Property wrapper around the <code>rotation</code> functionality handled by the
25504     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
25505     */
25506    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
25507        @Override
25508        public void setValue(View object, float value) {
25509            object.setRotation(value);
25510        }
25511
25512        @Override
25513        public Float get(View object) {
25514            return object.getRotation();
25515        }
25516    };
25517
25518    /**
25519     * A Property wrapper around the <code>rotationX</code> functionality handled by the
25520     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
25521     */
25522    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
25523        @Override
25524        public void setValue(View object, float value) {
25525            object.setRotationX(value);
25526        }
25527
25528        @Override
25529        public Float get(View object) {
25530            return object.getRotationX();
25531        }
25532    };
25533
25534    /**
25535     * A Property wrapper around the <code>rotationY</code> functionality handled by the
25536     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
25537     */
25538    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
25539        @Override
25540        public void setValue(View object, float value) {
25541            object.setRotationY(value);
25542        }
25543
25544        @Override
25545        public Float get(View object) {
25546            return object.getRotationY();
25547        }
25548    };
25549
25550    /**
25551     * A Property wrapper around the <code>scaleX</code> functionality handled by the
25552     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
25553     */
25554    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
25555        @Override
25556        public void setValue(View object, float value) {
25557            object.setScaleX(value);
25558        }
25559
25560        @Override
25561        public Float get(View object) {
25562            return object.getScaleX();
25563        }
25564    };
25565
25566    /**
25567     * A Property wrapper around the <code>scaleY</code> functionality handled by the
25568     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
25569     */
25570    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
25571        @Override
25572        public void setValue(View object, float value) {
25573            object.setScaleY(value);
25574        }
25575
25576        @Override
25577        public Float get(View object) {
25578            return object.getScaleY();
25579        }
25580    };
25581
25582    /**
25583     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
25584     * Each MeasureSpec represents a requirement for either the width or the height.
25585     * A MeasureSpec is comprised of a size and a mode. There are three possible
25586     * modes:
25587     * <dl>
25588     * <dt>UNSPECIFIED</dt>
25589     * <dd>
25590     * The parent has not imposed any constraint on the child. It can be whatever size
25591     * it wants.
25592     * </dd>
25593     *
25594     * <dt>EXACTLY</dt>
25595     * <dd>
25596     * The parent has determined an exact size for the child. The child is going to be
25597     * given those bounds regardless of how big it wants to be.
25598     * </dd>
25599     *
25600     * <dt>AT_MOST</dt>
25601     * <dd>
25602     * The child can be as large as it wants up to the specified size.
25603     * </dd>
25604     * </dl>
25605     *
25606     * MeasureSpecs are implemented as ints to reduce object allocation. This class
25607     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
25608     */
25609    public static class MeasureSpec {
25610        private static final int MODE_SHIFT = 30;
25611        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
25612
25613        /** @hide */
25614        @IntDef({UNSPECIFIED, EXACTLY, AT_MOST})
25615        @Retention(RetentionPolicy.SOURCE)
25616        public @interface MeasureSpecMode {}
25617
25618        /**
25619         * Measure specification mode: The parent has not imposed any constraint
25620         * on the child. It can be whatever size it wants.
25621         */
25622        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
25623
25624        /**
25625         * Measure specification mode: The parent has determined an exact size
25626         * for the child. The child is going to be given those bounds regardless
25627         * of how big it wants to be.
25628         */
25629        public static final int EXACTLY     = 1 << MODE_SHIFT;
25630
25631        /**
25632         * Measure specification mode: The child can be as large as it wants up
25633         * to the specified size.
25634         */
25635        public static final int AT_MOST     = 2 << MODE_SHIFT;
25636
25637        /**
25638         * Creates a measure specification based on the supplied size and mode.
25639         *
25640         * The mode must always be one of the following:
25641         * <ul>
25642         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
25643         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
25644         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
25645         * </ul>
25646         *
25647         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
25648         * implementation was such that the order of arguments did not matter
25649         * and overflow in either value could impact the resulting MeasureSpec.
25650         * {@link android.widget.RelativeLayout} was affected by this bug.
25651         * Apps targeting API levels greater than 17 will get the fixed, more strict
25652         * behavior.</p>
25653         *
25654         * @param size the size of the measure specification
25655         * @param mode the mode of the measure specification
25656         * @return the measure specification based on size and mode
25657         */
25658        public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size,
25659                                          @MeasureSpecMode int mode) {
25660            if (sUseBrokenMakeMeasureSpec) {
25661                return size + mode;
25662            } else {
25663                return (size & ~MODE_MASK) | (mode & MODE_MASK);
25664            }
25665        }
25666
25667        /**
25668         * Like {@link #makeMeasureSpec(int, int)}, but any spec with a mode of UNSPECIFIED
25669         * will automatically get a size of 0. Older apps expect this.
25670         *
25671         * @hide internal use only for compatibility with system widgets and older apps
25672         */
25673        public static int makeSafeMeasureSpec(int size, int mode) {
25674            if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) {
25675                return 0;
25676            }
25677            return makeMeasureSpec(size, mode);
25678        }
25679
25680        /**
25681         * Extracts the mode from the supplied measure specification.
25682         *
25683         * @param measureSpec the measure specification to extract the mode from
25684         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
25685         *         {@link android.view.View.MeasureSpec#AT_MOST} or
25686         *         {@link android.view.View.MeasureSpec#EXACTLY}
25687         */
25688        @MeasureSpecMode
25689        public static int getMode(int measureSpec) {
25690            //noinspection ResourceType
25691            return (measureSpec & MODE_MASK);
25692        }
25693
25694        /**
25695         * Extracts the size from the supplied measure specification.
25696         *
25697         * @param measureSpec the measure specification to extract the size from
25698         * @return the size in pixels defined in the supplied measure specification
25699         */
25700        public static int getSize(int measureSpec) {
25701            return (measureSpec & ~MODE_MASK);
25702        }
25703
25704        static int adjust(int measureSpec, int delta) {
25705            final int mode = getMode(measureSpec);
25706            int size = getSize(measureSpec);
25707            if (mode == UNSPECIFIED) {
25708                // No need to adjust size for UNSPECIFIED mode.
25709                return makeMeasureSpec(size, UNSPECIFIED);
25710            }
25711            size += delta;
25712            if (size < 0) {
25713                Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
25714                        ") spec: " + toString(measureSpec) + " delta: " + delta);
25715                size = 0;
25716            }
25717            return makeMeasureSpec(size, mode);
25718        }
25719
25720        /**
25721         * Returns a String representation of the specified measure
25722         * specification.
25723         *
25724         * @param measureSpec the measure specification to convert to a String
25725         * @return a String with the following format: "MeasureSpec: MODE SIZE"
25726         */
25727        public static String toString(int measureSpec) {
25728            int mode = getMode(measureSpec);
25729            int size = getSize(measureSpec);
25730
25731            StringBuilder sb = new StringBuilder("MeasureSpec: ");
25732
25733            if (mode == UNSPECIFIED)
25734                sb.append("UNSPECIFIED ");
25735            else if (mode == EXACTLY)
25736                sb.append("EXACTLY ");
25737            else if (mode == AT_MOST)
25738                sb.append("AT_MOST ");
25739            else
25740                sb.append(mode).append(" ");
25741
25742            sb.append(size);
25743            return sb.toString();
25744        }
25745    }
25746
25747    private final class CheckForLongPress implements Runnable {
25748        private int mOriginalWindowAttachCount;
25749        private float mX;
25750        private float mY;
25751        private boolean mOriginalPressedState;
25752
25753        @Override
25754        public void run() {
25755            if ((mOriginalPressedState == isPressed()) && (mParent != null)
25756                    && mOriginalWindowAttachCount == mWindowAttachCount) {
25757                if (performLongClick(mX, mY)) {
25758                    mHasPerformedLongPress = true;
25759                }
25760            }
25761        }
25762
25763        public void setAnchor(float x, float y) {
25764            mX = x;
25765            mY = y;
25766        }
25767
25768        public void rememberWindowAttachCount() {
25769            mOriginalWindowAttachCount = mWindowAttachCount;
25770        }
25771
25772        public void rememberPressedState() {
25773            mOriginalPressedState = isPressed();
25774        }
25775    }
25776
25777    private final class CheckForTap implements Runnable {
25778        public float x;
25779        public float y;
25780
25781        @Override
25782        public void run() {
25783            mPrivateFlags &= ~PFLAG_PREPRESSED;
25784            setPressed(true, x, y);
25785            checkForLongClick(ViewConfiguration.getTapTimeout(), x, y);
25786        }
25787    }
25788
25789    private final class PerformClick implements Runnable {
25790        @Override
25791        public void run() {
25792            performClickInternal();
25793        }
25794    }
25795
25796    /**
25797     * This method returns a ViewPropertyAnimator object, which can be used to animate
25798     * specific properties on this View.
25799     *
25800     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
25801     */
25802    public ViewPropertyAnimator animate() {
25803        if (mAnimator == null) {
25804            mAnimator = new ViewPropertyAnimator(this);
25805        }
25806        return mAnimator;
25807    }
25808
25809    /**
25810     * Sets the name of the View to be used to identify Views in Transitions.
25811     * Names should be unique in the View hierarchy.
25812     *
25813     * @param transitionName The name of the View to uniquely identify it for Transitions.
25814     */
25815    public final void setTransitionName(String transitionName) {
25816        mTransitionName = transitionName;
25817    }
25818
25819    /**
25820     * Returns the name of the View to be used to identify Views in Transitions.
25821     * Names should be unique in the View hierarchy.
25822     *
25823     * <p>This returns null if the View has not been given a name.</p>
25824     *
25825     * @return The name used of the View to be used to identify Views in Transitions or null
25826     * if no name has been given.
25827     */
25828    @ViewDebug.ExportedProperty
25829    public String getTransitionName() {
25830        return mTransitionName;
25831    }
25832
25833    /**
25834     * @hide
25835     */
25836    public void requestKeyboardShortcuts(List<KeyboardShortcutGroup> data, int deviceId) {
25837        // Do nothing.
25838    }
25839
25840    /**
25841     * Interface definition for a callback to be invoked when a hardware key event is
25842     * dispatched to this view. The callback will be invoked before the key event is
25843     * given to the view. This is only useful for hardware keyboards; a software input
25844     * method has no obligation to trigger this listener.
25845     */
25846    public interface OnKeyListener {
25847        /**
25848         * Called when a hardware key is dispatched to a view. This allows listeners to
25849         * get a chance to respond before the target view.
25850         * <p>Key presses in software keyboards will generally NOT trigger this method,
25851         * although some may elect to do so in some situations. Do not assume a
25852         * software input method has to be key-based; even if it is, it may use key presses
25853         * in a different way than you expect, so there is no way to reliably catch soft
25854         * input key presses.
25855         *
25856         * @param v The view the key has been dispatched to.
25857         * @param keyCode The code for the physical key that was pressed
25858         * @param event The KeyEvent object containing full information about
25859         *        the event.
25860         * @return True if the listener has consumed the event, false otherwise.
25861         */
25862        boolean onKey(View v, int keyCode, KeyEvent event);
25863    }
25864
25865    /**
25866     * Interface definition for a callback to be invoked when a hardware key event is
25867     * dispatched to this view during the fallback phase. This means no view in the hierarchy
25868     * has handled this event.
25869     */
25870    public interface OnKeyFallbackListener {
25871        /**
25872         * Called when a hardware key is dispatched to a view in the fallback phase. This allows
25873         * listeners to respond to events after the view hierarchy has had a chance to respond.
25874         * <p>Key presses in software keyboards will generally NOT trigger this method,
25875         * although some may elect to do so in some situations. Do not assume a
25876         * software input method has to be key-based; even if it is, it may use key presses
25877         * in a different way than you expect, so there is no way to reliably catch soft
25878         * input key presses.
25879         *
25880         * @param v The view the key has been dispatched to.
25881         * @param event The KeyEvent object containing full information about
25882         *        the event.
25883         * @return True if the listener has consumed the event, false otherwise.
25884         */
25885        boolean onKeyFallback(View v, KeyEvent event);
25886    }
25887
25888    /**
25889     * Interface definition for a callback to be invoked when a touch event is
25890     * dispatched to this view. The callback will be invoked before the touch
25891     * event is given to the view.
25892     */
25893    public interface OnTouchListener {
25894        /**
25895         * Called when a touch event is dispatched to a view. This allows listeners to
25896         * get a chance to respond before the target view.
25897         *
25898         * @param v The view the touch event has been dispatched to.
25899         * @param event The MotionEvent object containing full information about
25900         *        the event.
25901         * @return True if the listener has consumed the event, false otherwise.
25902         */
25903        boolean onTouch(View v, MotionEvent event);
25904    }
25905
25906    /**
25907     * Interface definition for a callback to be invoked when a hover event is
25908     * dispatched to this view. The callback will be invoked before the hover
25909     * event is given to the view.
25910     */
25911    public interface OnHoverListener {
25912        /**
25913         * Called when a hover event is dispatched to a view. This allows listeners to
25914         * get a chance to respond before the target view.
25915         *
25916         * @param v The view the hover event has been dispatched to.
25917         * @param event The MotionEvent object containing full information about
25918         *        the event.
25919         * @return True if the listener has consumed the event, false otherwise.
25920         */
25921        boolean onHover(View v, MotionEvent event);
25922    }
25923
25924    /**
25925     * Interface definition for a callback to be invoked when a generic motion event is
25926     * dispatched to this view. The callback will be invoked before the generic motion
25927     * event is given to the view.
25928     */
25929    public interface OnGenericMotionListener {
25930        /**
25931         * Called when a generic motion event is dispatched to a view. This allows listeners to
25932         * get a chance to respond before the target view.
25933         *
25934         * @param v The view the generic motion event has been dispatched to.
25935         * @param event The MotionEvent object containing full information about
25936         *        the event.
25937         * @return True if the listener has consumed the event, false otherwise.
25938         */
25939        boolean onGenericMotion(View v, MotionEvent event);
25940    }
25941
25942    /**
25943     * Interface definition for a callback to be invoked when a view has been clicked and held.
25944     */
25945    public interface OnLongClickListener {
25946        /**
25947         * Called when a view has been clicked and held.
25948         *
25949         * @param v The view that was clicked and held.
25950         *
25951         * @return true if the callback consumed the long click, false otherwise.
25952         */
25953        boolean onLongClick(View v);
25954    }
25955
25956    /**
25957     * Interface definition for a callback to be invoked when a drag is being dispatched
25958     * to this view.  The callback will be invoked before the hosting view's own
25959     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
25960     * onDrag(event) behavior, it should return 'false' from this callback.
25961     *
25962     * <div class="special reference">
25963     * <h3>Developer Guides</h3>
25964     * <p>For a guide to implementing drag and drop features, read the
25965     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
25966     * </div>
25967     */
25968    public interface OnDragListener {
25969        /**
25970         * Called when a drag event is dispatched to a view. This allows listeners
25971         * to get a chance to override base View behavior.
25972         *
25973         * @param v The View that received the drag event.
25974         * @param event The {@link android.view.DragEvent} object for the drag event.
25975         * @return {@code true} if the drag event was handled successfully, or {@code false}
25976         * if the drag event was not handled. Note that {@code false} will trigger the View
25977         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
25978         */
25979        boolean onDrag(View v, DragEvent event);
25980    }
25981
25982    /**
25983     * Interface definition for a callback to be invoked when the focus state of
25984     * a view changed.
25985     */
25986    public interface OnFocusChangeListener {
25987        /**
25988         * Called when the focus state of a view has changed.
25989         *
25990         * @param v The view whose state has changed.
25991         * @param hasFocus The new focus state of v.
25992         */
25993        void onFocusChange(View v, boolean hasFocus);
25994    }
25995
25996    /**
25997     * Interface definition for a callback to be invoked when a view is clicked.
25998     */
25999    public interface OnClickListener {
26000        /**
26001         * Called when a view has been clicked.
26002         *
26003         * @param v The view that was clicked.
26004         */
26005        void onClick(View v);
26006    }
26007
26008    /**
26009     * Interface definition for a callback to be invoked when a view is context clicked.
26010     */
26011    public interface OnContextClickListener {
26012        /**
26013         * Called when a view is context clicked.
26014         *
26015         * @param v The view that has been context clicked.
26016         * @return true if the callback consumed the context click, false otherwise.
26017         */
26018        boolean onContextClick(View v);
26019    }
26020
26021    /**
26022     * Interface definition for a callback to be invoked when the context menu
26023     * for this view is being built.
26024     */
26025    public interface OnCreateContextMenuListener {
26026        /**
26027         * Called when the context menu for this view is being built. It is not
26028         * safe to hold onto the menu after this method returns.
26029         *
26030         * @param menu The context menu that is being built
26031         * @param v The view for which the context menu is being built
26032         * @param menuInfo Extra information about the item for which the
26033         *            context menu should be shown. This information will vary
26034         *            depending on the class of v.
26035         */
26036        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
26037    }
26038
26039    /**
26040     * Interface definition for a callback to be invoked when the status bar changes
26041     * visibility.  This reports <strong>global</strong> changes to the system UI
26042     * state, not what the application is requesting.
26043     *
26044     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
26045     */
26046    public interface OnSystemUiVisibilityChangeListener {
26047        /**
26048         * Called when the status bar changes visibility because of a call to
26049         * {@link View#setSystemUiVisibility(int)}.
26050         *
26051         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
26052         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
26053         * This tells you the <strong>global</strong> state of these UI visibility
26054         * flags, not what your app is currently applying.
26055         */
26056        public void onSystemUiVisibilityChange(int visibility);
26057    }
26058
26059    /**
26060     * Interface definition for a callback to be invoked when this view is attached
26061     * or detached from its window.
26062     */
26063    public interface OnAttachStateChangeListener {
26064        /**
26065         * Called when the view is attached to a window.
26066         * @param v The view that was attached
26067         */
26068        public void onViewAttachedToWindow(View v);
26069        /**
26070         * Called when the view is detached from a window.
26071         * @param v The view that was detached
26072         */
26073        public void onViewDetachedFromWindow(View v);
26074    }
26075
26076    /**
26077     * Listener for applying window insets on a view in a custom way.
26078     *
26079     * <p>Apps may choose to implement this interface if they want to apply custom policy
26080     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
26081     * is set, its
26082     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
26083     * method will be called instead of the View's own
26084     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
26085     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
26086     * the View's normal behavior as part of its own.</p>
26087     */
26088    public interface OnApplyWindowInsetsListener {
26089        /**
26090         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
26091         * on a View, this listener method will be called instead of the view's own
26092         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
26093         *
26094         * @param v The view applying window insets
26095         * @param insets The insets to apply
26096         * @return The insets supplied, minus any insets that were consumed
26097         */
26098        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
26099    }
26100
26101    private final class UnsetPressedState implements Runnable {
26102        @Override
26103        public void run() {
26104            setPressed(false);
26105        }
26106    }
26107
26108    /**
26109     * When a view becomes invisible checks if autofill considers the view invisible too. This
26110     * happens after the regular removal operation to make sure the operation is finished by the
26111     * time this is called.
26112     */
26113    private static class VisibilityChangeForAutofillHandler extends Handler {
26114        private final AutofillManager mAfm;
26115        private final View mView;
26116
26117        private VisibilityChangeForAutofillHandler(@NonNull AutofillManager afm,
26118                @NonNull View view) {
26119            mAfm = afm;
26120            mView = view;
26121        }
26122
26123        @Override
26124        public void handleMessage(Message msg) {
26125            mAfm.notifyViewVisibilityChanged(mView, mView.isShown());
26126        }
26127    }
26128
26129    /**
26130     * Base class for derived classes that want to save and restore their own
26131     * state in {@link android.view.View#onSaveInstanceState()}.
26132     */
26133    public static class BaseSavedState extends AbsSavedState {
26134        static final int START_ACTIVITY_REQUESTED_WHO_SAVED = 0b1;
26135        static final int IS_AUTOFILLED = 0b10;
26136        static final int AUTOFILL_ID = 0b100;
26137
26138        // Flags that describe what data in this state is valid
26139        int mSavedData;
26140        String mStartActivityRequestWhoSaved;
26141        boolean mIsAutofilled;
26142        int mAutofillViewId;
26143
26144        /**
26145         * Constructor used when reading from a parcel. Reads the state of the superclass.
26146         *
26147         * @param source parcel to read from
26148         */
26149        public BaseSavedState(Parcel source) {
26150            this(source, null);
26151        }
26152
26153        /**
26154         * Constructor used when reading from a parcel using a given class loader.
26155         * Reads the state of the superclass.
26156         *
26157         * @param source parcel to read from
26158         * @param loader ClassLoader to use for reading
26159         */
26160        public BaseSavedState(Parcel source, ClassLoader loader) {
26161            super(source, loader);
26162            mSavedData = source.readInt();
26163            mStartActivityRequestWhoSaved = source.readString();
26164            mIsAutofilled = source.readBoolean();
26165            mAutofillViewId = source.readInt();
26166        }
26167
26168        /**
26169         * Constructor called by derived classes when creating their SavedState objects
26170         *
26171         * @param superState The state of the superclass of this view
26172         */
26173        public BaseSavedState(Parcelable superState) {
26174            super(superState);
26175        }
26176
26177        @Override
26178        public void writeToParcel(Parcel out, int flags) {
26179            super.writeToParcel(out, flags);
26180
26181            out.writeInt(mSavedData);
26182            out.writeString(mStartActivityRequestWhoSaved);
26183            out.writeBoolean(mIsAutofilled);
26184            out.writeInt(mAutofillViewId);
26185        }
26186
26187        public static final Parcelable.Creator<BaseSavedState> CREATOR
26188                = new Parcelable.ClassLoaderCreator<BaseSavedState>() {
26189            @Override
26190            public BaseSavedState createFromParcel(Parcel in) {
26191                return new BaseSavedState(in);
26192            }
26193
26194            @Override
26195            public BaseSavedState createFromParcel(Parcel in, ClassLoader loader) {
26196                return new BaseSavedState(in, loader);
26197            }
26198
26199            @Override
26200            public BaseSavedState[] newArray(int size) {
26201                return new BaseSavedState[size];
26202            }
26203        };
26204    }
26205
26206    /**
26207     * A set of information given to a view when it is attached to its parent
26208     * window.
26209     */
26210    final static class AttachInfo {
26211        interface Callbacks {
26212            void playSoundEffect(int effectId);
26213            boolean performHapticFeedback(int effectId, boolean always);
26214        }
26215
26216        /**
26217         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
26218         * to a Handler. This class contains the target (View) to invalidate and
26219         * the coordinates of the dirty rectangle.
26220         *
26221         * For performance purposes, this class also implements a pool of up to
26222         * POOL_LIMIT objects that get reused. This reduces memory allocations
26223         * whenever possible.
26224         */
26225        static class InvalidateInfo {
26226            private static final int POOL_LIMIT = 10;
26227
26228            private static final SynchronizedPool<InvalidateInfo> sPool =
26229                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
26230
26231            View target;
26232
26233            int left;
26234            int top;
26235            int right;
26236            int bottom;
26237
26238            public static InvalidateInfo obtain() {
26239                InvalidateInfo instance = sPool.acquire();
26240                return (instance != null) ? instance : new InvalidateInfo();
26241            }
26242
26243            public void recycle() {
26244                target = null;
26245                sPool.release(this);
26246            }
26247        }
26248
26249        final IWindowSession mSession;
26250
26251        final IWindow mWindow;
26252
26253        final IBinder mWindowToken;
26254
26255        Display mDisplay;
26256
26257        final Callbacks mRootCallbacks;
26258
26259        IWindowId mIWindowId;
26260        WindowId mWindowId;
26261
26262        /**
26263         * The top view of the hierarchy.
26264         */
26265        View mRootView;
26266
26267        IBinder mPanelParentWindowToken;
26268
26269        boolean mHardwareAccelerated;
26270        boolean mHardwareAccelerationRequested;
26271        ThreadedRenderer mThreadedRenderer;
26272        List<RenderNode> mPendingAnimatingRenderNodes;
26273
26274        /**
26275         * The state of the display to which the window is attached, as reported
26276         * by {@link Display#getState()}.  Note that the display state constants
26277         * declared by {@link Display} do not exactly line up with the screen state
26278         * constants declared by {@link View} (there are more display states than
26279         * screen states).
26280         */
26281        int mDisplayState = Display.STATE_UNKNOWN;
26282
26283        /**
26284         * Scale factor used by the compatibility mode
26285         */
26286        float mApplicationScale;
26287
26288        /**
26289         * Indicates whether the application is in compatibility mode
26290         */
26291        boolean mScalingRequired;
26292
26293        /**
26294         * Left position of this view's window
26295         */
26296        int mWindowLeft;
26297
26298        /**
26299         * Top position of this view's window
26300         */
26301        int mWindowTop;
26302
26303        /**
26304         * Indicates whether views need to use 32-bit drawing caches
26305         */
26306        boolean mUse32BitDrawingCache;
26307
26308        /**
26309         * For windows that are full-screen but using insets to layout inside
26310         * of the screen areas, these are the current insets to appear inside
26311         * the overscan area of the display.
26312         */
26313        final Rect mOverscanInsets = new Rect();
26314
26315        /**
26316         * For windows that are full-screen but using insets to layout inside
26317         * of the screen decorations, these are the current insets for the
26318         * content of the window.
26319         */
26320        final Rect mContentInsets = new Rect();
26321
26322        /**
26323         * For windows that are full-screen but using insets to layout inside
26324         * of the screen decorations, these are the current insets for the
26325         * actual visible parts of the window.
26326         */
26327        final Rect mVisibleInsets = new Rect();
26328
26329        /**
26330         * For windows that are full-screen but using insets to layout inside
26331         * of the screen decorations, these are the current insets for the
26332         * stable system windows.
26333         */
26334        final Rect mStableInsets = new Rect();
26335
26336        final DisplayCutout.ParcelableWrapper mDisplayCutout =
26337                new DisplayCutout.ParcelableWrapper(DisplayCutout.NO_CUTOUT);
26338
26339        /**
26340         * For windows that include areas that are not covered by real surface these are the outsets
26341         * for real surface.
26342         */
26343        final Rect mOutsets = new Rect();
26344
26345        /**
26346         * In multi-window we force show the navigation bar. Because we don't want that the surface
26347         * size changes in this mode, we instead have a flag whether the navigation bar size should
26348         * always be consumed, so the app is treated like there is no virtual navigation bar at all.
26349         */
26350        boolean mAlwaysConsumeNavBar;
26351
26352        /**
26353         * The internal insets given by this window.  This value is
26354         * supplied by the client (through
26355         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
26356         * be given to the window manager when changed to be used in laying
26357         * out windows behind it.
26358         */
26359        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
26360                = new ViewTreeObserver.InternalInsetsInfo();
26361
26362        /**
26363         * Set to true when mGivenInternalInsets is non-empty.
26364         */
26365        boolean mHasNonEmptyGivenInternalInsets;
26366
26367        /**
26368         * All views in the window's hierarchy that serve as scroll containers,
26369         * used to determine if the window can be resized or must be panned
26370         * to adjust for a soft input area.
26371         */
26372        final ArrayList<View> mScrollContainers = new ArrayList<View>();
26373
26374        final KeyEvent.DispatcherState mKeyDispatchState
26375                = new KeyEvent.DispatcherState();
26376
26377        /**
26378         * Indicates whether the view's window currently has the focus.
26379         */
26380        boolean mHasWindowFocus;
26381
26382        /**
26383         * The current visibility of the window.
26384         */
26385        int mWindowVisibility;
26386
26387        /**
26388         * Indicates the time at which drawing started to occur.
26389         */
26390        long mDrawingTime;
26391
26392        /**
26393         * Indicates whether or not ignoring the DIRTY_MASK flags.
26394         */
26395        boolean mIgnoreDirtyState;
26396
26397        /**
26398         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
26399         * to avoid clearing that flag prematurely.
26400         */
26401        boolean mSetIgnoreDirtyState = false;
26402
26403        /**
26404         * Indicates whether the view's window is currently in touch mode.
26405         */
26406        boolean mInTouchMode;
26407
26408        /**
26409         * Indicates whether the view has requested unbuffered input dispatching for the current
26410         * event stream.
26411         */
26412        boolean mUnbufferedDispatchRequested;
26413
26414        /**
26415         * Indicates that ViewAncestor should trigger a global layout change
26416         * the next time it performs a traversal
26417         */
26418        boolean mRecomputeGlobalAttributes;
26419
26420        /**
26421         * Always report new attributes at next traversal.
26422         */
26423        boolean mForceReportNewAttributes;
26424
26425        /**
26426         * Set during a traveral if any views want to keep the screen on.
26427         */
26428        boolean mKeepScreenOn;
26429
26430        /**
26431         * Set during a traveral if the light center needs to be updated.
26432         */
26433        boolean mNeedsUpdateLightCenter;
26434
26435        /**
26436         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
26437         */
26438        int mSystemUiVisibility;
26439
26440        /**
26441         * Hack to force certain system UI visibility flags to be cleared.
26442         */
26443        int mDisabledSystemUiVisibility;
26444
26445        /**
26446         * Last global system UI visibility reported by the window manager.
26447         */
26448        int mGlobalSystemUiVisibility = -1;
26449
26450        /**
26451         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
26452         * attached.
26453         */
26454        boolean mHasSystemUiListeners;
26455
26456        /**
26457         * Set if the window has requested to extend into the overscan region
26458         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
26459         */
26460        boolean mOverscanRequested;
26461
26462        /**
26463         * Set if the visibility of any views has changed.
26464         */
26465        boolean mViewVisibilityChanged;
26466
26467        /**
26468         * Set to true if a view has been scrolled.
26469         */
26470        boolean mViewScrollChanged;
26471
26472        /**
26473         * Set to true if a pointer event is currently being handled.
26474         */
26475        boolean mHandlingPointerEvent;
26476
26477        /**
26478         * Global to the view hierarchy used as a temporary for dealing with
26479         * x/y points in the transparent region computations.
26480         */
26481        final int[] mTransparentLocation = new int[2];
26482
26483        /**
26484         * Global to the view hierarchy used as a temporary for dealing with
26485         * x/y points in the ViewGroup.invalidateChild implementation.
26486         */
26487        final int[] mInvalidateChildLocation = new int[2];
26488
26489        /**
26490         * Global to the view hierarchy used as a temporary for dealing with
26491         * computing absolute on-screen location.
26492         */
26493        final int[] mTmpLocation = new int[2];
26494
26495        /**
26496         * Global to the view hierarchy used as a temporary for dealing with
26497         * x/y location when view is transformed.
26498         */
26499        final float[] mTmpTransformLocation = new float[2];
26500
26501        /**
26502         * The view tree observer used to dispatch global events like
26503         * layout, pre-draw, touch mode change, etc.
26504         */
26505        final ViewTreeObserver mTreeObserver;
26506
26507        /**
26508         * A Canvas used by the view hierarchy to perform bitmap caching.
26509         */
26510        Canvas mCanvas;
26511
26512        /**
26513         * The view root impl.
26514         */
26515        final ViewRootImpl mViewRootImpl;
26516
26517        /**
26518         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
26519         * handler can be used to pump events in the UI events queue.
26520         */
26521        final Handler mHandler;
26522
26523        /**
26524         * Temporary for use in computing invalidate rectangles while
26525         * calling up the hierarchy.
26526         */
26527        final Rect mTmpInvalRect = new Rect();
26528
26529        /**
26530         * Temporary for use in computing hit areas with transformed views
26531         */
26532        final RectF mTmpTransformRect = new RectF();
26533
26534        /**
26535         * Temporary for use in computing hit areas with transformed views
26536         */
26537        final RectF mTmpTransformRect1 = new RectF();
26538
26539        /**
26540         * Temporary list of rectanges.
26541         */
26542        final List<RectF> mTmpRectList = new ArrayList<>();
26543
26544        /**
26545         * Temporary for use in transforming invalidation rect
26546         */
26547        final Matrix mTmpMatrix = new Matrix();
26548
26549        /**
26550         * Temporary for use in transforming invalidation rect
26551         */
26552        final Transformation mTmpTransformation = new Transformation();
26553
26554        /**
26555         * Temporary for use in querying outlines from OutlineProviders
26556         */
26557        final Outline mTmpOutline = new Outline();
26558
26559        /**
26560         * Temporary list for use in collecting focusable descendents of a view.
26561         */
26562        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
26563
26564        /**
26565         * The id of the window for accessibility purposes.
26566         */
26567        int mAccessibilityWindowId = AccessibilityWindowInfo.UNDEFINED_WINDOW_ID;
26568
26569        /**
26570         * Flags related to accessibility processing.
26571         *
26572         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
26573         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
26574         */
26575        int mAccessibilityFetchFlags;
26576
26577        /**
26578         * The drawable for highlighting accessibility focus.
26579         */
26580        Drawable mAccessibilityFocusDrawable;
26581
26582        /**
26583         * The drawable for highlighting autofilled views.
26584         *
26585         * @see #isAutofilled()
26586         */
26587        Drawable mAutofilledDrawable;
26588
26589        /**
26590         * Show where the margins, bounds and layout bounds are for each view.
26591         */
26592        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
26593
26594        /**
26595         * Point used to compute visible regions.
26596         */
26597        final Point mPoint = new Point();
26598
26599        /**
26600         * Used to track which View originated a requestLayout() call, used when
26601         * requestLayout() is called during layout.
26602         */
26603        View mViewRequestingLayout;
26604
26605        /**
26606         * Used to track views that need (at least) a partial relayout at their current size
26607         * during the next traversal.
26608         */
26609        List<View> mPartialLayoutViews = new ArrayList<>();
26610
26611        /**
26612         * Swapped with mPartialLayoutViews during layout to avoid concurrent
26613         * modification. Lazily assigned during ViewRootImpl layout.
26614         */
26615        List<View> mEmptyPartialLayoutViews;
26616
26617        /**
26618         * Used to track the identity of the current drag operation.
26619         */
26620        IBinder mDragToken;
26621
26622        /**
26623         * The drag shadow surface for the current drag operation.
26624         */
26625        public Surface mDragSurface;
26626
26627
26628        /**
26629         * The view that currently has a tooltip displayed.
26630         */
26631        View mTooltipHost;
26632
26633        /**
26634         * Creates a new set of attachment information with the specified
26635         * events handler and thread.
26636         *
26637         * @param handler the events handler the view must use
26638         */
26639        AttachInfo(IWindowSession session, IWindow window, Display display,
26640                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer,
26641                Context context) {
26642            mSession = session;
26643            mWindow = window;
26644            mWindowToken = window.asBinder();
26645            mDisplay = display;
26646            mViewRootImpl = viewRootImpl;
26647            mHandler = handler;
26648            mRootCallbacks = effectPlayer;
26649            mTreeObserver = new ViewTreeObserver(context);
26650        }
26651    }
26652
26653    /**
26654     * <p>ScrollabilityCache holds various fields used by a View when scrolling
26655     * is supported. This avoids keeping too many unused fields in most
26656     * instances of View.</p>
26657     */
26658    private static class ScrollabilityCache implements Runnable {
26659
26660        /**
26661         * Scrollbars are not visible
26662         */
26663        public static final int OFF = 0;
26664
26665        /**
26666         * Scrollbars are visible
26667         */
26668        public static final int ON = 1;
26669
26670        /**
26671         * Scrollbars are fading away
26672         */
26673        public static final int FADING = 2;
26674
26675        public boolean fadeScrollBars;
26676
26677        public int fadingEdgeLength;
26678        public int scrollBarDefaultDelayBeforeFade;
26679        public int scrollBarFadeDuration;
26680
26681        public int scrollBarSize;
26682        public int scrollBarMinTouchTarget;
26683        public ScrollBarDrawable scrollBar;
26684        public float[] interpolatorValues;
26685        public View host;
26686
26687        public final Paint paint;
26688        public final Matrix matrix;
26689        public Shader shader;
26690
26691        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
26692
26693        private static final float[] OPAQUE = { 255 };
26694        private static final float[] TRANSPARENT = { 0.0f };
26695
26696        /**
26697         * When fading should start. This time moves into the future every time
26698         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
26699         */
26700        public long fadeStartTime;
26701
26702
26703        /**
26704         * The current state of the scrollbars: ON, OFF, or FADING
26705         */
26706        public int state = OFF;
26707
26708        private int mLastColor;
26709
26710        public final Rect mScrollBarBounds = new Rect();
26711        public final Rect mScrollBarTouchBounds = new Rect();
26712
26713        public static final int NOT_DRAGGING = 0;
26714        public static final int DRAGGING_VERTICAL_SCROLL_BAR = 1;
26715        public static final int DRAGGING_HORIZONTAL_SCROLL_BAR = 2;
26716        public int mScrollBarDraggingState = NOT_DRAGGING;
26717
26718        public float mScrollBarDraggingPos = 0;
26719
26720        public ScrollabilityCache(ViewConfiguration configuration, View host) {
26721            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
26722            scrollBarSize = configuration.getScaledScrollBarSize();
26723            scrollBarMinTouchTarget = configuration.getScaledMinScrollbarTouchTarget();
26724            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
26725            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
26726
26727            paint = new Paint();
26728            matrix = new Matrix();
26729            // use use a height of 1, and then wack the matrix each time we
26730            // actually use it.
26731            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
26732            paint.setShader(shader);
26733            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
26734
26735            this.host = host;
26736        }
26737
26738        public void setFadeColor(int color) {
26739            if (color != mLastColor) {
26740                mLastColor = color;
26741
26742                if (color != 0) {
26743                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
26744                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
26745                    paint.setShader(shader);
26746                    // Restore the default transfer mode (src_over)
26747                    paint.setXfermode(null);
26748                } else {
26749                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
26750                    paint.setShader(shader);
26751                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
26752                }
26753            }
26754        }
26755
26756        public void run() {
26757            long now = AnimationUtils.currentAnimationTimeMillis();
26758            if (now >= fadeStartTime) {
26759
26760                // the animation fades the scrollbars out by changing
26761                // the opacity (alpha) from fully opaque to fully
26762                // transparent
26763                int nextFrame = (int) now;
26764                int framesCount = 0;
26765
26766                Interpolator interpolator = scrollBarInterpolator;
26767
26768                // Start opaque
26769                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
26770
26771                // End transparent
26772                nextFrame += scrollBarFadeDuration;
26773                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
26774
26775                state = FADING;
26776
26777                // Kick off the fade animation
26778                host.invalidate(true);
26779            }
26780        }
26781    }
26782
26783    /**
26784     * Resuable callback for sending
26785     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
26786     */
26787    private class SendViewScrolledAccessibilityEvent implements Runnable {
26788        public volatile boolean mIsPending;
26789        public int mDeltaX;
26790        public int mDeltaY;
26791
26792        public void post(int dx, int dy) {
26793            mDeltaX += dx;
26794            mDeltaY += dy;
26795            if (!mIsPending) {
26796                mIsPending = true;
26797                postDelayed(this, ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
26798            }
26799        }
26800
26801        @Override
26802        public void run() {
26803            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
26804                AccessibilityEvent event = AccessibilityEvent.obtain(
26805                        AccessibilityEvent.TYPE_VIEW_SCROLLED);
26806                event.setScrollDeltaX(mDeltaX);
26807                event.setScrollDeltaY(mDeltaY);
26808                sendAccessibilityEventUnchecked(event);
26809            }
26810            reset();
26811        }
26812
26813        private void reset() {
26814            mIsPending = false;
26815            mDeltaX = 0;
26816            mDeltaY = 0;
26817        }
26818    }
26819
26820    /**
26821     * Remove the pending callback for sending a
26822     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
26823     */
26824    private void cancel(@Nullable SendViewScrolledAccessibilityEvent callback) {
26825        if (callback == null || !callback.mIsPending) return;
26826        removeCallbacks(callback);
26827        callback.reset();
26828    }
26829
26830    /**
26831     * <p>
26832     * This class represents a delegate that can be registered in a {@link View}
26833     * to enhance accessibility support via composition rather via inheritance.
26834     * It is specifically targeted to widget developers that extend basic View
26835     * classes i.e. classes in package android.view, that would like their
26836     * applications to be backwards compatible.
26837     * </p>
26838     * <div class="special reference">
26839     * <h3>Developer Guides</h3>
26840     * <p>For more information about making applications accessible, read the
26841     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
26842     * developer guide.</p>
26843     * </div>
26844     * <p>
26845     * A scenario in which a developer would like to use an accessibility delegate
26846     * is overriding a method introduced in a later API version than the minimal API
26847     * version supported by the application. For example, the method
26848     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
26849     * in API version 4 when the accessibility APIs were first introduced. If a
26850     * developer would like his application to run on API version 4 devices (assuming
26851     * all other APIs used by the application are version 4 or lower) and take advantage
26852     * of this method, instead of overriding the method which would break the application's
26853     * backwards compatibility, he can override the corresponding method in this
26854     * delegate and register the delegate in the target View if the API version of
26855     * the system is high enough, i.e. the API version is the same as or higher than the API
26856     * version that introduced
26857     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
26858     * </p>
26859     * <p>
26860     * Here is an example implementation:
26861     * </p>
26862     * <code><pre><p>
26863     * if (Build.VERSION.SDK_INT >= 14) {
26864     *     // If the API version is equal of higher than the version in
26865     *     // which onInitializeAccessibilityNodeInfo was introduced we
26866     *     // register a delegate with a customized implementation.
26867     *     View view = findViewById(R.id.view_id);
26868     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
26869     *         public void onInitializeAccessibilityNodeInfo(View host,
26870     *                 AccessibilityNodeInfo info) {
26871     *             // Let the default implementation populate the info.
26872     *             super.onInitializeAccessibilityNodeInfo(host, info);
26873     *             // Set some other information.
26874     *             info.setEnabled(host.isEnabled());
26875     *         }
26876     *     });
26877     * }
26878     * </code></pre></p>
26879     * <p>
26880     * This delegate contains methods that correspond to the accessibility methods
26881     * in View. If a delegate has been specified the implementation in View hands
26882     * off handling to the corresponding method in this delegate. The default
26883     * implementation the delegate methods behaves exactly as the corresponding
26884     * method in View for the case of no accessibility delegate been set. Hence,
26885     * to customize the behavior of a View method, clients can override only the
26886     * corresponding delegate method without altering the behavior of the rest
26887     * accessibility related methods of the host view.
26888     * </p>
26889     * <p>
26890     * <strong>Note:</strong> On platform versions prior to
26891     * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on
26892     * views in the {@code android.widget.*} package are called <i>before</i>
26893     * host methods. This prevents certain properties such as class name from
26894     * being modified by overriding
26895     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)},
26896     * as any changes will be overwritten by the host class.
26897     * <p>
26898     * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate
26899     * methods are called <i>after</i> host methods, which all properties to be
26900     * modified without being overwritten by the host class.
26901     */
26902    public static class AccessibilityDelegate {
26903
26904        /**
26905         * Sends an accessibility event of the given type. If accessibility is not
26906         * enabled this method has no effect.
26907         * <p>
26908         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
26909         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
26910         * been set.
26911         * </p>
26912         *
26913         * @param host The View hosting the delegate.
26914         * @param eventType The type of the event to send.
26915         *
26916         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
26917         */
26918        public void sendAccessibilityEvent(View host, int eventType) {
26919            host.sendAccessibilityEventInternal(eventType);
26920        }
26921
26922        /**
26923         * Performs the specified accessibility action on the view. For
26924         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
26925         * <p>
26926         * The default implementation behaves as
26927         * {@link View#performAccessibilityAction(int, Bundle)
26928         *  View#performAccessibilityAction(int, Bundle)} for the case of
26929         *  no accessibility delegate been set.
26930         * </p>
26931         *
26932         * @param action The action to perform.
26933         * @return Whether the action was performed.
26934         *
26935         * @see View#performAccessibilityAction(int, Bundle)
26936         *      View#performAccessibilityAction(int, Bundle)
26937         */
26938        public boolean performAccessibilityAction(View host, int action, Bundle args) {
26939            return host.performAccessibilityActionInternal(action, args);
26940        }
26941
26942        /**
26943         * Sends an accessibility event. This method behaves exactly as
26944         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
26945         * empty {@link AccessibilityEvent} and does not perform a check whether
26946         * accessibility is enabled.
26947         * <p>
26948         * The default implementation behaves as
26949         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
26950         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
26951         * the case of no accessibility delegate been set.
26952         * </p>
26953         *
26954         * @param host The View hosting the delegate.
26955         * @param event The event to send.
26956         *
26957         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
26958         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
26959         */
26960        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
26961            host.sendAccessibilityEventUncheckedInternal(event);
26962        }
26963
26964        /**
26965         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
26966         * to its children for adding their text content to the event.
26967         * <p>
26968         * The default implementation behaves as
26969         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
26970         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
26971         * the case of no accessibility delegate been set.
26972         * </p>
26973         *
26974         * @param host The View hosting the delegate.
26975         * @param event The event.
26976         * @return True if the event population was completed.
26977         *
26978         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
26979         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
26980         */
26981        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
26982            return host.dispatchPopulateAccessibilityEventInternal(event);
26983        }
26984
26985        /**
26986         * Gives a chance to the host View to populate the accessibility event with its
26987         * text content.
26988         * <p>
26989         * The default implementation behaves as
26990         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
26991         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
26992         * the case of no accessibility delegate been set.
26993         * </p>
26994         *
26995         * @param host The View hosting the delegate.
26996         * @param event The accessibility event which to populate.
26997         *
26998         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
26999         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
27000         */
27001        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
27002            host.onPopulateAccessibilityEventInternal(event);
27003        }
27004
27005        /**
27006         * Initializes an {@link AccessibilityEvent} with information about the
27007         * the host View which is the event source.
27008         * <p>
27009         * The default implementation behaves as
27010         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
27011         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
27012         * the case of no accessibility delegate been set.
27013         * </p>
27014         *
27015         * @param host The View hosting the delegate.
27016         * @param event The event to initialize.
27017         *
27018         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
27019         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
27020         */
27021        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
27022            host.onInitializeAccessibilityEventInternal(event);
27023        }
27024
27025        /**
27026         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
27027         * <p>
27028         * The default implementation behaves as
27029         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
27030         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
27031         * the case of no accessibility delegate been set.
27032         * </p>
27033         *
27034         * @param host The View hosting the delegate.
27035         * @param info The instance to initialize.
27036         *
27037         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
27038         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
27039         */
27040        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
27041            host.onInitializeAccessibilityNodeInfoInternal(info);
27042        }
27043
27044        /**
27045         * Adds extra data to an {@link AccessibilityNodeInfo} based on an explicit request for the
27046         * additional data.
27047         * <p>
27048         * This method only needs to be implemented if the View offers to provide additional data.
27049         * </p>
27050         * <p>
27051         * The default implementation behaves as
27052         * {@link View#addExtraDataToAccessibilityNodeInfo(AccessibilityNodeInfo, String, Bundle)
27053         * for the case where no accessibility delegate is set.
27054         * </p>
27055         *
27056         * @param host The View hosting the delegate. Never {@code null}.
27057         * @param info The info to which to add the extra data. Never {@code null}.
27058         * @param extraDataKey A key specifying the type of extra data to add to the info. The
27059         *                     extra data should be added to the {@link Bundle} returned by
27060         *                     the info's {@link AccessibilityNodeInfo#getExtras} method.  Never
27061         *                     {@code null}.
27062         * @param arguments A {@link Bundle} holding any arguments relevant for this request.
27063         *                  May be {@code null} if the if the service provided no arguments.
27064         *
27065         * @see AccessibilityNodeInfo#setExtraAvailableData
27066         */
27067        public void addExtraDataToAccessibilityNodeInfo(@NonNull View host,
27068                @NonNull AccessibilityNodeInfo info, @NonNull String extraDataKey,
27069                @Nullable Bundle arguments) {
27070            host.addExtraDataToAccessibilityNodeInfo(info, extraDataKey, arguments);
27071        }
27072
27073        /**
27074         * Called when a child of the host View has requested sending an
27075         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
27076         * to augment the event.
27077         * <p>
27078         * The default implementation behaves as
27079         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
27080         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
27081         * the case of no accessibility delegate been set.
27082         * </p>
27083         *
27084         * @param host The View hosting the delegate.
27085         * @param child The child which requests sending the event.
27086         * @param event The event to be sent.
27087         * @return True if the event should be sent
27088         *
27089         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
27090         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
27091         */
27092        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
27093                AccessibilityEvent event) {
27094            return host.onRequestSendAccessibilityEventInternal(child, event);
27095        }
27096
27097        /**
27098         * Gets the provider for managing a virtual view hierarchy rooted at this View
27099         * and reported to {@link android.accessibilityservice.AccessibilityService}s
27100         * that explore the window content.
27101         * <p>
27102         * The default implementation behaves as
27103         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
27104         * the case of no accessibility delegate been set.
27105         * </p>
27106         *
27107         * @return The provider.
27108         *
27109         * @see AccessibilityNodeProvider
27110         */
27111        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
27112            return null;
27113        }
27114
27115        /**
27116         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
27117         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
27118         * This method is responsible for obtaining an accessibility node info from a
27119         * pool of reusable instances and calling
27120         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
27121         * view to initialize the former.
27122         * <p>
27123         * <strong>Note:</strong> The client is responsible for recycling the obtained
27124         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
27125         * creation.
27126         * </p>
27127         * <p>
27128         * The default implementation behaves as
27129         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
27130         * the case of no accessibility delegate been set.
27131         * </p>
27132         * @return A populated {@link AccessibilityNodeInfo}.
27133         *
27134         * @see AccessibilityNodeInfo
27135         *
27136         * @hide
27137         */
27138        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
27139            return host.createAccessibilityNodeInfoInternal();
27140        }
27141    }
27142
27143    private static class MatchIdPredicate implements Predicate<View> {
27144        public int mId;
27145
27146        @Override
27147        public boolean test(View view) {
27148            return (view.mID == mId);
27149        }
27150    }
27151
27152    private static class MatchLabelForPredicate implements Predicate<View> {
27153        private int mLabeledId;
27154
27155        @Override
27156        public boolean test(View view) {
27157            return (view.mLabelForId == mLabeledId);
27158        }
27159    }
27160
27161    /**
27162     * Dump all private flags in readable format, useful for documentation and
27163     * sanity checking.
27164     */
27165    private static void dumpFlags() {
27166        final HashMap<String, String> found = Maps.newHashMap();
27167        try {
27168            for (Field field : View.class.getDeclaredFields()) {
27169                final int modifiers = field.getModifiers();
27170                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
27171                    if (field.getType().equals(int.class)) {
27172                        final int value = field.getInt(null);
27173                        dumpFlag(found, field.getName(), value);
27174                    } else if (field.getType().equals(int[].class)) {
27175                        final int[] values = (int[]) field.get(null);
27176                        for (int i = 0; i < values.length; i++) {
27177                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
27178                        }
27179                    }
27180                }
27181            }
27182        } catch (IllegalAccessException e) {
27183            throw new RuntimeException(e);
27184        }
27185
27186        final ArrayList<String> keys = Lists.newArrayList();
27187        keys.addAll(found.keySet());
27188        Collections.sort(keys);
27189        for (String key : keys) {
27190            Log.d(VIEW_LOG_TAG, found.get(key));
27191        }
27192    }
27193
27194    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
27195        // Sort flags by prefix, then by bits, always keeping unique keys
27196        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
27197        final int prefix = name.indexOf('_');
27198        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
27199        final String output = bits + " " + name;
27200        found.put(key, output);
27201    }
27202
27203    /** {@hide} */
27204    public void encode(@NonNull ViewHierarchyEncoder stream) {
27205        stream.beginObject(this);
27206        encodeProperties(stream);
27207        stream.endObject();
27208    }
27209
27210    /** {@hide} */
27211    @CallSuper
27212    protected void encodeProperties(@NonNull ViewHierarchyEncoder stream) {
27213        Object resolveId = ViewDebug.resolveId(getContext(), mID);
27214        if (resolveId instanceof String) {
27215            stream.addProperty("id", (String) resolveId);
27216        } else {
27217            stream.addProperty("id", mID);
27218        }
27219
27220        stream.addProperty("misc:transformation.alpha",
27221                mTransformationInfo != null ? mTransformationInfo.mAlpha : 0);
27222        stream.addProperty("misc:transitionName", getTransitionName());
27223
27224        // layout
27225        stream.addProperty("layout:left", mLeft);
27226        stream.addProperty("layout:right", mRight);
27227        stream.addProperty("layout:top", mTop);
27228        stream.addProperty("layout:bottom", mBottom);
27229        stream.addProperty("layout:width", getWidth());
27230        stream.addProperty("layout:height", getHeight());
27231        stream.addProperty("layout:layoutDirection", getLayoutDirection());
27232        stream.addProperty("layout:layoutRtl", isLayoutRtl());
27233        stream.addProperty("layout:hasTransientState", hasTransientState());
27234        stream.addProperty("layout:baseline", getBaseline());
27235
27236        // layout params
27237        ViewGroup.LayoutParams layoutParams = getLayoutParams();
27238        if (layoutParams != null) {
27239            stream.addPropertyKey("layoutParams");
27240            layoutParams.encode(stream);
27241        }
27242
27243        // scrolling
27244        stream.addProperty("scrolling:scrollX", mScrollX);
27245        stream.addProperty("scrolling:scrollY", mScrollY);
27246
27247        // padding
27248        stream.addProperty("padding:paddingLeft", mPaddingLeft);
27249        stream.addProperty("padding:paddingRight", mPaddingRight);
27250        stream.addProperty("padding:paddingTop", mPaddingTop);
27251        stream.addProperty("padding:paddingBottom", mPaddingBottom);
27252        stream.addProperty("padding:userPaddingRight", mUserPaddingRight);
27253        stream.addProperty("padding:userPaddingLeft", mUserPaddingLeft);
27254        stream.addProperty("padding:userPaddingBottom", mUserPaddingBottom);
27255        stream.addProperty("padding:userPaddingStart", mUserPaddingStart);
27256        stream.addProperty("padding:userPaddingEnd", mUserPaddingEnd);
27257
27258        // measurement
27259        stream.addProperty("measurement:minHeight", mMinHeight);
27260        stream.addProperty("measurement:minWidth", mMinWidth);
27261        stream.addProperty("measurement:measuredWidth", mMeasuredWidth);
27262        stream.addProperty("measurement:measuredHeight", mMeasuredHeight);
27263
27264        // drawing
27265        stream.addProperty("drawing:elevation", getElevation());
27266        stream.addProperty("drawing:translationX", getTranslationX());
27267        stream.addProperty("drawing:translationY", getTranslationY());
27268        stream.addProperty("drawing:translationZ", getTranslationZ());
27269        stream.addProperty("drawing:rotation", getRotation());
27270        stream.addProperty("drawing:rotationX", getRotationX());
27271        stream.addProperty("drawing:rotationY", getRotationY());
27272        stream.addProperty("drawing:scaleX", getScaleX());
27273        stream.addProperty("drawing:scaleY", getScaleY());
27274        stream.addProperty("drawing:pivotX", getPivotX());
27275        stream.addProperty("drawing:pivotY", getPivotY());
27276        stream.addProperty("drawing:clipBounds",
27277                mClipBounds == null ? null : mClipBounds.toString());
27278        stream.addProperty("drawing:opaque", isOpaque());
27279        stream.addProperty("drawing:alpha", getAlpha());
27280        stream.addProperty("drawing:transitionAlpha", getTransitionAlpha());
27281        stream.addProperty("drawing:shadow", hasShadow());
27282        stream.addProperty("drawing:solidColor", getSolidColor());
27283        stream.addProperty("drawing:layerType", mLayerType);
27284        stream.addProperty("drawing:willNotDraw", willNotDraw());
27285        stream.addProperty("drawing:hardwareAccelerated", isHardwareAccelerated());
27286        stream.addProperty("drawing:willNotCacheDrawing", willNotCacheDrawing());
27287        stream.addProperty("drawing:drawingCacheEnabled", isDrawingCacheEnabled());
27288        stream.addProperty("drawing:overlappingRendering", hasOverlappingRendering());
27289        stream.addProperty("drawing:outlineAmbientShadowColor", getOutlineAmbientShadowColor());
27290        stream.addProperty("drawing:outlineSpotShadowColor", getOutlineSpotShadowColor());
27291
27292        // focus
27293        stream.addProperty("focus:hasFocus", hasFocus());
27294        stream.addProperty("focus:isFocused", isFocused());
27295        stream.addProperty("focus:focusable", getFocusable());
27296        stream.addProperty("focus:isFocusable", isFocusable());
27297        stream.addProperty("focus:isFocusableInTouchMode", isFocusableInTouchMode());
27298
27299        stream.addProperty("misc:clickable", isClickable());
27300        stream.addProperty("misc:pressed", isPressed());
27301        stream.addProperty("misc:selected", isSelected());
27302        stream.addProperty("misc:touchMode", isInTouchMode());
27303        stream.addProperty("misc:hovered", isHovered());
27304        stream.addProperty("misc:activated", isActivated());
27305
27306        stream.addProperty("misc:visibility", getVisibility());
27307        stream.addProperty("misc:fitsSystemWindows", getFitsSystemWindows());
27308        stream.addProperty("misc:filterTouchesWhenObscured", getFilterTouchesWhenObscured());
27309
27310        stream.addProperty("misc:enabled", isEnabled());
27311        stream.addProperty("misc:soundEffectsEnabled", isSoundEffectsEnabled());
27312        stream.addProperty("misc:hapticFeedbackEnabled", isHapticFeedbackEnabled());
27313
27314        // theme attributes
27315        Resources.Theme theme = getContext().getTheme();
27316        if (theme != null) {
27317            stream.addPropertyKey("theme");
27318            theme.encode(stream);
27319        }
27320
27321        // view attribute information
27322        int n = mAttributes != null ? mAttributes.length : 0;
27323        stream.addProperty("meta:__attrCount__", n/2);
27324        for (int i = 0; i < n; i += 2) {
27325            stream.addProperty("meta:__attr__" + mAttributes[i], mAttributes[i+1]);
27326        }
27327
27328        stream.addProperty("misc:scrollBarStyle", getScrollBarStyle());
27329
27330        // text
27331        stream.addProperty("text:textDirection", getTextDirection());
27332        stream.addProperty("text:textAlignment", getTextAlignment());
27333
27334        // accessibility
27335        CharSequence contentDescription = getContentDescription();
27336        stream.addProperty("accessibility:contentDescription",
27337                contentDescription == null ? "" : contentDescription.toString());
27338        stream.addProperty("accessibility:labelFor", getLabelFor());
27339        stream.addProperty("accessibility:importantForAccessibility", getImportantForAccessibility());
27340    }
27341
27342    /**
27343     * Determine if this view is rendered on a round wearable device and is the main view
27344     * on the screen.
27345     */
27346    boolean shouldDrawRoundScrollbar() {
27347        if (!mResources.getConfiguration().isScreenRound() || mAttachInfo == null) {
27348            return false;
27349        }
27350
27351        final View rootView = getRootView();
27352        final WindowInsets insets = getRootWindowInsets();
27353
27354        int height = getHeight();
27355        int width = getWidth();
27356        int displayHeight = rootView.getHeight();
27357        int displayWidth = rootView.getWidth();
27358
27359        if (height != displayHeight || width != displayWidth) {
27360            return false;
27361        }
27362
27363        getLocationInWindow(mAttachInfo.mTmpLocation);
27364        return mAttachInfo.mTmpLocation[0] == insets.getStableInsetLeft()
27365                && mAttachInfo.mTmpLocation[1] == insets.getStableInsetTop();
27366    }
27367
27368    /**
27369     * Sets the tooltip text which will be displayed in a small popup next to the view.
27370     * <p>
27371     * The tooltip will be displayed:
27372     * <ul>
27373     * <li>On long click, unless it is handled otherwise (by OnLongClickListener or a context
27374     * menu). </li>
27375     * <li>On hover, after a brief delay since the pointer has stopped moving </li>
27376     * </ul>
27377     * <p>
27378     * <strong>Note:</strong> Do not override this method, as it will have no
27379     * effect on the text displayed in the tooltip.
27380     *
27381     * @param tooltipText the tooltip text, or null if no tooltip is required
27382     * @see #getTooltipText()
27383     * @attr ref android.R.styleable#View_tooltipText
27384     */
27385    public void setTooltipText(@Nullable CharSequence tooltipText) {
27386        if (TextUtils.isEmpty(tooltipText)) {
27387            setFlags(0, TOOLTIP);
27388            hideTooltip();
27389            mTooltipInfo = null;
27390        } else {
27391            setFlags(TOOLTIP, TOOLTIP);
27392            if (mTooltipInfo == null) {
27393                mTooltipInfo = new TooltipInfo();
27394                mTooltipInfo.mShowTooltipRunnable = this::showHoverTooltip;
27395                mTooltipInfo.mHideTooltipRunnable = this::hideTooltip;
27396                mTooltipInfo.mHoverSlop = ViewConfiguration.get(mContext).getScaledHoverSlop();
27397                mTooltipInfo.clearAnchorPos();
27398            }
27399            mTooltipInfo.mTooltipText = tooltipText;
27400        }
27401    }
27402
27403    /**
27404     * @hide Binary compatibility stub. To be removed when we finalize O APIs.
27405     */
27406    public void setTooltip(@Nullable CharSequence tooltipText) {
27407        setTooltipText(tooltipText);
27408    }
27409
27410    /**
27411     * Returns the view's tooltip text.
27412     *
27413     * <strong>Note:</strong> Do not override this method, as it will have no
27414     * effect on the text displayed in the tooltip. You must call
27415     * {@link #setTooltipText(CharSequence)} to modify the tooltip text.
27416     *
27417     * @return the tooltip text
27418     * @see #setTooltipText(CharSequence)
27419     * @attr ref android.R.styleable#View_tooltipText
27420     */
27421    @Nullable
27422    public CharSequence getTooltipText() {
27423        return mTooltipInfo != null ? mTooltipInfo.mTooltipText : null;
27424    }
27425
27426    /**
27427     * @hide Binary compatibility stub. To be removed when we finalize O APIs.
27428     */
27429    @Nullable
27430    public CharSequence getTooltip() {
27431        return getTooltipText();
27432    }
27433
27434    private boolean showTooltip(int x, int y, boolean fromLongClick) {
27435        if (mAttachInfo == null || mTooltipInfo == null) {
27436            return false;
27437        }
27438        if (fromLongClick && (mViewFlags & ENABLED_MASK) != ENABLED) {
27439            return false;
27440        }
27441        if (TextUtils.isEmpty(mTooltipInfo.mTooltipText)) {
27442            return false;
27443        }
27444        hideTooltip();
27445        mTooltipInfo.mTooltipFromLongClick = fromLongClick;
27446        mTooltipInfo.mTooltipPopup = new TooltipPopup(getContext());
27447        final boolean fromTouch = (mPrivateFlags3 & PFLAG3_FINGER_DOWN) == PFLAG3_FINGER_DOWN;
27448        mTooltipInfo.mTooltipPopup.show(this, x, y, fromTouch, mTooltipInfo.mTooltipText);
27449        mAttachInfo.mTooltipHost = this;
27450        // The available accessibility actions have changed
27451        notifyViewAccessibilityStateChangedIfNeeded(CONTENT_CHANGE_TYPE_UNDEFINED);
27452        return true;
27453    }
27454
27455    void hideTooltip() {
27456        if (mTooltipInfo == null) {
27457            return;
27458        }
27459        removeCallbacks(mTooltipInfo.mShowTooltipRunnable);
27460        if (mTooltipInfo.mTooltipPopup == null) {
27461            return;
27462        }
27463        mTooltipInfo.mTooltipPopup.hide();
27464        mTooltipInfo.mTooltipPopup = null;
27465        mTooltipInfo.mTooltipFromLongClick = false;
27466        mTooltipInfo.clearAnchorPos();
27467        if (mAttachInfo != null) {
27468            mAttachInfo.mTooltipHost = null;
27469        }
27470        // The available accessibility actions have changed
27471        notifyViewAccessibilityStateChangedIfNeeded(CONTENT_CHANGE_TYPE_UNDEFINED);
27472    }
27473
27474    private boolean showLongClickTooltip(int x, int y) {
27475        removeCallbacks(mTooltipInfo.mShowTooltipRunnable);
27476        removeCallbacks(mTooltipInfo.mHideTooltipRunnable);
27477        return showTooltip(x, y, true);
27478    }
27479
27480    private boolean showHoverTooltip() {
27481        return showTooltip(mTooltipInfo.mAnchorX, mTooltipInfo.mAnchorY, false);
27482    }
27483
27484    boolean dispatchTooltipHoverEvent(MotionEvent event) {
27485        if (mTooltipInfo == null) {
27486            return false;
27487        }
27488        switch(event.getAction()) {
27489            case MotionEvent.ACTION_HOVER_MOVE:
27490                if ((mViewFlags & TOOLTIP) != TOOLTIP) {
27491                    break;
27492                }
27493                if (!mTooltipInfo.mTooltipFromLongClick && mTooltipInfo.updateAnchorPos(event)) {
27494                    if (mTooltipInfo.mTooltipPopup == null) {
27495                        // Schedule showing the tooltip after a timeout.
27496                        removeCallbacks(mTooltipInfo.mShowTooltipRunnable);
27497                        postDelayed(mTooltipInfo.mShowTooltipRunnable,
27498                                ViewConfiguration.getHoverTooltipShowTimeout());
27499                    }
27500
27501                    // Hide hover-triggered tooltip after a period of inactivity.
27502                    // Match the timeout used by NativeInputManager to hide the mouse pointer
27503                    // (depends on SYSTEM_UI_FLAG_LOW_PROFILE being set).
27504                    final int timeout;
27505                    if ((getWindowSystemUiVisibility() & SYSTEM_UI_FLAG_LOW_PROFILE)
27506                            == SYSTEM_UI_FLAG_LOW_PROFILE) {
27507                        timeout = ViewConfiguration.getHoverTooltipHideShortTimeout();
27508                    } else {
27509                        timeout = ViewConfiguration.getHoverTooltipHideTimeout();
27510                    }
27511                    removeCallbacks(mTooltipInfo.mHideTooltipRunnable);
27512                    postDelayed(mTooltipInfo.mHideTooltipRunnable, timeout);
27513                }
27514                return true;
27515
27516            case MotionEvent.ACTION_HOVER_EXIT:
27517                mTooltipInfo.clearAnchorPos();
27518                if (!mTooltipInfo.mTooltipFromLongClick) {
27519                    hideTooltip();
27520                }
27521                break;
27522        }
27523        return false;
27524    }
27525
27526    void handleTooltipKey(KeyEvent event) {
27527        switch (event.getAction()) {
27528            case KeyEvent.ACTION_DOWN:
27529                if (event.getRepeatCount() == 0) {
27530                    hideTooltip();
27531                }
27532                break;
27533
27534            case KeyEvent.ACTION_UP:
27535                handleTooltipUp();
27536                break;
27537        }
27538    }
27539
27540    private void handleTooltipUp() {
27541        if (mTooltipInfo == null || mTooltipInfo.mTooltipPopup == null) {
27542            return;
27543        }
27544        removeCallbacks(mTooltipInfo.mHideTooltipRunnable);
27545        postDelayed(mTooltipInfo.mHideTooltipRunnable,
27546                ViewConfiguration.getLongPressTooltipHideTimeout());
27547    }
27548
27549    private int getFocusableAttribute(TypedArray attributes) {
27550        TypedValue val = new TypedValue();
27551        if (attributes.getValue(com.android.internal.R.styleable.View_focusable, val)) {
27552            if (val.type == TypedValue.TYPE_INT_BOOLEAN) {
27553                return (val.data == 0 ? NOT_FOCUSABLE : FOCUSABLE);
27554            } else {
27555                return val.data;
27556            }
27557        } else {
27558            return FOCUSABLE_AUTO;
27559        }
27560    }
27561
27562    /**
27563     * @return The content view of the tooltip popup currently being shown, or null if the tooltip
27564     * is not showing.
27565     * @hide
27566     */
27567    @TestApi
27568    public View getTooltipView() {
27569        if (mTooltipInfo == null || mTooltipInfo.mTooltipPopup == null) {
27570            return null;
27571        }
27572        return mTooltipInfo.mTooltipPopup.getContentView();
27573    }
27574
27575    /**
27576     * Allows this view to handle {@link KeyEvent}s which weren't handled by normal dispatch. This
27577     * occurs after the normal view hierarchy dispatch, but before the window callback. By default,
27578     * this will dispatch into all the listeners registered via
27579     * {@link #addKeyFallbackListener(OnKeyFallbackListener)} in last-in-first-out order (most
27580     * recently added will receive events first).
27581     *
27582     * @param event A not-previously-handled event.
27583     * @return {@code true} if the event was handled, {@code false} otherwise.
27584     * @see #addKeyFallbackListener
27585     */
27586    public boolean onKeyFallback(@NonNull KeyEvent event) {
27587        if (mListenerInfo != null && mListenerInfo.mKeyFallbackListeners != null) {
27588            for (int i = mListenerInfo.mKeyFallbackListeners.size() - 1; i >= 0; --i) {
27589                if (mListenerInfo.mKeyFallbackListeners.get(i).onKeyFallback(this, event)) {
27590                    return true;
27591                }
27592            }
27593        }
27594        return false;
27595    }
27596
27597    /**
27598     * Adds a listener which will receive unhandled {@link KeyEvent}s.
27599     * @param listener the receiver of fallback {@link KeyEvent}s.
27600     * @see #onKeyFallback(KeyEvent)
27601     */
27602    public void addKeyFallbackListener(OnKeyFallbackListener listener) {
27603        ArrayList<OnKeyFallbackListener> fallbacks = getListenerInfo().mKeyFallbackListeners;
27604        if (fallbacks == null) {
27605            fallbacks = new ArrayList<>();
27606            getListenerInfo().mKeyFallbackListeners = fallbacks;
27607        }
27608        fallbacks.add(listener);
27609    }
27610
27611    /**
27612     * Removes a listener which will receive unhandled {@link KeyEvent}s.
27613     * @param listener the receiver of fallback {@link KeyEvent}s.
27614     * @see #onKeyFallback(KeyEvent)
27615     */
27616    public void removeKeyFallbackListener(OnKeyFallbackListener listener) {
27617        if (mListenerInfo != null) {
27618            if (mListenerInfo.mKeyFallbackListeners != null) {
27619                mListenerInfo.mKeyFallbackListeners.remove(listener);
27620                if (mListenerInfo.mKeyFallbackListeners.isEmpty()) {
27621                    mListenerInfo.mKeyFallbackListeners = null;
27622                }
27623            }
27624        }
27625    }
27626}
27627