View.java revision 2d4f01ba7f544f1bd772239a0f19946b01ed98d9
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 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     * Returns whether or not a pivot has been set by a call to {@link #setPivotX(float)} or
14850     * {@link #setPivotY(float)}. If no pivot has been set then the pivot will be the center
14851     * of the view.
14852     *
14853     * @return True if a pivot has been set, false if the default pivot is being used
14854     */
14855    public boolean isPivotSet() {
14856        return mRenderNode.isPivotExplicitlySet();
14857    }
14858
14859    /**
14860     * Clears any pivot previously set by a call to  {@link #setPivotX(float)} or
14861     * {@link #setPivotY(float)}. After calling this {@link #isPivotSet()} will be false
14862     * and the pivot used for rotation will return to default of being centered on the view.
14863     */
14864    public void resetPivot() {
14865        if (mRenderNode.resetPivot()) {
14866            invalidateViewProperty(false, false);
14867        }
14868    }
14869
14870    /**
14871     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
14872     * completely transparent and 1 means the view is completely opaque.
14873     *
14874     * <p>By default this is 1.0f.
14875     * @return The opacity of the view.
14876     */
14877    @ViewDebug.ExportedProperty(category = "drawing")
14878    public float getAlpha() {
14879        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
14880    }
14881
14882    /**
14883     * Sets the behavior for overlapping rendering for this view (see {@link
14884     * #hasOverlappingRendering()} for more details on this behavior). Calling this method
14885     * is an alternative to overriding {@link #hasOverlappingRendering()} in a subclass,
14886     * providing the value which is then used internally. That is, when {@link
14887     * #forceHasOverlappingRendering(boolean)} is called, the value of {@link
14888     * #hasOverlappingRendering()} is ignored and the value passed into this method is used
14889     * instead.
14890     *
14891     * @param hasOverlappingRendering The value for overlapping rendering to be used internally
14892     * instead of that returned by {@link #hasOverlappingRendering()}.
14893     *
14894     * @attr ref android.R.styleable#View_forceHasOverlappingRendering
14895     */
14896    public void forceHasOverlappingRendering(boolean hasOverlappingRendering) {
14897        mPrivateFlags3 |= PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED;
14898        if (hasOverlappingRendering) {
14899            mPrivateFlags3 |= PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE;
14900        } else {
14901            mPrivateFlags3 &= ~PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE;
14902        }
14903    }
14904
14905    /**
14906     * Returns the value for overlapping rendering that is used internally. This is either
14907     * the value passed into {@link #forceHasOverlappingRendering(boolean)}, if called, or
14908     * the return value of {@link #hasOverlappingRendering()}, otherwise.
14909     *
14910     * @return The value for overlapping rendering being used internally.
14911     */
14912    public final boolean getHasOverlappingRendering() {
14913        return (mPrivateFlags3 & PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED) != 0 ?
14914                (mPrivateFlags3 & PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE) != 0 :
14915                hasOverlappingRendering();
14916    }
14917
14918    /**
14919     * Returns whether this View has content which overlaps.
14920     *
14921     * <p>This function, intended to be overridden by specific View types, is an optimization when
14922     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
14923     * an offscreen buffer and then composited into place, which can be expensive. If the view has
14924     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
14925     * directly. An example of overlapping rendering is a TextView with a background image, such as
14926     * a Button. An example of non-overlapping rendering is a TextView with no background, or an
14927     * ImageView with only the foreground image. The default implementation returns true; subclasses
14928     * should override if they have cases which can be optimized.</p>
14929     *
14930     * <p><strong>Note:</strong> The return value of this method is ignored if {@link
14931     * #forceHasOverlappingRendering(boolean)} has been called on this view.</p>
14932     *
14933     * @return true if the content in this view might overlap, false otherwise.
14934     */
14935    @ViewDebug.ExportedProperty(category = "drawing")
14936    public boolean hasOverlappingRendering() {
14937        return true;
14938    }
14939
14940    /**
14941     * Sets the opacity of the view to a value from 0 to 1, where 0 means the view is
14942     * completely transparent and 1 means the view is completely opaque.
14943     *
14944     * <p class="note"><strong>Note:</strong> setting alpha to a translucent value (0 < alpha < 1)
14945     * can have significant performance implications, especially for large views. It is best to use
14946     * the alpha property sparingly and transiently, as in the case of fading animations.</p>
14947     *
14948     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
14949     * strongly recommended for performance reasons to either override
14950     * {@link #hasOverlappingRendering()} to return <code>false</code> if appropriate, or setting a
14951     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view for the duration
14952     * of the animation. On versions {@link android.os.Build.VERSION_CODES#M} and below,
14953     * the default path for rendering an unlayered View with alpha could add multiple milliseconds
14954     * of rendering cost, even for simple or small views. Starting with
14955     * {@link android.os.Build.VERSION_CODES#M}, {@link #LAYER_TYPE_HARDWARE} is automatically
14956     * applied to the view at the rendering level.</p>
14957     *
14958     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
14959     * responsible for applying the opacity itself.</p>
14960     *
14961     * <p>On versions {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} and below, note that if
14962     * the view is backed by a {@link #setLayerType(int, android.graphics.Paint) layer} and is
14963     * associated with a {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an
14964     * alpha value less than 1.0 will supersede the alpha of the layer paint.</p>
14965     *
14966     * <p>Starting with {@link android.os.Build.VERSION_CODES#M}, setting a translucent alpha
14967     * value will clip a View to its bounds, unless the View returns <code>false</code> from
14968     * {@link #hasOverlappingRendering}.</p>
14969     *
14970     * @param alpha The opacity of the view.
14971     *
14972     * @see #hasOverlappingRendering()
14973     * @see #setLayerType(int, android.graphics.Paint)
14974     *
14975     * @attr ref android.R.styleable#View_alpha
14976     */
14977    public void setAlpha(@FloatRange(from=0.0, to=1.0) float alpha) {
14978        ensureTransformationInfo();
14979        if (mTransformationInfo.mAlpha != alpha) {
14980            // Report visibility changes, which can affect children, to accessibility
14981            if ((alpha == 0) ^ (mTransformationInfo.mAlpha == 0)) {
14982                notifySubtreeAccessibilityStateChangedIfNeeded();
14983            }
14984            mTransformationInfo.mAlpha = alpha;
14985            if (onSetAlpha((int) (alpha * 255))) {
14986                mPrivateFlags |= PFLAG_ALPHA_SET;
14987                // subclass is handling alpha - don't optimize rendering cache invalidation
14988                invalidateParentCaches();
14989                invalidate(true);
14990            } else {
14991                mPrivateFlags &= ~PFLAG_ALPHA_SET;
14992                invalidateViewProperty(true, false);
14993                mRenderNode.setAlpha(getFinalAlpha());
14994            }
14995        }
14996    }
14997
14998    /**
14999     * Faster version of setAlpha() which performs the same steps except there are
15000     * no calls to invalidate(). The caller of this function should perform proper invalidation
15001     * on the parent and this object. The return value indicates whether the subclass handles
15002     * alpha (the return value for onSetAlpha()).
15003     *
15004     * @param alpha The new value for the alpha property
15005     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
15006     *         the new value for the alpha property is different from the old value
15007     */
15008    boolean setAlphaNoInvalidation(float alpha) {
15009        ensureTransformationInfo();
15010        if (mTransformationInfo.mAlpha != alpha) {
15011            mTransformationInfo.mAlpha = alpha;
15012            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
15013            if (subclassHandlesAlpha) {
15014                mPrivateFlags |= PFLAG_ALPHA_SET;
15015                return true;
15016            } else {
15017                mPrivateFlags &= ~PFLAG_ALPHA_SET;
15018                mRenderNode.setAlpha(getFinalAlpha());
15019            }
15020        }
15021        return false;
15022    }
15023
15024    /**
15025     * This property is hidden and intended only for use by the Fade transition, which
15026     * animates it to produce a visual translucency that does not side-effect (or get
15027     * affected by) the real alpha property. This value is composited with the other
15028     * alpha value (and the AlphaAnimation value, when that is present) to produce
15029     * a final visual translucency result, which is what is passed into the DisplayList.
15030     *
15031     * @hide
15032     */
15033    public void setTransitionAlpha(float alpha) {
15034        ensureTransformationInfo();
15035        if (mTransformationInfo.mTransitionAlpha != alpha) {
15036            mTransformationInfo.mTransitionAlpha = alpha;
15037            mPrivateFlags &= ~PFLAG_ALPHA_SET;
15038            invalidateViewProperty(true, false);
15039            mRenderNode.setAlpha(getFinalAlpha());
15040        }
15041    }
15042
15043    /**
15044     * Calculates the visual alpha of this view, which is a combination of the actual
15045     * alpha value and the transitionAlpha value (if set).
15046     */
15047    private float getFinalAlpha() {
15048        if (mTransformationInfo != null) {
15049            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
15050        }
15051        return 1;
15052    }
15053
15054    /**
15055     * This property is hidden and intended only for use by the Fade transition, which
15056     * animates it to produce a visual translucency that does not side-effect (or get
15057     * affected by) the real alpha property. This value is composited with the other
15058     * alpha value (and the AlphaAnimation value, when that is present) to produce
15059     * a final visual translucency result, which is what is passed into the DisplayList.
15060     *
15061     * @hide
15062     */
15063    @ViewDebug.ExportedProperty(category = "drawing")
15064    public float getTransitionAlpha() {
15065        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
15066    }
15067
15068    /**
15069     * Top position of this view relative to its parent.
15070     *
15071     * @return The top of this view, in pixels.
15072     */
15073    @ViewDebug.CapturedViewProperty
15074    public final int getTop() {
15075        return mTop;
15076    }
15077
15078    /**
15079     * Sets the top position of this view relative to its parent. This method is meant to be called
15080     * by the layout system and should not generally be called otherwise, because the property
15081     * may be changed at any time by the layout.
15082     *
15083     * @param top The top of this view, in pixels.
15084     */
15085    public final void setTop(int top) {
15086        if (top != mTop) {
15087            final boolean matrixIsIdentity = hasIdentityMatrix();
15088            if (matrixIsIdentity) {
15089                if (mAttachInfo != null) {
15090                    int minTop;
15091                    int yLoc;
15092                    if (top < mTop) {
15093                        minTop = top;
15094                        yLoc = top - mTop;
15095                    } else {
15096                        minTop = mTop;
15097                        yLoc = 0;
15098                    }
15099                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
15100                }
15101            } else {
15102                // Double-invalidation is necessary to capture view's old and new areas
15103                invalidate(true);
15104            }
15105
15106            int width = mRight - mLeft;
15107            int oldHeight = mBottom - mTop;
15108
15109            mTop = top;
15110            mRenderNode.setTop(mTop);
15111
15112            sizeChange(width, mBottom - mTop, width, oldHeight);
15113
15114            if (!matrixIsIdentity) {
15115                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
15116                invalidate(true);
15117            }
15118            mBackgroundSizeChanged = true;
15119            mDefaultFocusHighlightSizeChanged = true;
15120            if (mForegroundInfo != null) {
15121                mForegroundInfo.mBoundsChanged = true;
15122            }
15123            invalidateParentIfNeeded();
15124            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
15125                // View was rejected last time it was drawn by its parent; this may have changed
15126                invalidateParentIfNeeded();
15127            }
15128        }
15129    }
15130
15131    /**
15132     * Bottom position of this view relative to its parent.
15133     *
15134     * @return The bottom of this view, in pixels.
15135     */
15136    @ViewDebug.CapturedViewProperty
15137    public final int getBottom() {
15138        return mBottom;
15139    }
15140
15141    /**
15142     * True if this view has changed since the last time being drawn.
15143     *
15144     * @return The dirty state of this view.
15145     */
15146    public boolean isDirty() {
15147        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
15148    }
15149
15150    /**
15151     * Sets the bottom position of this view relative to its parent. This method is meant to be
15152     * called by the layout system and should not generally be called otherwise, because the
15153     * property may be changed at any time by the layout.
15154     *
15155     * @param bottom The bottom of this view, in pixels.
15156     */
15157    public final void setBottom(int bottom) {
15158        if (bottom != mBottom) {
15159            final boolean matrixIsIdentity = hasIdentityMatrix();
15160            if (matrixIsIdentity) {
15161                if (mAttachInfo != null) {
15162                    int maxBottom;
15163                    if (bottom < mBottom) {
15164                        maxBottom = mBottom;
15165                    } else {
15166                        maxBottom = bottom;
15167                    }
15168                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
15169                }
15170            } else {
15171                // Double-invalidation is necessary to capture view's old and new areas
15172                invalidate(true);
15173            }
15174
15175            int width = mRight - mLeft;
15176            int oldHeight = mBottom - mTop;
15177
15178            mBottom = bottom;
15179            mRenderNode.setBottom(mBottom);
15180
15181            sizeChange(width, mBottom - mTop, width, oldHeight);
15182
15183            if (!matrixIsIdentity) {
15184                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
15185                invalidate(true);
15186            }
15187            mBackgroundSizeChanged = true;
15188            mDefaultFocusHighlightSizeChanged = true;
15189            if (mForegroundInfo != null) {
15190                mForegroundInfo.mBoundsChanged = true;
15191            }
15192            invalidateParentIfNeeded();
15193            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
15194                // View was rejected last time it was drawn by its parent; this may have changed
15195                invalidateParentIfNeeded();
15196            }
15197        }
15198    }
15199
15200    /**
15201     * Left position of this view relative to its parent.
15202     *
15203     * @return The left edge of this view, in pixels.
15204     */
15205    @ViewDebug.CapturedViewProperty
15206    public final int getLeft() {
15207        return mLeft;
15208    }
15209
15210    /**
15211     * Sets the left position of this view relative to its parent. This method is meant to be called
15212     * by the layout system and should not generally be called otherwise, because the property
15213     * may be changed at any time by the layout.
15214     *
15215     * @param left The left of this view, in pixels.
15216     */
15217    public final void setLeft(int left) {
15218        if (left != mLeft) {
15219            final boolean matrixIsIdentity = hasIdentityMatrix();
15220            if (matrixIsIdentity) {
15221                if (mAttachInfo != null) {
15222                    int minLeft;
15223                    int xLoc;
15224                    if (left < mLeft) {
15225                        minLeft = left;
15226                        xLoc = left - mLeft;
15227                    } else {
15228                        minLeft = mLeft;
15229                        xLoc = 0;
15230                    }
15231                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
15232                }
15233            } else {
15234                // Double-invalidation is necessary to capture view's old and new areas
15235                invalidate(true);
15236            }
15237
15238            int oldWidth = mRight - mLeft;
15239            int height = mBottom - mTop;
15240
15241            mLeft = left;
15242            mRenderNode.setLeft(left);
15243
15244            sizeChange(mRight - mLeft, height, oldWidth, height);
15245
15246            if (!matrixIsIdentity) {
15247                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
15248                invalidate(true);
15249            }
15250            mBackgroundSizeChanged = true;
15251            mDefaultFocusHighlightSizeChanged = true;
15252            if (mForegroundInfo != null) {
15253                mForegroundInfo.mBoundsChanged = true;
15254            }
15255            invalidateParentIfNeeded();
15256            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
15257                // View was rejected last time it was drawn by its parent; this may have changed
15258                invalidateParentIfNeeded();
15259            }
15260        }
15261    }
15262
15263    /**
15264     * Right position of this view relative to its parent.
15265     *
15266     * @return The right edge of this view, in pixels.
15267     */
15268    @ViewDebug.CapturedViewProperty
15269    public final int getRight() {
15270        return mRight;
15271    }
15272
15273    /**
15274     * Sets the right position of this view relative to its parent. This method is meant to be called
15275     * by the layout system and should not generally be called otherwise, because the property
15276     * may be changed at any time by the layout.
15277     *
15278     * @param right The right of this view, in pixels.
15279     */
15280    public final void setRight(int right) {
15281        if (right != mRight) {
15282            final boolean matrixIsIdentity = hasIdentityMatrix();
15283            if (matrixIsIdentity) {
15284                if (mAttachInfo != null) {
15285                    int maxRight;
15286                    if (right < mRight) {
15287                        maxRight = mRight;
15288                    } else {
15289                        maxRight = right;
15290                    }
15291                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
15292                }
15293            } else {
15294                // Double-invalidation is necessary to capture view's old and new areas
15295                invalidate(true);
15296            }
15297
15298            int oldWidth = mRight - mLeft;
15299            int height = mBottom - mTop;
15300
15301            mRight = right;
15302            mRenderNode.setRight(mRight);
15303
15304            sizeChange(mRight - mLeft, height, oldWidth, height);
15305
15306            if (!matrixIsIdentity) {
15307                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
15308                invalidate(true);
15309            }
15310            mBackgroundSizeChanged = true;
15311            mDefaultFocusHighlightSizeChanged = true;
15312            if (mForegroundInfo != null) {
15313                mForegroundInfo.mBoundsChanged = true;
15314            }
15315            invalidateParentIfNeeded();
15316            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
15317                // View was rejected last time it was drawn by its parent; this may have changed
15318                invalidateParentIfNeeded();
15319            }
15320        }
15321    }
15322
15323    private static float sanitizeFloatPropertyValue(float value, String propertyName) {
15324        return sanitizeFloatPropertyValue(value, propertyName, -Float.MAX_VALUE, Float.MAX_VALUE);
15325    }
15326
15327    private static float sanitizeFloatPropertyValue(float value, String propertyName,
15328            float min, float max) {
15329        // The expected "nothing bad happened" path
15330        if (value >= min && value <= max) return value;
15331
15332        if (value < min || value == Float.NEGATIVE_INFINITY) {
15333            if (sThrowOnInvalidFloatProperties) {
15334                throw new IllegalArgumentException("Cannot set '" + propertyName + "' to "
15335                        + value + ", the value must be >= " + min);
15336            }
15337            return min;
15338        }
15339
15340        if (value > max || value == Float.POSITIVE_INFINITY) {
15341            if (sThrowOnInvalidFloatProperties) {
15342                throw new IllegalArgumentException("Cannot set '" + propertyName + "' to "
15343                        + value + ", the value must be <= " + max);
15344            }
15345            return max;
15346        }
15347
15348        if (Float.isNaN(value)) {
15349            if (sThrowOnInvalidFloatProperties) {
15350                throw new IllegalArgumentException(
15351                        "Cannot set '" + propertyName + "' to Float.NaN");
15352            }
15353            return 0; // Unclear which direction this NaN went so... 0?
15354        }
15355
15356        // Shouldn't be possible to reach this.
15357        throw new IllegalStateException("How do you get here?? " + value);
15358    }
15359
15360    /**
15361     * The visual x position of this view, in pixels. This is equivalent to the
15362     * {@link #setTranslationX(float) translationX} property plus the current
15363     * {@link #getLeft() left} property.
15364     *
15365     * @return The visual x position of this view, in pixels.
15366     */
15367    @ViewDebug.ExportedProperty(category = "drawing")
15368    public float getX() {
15369        return mLeft + getTranslationX();
15370    }
15371
15372    /**
15373     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
15374     * {@link #setTranslationX(float) translationX} property to be the difference between
15375     * the x value passed in and the current {@link #getLeft() left} property.
15376     *
15377     * @param x The visual x position of this view, in pixels.
15378     */
15379    public void setX(float x) {
15380        setTranslationX(x - mLeft);
15381    }
15382
15383    /**
15384     * The visual y position of this view, in pixels. This is equivalent to the
15385     * {@link #setTranslationY(float) translationY} property plus the current
15386     * {@link #getTop() top} property.
15387     *
15388     * @return The visual y position of this view, in pixels.
15389     */
15390    @ViewDebug.ExportedProperty(category = "drawing")
15391    public float getY() {
15392        return mTop + getTranslationY();
15393    }
15394
15395    /**
15396     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
15397     * {@link #setTranslationY(float) translationY} property to be the difference between
15398     * the y value passed in and the current {@link #getTop() top} property.
15399     *
15400     * @param y The visual y position of this view, in pixels.
15401     */
15402    public void setY(float y) {
15403        setTranslationY(y - mTop);
15404    }
15405
15406    /**
15407     * The visual z position of this view, in pixels. This is equivalent to the
15408     * {@link #setTranslationZ(float) translationZ} property plus the current
15409     * {@link #getElevation() elevation} property.
15410     *
15411     * @return The visual z position of this view, in pixels.
15412     */
15413    @ViewDebug.ExportedProperty(category = "drawing")
15414    public float getZ() {
15415        return getElevation() + getTranslationZ();
15416    }
15417
15418    /**
15419     * Sets the visual z position of this view, in pixels. This is equivalent to setting the
15420     * {@link #setTranslationZ(float) translationZ} property to be the difference between
15421     * the x value passed in and the current {@link #getElevation() elevation} property.
15422     *
15423     * @param z The visual z position of this view, in pixels.
15424     */
15425    public void setZ(float z) {
15426        setTranslationZ(z - getElevation());
15427    }
15428
15429    /**
15430     * The base elevation of this view relative to its parent, in pixels.
15431     *
15432     * @return The base depth position of the view, in pixels.
15433     */
15434    @ViewDebug.ExportedProperty(category = "drawing")
15435    public float getElevation() {
15436        return mRenderNode.getElevation();
15437    }
15438
15439    /**
15440     * Sets the base elevation of this view, in pixels.
15441     *
15442     * @attr ref android.R.styleable#View_elevation
15443     */
15444    public void setElevation(float elevation) {
15445        if (elevation != getElevation()) {
15446            elevation = sanitizeFloatPropertyValue(elevation, "elevation");
15447            invalidateViewProperty(true, false);
15448            mRenderNode.setElevation(elevation);
15449            invalidateViewProperty(false, true);
15450
15451            invalidateParentIfNeededAndWasQuickRejected();
15452        }
15453    }
15454
15455    /**
15456     * The horizontal location of this view relative to its {@link #getLeft() left} position.
15457     * This position is post-layout, in addition to wherever the object's
15458     * layout placed it.
15459     *
15460     * @return The horizontal position of this view relative to its left position, in pixels.
15461     */
15462    @ViewDebug.ExportedProperty(category = "drawing")
15463    public float getTranslationX() {
15464        return mRenderNode.getTranslationX();
15465    }
15466
15467    /**
15468     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
15469     * This effectively positions the object post-layout, in addition to wherever the object's
15470     * layout placed it.
15471     *
15472     * @param translationX The horizontal position of this view relative to its left position,
15473     * in pixels.
15474     *
15475     * @attr ref android.R.styleable#View_translationX
15476     */
15477    public void setTranslationX(float translationX) {
15478        if (translationX != getTranslationX()) {
15479            invalidateViewProperty(true, false);
15480            mRenderNode.setTranslationX(translationX);
15481            invalidateViewProperty(false, true);
15482
15483            invalidateParentIfNeededAndWasQuickRejected();
15484            notifySubtreeAccessibilityStateChangedIfNeeded();
15485        }
15486    }
15487
15488    /**
15489     * The vertical location of this view relative to its {@link #getTop() top} position.
15490     * This position is post-layout, in addition to wherever the object's
15491     * layout placed it.
15492     *
15493     * @return The vertical position of this view relative to its top position,
15494     * in pixels.
15495     */
15496    @ViewDebug.ExportedProperty(category = "drawing")
15497    public float getTranslationY() {
15498        return mRenderNode.getTranslationY();
15499    }
15500
15501    /**
15502     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
15503     * This effectively positions the object post-layout, in addition to wherever the object's
15504     * layout placed it.
15505     *
15506     * @param translationY The vertical position of this view relative to its top position,
15507     * in pixels.
15508     *
15509     * @attr ref android.R.styleable#View_translationY
15510     */
15511    public void setTranslationY(float translationY) {
15512        if (translationY != getTranslationY()) {
15513            invalidateViewProperty(true, false);
15514            mRenderNode.setTranslationY(translationY);
15515            invalidateViewProperty(false, true);
15516
15517            invalidateParentIfNeededAndWasQuickRejected();
15518            notifySubtreeAccessibilityStateChangedIfNeeded();
15519        }
15520    }
15521
15522    /**
15523     * The depth location of this view relative to its {@link #getElevation() elevation}.
15524     *
15525     * @return The depth of this view relative to its elevation.
15526     */
15527    @ViewDebug.ExportedProperty(category = "drawing")
15528    public float getTranslationZ() {
15529        return mRenderNode.getTranslationZ();
15530    }
15531
15532    /**
15533     * Sets the depth location of this view relative to its {@link #getElevation() elevation}.
15534     *
15535     * @attr ref android.R.styleable#View_translationZ
15536     */
15537    public void setTranslationZ(float translationZ) {
15538        if (translationZ != getTranslationZ()) {
15539            translationZ = sanitizeFloatPropertyValue(translationZ, "translationZ");
15540            invalidateViewProperty(true, false);
15541            mRenderNode.setTranslationZ(translationZ);
15542            invalidateViewProperty(false, true);
15543
15544            invalidateParentIfNeededAndWasQuickRejected();
15545        }
15546    }
15547
15548    /** @hide */
15549    public void setAnimationMatrix(Matrix matrix) {
15550        invalidateViewProperty(true, false);
15551        mRenderNode.setAnimationMatrix(matrix);
15552        invalidateViewProperty(false, true);
15553
15554        invalidateParentIfNeededAndWasQuickRejected();
15555    }
15556
15557    /**
15558     * Returns the current StateListAnimator if exists.
15559     *
15560     * @return StateListAnimator or null if it does not exists
15561     * @see    #setStateListAnimator(android.animation.StateListAnimator)
15562     */
15563    public StateListAnimator getStateListAnimator() {
15564        return mStateListAnimator;
15565    }
15566
15567    /**
15568     * Attaches the provided StateListAnimator to this View.
15569     * <p>
15570     * Any previously attached StateListAnimator will be detached.
15571     *
15572     * @param stateListAnimator The StateListAnimator to update the view
15573     * @see android.animation.StateListAnimator
15574     */
15575    public void setStateListAnimator(StateListAnimator stateListAnimator) {
15576        if (mStateListAnimator == stateListAnimator) {
15577            return;
15578        }
15579        if (mStateListAnimator != null) {
15580            mStateListAnimator.setTarget(null);
15581        }
15582        mStateListAnimator = stateListAnimator;
15583        if (stateListAnimator != null) {
15584            stateListAnimator.setTarget(this);
15585            if (isAttachedToWindow()) {
15586                stateListAnimator.setState(getDrawableState());
15587            }
15588        }
15589    }
15590
15591    /**
15592     * Returns whether the Outline should be used to clip the contents of the View.
15593     * <p>
15594     * Note that this flag will only be respected if the View's Outline returns true from
15595     * {@link Outline#canClip()}.
15596     *
15597     * @see #setOutlineProvider(ViewOutlineProvider)
15598     * @see #setClipToOutline(boolean)
15599     */
15600    public final boolean getClipToOutline() {
15601        return mRenderNode.getClipToOutline();
15602    }
15603
15604    /**
15605     * Sets whether the View's Outline should be used to clip the contents of the View.
15606     * <p>
15607     * Only a single non-rectangular clip can be applied on a View at any time.
15608     * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float)
15609     * circular reveal} animation take priority over Outline clipping, and
15610     * child Outline clipping takes priority over Outline clipping done by a
15611     * parent.
15612     * <p>
15613     * Note that this flag will only be respected if the View's Outline returns true from
15614     * {@link Outline#canClip()}.
15615     *
15616     * @see #setOutlineProvider(ViewOutlineProvider)
15617     * @see #getClipToOutline()
15618     */
15619    public void setClipToOutline(boolean clipToOutline) {
15620        damageInParent();
15621        if (getClipToOutline() != clipToOutline) {
15622            mRenderNode.setClipToOutline(clipToOutline);
15623        }
15624    }
15625
15626    // correspond to the enum values of View_outlineProvider
15627    private static final int PROVIDER_BACKGROUND = 0;
15628    private static final int PROVIDER_NONE = 1;
15629    private static final int PROVIDER_BOUNDS = 2;
15630    private static final int PROVIDER_PADDED_BOUNDS = 3;
15631    private void setOutlineProviderFromAttribute(int providerInt) {
15632        switch (providerInt) {
15633            case PROVIDER_BACKGROUND:
15634                setOutlineProvider(ViewOutlineProvider.BACKGROUND);
15635                break;
15636            case PROVIDER_NONE:
15637                setOutlineProvider(null);
15638                break;
15639            case PROVIDER_BOUNDS:
15640                setOutlineProvider(ViewOutlineProvider.BOUNDS);
15641                break;
15642            case PROVIDER_PADDED_BOUNDS:
15643                setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS);
15644                break;
15645        }
15646    }
15647
15648    /**
15649     * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines
15650     * the shape of the shadow it casts, and enables outline clipping.
15651     * <p>
15652     * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline
15653     * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the
15654     * outline provider with this method allows this behavior to be overridden.
15655     * <p>
15656     * If the ViewOutlineProvider is null, if querying it for an outline returns false,
15657     * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast.
15658     * <p>
15659     * Only outlines that return true from {@link Outline#canClip()} may be used for clipping.
15660     *
15661     * @see #setClipToOutline(boolean)
15662     * @see #getClipToOutline()
15663     * @see #getOutlineProvider()
15664     */
15665    public void setOutlineProvider(ViewOutlineProvider provider) {
15666        mOutlineProvider = provider;
15667        invalidateOutline();
15668    }
15669
15670    /**
15671     * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline
15672     * that defines the shape of the shadow it casts, and enables outline clipping.
15673     *
15674     * @see #setOutlineProvider(ViewOutlineProvider)
15675     */
15676    public ViewOutlineProvider getOutlineProvider() {
15677        return mOutlineProvider;
15678    }
15679
15680    /**
15681     * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider}
15682     *
15683     * @see #setOutlineProvider(ViewOutlineProvider)
15684     */
15685    public void invalidateOutline() {
15686        rebuildOutline();
15687
15688        notifySubtreeAccessibilityStateChangedIfNeeded();
15689        invalidateViewProperty(false, false);
15690    }
15691
15692    /**
15693     * Internal version of {@link #invalidateOutline()} which invalidates the
15694     * outline without invalidating the view itself. This is intended to be called from
15695     * within methods in the View class itself which are the result of the view being
15696     * invalidated already. For example, when we are drawing the background of a View,
15697     * we invalidate the outline in case it changed in the meantime, but we do not
15698     * need to invalidate the view because we're already drawing the background as part
15699     * of drawing the view in response to an earlier invalidation of the view.
15700     */
15701    private void rebuildOutline() {
15702        // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow()
15703        if (mAttachInfo == null) return;
15704
15705        if (mOutlineProvider == null) {
15706            // no provider, remove outline
15707            mRenderNode.setOutline(null);
15708        } else {
15709            final Outline outline = mAttachInfo.mTmpOutline;
15710            outline.setEmpty();
15711            outline.setAlpha(1.0f);
15712
15713            mOutlineProvider.getOutline(this, outline);
15714            mRenderNode.setOutline(outline);
15715        }
15716    }
15717
15718    /**
15719     * HierarchyViewer only
15720     *
15721     * @hide
15722     */
15723    @ViewDebug.ExportedProperty(category = "drawing")
15724    public boolean hasShadow() {
15725        return mRenderNode.hasShadow();
15726    }
15727
15728    /**
15729     * Sets the color of the spot shadow that is drawn when the view has a positive Z or
15730     * elevation value.
15731     * <p>
15732     * By default the shadow color is black. Generally, this color will be opaque so the intensity
15733     * of the shadow is consistent between different views with different colors.
15734     * <p>
15735     * The opacity of the final spot shadow is a function of the shadow caster height, the
15736     * alpha channel of the outlineSpotShadowColor (typically opaque), and the
15737     * {@link android.R.attr#spotShadowAlpha} theme attribute.
15738     *
15739     * @attr ref android.R.styleable#View_outlineSpotShadowColor
15740     * @param color The color this View will cast for its elevation spot shadow.
15741     */
15742    public void setOutlineSpotShadowColor(@ColorInt int color) {
15743        if (mRenderNode.setSpotShadowColor(color)) {
15744            invalidateViewProperty(true, true);
15745        }
15746    }
15747
15748    /**
15749     * @return The shadow color set by {@link #setOutlineSpotShadowColor(int)}, or black if nothing
15750     * was set
15751     */
15752    public @ColorInt int getOutlineSpotShadowColor() {
15753        return mRenderNode.getSpotShadowColor();
15754    }
15755
15756    /**
15757     * Sets the color of the ambient shadow that is drawn when the view has a positive Z or
15758     * elevation value.
15759     * <p>
15760     * By default the shadow color is black. Generally, this color will be opaque so the intensity
15761     * of the shadow is consistent between different views with different colors.
15762     * <p>
15763     * The opacity of the final ambient shadow is a function of the shadow caster height, the
15764     * alpha channel of the outlineAmbientShadowColor (typically opaque), and the
15765     * {@link android.R.attr#ambientShadowAlpha} theme attribute.
15766     *
15767     * @attr ref android.R.styleable#View_outlineAmbientShadowColor
15768     * @param color The color this View will cast for its elevation shadow.
15769     */
15770    public void setOutlineAmbientShadowColor(@ColorInt int color) {
15771        if (mRenderNode.setAmbientShadowColor(color)) {
15772            invalidateViewProperty(true, true);
15773        }
15774    }
15775
15776    /**
15777     * @return The shadow color set by {@link #setOutlineAmbientShadowColor(int)}, or black if
15778     * nothing was set
15779     */
15780    public @ColorInt int getOutlineAmbientShadowColor() {
15781        return mRenderNode.getAmbientShadowColor();
15782    }
15783
15784
15785    /** @hide */
15786    public void setRevealClip(boolean shouldClip, float x, float y, float radius) {
15787        mRenderNode.setRevealClip(shouldClip, x, y, radius);
15788        invalidateViewProperty(false, false);
15789    }
15790
15791    /**
15792     * Hit rectangle in parent's coordinates
15793     *
15794     * @param outRect The hit rectangle of the view.
15795     */
15796    public void getHitRect(Rect outRect) {
15797        if (hasIdentityMatrix() || mAttachInfo == null) {
15798            outRect.set(mLeft, mTop, mRight, mBottom);
15799        } else {
15800            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
15801            tmpRect.set(0, 0, getWidth(), getHeight());
15802            getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect)
15803            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
15804                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
15805        }
15806    }
15807
15808    /**
15809     * Determines whether the given point, in local coordinates is inside the view.
15810     */
15811    /*package*/ final boolean pointInView(float localX, float localY) {
15812        return pointInView(localX, localY, 0);
15813    }
15814
15815    /**
15816     * Utility method to determine whether the given point, in local coordinates,
15817     * is inside the view, where the area of the view is expanded by the slop factor.
15818     * This method is called while processing touch-move events to determine if the event
15819     * is still within the view.
15820     *
15821     * @hide
15822     */
15823    public boolean pointInView(float localX, float localY, float slop) {
15824        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
15825                localY < ((mBottom - mTop) + slop);
15826    }
15827
15828    /**
15829     * When a view has focus and the user navigates away from it, the next view is searched for
15830     * starting from the rectangle filled in by this method.
15831     *
15832     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
15833     * of the view.  However, if your view maintains some idea of internal selection,
15834     * such as a cursor, or a selected row or column, you should override this method and
15835     * fill in a more specific rectangle.
15836     *
15837     * @param r The rectangle to fill in, in this view's coordinates.
15838     */
15839    public void getFocusedRect(Rect r) {
15840        getDrawingRect(r);
15841    }
15842
15843    /**
15844     * If some part of this view is not clipped by any of its parents, then
15845     * return that area in r in global (root) coordinates. To convert r to local
15846     * coordinates (without taking possible View rotations into account), offset
15847     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
15848     * If the view is completely clipped or translated out, return false.
15849     *
15850     * @param r If true is returned, r holds the global coordinates of the
15851     *        visible portion of this view.
15852     * @param globalOffset If true is returned, globalOffset holds the dx,dy
15853     *        between this view and its root. globalOffet may be null.
15854     * @return true if r is non-empty (i.e. part of the view is visible at the
15855     *         root level.
15856     */
15857    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
15858        int width = mRight - mLeft;
15859        int height = mBottom - mTop;
15860        if (width > 0 && height > 0) {
15861            r.set(0, 0, width, height);
15862            if (globalOffset != null) {
15863                globalOffset.set(-mScrollX, -mScrollY);
15864            }
15865            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
15866        }
15867        return false;
15868    }
15869
15870    public final boolean getGlobalVisibleRect(Rect r) {
15871        return getGlobalVisibleRect(r, null);
15872    }
15873
15874    public final boolean getLocalVisibleRect(Rect r) {
15875        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
15876        if (getGlobalVisibleRect(r, offset)) {
15877            r.offset(-offset.x, -offset.y); // make r local
15878            return true;
15879        }
15880        return false;
15881    }
15882
15883    /**
15884     * Offset this view's vertical location by the specified number of pixels.
15885     *
15886     * @param offset the number of pixels to offset the view by
15887     */
15888    public void offsetTopAndBottom(int offset) {
15889        if (offset != 0) {
15890            final boolean matrixIsIdentity = hasIdentityMatrix();
15891            if (matrixIsIdentity) {
15892                if (isHardwareAccelerated()) {
15893                    invalidateViewProperty(false, false);
15894                } else {
15895                    final ViewParent p = mParent;
15896                    if (p != null && mAttachInfo != null) {
15897                        final Rect r = mAttachInfo.mTmpInvalRect;
15898                        int minTop;
15899                        int maxBottom;
15900                        int yLoc;
15901                        if (offset < 0) {
15902                            minTop = mTop + offset;
15903                            maxBottom = mBottom;
15904                            yLoc = offset;
15905                        } else {
15906                            minTop = mTop;
15907                            maxBottom = mBottom + offset;
15908                            yLoc = 0;
15909                        }
15910                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
15911                        p.invalidateChild(this, r);
15912                    }
15913                }
15914            } else {
15915                invalidateViewProperty(false, false);
15916            }
15917
15918            mTop += offset;
15919            mBottom += offset;
15920            mRenderNode.offsetTopAndBottom(offset);
15921            if (isHardwareAccelerated()) {
15922                invalidateViewProperty(false, false);
15923                invalidateParentIfNeededAndWasQuickRejected();
15924            } else {
15925                if (!matrixIsIdentity) {
15926                    invalidateViewProperty(false, true);
15927                }
15928                invalidateParentIfNeeded();
15929            }
15930            notifySubtreeAccessibilityStateChangedIfNeeded();
15931        }
15932    }
15933
15934    /**
15935     * Offset this view's horizontal location by the specified amount of pixels.
15936     *
15937     * @param offset the number of pixels to offset the view by
15938     */
15939    public void offsetLeftAndRight(int offset) {
15940        if (offset != 0) {
15941            final boolean matrixIsIdentity = hasIdentityMatrix();
15942            if (matrixIsIdentity) {
15943                if (isHardwareAccelerated()) {
15944                    invalidateViewProperty(false, false);
15945                } else {
15946                    final ViewParent p = mParent;
15947                    if (p != null && mAttachInfo != null) {
15948                        final Rect r = mAttachInfo.mTmpInvalRect;
15949                        int minLeft;
15950                        int maxRight;
15951                        if (offset < 0) {
15952                            minLeft = mLeft + offset;
15953                            maxRight = mRight;
15954                        } else {
15955                            minLeft = mLeft;
15956                            maxRight = mRight + offset;
15957                        }
15958                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
15959                        p.invalidateChild(this, r);
15960                    }
15961                }
15962            } else {
15963                invalidateViewProperty(false, false);
15964            }
15965
15966            mLeft += offset;
15967            mRight += offset;
15968            mRenderNode.offsetLeftAndRight(offset);
15969            if (isHardwareAccelerated()) {
15970                invalidateViewProperty(false, false);
15971                invalidateParentIfNeededAndWasQuickRejected();
15972            } else {
15973                if (!matrixIsIdentity) {
15974                    invalidateViewProperty(false, true);
15975                }
15976                invalidateParentIfNeeded();
15977            }
15978            notifySubtreeAccessibilityStateChangedIfNeeded();
15979        }
15980    }
15981
15982    /**
15983     * Get the LayoutParams associated with this view. All views should have
15984     * layout parameters. These supply parameters to the <i>parent</i> of this
15985     * view specifying how it should be arranged. There are many subclasses of
15986     * ViewGroup.LayoutParams, and these correspond to the different subclasses
15987     * of ViewGroup that are responsible for arranging their children.
15988     *
15989     * This method may return null if this View is not attached to a parent
15990     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
15991     * was not invoked successfully. When a View is attached to a parent
15992     * ViewGroup, this method must not return null.
15993     *
15994     * @return The LayoutParams associated with this view, or null if no
15995     *         parameters have been set yet
15996     */
15997    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
15998    public ViewGroup.LayoutParams getLayoutParams() {
15999        return mLayoutParams;
16000    }
16001
16002    /**
16003     * Set the layout parameters associated with this view. These supply
16004     * parameters to the <i>parent</i> of this view specifying how it should be
16005     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
16006     * correspond to the different subclasses of ViewGroup that are responsible
16007     * for arranging their children.
16008     *
16009     * @param params The layout parameters for this view, cannot be null
16010     */
16011    public void setLayoutParams(ViewGroup.LayoutParams params) {
16012        if (params == null) {
16013            throw new NullPointerException("Layout parameters cannot be null");
16014        }
16015        mLayoutParams = params;
16016        resolveLayoutParams();
16017        if (mParent instanceof ViewGroup) {
16018            ((ViewGroup) mParent).onSetLayoutParams(this, params);
16019        }
16020        requestLayout();
16021    }
16022
16023    /**
16024     * Resolve the layout parameters depending on the resolved layout direction
16025     *
16026     * @hide
16027     */
16028    public void resolveLayoutParams() {
16029        if (mLayoutParams != null) {
16030            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
16031        }
16032    }
16033
16034    /**
16035     * Set the scrolled position of your view. This will cause a call to
16036     * {@link #onScrollChanged(int, int, int, int)} and the view will be
16037     * invalidated.
16038     * @param x the x position to scroll to
16039     * @param y the y position to scroll to
16040     */
16041    public void scrollTo(int x, int y) {
16042        if (mScrollX != x || mScrollY != y) {
16043            int oldX = mScrollX;
16044            int oldY = mScrollY;
16045            mScrollX = x;
16046            mScrollY = y;
16047            invalidateParentCaches();
16048            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
16049            if (!awakenScrollBars()) {
16050                postInvalidateOnAnimation();
16051            }
16052        }
16053    }
16054
16055    /**
16056     * Move the scrolled position of your view. This will cause a call to
16057     * {@link #onScrollChanged(int, int, int, int)} and the view will be
16058     * invalidated.
16059     * @param x the amount of pixels to scroll by horizontally
16060     * @param y the amount of pixels to scroll by vertically
16061     */
16062    public void scrollBy(int x, int y) {
16063        scrollTo(mScrollX + x, mScrollY + y);
16064    }
16065
16066    /**
16067     * <p>Trigger the scrollbars to draw. When invoked this method starts an
16068     * animation to fade the scrollbars out after a default delay. If a subclass
16069     * provides animated scrolling, the start delay should equal the duration
16070     * of the scrolling animation.</p>
16071     *
16072     * <p>The animation starts only if at least one of the scrollbars is
16073     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
16074     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
16075     * this method returns true, and false otherwise. If the animation is
16076     * started, this method calls {@link #invalidate()}; in that case the
16077     * caller should not call {@link #invalidate()}.</p>
16078     *
16079     * <p>This method should be invoked every time a subclass directly updates
16080     * the scroll parameters.</p>
16081     *
16082     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
16083     * and {@link #scrollTo(int, int)}.</p>
16084     *
16085     * @return true if the animation is played, false otherwise
16086     *
16087     * @see #awakenScrollBars(int)
16088     * @see #scrollBy(int, int)
16089     * @see #scrollTo(int, int)
16090     * @see #isHorizontalScrollBarEnabled()
16091     * @see #isVerticalScrollBarEnabled()
16092     * @see #setHorizontalScrollBarEnabled(boolean)
16093     * @see #setVerticalScrollBarEnabled(boolean)
16094     */
16095    protected boolean awakenScrollBars() {
16096        return mScrollCache != null &&
16097                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
16098    }
16099
16100    /**
16101     * Trigger the scrollbars to draw.
16102     * This method differs from awakenScrollBars() only in its default duration.
16103     * initialAwakenScrollBars() will show the scroll bars for longer than
16104     * usual to give the user more of a chance to notice them.
16105     *
16106     * @return true if the animation is played, false otherwise.
16107     */
16108    private boolean initialAwakenScrollBars() {
16109        return mScrollCache != null &&
16110                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
16111    }
16112
16113    /**
16114     * <p>
16115     * Trigger the scrollbars to draw. When invoked this method starts an
16116     * animation to fade the scrollbars out after a fixed delay. If a subclass
16117     * provides animated scrolling, the start delay should equal the duration of
16118     * the scrolling animation.
16119     * </p>
16120     *
16121     * <p>
16122     * The animation starts only if at least one of the scrollbars is enabled,
16123     * as specified by {@link #isHorizontalScrollBarEnabled()} and
16124     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
16125     * this method returns true, and false otherwise. If the animation is
16126     * started, this method calls {@link #invalidate()}; in that case the caller
16127     * should not call {@link #invalidate()}.
16128     * </p>
16129     *
16130     * <p>
16131     * This method should be invoked every time a subclass directly updates the
16132     * scroll parameters.
16133     * </p>
16134     *
16135     * @param startDelay the delay, in milliseconds, after which the animation
16136     *        should start; when the delay is 0, the animation starts
16137     *        immediately
16138     * @return true if the animation is played, false otherwise
16139     *
16140     * @see #scrollBy(int, int)
16141     * @see #scrollTo(int, int)
16142     * @see #isHorizontalScrollBarEnabled()
16143     * @see #isVerticalScrollBarEnabled()
16144     * @see #setHorizontalScrollBarEnabled(boolean)
16145     * @see #setVerticalScrollBarEnabled(boolean)
16146     */
16147    protected boolean awakenScrollBars(int startDelay) {
16148        return awakenScrollBars(startDelay, true);
16149    }
16150
16151    /**
16152     * <p>
16153     * Trigger the scrollbars to draw. When invoked this method starts an
16154     * animation to fade the scrollbars out after a fixed delay. If a subclass
16155     * provides animated scrolling, the start delay should equal the duration of
16156     * the scrolling animation.
16157     * </p>
16158     *
16159     * <p>
16160     * The animation starts only if at least one of the scrollbars is enabled,
16161     * as specified by {@link #isHorizontalScrollBarEnabled()} and
16162     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
16163     * this method returns true, and false otherwise. If the animation is
16164     * started, this method calls {@link #invalidate()} if the invalidate parameter
16165     * is set to true; in that case the caller
16166     * should not call {@link #invalidate()}.
16167     * </p>
16168     *
16169     * <p>
16170     * This method should be invoked every time a subclass directly updates the
16171     * scroll parameters.
16172     * </p>
16173     *
16174     * @param startDelay the delay, in milliseconds, after which the animation
16175     *        should start; when the delay is 0, the animation starts
16176     *        immediately
16177     *
16178     * @param invalidate Whether this method should call invalidate
16179     *
16180     * @return true if the animation is played, false otherwise
16181     *
16182     * @see #scrollBy(int, int)
16183     * @see #scrollTo(int, int)
16184     * @see #isHorizontalScrollBarEnabled()
16185     * @see #isVerticalScrollBarEnabled()
16186     * @see #setHorizontalScrollBarEnabled(boolean)
16187     * @see #setVerticalScrollBarEnabled(boolean)
16188     */
16189    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
16190        final ScrollabilityCache scrollCache = mScrollCache;
16191
16192        if (scrollCache == null || !scrollCache.fadeScrollBars) {
16193            return false;
16194        }
16195
16196        if (scrollCache.scrollBar == null) {
16197            scrollCache.scrollBar = new ScrollBarDrawable();
16198            scrollCache.scrollBar.setState(getDrawableState());
16199            scrollCache.scrollBar.setCallback(this);
16200        }
16201
16202        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
16203
16204            if (invalidate) {
16205                // Invalidate to show the scrollbars
16206                postInvalidateOnAnimation();
16207            }
16208
16209            if (scrollCache.state == ScrollabilityCache.OFF) {
16210                // FIXME: this is copied from WindowManagerService.
16211                // We should get this value from the system when it
16212                // is possible to do so.
16213                final int KEY_REPEAT_FIRST_DELAY = 750;
16214                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
16215            }
16216
16217            // Tell mScrollCache when we should start fading. This may
16218            // extend the fade start time if one was already scheduled
16219            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
16220            scrollCache.fadeStartTime = fadeStartTime;
16221            scrollCache.state = ScrollabilityCache.ON;
16222
16223            // Schedule our fader to run, unscheduling any old ones first
16224            if (mAttachInfo != null) {
16225                mAttachInfo.mHandler.removeCallbacks(scrollCache);
16226                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
16227            }
16228
16229            return true;
16230        }
16231
16232        return false;
16233    }
16234
16235    /**
16236     * Do not invalidate views which are not visible and which are not running an animation. They
16237     * will not get drawn and they should not set dirty flags as if they will be drawn
16238     */
16239    private boolean skipInvalidate() {
16240        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
16241                (!(mParent instanceof ViewGroup) ||
16242                        !((ViewGroup) mParent).isViewTransitioning(this));
16243    }
16244
16245    /**
16246     * Mark the area defined by dirty as needing to be drawn. If the view is
16247     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
16248     * point in the future.
16249     * <p>
16250     * This must be called from a UI thread. To call from a non-UI thread, call
16251     * {@link #postInvalidate()}.
16252     * <p>
16253     * <b>WARNING:</b> In API 19 and below, this method may be destructive to
16254     * {@code dirty}.
16255     *
16256     * @param dirty the rectangle representing the bounds of the dirty region
16257     *
16258     * @deprecated The switch to hardware accelerated rendering in API 14 reduced
16259     * the importance of the dirty rectangle. In API 21 the given rectangle is
16260     * ignored entirely in favor of an internally-calculated area instead.
16261     * Because of this, clients are encouraged to just call {@link #invalidate()}.
16262     */
16263    @Deprecated
16264    public void invalidate(Rect dirty) {
16265        final int scrollX = mScrollX;
16266        final int scrollY = mScrollY;
16267        invalidateInternal(dirty.left - scrollX, dirty.top - scrollY,
16268                dirty.right - scrollX, dirty.bottom - scrollY, true, false);
16269    }
16270
16271    /**
16272     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The
16273     * coordinates of the dirty rect are relative to the view. If the view is
16274     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
16275     * point in the future.
16276     * <p>
16277     * This must be called from a UI thread. To call from a non-UI thread, call
16278     * {@link #postInvalidate()}.
16279     *
16280     * @param l the left position of the dirty region
16281     * @param t the top position of the dirty region
16282     * @param r the right position of the dirty region
16283     * @param b the bottom position of the dirty region
16284     *
16285     * @deprecated The switch to hardware accelerated rendering in API 14 reduced
16286     * the importance of the dirty rectangle. In API 21 the given rectangle is
16287     * ignored entirely in favor of an internally-calculated area instead.
16288     * Because of this, clients are encouraged to just call {@link #invalidate()}.
16289     */
16290    @Deprecated
16291    public void invalidate(int l, int t, int r, int b) {
16292        final int scrollX = mScrollX;
16293        final int scrollY = mScrollY;
16294        invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false);
16295    }
16296
16297    /**
16298     * Invalidate the whole view. If the view is visible,
16299     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
16300     * the future.
16301     * <p>
16302     * This must be called from a UI thread. To call from a non-UI thread, call
16303     * {@link #postInvalidate()}.
16304     */
16305    public void invalidate() {
16306        invalidate(true);
16307    }
16308
16309    /**
16310     * This is where the invalidate() work actually happens. A full invalidate()
16311     * causes the drawing cache to be invalidated, but this function can be
16312     * called with invalidateCache set to false to skip that invalidation step
16313     * for cases that do not need it (for example, a component that remains at
16314     * the same dimensions with the same content).
16315     *
16316     * @param invalidateCache Whether the drawing cache for this view should be
16317     *            invalidated as well. This is usually true for a full
16318     *            invalidate, but may be set to false if the View's contents or
16319     *            dimensions have not changed.
16320     * @hide
16321     */
16322    public void invalidate(boolean invalidateCache) {
16323        invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
16324    }
16325
16326    void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
16327            boolean fullInvalidate) {
16328        if (mGhostView != null) {
16329            mGhostView.invalidate(true);
16330            return;
16331        }
16332
16333        if (skipInvalidate()) {
16334            return;
16335        }
16336
16337        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)
16338                || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID)
16339                || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED
16340                || (fullInvalidate && isOpaque() != mLastIsOpaque)) {
16341            if (fullInvalidate) {
16342                mLastIsOpaque = isOpaque();
16343                mPrivateFlags &= ~PFLAG_DRAWN;
16344            }
16345
16346            mPrivateFlags |= PFLAG_DIRTY;
16347
16348            if (invalidateCache) {
16349                mPrivateFlags |= PFLAG_INVALIDATED;
16350                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
16351            }
16352
16353            // Propagate the damage rectangle to the parent view.
16354            final AttachInfo ai = mAttachInfo;
16355            final ViewParent p = mParent;
16356            if (p != null && ai != null && l < r && t < b) {
16357                final Rect damage = ai.mTmpInvalRect;
16358                damage.set(l, t, r, b);
16359                p.invalidateChild(this, damage);
16360            }
16361
16362            // Damage the entire projection receiver, if necessary.
16363            if (mBackground != null && mBackground.isProjected()) {
16364                final View receiver = getProjectionReceiver();
16365                if (receiver != null) {
16366                    receiver.damageInParent();
16367                }
16368            }
16369        }
16370    }
16371
16372    /**
16373     * @return this view's projection receiver, or {@code null} if none exists
16374     */
16375    private View getProjectionReceiver() {
16376        ViewParent p = getParent();
16377        while (p != null && p instanceof View) {
16378            final View v = (View) p;
16379            if (v.isProjectionReceiver()) {
16380                return v;
16381            }
16382            p = p.getParent();
16383        }
16384
16385        return null;
16386    }
16387
16388    /**
16389     * @return whether the view is a projection receiver
16390     */
16391    private boolean isProjectionReceiver() {
16392        return mBackground != null;
16393    }
16394
16395    /**
16396     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
16397     * set any flags or handle all of the cases handled by the default invalidation methods.
16398     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
16399     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
16400     * walk up the hierarchy, transforming the dirty rect as necessary.
16401     *
16402     * The method also handles normal invalidation logic if display list properties are not
16403     * being used in this view. The invalidateParent and forceRedraw flags are used by that
16404     * backup approach, to handle these cases used in the various property-setting methods.
16405     *
16406     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
16407     * are not being used in this view
16408     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
16409     * list properties are not being used in this view
16410     */
16411    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
16412        if (!isHardwareAccelerated()
16413                || !mRenderNode.isValid()
16414                || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) {
16415            if (invalidateParent) {
16416                invalidateParentCaches();
16417            }
16418            if (forceRedraw) {
16419                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
16420            }
16421            invalidate(false);
16422        } else {
16423            damageInParent();
16424        }
16425    }
16426
16427    /**
16428     * Tells the parent view to damage this view's bounds.
16429     *
16430     * @hide
16431     */
16432    protected void damageInParent() {
16433        if (mParent != null && mAttachInfo != null) {
16434            mParent.onDescendantInvalidated(this, this);
16435        }
16436    }
16437
16438    /**
16439     * Utility method to transform a given Rect by the current matrix of this view.
16440     */
16441    void transformRect(final Rect rect) {
16442        if (!getMatrix().isIdentity()) {
16443            RectF boundingRect = mAttachInfo.mTmpTransformRect;
16444            boundingRect.set(rect);
16445            getMatrix().mapRect(boundingRect);
16446            rect.set((int) Math.floor(boundingRect.left),
16447                    (int) Math.floor(boundingRect.top),
16448                    (int) Math.ceil(boundingRect.right),
16449                    (int) Math.ceil(boundingRect.bottom));
16450        }
16451    }
16452
16453    /**
16454     * Used to indicate that the parent of this view should clear its caches. This functionality
16455     * is used to force the parent to rebuild its display list (when hardware-accelerated),
16456     * which is necessary when various parent-managed properties of the view change, such as
16457     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
16458     * clears the parent caches and does not causes an invalidate event.
16459     *
16460     * @hide
16461     */
16462    protected void invalidateParentCaches() {
16463        if (mParent instanceof View) {
16464            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
16465        }
16466    }
16467
16468    /**
16469     * Used to indicate that the parent of this view should be invalidated. This functionality
16470     * is used to force the parent to rebuild its display list (when hardware-accelerated),
16471     * which is necessary when various parent-managed properties of the view change, such as
16472     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
16473     * an invalidation event to the parent.
16474     *
16475     * @hide
16476     */
16477    protected void invalidateParentIfNeeded() {
16478        if (isHardwareAccelerated() && mParent instanceof View) {
16479            ((View) mParent).invalidate(true);
16480        }
16481    }
16482
16483    /**
16484     * @hide
16485     */
16486    protected void invalidateParentIfNeededAndWasQuickRejected() {
16487        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) {
16488            // View was rejected last time it was drawn by its parent; this may have changed
16489            invalidateParentIfNeeded();
16490        }
16491    }
16492
16493    /**
16494     * Indicates whether this View is opaque. An opaque View guarantees that it will
16495     * draw all the pixels overlapping its bounds using a fully opaque color.
16496     *
16497     * Subclasses of View should override this method whenever possible to indicate
16498     * whether an instance is opaque. Opaque Views are treated in a special way by
16499     * the View hierarchy, possibly allowing it to perform optimizations during
16500     * invalidate/draw passes.
16501     *
16502     * @return True if this View is guaranteed to be fully opaque, false otherwise.
16503     */
16504    @ViewDebug.ExportedProperty(category = "drawing")
16505    public boolean isOpaque() {
16506        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
16507                getFinalAlpha() >= 1.0f;
16508    }
16509
16510    /**
16511     * @hide
16512     */
16513    protected void computeOpaqueFlags() {
16514        // Opaque if:
16515        //   - Has a background
16516        //   - Background is opaque
16517        //   - Doesn't have scrollbars or scrollbars overlay
16518
16519        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
16520            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
16521        } else {
16522            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
16523        }
16524
16525        final int flags = mViewFlags;
16526        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
16527                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
16528                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
16529            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
16530        } else {
16531            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
16532        }
16533    }
16534
16535    /**
16536     * @hide
16537     */
16538    protected boolean hasOpaqueScrollbars() {
16539        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
16540    }
16541
16542    /**
16543     * @return A handler associated with the thread running the View. This
16544     * handler can be used to pump events in the UI events queue.
16545     */
16546    public Handler getHandler() {
16547        final AttachInfo attachInfo = mAttachInfo;
16548        if (attachInfo != null) {
16549            return attachInfo.mHandler;
16550        }
16551        return null;
16552    }
16553
16554    /**
16555     * Returns the queue of runnable for this view.
16556     *
16557     * @return the queue of runnables for this view
16558     */
16559    private HandlerActionQueue getRunQueue() {
16560        if (mRunQueue == null) {
16561            mRunQueue = new HandlerActionQueue();
16562        }
16563        return mRunQueue;
16564    }
16565
16566    /**
16567     * Gets the view root associated with the View.
16568     * @return The view root, or null if none.
16569     * @hide
16570     */
16571    public ViewRootImpl getViewRootImpl() {
16572        if (mAttachInfo != null) {
16573            return mAttachInfo.mViewRootImpl;
16574        }
16575        return null;
16576    }
16577
16578    /**
16579     * @hide
16580     */
16581    public ThreadedRenderer getThreadedRenderer() {
16582        return mAttachInfo != null ? mAttachInfo.mThreadedRenderer : null;
16583    }
16584
16585    /**
16586     * <p>Causes the Runnable to be added to the message queue.
16587     * The runnable will be run on the user interface thread.</p>
16588     *
16589     * @param action The Runnable that will be executed.
16590     *
16591     * @return Returns true if the Runnable was successfully placed in to the
16592     *         message queue.  Returns false on failure, usually because the
16593     *         looper processing the message queue is exiting.
16594     *
16595     * @see #postDelayed
16596     * @see #removeCallbacks
16597     */
16598    public boolean post(Runnable action) {
16599        final AttachInfo attachInfo = mAttachInfo;
16600        if (attachInfo != null) {
16601            return attachInfo.mHandler.post(action);
16602        }
16603
16604        // Postpone the runnable until we know on which thread it needs to run.
16605        // Assume that the runnable will be successfully placed after attach.
16606        getRunQueue().post(action);
16607        return true;
16608    }
16609
16610    /**
16611     * <p>Causes the Runnable to be added to the message queue, to be run
16612     * after the specified amount of time elapses.
16613     * The runnable will be run on the user interface thread.</p>
16614     *
16615     * @param action The Runnable that will be executed.
16616     * @param delayMillis The delay (in milliseconds) until the Runnable
16617     *        will be executed.
16618     *
16619     * @return true if the Runnable was successfully placed in to the
16620     *         message queue.  Returns false on failure, usually because the
16621     *         looper processing the message queue is exiting.  Note that a
16622     *         result of true does not mean the Runnable will be processed --
16623     *         if the looper is quit before the delivery time of the message
16624     *         occurs then the message will be dropped.
16625     *
16626     * @see #post
16627     * @see #removeCallbacks
16628     */
16629    public boolean postDelayed(Runnable action, long delayMillis) {
16630        final AttachInfo attachInfo = mAttachInfo;
16631        if (attachInfo != null) {
16632            return attachInfo.mHandler.postDelayed(action, delayMillis);
16633        }
16634
16635        // Postpone the runnable until we know on which thread it needs to run.
16636        // Assume that the runnable will be successfully placed after attach.
16637        getRunQueue().postDelayed(action, delayMillis);
16638        return true;
16639    }
16640
16641    /**
16642     * <p>Causes the Runnable to execute on the next animation time step.
16643     * The runnable will be run on the user interface thread.</p>
16644     *
16645     * @param action The Runnable that will be executed.
16646     *
16647     * @see #postOnAnimationDelayed
16648     * @see #removeCallbacks
16649     */
16650    public void postOnAnimation(Runnable action) {
16651        final AttachInfo attachInfo = mAttachInfo;
16652        if (attachInfo != null) {
16653            attachInfo.mViewRootImpl.mChoreographer.postCallback(
16654                    Choreographer.CALLBACK_ANIMATION, action, null);
16655        } else {
16656            // Postpone the runnable until we know
16657            // on which thread it needs to run.
16658            getRunQueue().post(action);
16659        }
16660    }
16661
16662    /**
16663     * <p>Causes the Runnable to execute on the next animation time step,
16664     * after the specified amount of time elapses.
16665     * The runnable will be run on the user interface thread.</p>
16666     *
16667     * @param action The Runnable that will be executed.
16668     * @param delayMillis The delay (in milliseconds) until the Runnable
16669     *        will be executed.
16670     *
16671     * @see #postOnAnimation
16672     * @see #removeCallbacks
16673     */
16674    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
16675        final AttachInfo attachInfo = mAttachInfo;
16676        if (attachInfo != null) {
16677            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
16678                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
16679        } else {
16680            // Postpone the runnable until we know
16681            // on which thread it needs to run.
16682            getRunQueue().postDelayed(action, delayMillis);
16683        }
16684    }
16685
16686    /**
16687     * <p>Removes the specified Runnable from the message queue.</p>
16688     *
16689     * @param action The Runnable to remove from the message handling queue
16690     *
16691     * @return true if this view could ask the Handler to remove the Runnable,
16692     *         false otherwise. When the returned value is true, the Runnable
16693     *         may or may not have been actually removed from the message queue
16694     *         (for instance, if the Runnable was not in the queue already.)
16695     *
16696     * @see #post
16697     * @see #postDelayed
16698     * @see #postOnAnimation
16699     * @see #postOnAnimationDelayed
16700     */
16701    public boolean removeCallbacks(Runnable action) {
16702        if (action != null) {
16703            final AttachInfo attachInfo = mAttachInfo;
16704            if (attachInfo != null) {
16705                attachInfo.mHandler.removeCallbacks(action);
16706                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
16707                        Choreographer.CALLBACK_ANIMATION, action, null);
16708            }
16709            getRunQueue().removeCallbacks(action);
16710        }
16711        return true;
16712    }
16713
16714    /**
16715     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
16716     * Use this to invalidate the View from a non-UI thread.</p>
16717     *
16718     * <p>This method can be invoked from outside of the UI thread
16719     * only when this View is attached to a window.</p>
16720     *
16721     * @see #invalidate()
16722     * @see #postInvalidateDelayed(long)
16723     */
16724    public void postInvalidate() {
16725        postInvalidateDelayed(0);
16726    }
16727
16728    /**
16729     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
16730     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
16731     *
16732     * <p>This method can be invoked from outside of the UI thread
16733     * only when this View is attached to a window.</p>
16734     *
16735     * @param left The left coordinate of the rectangle to invalidate.
16736     * @param top The top coordinate of the rectangle to invalidate.
16737     * @param right The right coordinate of the rectangle to invalidate.
16738     * @param bottom The bottom coordinate of the rectangle to invalidate.
16739     *
16740     * @see #invalidate(int, int, int, int)
16741     * @see #invalidate(Rect)
16742     * @see #postInvalidateDelayed(long, int, int, int, int)
16743     */
16744    public void postInvalidate(int left, int top, int right, int bottom) {
16745        postInvalidateDelayed(0, left, top, right, bottom);
16746    }
16747
16748    /**
16749     * <p>Cause an invalidate to happen on a subsequent cycle through the event
16750     * loop. Waits for the specified amount of time.</p>
16751     *
16752     * <p>This method can be invoked from outside of the UI thread
16753     * only when this View is attached to a window.</p>
16754     *
16755     * @param delayMilliseconds the duration in milliseconds to delay the
16756     *         invalidation by
16757     *
16758     * @see #invalidate()
16759     * @see #postInvalidate()
16760     */
16761    public void postInvalidateDelayed(long delayMilliseconds) {
16762        // We try only with the AttachInfo because there's no point in invalidating
16763        // if we are not attached to our window
16764        final AttachInfo attachInfo = mAttachInfo;
16765        if (attachInfo != null) {
16766            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
16767        }
16768    }
16769
16770    /**
16771     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
16772     * through the event loop. Waits for the specified amount of time.</p>
16773     *
16774     * <p>This method can be invoked from outside of the UI thread
16775     * only when this View is attached to a window.</p>
16776     *
16777     * @param delayMilliseconds the duration in milliseconds to delay the
16778     *         invalidation by
16779     * @param left The left coordinate of the rectangle to invalidate.
16780     * @param top The top coordinate of the rectangle to invalidate.
16781     * @param right The right coordinate of the rectangle to invalidate.
16782     * @param bottom The bottom coordinate of the rectangle to invalidate.
16783     *
16784     * @see #invalidate(int, int, int, int)
16785     * @see #invalidate(Rect)
16786     * @see #postInvalidate(int, int, int, int)
16787     */
16788    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
16789            int right, int bottom) {
16790
16791        // We try only with the AttachInfo because there's no point in invalidating
16792        // if we are not attached to our window
16793        final AttachInfo attachInfo = mAttachInfo;
16794        if (attachInfo != null) {
16795            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
16796            info.target = this;
16797            info.left = left;
16798            info.top = top;
16799            info.right = right;
16800            info.bottom = bottom;
16801
16802            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
16803        }
16804    }
16805
16806    /**
16807     * <p>Cause an invalidate to happen on the next animation time step, typically the
16808     * 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     * @see #invalidate()
16814     */
16815    public void postInvalidateOnAnimation() {
16816        // We try only with the AttachInfo because there's no point in invalidating
16817        // if we are not attached to our window
16818        final AttachInfo attachInfo = mAttachInfo;
16819        if (attachInfo != null) {
16820            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
16821        }
16822    }
16823
16824    /**
16825     * <p>Cause an invalidate of the specified area to happen on the next animation
16826     * time step, typically the next display frame.</p>
16827     *
16828     * <p>This method can be invoked from outside of the UI thread
16829     * only when this View is attached to a window.</p>
16830     *
16831     * @param left The left coordinate of the rectangle to invalidate.
16832     * @param top The top coordinate of the rectangle to invalidate.
16833     * @param right The right coordinate of the rectangle to invalidate.
16834     * @param bottom The bottom coordinate of the rectangle to invalidate.
16835     *
16836     * @see #invalidate(int, int, int, int)
16837     * @see #invalidate(Rect)
16838     */
16839    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
16840        // We try only with the AttachInfo because there's no point in invalidating
16841        // if we are not attached to our window
16842        final AttachInfo attachInfo = mAttachInfo;
16843        if (attachInfo != null) {
16844            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
16845            info.target = this;
16846            info.left = left;
16847            info.top = top;
16848            info.right = right;
16849            info.bottom = bottom;
16850
16851            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
16852        }
16853    }
16854
16855    /**
16856     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
16857     * This event is sent at most once every
16858     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
16859     */
16860    private void postSendViewScrolledAccessibilityEventCallback(int dx, int dy) {
16861        if (mSendViewScrolledAccessibilityEvent == null) {
16862            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
16863        }
16864        mSendViewScrolledAccessibilityEvent.post(dx, dy);
16865    }
16866
16867    /**
16868     * Called by a parent to request that a child update its values for mScrollX
16869     * and mScrollY if necessary. This will typically be done if the child is
16870     * animating a scroll using a {@link android.widget.Scroller Scroller}
16871     * object.
16872     */
16873    public void computeScroll() {
16874    }
16875
16876    /**
16877     * <p>Indicate whether the horizontal edges are faded when the view is
16878     * scrolled horizontally.</p>
16879     *
16880     * @return true if the horizontal edges should are faded on scroll, false
16881     *         otherwise
16882     *
16883     * @see #setHorizontalFadingEdgeEnabled(boolean)
16884     *
16885     * @attr ref android.R.styleable#View_requiresFadingEdge
16886     */
16887    public boolean isHorizontalFadingEdgeEnabled() {
16888        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
16889    }
16890
16891    /**
16892     * <p>Define whether the horizontal edges should be faded when this view
16893     * is scrolled horizontally.</p>
16894     *
16895     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
16896     *                                    be faded when the view is scrolled
16897     *                                    horizontally
16898     *
16899     * @see #isHorizontalFadingEdgeEnabled()
16900     *
16901     * @attr ref android.R.styleable#View_requiresFadingEdge
16902     */
16903    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
16904        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
16905            if (horizontalFadingEdgeEnabled) {
16906                initScrollCache();
16907            }
16908
16909            mViewFlags ^= FADING_EDGE_HORIZONTAL;
16910        }
16911    }
16912
16913    /**
16914     * <p>Indicate whether the vertical edges are faded when the view is
16915     * scrolled horizontally.</p>
16916     *
16917     * @return true if the vertical edges should are faded on scroll, false
16918     *         otherwise
16919     *
16920     * @see #setVerticalFadingEdgeEnabled(boolean)
16921     *
16922     * @attr ref android.R.styleable#View_requiresFadingEdge
16923     */
16924    public boolean isVerticalFadingEdgeEnabled() {
16925        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
16926    }
16927
16928    /**
16929     * <p>Define whether the vertical edges should be faded when this view
16930     * is scrolled vertically.</p>
16931     *
16932     * @param verticalFadingEdgeEnabled true if the vertical edges should
16933     *                                  be faded when the view is scrolled
16934     *                                  vertically
16935     *
16936     * @see #isVerticalFadingEdgeEnabled()
16937     *
16938     * @attr ref android.R.styleable#View_requiresFadingEdge
16939     */
16940    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
16941        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
16942            if (verticalFadingEdgeEnabled) {
16943                initScrollCache();
16944            }
16945
16946            mViewFlags ^= FADING_EDGE_VERTICAL;
16947        }
16948    }
16949
16950    /**
16951     * Returns the strength, or intensity, of the top faded edge. The strength is
16952     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
16953     * returns 0.0 or 1.0 but no value in between.
16954     *
16955     * Subclasses should override this method to provide a smoother fade transition
16956     * when scrolling occurs.
16957     *
16958     * @return the intensity of the top fade as a float between 0.0f and 1.0f
16959     */
16960    protected float getTopFadingEdgeStrength() {
16961        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
16962    }
16963
16964    /**
16965     * Returns the strength, or intensity, of the bottom faded edge. The strength is
16966     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
16967     * returns 0.0 or 1.0 but no value in between.
16968     *
16969     * Subclasses should override this method to provide a smoother fade transition
16970     * when scrolling occurs.
16971     *
16972     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
16973     */
16974    protected float getBottomFadingEdgeStrength() {
16975        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
16976                computeVerticalScrollRange() ? 1.0f : 0.0f;
16977    }
16978
16979    /**
16980     * Returns the strength, or intensity, of the left faded edge. The strength is
16981     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
16982     * returns 0.0 or 1.0 but no value in between.
16983     *
16984     * Subclasses should override this method to provide a smoother fade transition
16985     * when scrolling occurs.
16986     *
16987     * @return the intensity of the left fade as a float between 0.0f and 1.0f
16988     */
16989    protected float getLeftFadingEdgeStrength() {
16990        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
16991    }
16992
16993    /**
16994     * Returns the strength, or intensity, of the right faded edge. The strength is
16995     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
16996     * returns 0.0 or 1.0 but no value in between.
16997     *
16998     * Subclasses should override this method to provide a smoother fade transition
16999     * when scrolling occurs.
17000     *
17001     * @return the intensity of the right fade as a float between 0.0f and 1.0f
17002     */
17003    protected float getRightFadingEdgeStrength() {
17004        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
17005                computeHorizontalScrollRange() ? 1.0f : 0.0f;
17006    }
17007
17008    /**
17009     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
17010     * scrollbar is not drawn by default.</p>
17011     *
17012     * @return true if the horizontal scrollbar should be painted, false
17013     *         otherwise
17014     *
17015     * @see #setHorizontalScrollBarEnabled(boolean)
17016     */
17017    public boolean isHorizontalScrollBarEnabled() {
17018        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
17019    }
17020
17021    /**
17022     * <p>Define whether the horizontal scrollbar should be drawn or not. The
17023     * scrollbar is not drawn by default.</p>
17024     *
17025     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
17026     *                                   be painted
17027     *
17028     * @see #isHorizontalScrollBarEnabled()
17029     */
17030    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
17031        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
17032            mViewFlags ^= SCROLLBARS_HORIZONTAL;
17033            computeOpaqueFlags();
17034            resolvePadding();
17035        }
17036    }
17037
17038    /**
17039     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
17040     * scrollbar is not drawn by default.</p>
17041     *
17042     * @return true if the vertical scrollbar should be painted, false
17043     *         otherwise
17044     *
17045     * @see #setVerticalScrollBarEnabled(boolean)
17046     */
17047    public boolean isVerticalScrollBarEnabled() {
17048        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
17049    }
17050
17051    /**
17052     * <p>Define whether the vertical scrollbar should be drawn or not. The
17053     * scrollbar is not drawn by default.</p>
17054     *
17055     * @param verticalScrollBarEnabled true if the vertical scrollbar should
17056     *                                 be painted
17057     *
17058     * @see #isVerticalScrollBarEnabled()
17059     */
17060    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
17061        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
17062            mViewFlags ^= SCROLLBARS_VERTICAL;
17063            computeOpaqueFlags();
17064            resolvePadding();
17065        }
17066    }
17067
17068    /**
17069     * @hide
17070     */
17071    protected void recomputePadding() {
17072        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
17073    }
17074
17075    /**
17076     * Define whether scrollbars will fade when the view is not scrolling.
17077     *
17078     * @param fadeScrollbars whether to enable fading
17079     *
17080     * @attr ref android.R.styleable#View_fadeScrollbars
17081     */
17082    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
17083        initScrollCache();
17084        final ScrollabilityCache scrollabilityCache = mScrollCache;
17085        scrollabilityCache.fadeScrollBars = fadeScrollbars;
17086        if (fadeScrollbars) {
17087            scrollabilityCache.state = ScrollabilityCache.OFF;
17088        } else {
17089            scrollabilityCache.state = ScrollabilityCache.ON;
17090        }
17091    }
17092
17093    /**
17094     *
17095     * Returns true if scrollbars will fade when this view is not scrolling
17096     *
17097     * @return true if scrollbar fading is enabled
17098     *
17099     * @attr ref android.R.styleable#View_fadeScrollbars
17100     */
17101    public boolean isScrollbarFadingEnabled() {
17102        return mScrollCache != null && mScrollCache.fadeScrollBars;
17103    }
17104
17105    /**
17106     *
17107     * Returns the delay before scrollbars fade.
17108     *
17109     * @return the delay before scrollbars fade
17110     *
17111     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
17112     */
17113    public int getScrollBarDefaultDelayBeforeFade() {
17114        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
17115                mScrollCache.scrollBarDefaultDelayBeforeFade;
17116    }
17117
17118    /**
17119     * Define the delay before scrollbars fade.
17120     *
17121     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
17122     *
17123     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
17124     */
17125    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
17126        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
17127    }
17128
17129    /**
17130     *
17131     * Returns the scrollbar fade duration.
17132     *
17133     * @return the scrollbar fade duration, in milliseconds
17134     *
17135     * @attr ref android.R.styleable#View_scrollbarFadeDuration
17136     */
17137    public int getScrollBarFadeDuration() {
17138        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
17139                mScrollCache.scrollBarFadeDuration;
17140    }
17141
17142    /**
17143     * Define the scrollbar fade duration.
17144     *
17145     * @param scrollBarFadeDuration - the scrollbar fade duration, in milliseconds
17146     *
17147     * @attr ref android.R.styleable#View_scrollbarFadeDuration
17148     */
17149    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
17150        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
17151    }
17152
17153    /**
17154     *
17155     * Returns the scrollbar size.
17156     *
17157     * @return the scrollbar size
17158     *
17159     * @attr ref android.R.styleable#View_scrollbarSize
17160     */
17161    public int getScrollBarSize() {
17162        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
17163                mScrollCache.scrollBarSize;
17164    }
17165
17166    /**
17167     * Define the scrollbar size.
17168     *
17169     * @param scrollBarSize - the scrollbar size
17170     *
17171     * @attr ref android.R.styleable#View_scrollbarSize
17172     */
17173    public void setScrollBarSize(int scrollBarSize) {
17174        getScrollCache().scrollBarSize = scrollBarSize;
17175    }
17176
17177    /**
17178     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
17179     * inset. When inset, they add to the padding of the view. And the scrollbars
17180     * can be drawn inside the padding area or on the edge of the view. For example,
17181     * if a view has a background drawable and you want to draw the scrollbars
17182     * inside the padding specified by the drawable, you can use
17183     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
17184     * appear at the edge of the view, ignoring the padding, then you can use
17185     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
17186     * @param style the style of the scrollbars. Should be one of
17187     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
17188     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
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    public void setScrollBarStyle(@ScrollBarStyle int style) {
17197        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
17198            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
17199            computeOpaqueFlags();
17200            resolvePadding();
17201        }
17202    }
17203
17204    /**
17205     * <p>Returns the current scrollbar style.</p>
17206     * @return the current scrollbar style
17207     * @see #SCROLLBARS_INSIDE_OVERLAY
17208     * @see #SCROLLBARS_INSIDE_INSET
17209     * @see #SCROLLBARS_OUTSIDE_OVERLAY
17210     * @see #SCROLLBARS_OUTSIDE_INSET
17211     *
17212     * @attr ref android.R.styleable#View_scrollbarStyle
17213     */
17214    @ViewDebug.ExportedProperty(mapping = {
17215            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
17216            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
17217            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
17218            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
17219    })
17220    @ScrollBarStyle
17221    public int getScrollBarStyle() {
17222        return mViewFlags & SCROLLBARS_STYLE_MASK;
17223    }
17224
17225    /**
17226     * <p>Compute the horizontal range that the horizontal scrollbar
17227     * represents.</p>
17228     *
17229     * <p>The range is expressed in arbitrary units that must be the same as the
17230     * units used by {@link #computeHorizontalScrollExtent()} and
17231     * {@link #computeHorizontalScrollOffset()}.</p>
17232     *
17233     * <p>The default range is the drawing width of this view.</p>
17234     *
17235     * @return the total horizontal range represented by the horizontal
17236     *         scrollbar
17237     *
17238     * @see #computeHorizontalScrollExtent()
17239     * @see #computeHorizontalScrollOffset()
17240     * @see android.widget.ScrollBarDrawable
17241     */
17242    protected int computeHorizontalScrollRange() {
17243        return getWidth();
17244    }
17245
17246    /**
17247     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
17248     * within the horizontal range. This value is used to compute the position
17249     * of the thumb within the scrollbar's track.</p>
17250     *
17251     * <p>The range is expressed in arbitrary units that must be the same as the
17252     * units used by {@link #computeHorizontalScrollRange()} and
17253     * {@link #computeHorizontalScrollExtent()}.</p>
17254     *
17255     * <p>The default offset is the scroll offset of this view.</p>
17256     *
17257     * @return the horizontal offset of the scrollbar's thumb
17258     *
17259     * @see #computeHorizontalScrollRange()
17260     * @see #computeHorizontalScrollExtent()
17261     * @see android.widget.ScrollBarDrawable
17262     */
17263    protected int computeHorizontalScrollOffset() {
17264        return mScrollX;
17265    }
17266
17267    /**
17268     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
17269     * within the horizontal range. This value is used to compute the length
17270     * of the thumb within the scrollbar's track.</p>
17271     *
17272     * <p>The range is expressed in arbitrary units that must be the same as the
17273     * units used by {@link #computeHorizontalScrollRange()} and
17274     * {@link #computeHorizontalScrollOffset()}.</p>
17275     *
17276     * <p>The default extent is the drawing width of this view.</p>
17277     *
17278     * @return the horizontal extent of the scrollbar's thumb
17279     *
17280     * @see #computeHorizontalScrollRange()
17281     * @see #computeHorizontalScrollOffset()
17282     * @see android.widget.ScrollBarDrawable
17283     */
17284    protected int computeHorizontalScrollExtent() {
17285        return getWidth();
17286    }
17287
17288    /**
17289     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
17290     *
17291     * <p>The range is expressed in arbitrary units that must be the same as the
17292     * units used by {@link #computeVerticalScrollExtent()} and
17293     * {@link #computeVerticalScrollOffset()}.</p>
17294     *
17295     * @return the total vertical range represented by the vertical scrollbar
17296     *
17297     * <p>The default range is the drawing height of this view.</p>
17298     *
17299     * @see #computeVerticalScrollExtent()
17300     * @see #computeVerticalScrollOffset()
17301     * @see android.widget.ScrollBarDrawable
17302     */
17303    protected int computeVerticalScrollRange() {
17304        return getHeight();
17305    }
17306
17307    /**
17308     * <p>Compute the vertical offset of the vertical scrollbar's thumb
17309     * within the horizontal range. This value is used to compute the position
17310     * of the thumb within the scrollbar's track.</p>
17311     *
17312     * <p>The range is expressed in arbitrary units that must be the same as the
17313     * units used by {@link #computeVerticalScrollRange()} and
17314     * {@link #computeVerticalScrollExtent()}.</p>
17315     *
17316     * <p>The default offset is the scroll offset of this view.</p>
17317     *
17318     * @return the vertical offset of the scrollbar's thumb
17319     *
17320     * @see #computeVerticalScrollRange()
17321     * @see #computeVerticalScrollExtent()
17322     * @see android.widget.ScrollBarDrawable
17323     */
17324    protected int computeVerticalScrollOffset() {
17325        return mScrollY;
17326    }
17327
17328    /**
17329     * <p>Compute the vertical extent of the vertical scrollbar's thumb
17330     * within the vertical range. This value is used to compute the length
17331     * of the thumb within the scrollbar's track.</p>
17332     *
17333     * <p>The range is expressed in arbitrary units that must be the same as the
17334     * units used by {@link #computeVerticalScrollRange()} and
17335     * {@link #computeVerticalScrollOffset()}.</p>
17336     *
17337     * <p>The default extent is the drawing height of this view.</p>
17338     *
17339     * @return the vertical extent of the scrollbar's thumb
17340     *
17341     * @see #computeVerticalScrollRange()
17342     * @see #computeVerticalScrollOffset()
17343     * @see android.widget.ScrollBarDrawable
17344     */
17345    protected int computeVerticalScrollExtent() {
17346        return getHeight();
17347    }
17348
17349    /**
17350     * Check if this view can be scrolled horizontally in a certain direction.
17351     *
17352     * @param direction Negative to check scrolling left, positive to check scrolling right.
17353     * @return true if this view can be scrolled in the specified direction, false otherwise.
17354     */
17355    public boolean canScrollHorizontally(int direction) {
17356        final int offset = computeHorizontalScrollOffset();
17357        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
17358        if (range == 0) return false;
17359        if (direction < 0) {
17360            return offset > 0;
17361        } else {
17362            return offset < range - 1;
17363        }
17364    }
17365
17366    /**
17367     * Check if this view can be scrolled vertically in a certain direction.
17368     *
17369     * @param direction Negative to check scrolling up, positive to check scrolling down.
17370     * @return true if this view can be scrolled in the specified direction, false otherwise.
17371     */
17372    public boolean canScrollVertically(int direction) {
17373        final int offset = computeVerticalScrollOffset();
17374        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
17375        if (range == 0) return false;
17376        if (direction < 0) {
17377            return offset > 0;
17378        } else {
17379            return offset < range - 1;
17380        }
17381    }
17382
17383    void getScrollIndicatorBounds(@NonNull Rect out) {
17384        out.left = mScrollX;
17385        out.right = mScrollX + mRight - mLeft;
17386        out.top = mScrollY;
17387        out.bottom = mScrollY + mBottom - mTop;
17388    }
17389
17390    private void onDrawScrollIndicators(Canvas c) {
17391        if ((mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK) == 0) {
17392            // No scroll indicators enabled.
17393            return;
17394        }
17395
17396        final Drawable dr = mScrollIndicatorDrawable;
17397        if (dr == null) {
17398            // Scroll indicators aren't supported here.
17399            return;
17400        }
17401
17402        final int h = dr.getIntrinsicHeight();
17403        final int w = dr.getIntrinsicWidth();
17404        final Rect rect = mAttachInfo.mTmpInvalRect;
17405        getScrollIndicatorBounds(rect);
17406
17407        if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_TOP) != 0) {
17408            final boolean canScrollUp = canScrollVertically(-1);
17409            if (canScrollUp) {
17410                dr.setBounds(rect.left, rect.top, rect.right, rect.top + h);
17411                dr.draw(c);
17412            }
17413        }
17414
17415        if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_BOTTOM) != 0) {
17416            final boolean canScrollDown = canScrollVertically(1);
17417            if (canScrollDown) {
17418                dr.setBounds(rect.left, rect.bottom - h, rect.right, rect.bottom);
17419                dr.draw(c);
17420            }
17421        }
17422
17423        final int leftRtl;
17424        final int rightRtl;
17425        if (getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
17426            leftRtl = PFLAG3_SCROLL_INDICATOR_END;
17427            rightRtl = PFLAG3_SCROLL_INDICATOR_START;
17428        } else {
17429            leftRtl = PFLAG3_SCROLL_INDICATOR_START;
17430            rightRtl = PFLAG3_SCROLL_INDICATOR_END;
17431        }
17432
17433        final int leftMask = PFLAG3_SCROLL_INDICATOR_LEFT | leftRtl;
17434        if ((mPrivateFlags3 & leftMask) != 0) {
17435            final boolean canScrollLeft = canScrollHorizontally(-1);
17436            if (canScrollLeft) {
17437                dr.setBounds(rect.left, rect.top, rect.left + w, rect.bottom);
17438                dr.draw(c);
17439            }
17440        }
17441
17442        final int rightMask = PFLAG3_SCROLL_INDICATOR_RIGHT | rightRtl;
17443        if ((mPrivateFlags3 & rightMask) != 0) {
17444            final boolean canScrollRight = canScrollHorizontally(1);
17445            if (canScrollRight) {
17446                dr.setBounds(rect.right - w, rect.top, rect.right, rect.bottom);
17447                dr.draw(c);
17448            }
17449        }
17450    }
17451
17452    private void getHorizontalScrollBarBounds(@Nullable Rect drawBounds,
17453            @Nullable Rect touchBounds) {
17454        final Rect bounds = drawBounds != null ? drawBounds : touchBounds;
17455        if (bounds == null) {
17456            return;
17457        }
17458        final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
17459        final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled()
17460                && !isVerticalScrollBarHidden();
17461        final int size = getHorizontalScrollbarHeight();
17462        final int verticalScrollBarGap = drawVerticalScrollBar ?
17463                getVerticalScrollbarWidth() : 0;
17464        final int width = mRight - mLeft;
17465        final int height = mBottom - mTop;
17466        bounds.top = mScrollY + height - size - (mUserPaddingBottom & inside);
17467        bounds.left = mScrollX + (mPaddingLeft & inside);
17468        bounds.right = mScrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
17469        bounds.bottom = bounds.top + size;
17470
17471        if (touchBounds == null) {
17472            return;
17473        }
17474        if (touchBounds != bounds) {
17475            touchBounds.set(bounds);
17476        }
17477        final int minTouchTarget = mScrollCache.scrollBarMinTouchTarget;
17478        if (touchBounds.height() < minTouchTarget) {
17479            final int adjust = (minTouchTarget - touchBounds.height()) / 2;
17480            touchBounds.bottom = Math.min(touchBounds.bottom + adjust, mScrollY + height);
17481            touchBounds.top = touchBounds.bottom - minTouchTarget;
17482        }
17483        if (touchBounds.width() < minTouchTarget) {
17484            final int adjust = (minTouchTarget - touchBounds.width()) / 2;
17485            touchBounds.left -= adjust;
17486            touchBounds.right = touchBounds.left + minTouchTarget;
17487        }
17488    }
17489
17490    private void getVerticalScrollBarBounds(@Nullable Rect bounds, @Nullable Rect touchBounds) {
17491        if (mRoundScrollbarRenderer == null) {
17492            getStraightVerticalScrollBarBounds(bounds, touchBounds);
17493        } else {
17494            getRoundVerticalScrollBarBounds(bounds != null ? bounds : touchBounds);
17495        }
17496    }
17497
17498    private void getRoundVerticalScrollBarBounds(Rect bounds) {
17499        final int width = mRight - mLeft;
17500        final int height = mBottom - mTop;
17501        // Do not take padding into account as we always want the scrollbars
17502        // to hug the screen for round wearable devices.
17503        bounds.left = mScrollX;
17504        bounds.top = mScrollY;
17505        bounds.right = bounds.left + width;
17506        bounds.bottom = mScrollY + height;
17507    }
17508
17509    private void getStraightVerticalScrollBarBounds(@Nullable Rect drawBounds,
17510            @Nullable Rect touchBounds) {
17511        final Rect bounds = drawBounds != null ? drawBounds : touchBounds;
17512        if (bounds == null) {
17513            return;
17514        }
17515        final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
17516        final int size = getVerticalScrollbarWidth();
17517        int verticalScrollbarPosition = mVerticalScrollbarPosition;
17518        if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
17519            verticalScrollbarPosition = isLayoutRtl() ?
17520                    SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
17521        }
17522        final int width = mRight - mLeft;
17523        final int height = mBottom - mTop;
17524        switch (verticalScrollbarPosition) {
17525            default:
17526            case SCROLLBAR_POSITION_RIGHT:
17527                bounds.left = mScrollX + width - size - (mUserPaddingRight & inside);
17528                break;
17529            case SCROLLBAR_POSITION_LEFT:
17530                bounds.left = mScrollX + (mUserPaddingLeft & inside);
17531                break;
17532        }
17533        bounds.top = mScrollY + (mPaddingTop & inside);
17534        bounds.right = bounds.left + size;
17535        bounds.bottom = mScrollY + height - (mUserPaddingBottom & inside);
17536
17537        if (touchBounds == null) {
17538            return;
17539        }
17540        if (touchBounds != bounds) {
17541            touchBounds.set(bounds);
17542        }
17543        final int minTouchTarget = mScrollCache.scrollBarMinTouchTarget;
17544        if (touchBounds.width() < minTouchTarget) {
17545            final int adjust = (minTouchTarget - touchBounds.width()) / 2;
17546            if (verticalScrollbarPosition == SCROLLBAR_POSITION_RIGHT) {
17547                touchBounds.right = Math.min(touchBounds.right + adjust, mScrollX + width);
17548                touchBounds.left = touchBounds.right - minTouchTarget;
17549            } else {
17550                touchBounds.left = Math.max(touchBounds.left + adjust, mScrollX);
17551                touchBounds.right = touchBounds.left + minTouchTarget;
17552            }
17553        }
17554        if (touchBounds.height() < minTouchTarget) {
17555            final int adjust = (minTouchTarget - touchBounds.height()) / 2;
17556            touchBounds.top -= adjust;
17557            touchBounds.bottom = touchBounds.top + minTouchTarget;
17558        }
17559    }
17560
17561    /**
17562     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
17563     * scrollbars are painted only if they have been awakened first.</p>
17564     *
17565     * @param canvas the canvas on which to draw the scrollbars
17566     *
17567     * @see #awakenScrollBars(int)
17568     */
17569    protected final void onDrawScrollBars(Canvas canvas) {
17570        // scrollbars are drawn only when the animation is running
17571        final ScrollabilityCache cache = mScrollCache;
17572
17573        if (cache != null) {
17574
17575            int state = cache.state;
17576
17577            if (state == ScrollabilityCache.OFF) {
17578                return;
17579            }
17580
17581            boolean invalidate = false;
17582
17583            if (state == ScrollabilityCache.FADING) {
17584                // We're fading -- get our fade interpolation
17585                if (cache.interpolatorValues == null) {
17586                    cache.interpolatorValues = new float[1];
17587                }
17588
17589                float[] values = cache.interpolatorValues;
17590
17591                // Stops the animation if we're done
17592                if (cache.scrollBarInterpolator.timeToValues(values) ==
17593                        Interpolator.Result.FREEZE_END) {
17594                    cache.state = ScrollabilityCache.OFF;
17595                } else {
17596                    cache.scrollBar.mutate().setAlpha(Math.round(values[0]));
17597                }
17598
17599                // This will make the scroll bars inval themselves after
17600                // drawing. We only want this when we're fading so that
17601                // we prevent excessive redraws
17602                invalidate = true;
17603            } else {
17604                // We're just on -- but we may have been fading before so
17605                // reset alpha
17606                cache.scrollBar.mutate().setAlpha(255);
17607            }
17608
17609            final boolean drawHorizontalScrollBar = isHorizontalScrollBarEnabled();
17610            final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled()
17611                    && !isVerticalScrollBarHidden();
17612
17613            // Fork out the scroll bar drawing for round wearable devices.
17614            if (mRoundScrollbarRenderer != null) {
17615                if (drawVerticalScrollBar) {
17616                    final Rect bounds = cache.mScrollBarBounds;
17617                    getVerticalScrollBarBounds(bounds, null);
17618                    mRoundScrollbarRenderer.drawRoundScrollbars(
17619                            canvas, (float) cache.scrollBar.getAlpha() / 255f, bounds);
17620                    if (invalidate) {
17621                        invalidate();
17622                    }
17623                }
17624                // Do not draw horizontal scroll bars for round wearable devices.
17625            } else if (drawVerticalScrollBar || drawHorizontalScrollBar) {
17626                final ScrollBarDrawable scrollBar = cache.scrollBar;
17627
17628                if (drawHorizontalScrollBar) {
17629                    scrollBar.setParameters(computeHorizontalScrollRange(),
17630                            computeHorizontalScrollOffset(),
17631                            computeHorizontalScrollExtent(), false);
17632                    final Rect bounds = cache.mScrollBarBounds;
17633                    getHorizontalScrollBarBounds(bounds, null);
17634                    onDrawHorizontalScrollBar(canvas, scrollBar, bounds.left, bounds.top,
17635                            bounds.right, bounds.bottom);
17636                    if (invalidate) {
17637                        invalidate(bounds);
17638                    }
17639                }
17640
17641                if (drawVerticalScrollBar) {
17642                    scrollBar.setParameters(computeVerticalScrollRange(),
17643                            computeVerticalScrollOffset(),
17644                            computeVerticalScrollExtent(), true);
17645                    final Rect bounds = cache.mScrollBarBounds;
17646                    getVerticalScrollBarBounds(bounds, null);
17647                    onDrawVerticalScrollBar(canvas, scrollBar, bounds.left, bounds.top,
17648                            bounds.right, bounds.bottom);
17649                    if (invalidate) {
17650                        invalidate(bounds);
17651                    }
17652                }
17653            }
17654        }
17655    }
17656
17657    /**
17658     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
17659     * FastScroller is visible.
17660     * @return whether to temporarily hide the vertical scrollbar
17661     * @hide
17662     */
17663    protected boolean isVerticalScrollBarHidden() {
17664        return false;
17665    }
17666
17667    /**
17668     * <p>Draw the horizontal scrollbar if
17669     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
17670     *
17671     * @param canvas the canvas on which to draw the scrollbar
17672     * @param scrollBar the scrollbar's drawable
17673     *
17674     * @see #isHorizontalScrollBarEnabled()
17675     * @see #computeHorizontalScrollRange()
17676     * @see #computeHorizontalScrollExtent()
17677     * @see #computeHorizontalScrollOffset()
17678     * @see android.widget.ScrollBarDrawable
17679     * @hide
17680     */
17681    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
17682            int l, int t, int r, int b) {
17683        scrollBar.setBounds(l, t, r, b);
17684        scrollBar.draw(canvas);
17685    }
17686
17687    /**
17688     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
17689     * returns true.</p>
17690     *
17691     * @param canvas the canvas on which to draw the scrollbar
17692     * @param scrollBar the scrollbar's drawable
17693     *
17694     * @see #isVerticalScrollBarEnabled()
17695     * @see #computeVerticalScrollRange()
17696     * @see #computeVerticalScrollExtent()
17697     * @see #computeVerticalScrollOffset()
17698     * @see android.widget.ScrollBarDrawable
17699     * @hide
17700     */
17701    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
17702            int l, int t, int r, int b) {
17703        scrollBar.setBounds(l, t, r, b);
17704        scrollBar.draw(canvas);
17705    }
17706
17707    /**
17708     * Implement this to do your drawing.
17709     *
17710     * @param canvas the canvas on which the background will be drawn
17711     */
17712    protected void onDraw(Canvas canvas) {
17713    }
17714
17715    /*
17716     * Caller is responsible for calling requestLayout if necessary.
17717     * (This allows addViewInLayout to not request a new layout.)
17718     */
17719    void assignParent(ViewParent parent) {
17720        if (mParent == null) {
17721            mParent = parent;
17722        } else if (parent == null) {
17723            mParent = null;
17724        } else {
17725            throw new RuntimeException("view " + this + " being added, but"
17726                    + " it already has a parent");
17727        }
17728    }
17729
17730    /**
17731     * This is called when the view is attached to a window.  At this point it
17732     * has a Surface and will start drawing.  Note that this function is
17733     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
17734     * however it may be called any time before the first onDraw -- including
17735     * before or after {@link #onMeasure(int, int)}.
17736     *
17737     * @see #onDetachedFromWindow()
17738     */
17739    @CallSuper
17740    protected void onAttachedToWindow() {
17741        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
17742            mParent.requestTransparentRegion(this);
17743        }
17744
17745        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
17746
17747        jumpDrawablesToCurrentState();
17748
17749        resetSubtreeAccessibilityStateChanged();
17750
17751        // rebuild, since Outline not maintained while View is detached
17752        rebuildOutline();
17753
17754        if (isFocused()) {
17755            InputMethodManager imm = InputMethodManager.peekInstance();
17756            if (imm != null) {
17757                imm.focusIn(this);
17758            }
17759        }
17760    }
17761
17762    /**
17763     * Resolve all RTL related properties.
17764     *
17765     * @return true if resolution of RTL properties has been done
17766     *
17767     * @hide
17768     */
17769    public boolean resolveRtlPropertiesIfNeeded() {
17770        if (!needRtlPropertiesResolution()) return false;
17771
17772        // Order is important here: LayoutDirection MUST be resolved first
17773        if (!isLayoutDirectionResolved()) {
17774            resolveLayoutDirection();
17775            resolveLayoutParams();
17776        }
17777        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
17778        if (!isTextDirectionResolved()) {
17779            resolveTextDirection();
17780        }
17781        if (!isTextAlignmentResolved()) {
17782            resolveTextAlignment();
17783        }
17784        // Should resolve Drawables before Padding because we need the layout direction of the
17785        // Drawable to correctly resolve Padding.
17786        if (!areDrawablesResolved()) {
17787            resolveDrawables();
17788        }
17789        if (!isPaddingResolved()) {
17790            resolvePadding();
17791        }
17792        onRtlPropertiesChanged(getLayoutDirection());
17793        return true;
17794    }
17795
17796    /**
17797     * Reset resolution of all RTL related properties.
17798     *
17799     * @hide
17800     */
17801    public void resetRtlProperties() {
17802        resetResolvedLayoutDirection();
17803        resetResolvedTextDirection();
17804        resetResolvedTextAlignment();
17805        resetResolvedPadding();
17806        resetResolvedDrawables();
17807    }
17808
17809    /**
17810     * @see #onScreenStateChanged(int)
17811     */
17812    void dispatchScreenStateChanged(int screenState) {
17813        onScreenStateChanged(screenState);
17814    }
17815
17816    /**
17817     * This method is called whenever the state of the screen this view is
17818     * attached to changes. A state change will usually occurs when the screen
17819     * turns on or off (whether it happens automatically or the user does it
17820     * manually.)
17821     *
17822     * @param screenState The new state of the screen. Can be either
17823     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
17824     */
17825    public void onScreenStateChanged(int screenState) {
17826    }
17827
17828    /**
17829     * @see #onMovedToDisplay(int, Configuration)
17830     */
17831    void dispatchMovedToDisplay(Display display, Configuration config) {
17832        mAttachInfo.mDisplay = display;
17833        mAttachInfo.mDisplayState = display.getState();
17834        onMovedToDisplay(display.getDisplayId(), config);
17835    }
17836
17837    /**
17838     * Called by the system when the hosting activity is moved from one display to another without
17839     * recreation. This means that the activity is declared to handle all changes to configuration
17840     * that happened when it was switched to another display, so it wasn't destroyed and created
17841     * again.
17842     *
17843     * <p>This call will be followed by {@link #onConfigurationChanged(Configuration)} if the
17844     * applied configuration actually changed. It is up to app developer to choose whether to handle
17845     * the change in this method or in the following {@link #onConfigurationChanged(Configuration)}
17846     * call.
17847     *
17848     * <p>Use this callback to track changes to the displays if some functionality relies on an
17849     * association with some display properties.
17850     *
17851     * @param displayId The id of the display to which the view was moved.
17852     * @param config Configuration of the resources on new display after move.
17853     *
17854     * @see #onConfigurationChanged(Configuration)
17855     * @hide
17856     */
17857    public void onMovedToDisplay(int displayId, Configuration config) {
17858    }
17859
17860    /**
17861     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
17862     */
17863    private boolean hasRtlSupport() {
17864        return mContext.getApplicationInfo().hasRtlSupport();
17865    }
17866
17867    /**
17868     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
17869     * RTL not supported)
17870     */
17871    private boolean isRtlCompatibilityMode() {
17872        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
17873        return targetSdkVersion < Build.VERSION_CODES.JELLY_BEAN_MR1 || !hasRtlSupport();
17874    }
17875
17876    /**
17877     * @return true if RTL properties need resolution.
17878     *
17879     */
17880    private boolean needRtlPropertiesResolution() {
17881        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
17882    }
17883
17884    /**
17885     * Called when any RTL property (layout direction or text direction or text alignment) has
17886     * been changed.
17887     *
17888     * Subclasses need to override this method to take care of cached information that depends on the
17889     * resolved layout direction, or to inform child views that inherit their layout direction.
17890     *
17891     * The default implementation does nothing.
17892     *
17893     * @param layoutDirection the direction of the layout
17894     *
17895     * @see #LAYOUT_DIRECTION_LTR
17896     * @see #LAYOUT_DIRECTION_RTL
17897     */
17898    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
17899    }
17900
17901    /**
17902     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
17903     * that the parent directionality can and will be resolved before its children.
17904     *
17905     * @return true if resolution has been done, false otherwise.
17906     *
17907     * @hide
17908     */
17909    public boolean resolveLayoutDirection() {
17910        // Clear any previous layout direction resolution
17911        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
17912
17913        if (hasRtlSupport()) {
17914            // Set resolved depending on layout direction
17915            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
17916                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
17917                case LAYOUT_DIRECTION_INHERIT:
17918                    // We cannot resolve yet. LTR is by default and let the resolution happen again
17919                    // later to get the correct resolved value
17920                    if (!canResolveLayoutDirection()) return false;
17921
17922                    // Parent has not yet resolved, LTR is still the default
17923                    try {
17924                        if (!mParent.isLayoutDirectionResolved()) return false;
17925
17926                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
17927                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
17928                        }
17929                    } catch (AbstractMethodError e) {
17930                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17931                                " does not fully implement ViewParent", e);
17932                    }
17933                    break;
17934                case LAYOUT_DIRECTION_RTL:
17935                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
17936                    break;
17937                case LAYOUT_DIRECTION_LOCALE:
17938                    if((LAYOUT_DIRECTION_RTL ==
17939                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
17940                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
17941                    }
17942                    break;
17943                default:
17944                    // Nothing to do, LTR by default
17945            }
17946        }
17947
17948        // Set to resolved
17949        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
17950        return true;
17951    }
17952
17953    /**
17954     * Check if layout direction resolution can be done.
17955     *
17956     * @return true if layout direction resolution can be done otherwise return false.
17957     */
17958    public boolean canResolveLayoutDirection() {
17959        switch (getRawLayoutDirection()) {
17960            case LAYOUT_DIRECTION_INHERIT:
17961                if (mParent != null) {
17962                    try {
17963                        return mParent.canResolveLayoutDirection();
17964                    } catch (AbstractMethodError e) {
17965                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17966                                " does not fully implement ViewParent", e);
17967                    }
17968                }
17969                return false;
17970
17971            default:
17972                return true;
17973        }
17974    }
17975
17976    /**
17977     * Reset the resolved layout direction. Layout direction will be resolved during a call to
17978     * {@link #onMeasure(int, int)}.
17979     *
17980     * @hide
17981     */
17982    public void resetResolvedLayoutDirection() {
17983        // Reset the current resolved bits
17984        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
17985    }
17986
17987    /**
17988     * @return true if the layout direction is inherited.
17989     *
17990     * @hide
17991     */
17992    public boolean isLayoutDirectionInherited() {
17993        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
17994    }
17995
17996    /**
17997     * @return true if layout direction has been resolved.
17998     */
17999    public boolean isLayoutDirectionResolved() {
18000        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
18001    }
18002
18003    /**
18004     * Return if padding has been resolved
18005     *
18006     * @hide
18007     */
18008    boolean isPaddingResolved() {
18009        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
18010    }
18011
18012    /**
18013     * Resolves padding depending on layout direction, if applicable, and
18014     * recomputes internal padding values to adjust for scroll bars.
18015     *
18016     * @hide
18017     */
18018    public void resolvePadding() {
18019        final int resolvedLayoutDirection = getLayoutDirection();
18020
18021        if (!isRtlCompatibilityMode()) {
18022            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
18023            // If start / end padding are defined, they will be resolved (hence overriding) to
18024            // left / right or right / left depending on the resolved layout direction.
18025            // If start / end padding are not defined, use the left / right ones.
18026            if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
18027                Rect padding = sThreadLocal.get();
18028                if (padding == null) {
18029                    padding = new Rect();
18030                    sThreadLocal.set(padding);
18031                }
18032                mBackground.getPadding(padding);
18033                if (!mLeftPaddingDefined) {
18034                    mUserPaddingLeftInitial = padding.left;
18035                }
18036                if (!mRightPaddingDefined) {
18037                    mUserPaddingRightInitial = padding.right;
18038                }
18039            }
18040            switch (resolvedLayoutDirection) {
18041                case LAYOUT_DIRECTION_RTL:
18042                    if (mUserPaddingStart != UNDEFINED_PADDING) {
18043                        mUserPaddingRight = mUserPaddingStart;
18044                    } else {
18045                        mUserPaddingRight = mUserPaddingRightInitial;
18046                    }
18047                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
18048                        mUserPaddingLeft = mUserPaddingEnd;
18049                    } else {
18050                        mUserPaddingLeft = mUserPaddingLeftInitial;
18051                    }
18052                    break;
18053                case LAYOUT_DIRECTION_LTR:
18054                default:
18055                    if (mUserPaddingStart != UNDEFINED_PADDING) {
18056                        mUserPaddingLeft = mUserPaddingStart;
18057                    } else {
18058                        mUserPaddingLeft = mUserPaddingLeftInitial;
18059                    }
18060                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
18061                        mUserPaddingRight = mUserPaddingEnd;
18062                    } else {
18063                        mUserPaddingRight = mUserPaddingRightInitial;
18064                    }
18065            }
18066
18067            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
18068        }
18069
18070        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
18071        onRtlPropertiesChanged(resolvedLayoutDirection);
18072
18073        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
18074    }
18075
18076    /**
18077     * Reset the resolved layout direction.
18078     *
18079     * @hide
18080     */
18081    public void resetResolvedPadding() {
18082        resetResolvedPaddingInternal();
18083    }
18084
18085    /**
18086     * Used when we only want to reset *this* view's padding and not trigger overrides
18087     * in ViewGroup that reset children too.
18088     */
18089    void resetResolvedPaddingInternal() {
18090        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
18091    }
18092
18093    /**
18094     * This is called when the view is detached from a window.  At this point it
18095     * no longer has a surface for drawing.
18096     *
18097     * @see #onAttachedToWindow()
18098     */
18099    @CallSuper
18100    protected void onDetachedFromWindow() {
18101    }
18102
18103    /**
18104     * This is a framework-internal mirror of onDetachedFromWindow() that's called
18105     * after onDetachedFromWindow().
18106     *
18107     * If you override this you *MUST* call super.onDetachedFromWindowInternal()!
18108     * The super method should be called at the end of the overridden method to ensure
18109     * subclasses are destroyed first
18110     *
18111     * @hide
18112     */
18113    @CallSuper
18114    protected void onDetachedFromWindowInternal() {
18115        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
18116        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
18117        mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH;
18118
18119        removeUnsetPressCallback();
18120        removeLongPressCallback();
18121        removePerformClickCallback();
18122        cancel(mSendViewScrolledAccessibilityEvent);
18123        stopNestedScroll();
18124
18125        // Anything that started animating right before detach should already
18126        // be in its final state when re-attached.
18127        jumpDrawablesToCurrentState();
18128
18129        destroyDrawingCache();
18130
18131        cleanupDraw();
18132        mCurrentAnimation = null;
18133
18134        if ((mViewFlags & TOOLTIP) == TOOLTIP) {
18135            hideTooltip();
18136        }
18137    }
18138
18139    private void cleanupDraw() {
18140        resetDisplayList();
18141        if (mAttachInfo != null) {
18142            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
18143        }
18144    }
18145
18146    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
18147    }
18148
18149    /**
18150     * @return The number of times this view has been attached to a window
18151     */
18152    protected int getWindowAttachCount() {
18153        return mWindowAttachCount;
18154    }
18155
18156    /**
18157     * Retrieve a unique token identifying the window this view is attached to.
18158     * @return Return the window's token for use in
18159     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
18160     */
18161    public IBinder getWindowToken() {
18162        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
18163    }
18164
18165    /**
18166     * Retrieve the {@link WindowId} for the window this view is
18167     * currently attached to.
18168     */
18169    public WindowId getWindowId() {
18170        AttachInfo ai = mAttachInfo;
18171        if (ai == null) {
18172            return null;
18173        }
18174        if (ai.mWindowId == null) {
18175            try {
18176                ai.mIWindowId = ai.mSession.getWindowId(ai.mWindowToken);
18177                if (ai.mIWindowId != null) {
18178                    ai.mWindowId = new WindowId(ai.mIWindowId);
18179                }
18180            } catch (RemoteException e) {
18181            }
18182        }
18183        return ai.mWindowId;
18184    }
18185
18186    /**
18187     * Retrieve a unique token identifying the top-level "real" window of
18188     * the window that this view is attached to.  That is, this is like
18189     * {@link #getWindowToken}, except if the window this view in is a panel
18190     * window (attached to another containing window), then the token of
18191     * the containing window is returned instead.
18192     *
18193     * @return Returns the associated window token, either
18194     * {@link #getWindowToken()} or the containing window's token.
18195     */
18196    public IBinder getApplicationWindowToken() {
18197        AttachInfo ai = mAttachInfo;
18198        if (ai != null) {
18199            IBinder appWindowToken = ai.mPanelParentWindowToken;
18200            if (appWindowToken == null) {
18201                appWindowToken = ai.mWindowToken;
18202            }
18203            return appWindowToken;
18204        }
18205        return null;
18206    }
18207
18208    /**
18209     * Gets the logical display to which the view's window has been attached.
18210     *
18211     * @return The logical display, or null if the view is not currently attached to a window.
18212     */
18213    public Display getDisplay() {
18214        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
18215    }
18216
18217    /**
18218     * Retrieve private session object this view hierarchy is using to
18219     * communicate with the window manager.
18220     * @return the session object to communicate with the window manager
18221     */
18222    /*package*/ IWindowSession getWindowSession() {
18223        return mAttachInfo != null ? mAttachInfo.mSession : null;
18224    }
18225
18226    /**
18227     * Return the window this view is currently attached to. Used in
18228     * {@link android.app.ActivityView} to communicate with WM.
18229     * @hide
18230     */
18231    protected IWindow getWindow() {
18232        return mAttachInfo != null ? mAttachInfo.mWindow : null;
18233    }
18234
18235    /**
18236     * Return the visibility value of the least visible component passed.
18237     */
18238    int combineVisibility(int vis1, int vis2) {
18239        // This works because VISIBLE < INVISIBLE < GONE.
18240        return Math.max(vis1, vis2);
18241    }
18242
18243    /**
18244     * @param info the {@link android.view.View.AttachInfo} to associated with
18245     *        this view
18246     */
18247    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
18248        mAttachInfo = info;
18249        if (mOverlay != null) {
18250            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
18251        }
18252        mWindowAttachCount++;
18253        // We will need to evaluate the drawable state at least once.
18254        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
18255        if (mFloatingTreeObserver != null) {
18256            info.mTreeObserver.merge(mFloatingTreeObserver);
18257            mFloatingTreeObserver = null;
18258        }
18259
18260        registerPendingFrameMetricsObservers();
18261
18262        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
18263            mAttachInfo.mScrollContainers.add(this);
18264            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
18265        }
18266        // Transfer all pending runnables.
18267        if (mRunQueue != null) {
18268            mRunQueue.executeActions(info.mHandler);
18269            mRunQueue = null;
18270        }
18271        performCollectViewAttributes(mAttachInfo, visibility);
18272        onAttachedToWindow();
18273
18274        ListenerInfo li = mListenerInfo;
18275        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
18276                li != null ? li.mOnAttachStateChangeListeners : null;
18277        if (listeners != null && listeners.size() > 0) {
18278            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
18279            // perform the dispatching. The iterator is a safe guard against listeners that
18280            // could mutate the list by calling the various add/remove methods. This prevents
18281            // the array from being modified while we iterate it.
18282            for (OnAttachStateChangeListener listener : listeners) {
18283                listener.onViewAttachedToWindow(this);
18284            }
18285        }
18286
18287        int vis = info.mWindowVisibility;
18288        if (vis != GONE) {
18289            onWindowVisibilityChanged(vis);
18290            if (isShown()) {
18291                // Calling onVisibilityAggregated directly here since the subtree will also
18292                // receive dispatchAttachedToWindow and this same call
18293                onVisibilityAggregated(vis == VISIBLE);
18294            }
18295        }
18296
18297        // Send onVisibilityChanged directly instead of dispatchVisibilityChanged.
18298        // As all views in the subtree will already receive dispatchAttachedToWindow
18299        // traversing the subtree again here is not desired.
18300        onVisibilityChanged(this, visibility);
18301
18302        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
18303            // If nobody has evaluated the drawable state yet, then do it now.
18304            refreshDrawableState();
18305        }
18306        needGlobalAttributesUpdate(false);
18307
18308        notifyEnterOrExitForAutoFillIfNeeded(true);
18309    }
18310
18311    void dispatchDetachedFromWindow() {
18312        AttachInfo info = mAttachInfo;
18313        if (info != null) {
18314            int vis = info.mWindowVisibility;
18315            if (vis != GONE) {
18316                onWindowVisibilityChanged(GONE);
18317                if (isShown()) {
18318                    // Invoking onVisibilityAggregated directly here since the subtree
18319                    // will also receive detached from window
18320                    onVisibilityAggregated(false);
18321                }
18322            }
18323        }
18324
18325        onDetachedFromWindow();
18326        onDetachedFromWindowInternal();
18327
18328        InputMethodManager imm = InputMethodManager.peekInstance();
18329        if (imm != null) {
18330            imm.onViewDetachedFromWindow(this);
18331        }
18332
18333        ListenerInfo li = mListenerInfo;
18334        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
18335                li != null ? li.mOnAttachStateChangeListeners : null;
18336        if (listeners != null && listeners.size() > 0) {
18337            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
18338            // perform the dispatching. The iterator is a safe guard against listeners that
18339            // could mutate the list by calling the various add/remove methods. This prevents
18340            // the array from being modified while we iterate it.
18341            for (OnAttachStateChangeListener listener : listeners) {
18342                listener.onViewDetachedFromWindow(this);
18343            }
18344        }
18345
18346        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
18347            mAttachInfo.mScrollContainers.remove(this);
18348            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
18349        }
18350
18351        mAttachInfo = null;
18352        if (mOverlay != null) {
18353            mOverlay.getOverlayView().dispatchDetachedFromWindow();
18354        }
18355
18356        notifyEnterOrExitForAutoFillIfNeeded(false);
18357    }
18358
18359    /**
18360     * Cancel any deferred high-level input events that were previously posted to the event queue.
18361     *
18362     * <p>Many views post high-level events such as click handlers to the event queue
18363     * to run deferred in order to preserve a desired user experience - clearing visible
18364     * pressed states before executing, etc. This method will abort any events of this nature
18365     * that are currently in flight.</p>
18366     *
18367     * <p>Custom views that generate their own high-level deferred input events should override
18368     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
18369     *
18370     * <p>This will also cancel pending input events for any child views.</p>
18371     *
18372     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
18373     * This will not impact newer events posted after this call that may occur as a result of
18374     * lower-level input events still waiting in the queue. If you are trying to prevent
18375     * double-submitted  events for the duration of some sort of asynchronous transaction
18376     * you should also take other steps to protect against unexpected double inputs e.g. calling
18377     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
18378     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
18379     */
18380    public final void cancelPendingInputEvents() {
18381        dispatchCancelPendingInputEvents();
18382    }
18383
18384    /**
18385     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
18386     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
18387     */
18388    void dispatchCancelPendingInputEvents() {
18389        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
18390        onCancelPendingInputEvents();
18391        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
18392            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
18393                    " did not call through to super.onCancelPendingInputEvents()");
18394        }
18395    }
18396
18397    /**
18398     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
18399     * a parent view.
18400     *
18401     * <p>This method is responsible for removing any pending high-level input events that were
18402     * posted to the event queue to run later. Custom view classes that post their own deferred
18403     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
18404     * {@link android.os.Handler} should override this method, call
18405     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
18406     * </p>
18407     */
18408    public void onCancelPendingInputEvents() {
18409        removePerformClickCallback();
18410        cancelLongPress();
18411        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
18412    }
18413
18414    /**
18415     * Store this view hierarchy's frozen state into the given container.
18416     *
18417     * @param container The SparseArray in which to save the view's state.
18418     *
18419     * @see #restoreHierarchyState(android.util.SparseArray)
18420     * @see #dispatchSaveInstanceState(android.util.SparseArray)
18421     * @see #onSaveInstanceState()
18422     */
18423    public void saveHierarchyState(SparseArray<Parcelable> container) {
18424        dispatchSaveInstanceState(container);
18425    }
18426
18427    /**
18428     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
18429     * this view and its children. May be overridden to modify how freezing happens to a
18430     * view's children; for example, some views may want to not store state for their children.
18431     *
18432     * @param container The SparseArray in which to save the view's state.
18433     *
18434     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
18435     * @see #saveHierarchyState(android.util.SparseArray)
18436     * @see #onSaveInstanceState()
18437     */
18438    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
18439        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
18440            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
18441            Parcelable state = onSaveInstanceState();
18442            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
18443                throw new IllegalStateException(
18444                        "Derived class did not call super.onSaveInstanceState()");
18445            }
18446            if (state != null) {
18447                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
18448                // + ": " + state);
18449                container.put(mID, state);
18450            }
18451        }
18452    }
18453
18454    /**
18455     * Hook allowing a view to generate a representation of its internal state
18456     * that can later be used to create a new instance with that same state.
18457     * This state should only contain information that is not persistent or can
18458     * not be reconstructed later. For example, you will never store your
18459     * current position on screen because that will be computed again when a
18460     * new instance of the view is placed in its view hierarchy.
18461     * <p>
18462     * Some examples of things you may store here: the current cursor position
18463     * in a text view (but usually not the text itself since that is stored in a
18464     * content provider or other persistent storage), the currently selected
18465     * item in a list view.
18466     *
18467     * @return Returns a Parcelable object containing the view's current dynamic
18468     *         state, or null if there is nothing interesting to save.
18469     * @see #onRestoreInstanceState(Parcelable)
18470     * @see #saveHierarchyState(SparseArray)
18471     * @see #dispatchSaveInstanceState(SparseArray)
18472     * @see #setSaveEnabled(boolean)
18473     */
18474    @CallSuper
18475    @Nullable protected Parcelable onSaveInstanceState() {
18476        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
18477        if (mStartActivityRequestWho != null || isAutofilled()
18478                || mAutofillViewId > LAST_APP_AUTOFILL_ID) {
18479            BaseSavedState state = new BaseSavedState(AbsSavedState.EMPTY_STATE);
18480
18481            if (mStartActivityRequestWho != null) {
18482                state.mSavedData |= BaseSavedState.START_ACTIVITY_REQUESTED_WHO_SAVED;
18483            }
18484
18485            if (isAutofilled()) {
18486                state.mSavedData |= BaseSavedState.IS_AUTOFILLED;
18487            }
18488
18489            if (mAutofillViewId > LAST_APP_AUTOFILL_ID) {
18490                state.mSavedData |= BaseSavedState.AUTOFILL_ID;
18491            }
18492
18493            state.mStartActivityRequestWhoSaved = mStartActivityRequestWho;
18494            state.mIsAutofilled = isAutofilled();
18495            state.mAutofillViewId = mAutofillViewId;
18496            return state;
18497        }
18498        return BaseSavedState.EMPTY_STATE;
18499    }
18500
18501    /**
18502     * Restore this view hierarchy's frozen state from the given container.
18503     *
18504     * @param container The SparseArray which holds previously frozen states.
18505     *
18506     * @see #saveHierarchyState(android.util.SparseArray)
18507     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
18508     * @see #onRestoreInstanceState(android.os.Parcelable)
18509     */
18510    public void restoreHierarchyState(SparseArray<Parcelable> container) {
18511        dispatchRestoreInstanceState(container);
18512    }
18513
18514    /**
18515     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
18516     * state for this view and its children. May be overridden to modify how restoring
18517     * happens to a view's children; for example, some views may want to not store state
18518     * for their children.
18519     *
18520     * @param container The SparseArray which holds previously saved state.
18521     *
18522     * @see #dispatchSaveInstanceState(android.util.SparseArray)
18523     * @see #restoreHierarchyState(android.util.SparseArray)
18524     * @see #onRestoreInstanceState(android.os.Parcelable)
18525     */
18526    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
18527        if (mID != NO_ID) {
18528            Parcelable state = container.get(mID);
18529            if (state != null) {
18530                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
18531                // + ": " + state);
18532                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
18533                onRestoreInstanceState(state);
18534                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
18535                    throw new IllegalStateException(
18536                            "Derived class did not call super.onRestoreInstanceState()");
18537                }
18538            }
18539        }
18540    }
18541
18542    /**
18543     * Hook allowing a view to re-apply a representation of its internal state that had previously
18544     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
18545     * null state.
18546     *
18547     * @param state The frozen state that had previously been returned by
18548     *        {@link #onSaveInstanceState}.
18549     *
18550     * @see #onSaveInstanceState()
18551     * @see #restoreHierarchyState(android.util.SparseArray)
18552     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
18553     */
18554    @CallSuper
18555    protected void onRestoreInstanceState(Parcelable state) {
18556        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
18557        if (state != null && !(state instanceof AbsSavedState)) {
18558            throw new IllegalArgumentException("Wrong state class, expecting View State but "
18559                    + "received " + state.getClass().toString() + " instead. This usually happens "
18560                    + "when two views of different type have the same id in the same hierarchy. "
18561                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
18562                    + "other views do not use the same id.");
18563        }
18564        if (state != null && state instanceof BaseSavedState) {
18565            BaseSavedState baseState = (BaseSavedState) state;
18566
18567            if ((baseState.mSavedData & BaseSavedState.START_ACTIVITY_REQUESTED_WHO_SAVED) != 0) {
18568                mStartActivityRequestWho = baseState.mStartActivityRequestWhoSaved;
18569            }
18570            if ((baseState.mSavedData & BaseSavedState.IS_AUTOFILLED) != 0) {
18571                setAutofilled(baseState.mIsAutofilled);
18572            }
18573            if ((baseState.mSavedData & BaseSavedState.AUTOFILL_ID) != 0) {
18574                // It can happen that views have the same view id and the restoration path will not
18575                // be able to distinguish between them. The autofill id needs to be unique though.
18576                // Hence prevent the same autofill view id from being restored multiple times.
18577                ((BaseSavedState) state).mSavedData &= ~BaseSavedState.AUTOFILL_ID;
18578
18579                if ((mPrivateFlags3 & PFLAG3_AUTOFILLID_EXPLICITLY_SET) != 0) {
18580                    // Ignore when view already set it through setAutofillId();
18581                    if (android.view.autofill.Helper.sDebug) {
18582                        Log.d(VIEW_LOG_TAG, "onRestoreInstanceState(): not setting autofillId to "
18583                                + baseState.mAutofillViewId + " because view explicitly set it to "
18584                                + mAutofillId);
18585                    }
18586                } else {
18587                    mAutofillViewId = baseState.mAutofillViewId;
18588                    mAutofillId = null; // will be set on demand by getAutofillId()
18589                }
18590            }
18591        }
18592    }
18593
18594    /**
18595     * <p>Return the time at which the drawing of the view hierarchy started.</p>
18596     *
18597     * @return the drawing start time in milliseconds
18598     */
18599    public long getDrawingTime() {
18600        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
18601    }
18602
18603    /**
18604     * <p>Enables or disables the duplication of the parent's state into this view. When
18605     * duplication is enabled, this view gets its drawable state from its parent rather
18606     * than from its own internal properties.</p>
18607     *
18608     * <p>Note: in the current implementation, setting this property to true after the
18609     * view was added to a ViewGroup might have no effect at all. This property should
18610     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
18611     *
18612     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
18613     * property is enabled, an exception will be thrown.</p>
18614     *
18615     * <p>Note: if the child view uses and updates additional states which are unknown to the
18616     * parent, these states should not be affected by this method.</p>
18617     *
18618     * @param enabled True to enable duplication of the parent's drawable state, false
18619     *                to disable it.
18620     *
18621     * @see #getDrawableState()
18622     * @see #isDuplicateParentStateEnabled()
18623     */
18624    public void setDuplicateParentStateEnabled(boolean enabled) {
18625        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
18626    }
18627
18628    /**
18629     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
18630     *
18631     * @return True if this view's drawable state is duplicated from the parent,
18632     *         false otherwise
18633     *
18634     * @see #getDrawableState()
18635     * @see #setDuplicateParentStateEnabled(boolean)
18636     */
18637    public boolean isDuplicateParentStateEnabled() {
18638        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
18639    }
18640
18641    /**
18642     * <p>Specifies the type of layer backing this view. The layer can be
18643     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
18644     * {@link #LAYER_TYPE_HARDWARE}.</p>
18645     *
18646     * <p>A layer is associated with an optional {@link android.graphics.Paint}
18647     * instance that controls how the layer is composed on screen. The following
18648     * properties of the paint are taken into account when composing the layer:</p>
18649     * <ul>
18650     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
18651     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
18652     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
18653     * </ul>
18654     *
18655     * <p>If this view has an alpha value set to < 1.0 by calling
18656     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superseded
18657     * by this view's alpha value.</p>
18658     *
18659     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
18660     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
18661     * for more information on when and how to use layers.</p>
18662     *
18663     * @param layerType The type of layer to use with this view, must be one of
18664     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
18665     *        {@link #LAYER_TYPE_HARDWARE}
18666     * @param paint The paint used to compose the layer. This argument is optional
18667     *        and can be null. It is ignored when the layer type is
18668     *        {@link #LAYER_TYPE_NONE}
18669     *
18670     * @see #getLayerType()
18671     * @see #LAYER_TYPE_NONE
18672     * @see #LAYER_TYPE_SOFTWARE
18673     * @see #LAYER_TYPE_HARDWARE
18674     * @see #setAlpha(float)
18675     *
18676     * @attr ref android.R.styleable#View_layerType
18677     */
18678    public void setLayerType(int layerType, @Nullable Paint paint) {
18679        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
18680            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
18681                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
18682        }
18683
18684        boolean typeChanged = mRenderNode.setLayerType(layerType);
18685
18686        if (!typeChanged) {
18687            setLayerPaint(paint);
18688            return;
18689        }
18690
18691        if (layerType != LAYER_TYPE_SOFTWARE) {
18692            // Destroy any previous software drawing cache if present
18693            // NOTE: even if previous layer type is HW, we do this to ensure we've cleaned up
18694            // drawing cache created in View#draw when drawing to a SW canvas.
18695            destroyDrawingCache();
18696        }
18697
18698        mLayerType = layerType;
18699        mLayerPaint = mLayerType == LAYER_TYPE_NONE ? null : paint;
18700        mRenderNode.setLayerPaint(mLayerPaint);
18701
18702        // draw() behaves differently if we are on a layer, so we need to
18703        // invalidate() here
18704        invalidateParentCaches();
18705        invalidate(true);
18706    }
18707
18708    /**
18709     * Updates the {@link Paint} object used with the current layer (used only if the current
18710     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
18711     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
18712     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
18713     * ensure that the view gets redrawn immediately.
18714     *
18715     * <p>A layer is associated with an optional {@link android.graphics.Paint}
18716     * instance that controls how the layer is composed on screen. The following
18717     * properties of the paint are taken into account when composing the layer:</p>
18718     * <ul>
18719     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
18720     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
18721     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
18722     * </ul>
18723     *
18724     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
18725     * alpha value of the layer's paint is superseded by this view's alpha value.</p>
18726     *
18727     * @param paint The paint used to compose the layer. This argument is optional
18728     *        and can be null. It is ignored when the layer type is
18729     *        {@link #LAYER_TYPE_NONE}
18730     *
18731     * @see #setLayerType(int, android.graphics.Paint)
18732     */
18733    public void setLayerPaint(@Nullable Paint paint) {
18734        int layerType = getLayerType();
18735        if (layerType != LAYER_TYPE_NONE) {
18736            mLayerPaint = paint;
18737            if (layerType == LAYER_TYPE_HARDWARE) {
18738                if (mRenderNode.setLayerPaint(paint)) {
18739                    invalidateViewProperty(false, false);
18740                }
18741            } else {
18742                invalidate();
18743            }
18744        }
18745    }
18746
18747    /**
18748     * Indicates what type of layer is currently associated with this view. By default
18749     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
18750     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
18751     * for more information on the different types of layers.
18752     *
18753     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
18754     *         {@link #LAYER_TYPE_HARDWARE}
18755     *
18756     * @see #setLayerType(int, android.graphics.Paint)
18757     * @see #buildLayer()
18758     * @see #LAYER_TYPE_NONE
18759     * @see #LAYER_TYPE_SOFTWARE
18760     * @see #LAYER_TYPE_HARDWARE
18761     */
18762    public int getLayerType() {
18763        return mLayerType;
18764    }
18765
18766    /**
18767     * Forces this view's layer to be created and this view to be rendered
18768     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
18769     * invoking this method will have no effect.
18770     *
18771     * This method can for instance be used to render a view into its layer before
18772     * starting an animation. If this view is complex, rendering into the layer
18773     * before starting the animation will avoid skipping frames.
18774     *
18775     * @throws IllegalStateException If this view is not attached to a window
18776     *
18777     * @see #setLayerType(int, android.graphics.Paint)
18778     */
18779    public void buildLayer() {
18780        if (mLayerType == LAYER_TYPE_NONE) return;
18781
18782        final AttachInfo attachInfo = mAttachInfo;
18783        if (attachInfo == null) {
18784            throw new IllegalStateException("This view must be attached to a window first");
18785        }
18786
18787        if (getWidth() == 0 || getHeight() == 0) {
18788            return;
18789        }
18790
18791        switch (mLayerType) {
18792            case LAYER_TYPE_HARDWARE:
18793                updateDisplayListIfDirty();
18794                if (attachInfo.mThreadedRenderer != null && mRenderNode.isValid()) {
18795                    attachInfo.mThreadedRenderer.buildLayer(mRenderNode);
18796                }
18797                break;
18798            case LAYER_TYPE_SOFTWARE:
18799                buildDrawingCache(true);
18800                break;
18801        }
18802    }
18803
18804    /**
18805     * Destroys all hardware rendering resources. This method is invoked
18806     * when the system needs to reclaim resources. Upon execution of this
18807     * method, you should free any OpenGL resources created by the view.
18808     *
18809     * Note: you <strong>must</strong> call
18810     * <code>super.destroyHardwareResources()</code> when overriding
18811     * this method.
18812     *
18813     * @hide
18814     */
18815    @CallSuper
18816    protected void destroyHardwareResources() {
18817        if (mOverlay != null) {
18818            mOverlay.getOverlayView().destroyHardwareResources();
18819        }
18820        if (mGhostView != null) {
18821            mGhostView.destroyHardwareResources();
18822        }
18823    }
18824
18825    /**
18826     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
18827     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
18828     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
18829     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
18830     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
18831     * null.</p>
18832     *
18833     * <p>Enabling the drawing cache is similar to
18834     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
18835     * acceleration is turned off. When hardware acceleration is turned on, enabling the
18836     * drawing cache has no effect on rendering because the system uses a different mechanism
18837     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
18838     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
18839     * for information on how to enable software and hardware layers.</p>
18840     *
18841     * <p>This API can be used to manually generate
18842     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
18843     * {@link #getDrawingCache()}.</p>
18844     *
18845     * @param enabled true to enable the drawing cache, false otherwise
18846     *
18847     * @see #isDrawingCacheEnabled()
18848     * @see #getDrawingCache()
18849     * @see #buildDrawingCache()
18850     * @see #setLayerType(int, android.graphics.Paint)
18851     *
18852     * @deprecated The view drawing cache was largely made obsolete with the introduction of
18853     * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
18854     * layers are largely unnecessary and can easily result in a net loss in performance due to the
18855     * cost of creating and updating the layer. In the rare cases where caching layers are useful,
18856     * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
18857     * rendering. For software-rendered snapshots of a small part of the View hierarchy or
18858     * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
18859     * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
18860     * software-rendered usages are discouraged and have compatibility issues with hardware-only
18861     * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
18862     * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
18863     * reports or unit testing the {@link PixelCopy} API is recommended.
18864     */
18865    @Deprecated
18866    public void setDrawingCacheEnabled(boolean enabled) {
18867        mCachingFailed = false;
18868        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
18869    }
18870
18871    /**
18872     * <p>Indicates whether the drawing cache is enabled for this view.</p>
18873     *
18874     * @return true if the drawing cache is enabled
18875     *
18876     * @see #setDrawingCacheEnabled(boolean)
18877     * @see #getDrawingCache()
18878     *
18879     * @deprecated The view drawing cache was largely made obsolete with the introduction of
18880     * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
18881     * layers are largely unnecessary and can easily result in a net loss in performance due to the
18882     * cost of creating and updating the layer. In the rare cases where caching layers are useful,
18883     * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
18884     * rendering. For software-rendered snapshots of a small part of the View hierarchy or
18885     * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
18886     * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
18887     * software-rendered usages are discouraged and have compatibility issues with hardware-only
18888     * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
18889     * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
18890     * reports or unit testing the {@link PixelCopy} API is recommended.
18891     */
18892    @Deprecated
18893    @ViewDebug.ExportedProperty(category = "drawing")
18894    public boolean isDrawingCacheEnabled() {
18895        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
18896    }
18897
18898    /**
18899     * Debugging utility which recursively outputs the dirty state of a view and its
18900     * descendants.
18901     *
18902     * @hide
18903     */
18904    @SuppressWarnings({"UnusedDeclaration"})
18905    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
18906        Log.d(VIEW_LOG_TAG, indent + this + "             DIRTY("
18907                + (mPrivateFlags & View.PFLAG_DIRTY_MASK)
18908                + ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID("
18909                + (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID)
18910                + ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
18911        if (clear) {
18912            mPrivateFlags &= clearMask;
18913        }
18914        if (this instanceof ViewGroup) {
18915            ViewGroup parent = (ViewGroup) this;
18916            final int count = parent.getChildCount();
18917            for (int i = 0; i < count; i++) {
18918                final View child = parent.getChildAt(i);
18919                child.outputDirtyFlags(indent + "  ", clear, clearMask);
18920            }
18921        }
18922    }
18923
18924    /**
18925     * This method is used by ViewGroup to cause its children to restore or recreate their
18926     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
18927     * to recreate its own display list, which would happen if it went through the normal
18928     * draw/dispatchDraw mechanisms.
18929     *
18930     * @hide
18931     */
18932    protected void dispatchGetDisplayList() {}
18933
18934    /**
18935     * A view that is not attached or hardware accelerated cannot create a display list.
18936     * This method checks these conditions and returns the appropriate result.
18937     *
18938     * @return true if view has the ability to create a display list, false otherwise.
18939     *
18940     * @hide
18941     */
18942    public boolean canHaveDisplayList() {
18943        return !(mAttachInfo == null || mAttachInfo.mThreadedRenderer == null);
18944    }
18945
18946    /**
18947     * Gets the RenderNode for the view, and updates its DisplayList (if needed and supported)
18948     * @hide
18949     */
18950    @NonNull
18951    public RenderNode updateDisplayListIfDirty() {
18952        final RenderNode renderNode = mRenderNode;
18953        if (!canHaveDisplayList()) {
18954            // can't populate RenderNode, don't try
18955            return renderNode;
18956        }
18957
18958        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0
18959                || !renderNode.isValid()
18960                || (mRecreateDisplayList)) {
18961            // Don't need to recreate the display list, just need to tell our
18962            // children to restore/recreate theirs
18963            if (renderNode.isValid()
18964                    && !mRecreateDisplayList) {
18965                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
18966                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
18967                dispatchGetDisplayList();
18968
18969                return renderNode; // no work needed
18970            }
18971
18972            // If we got here, we're recreating it. Mark it as such to ensure that
18973            // we copy in child display lists into ours in drawChild()
18974            mRecreateDisplayList = true;
18975
18976            int width = mRight - mLeft;
18977            int height = mBottom - mTop;
18978            int layerType = getLayerType();
18979
18980            final DisplayListCanvas canvas = renderNode.start(width, height);
18981
18982            try {
18983                if (layerType == LAYER_TYPE_SOFTWARE) {
18984                    buildDrawingCache(true);
18985                    Bitmap cache = getDrawingCache(true);
18986                    if (cache != null) {
18987                        canvas.drawBitmap(cache, 0, 0, mLayerPaint);
18988                    }
18989                } else {
18990                    computeScroll();
18991
18992                    canvas.translate(-mScrollX, -mScrollY);
18993                    mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
18994                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
18995
18996                    // Fast path for layouts with no backgrounds
18997                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
18998                        dispatchDraw(canvas);
18999                        drawAutofilledHighlight(canvas);
19000                        if (mOverlay != null && !mOverlay.isEmpty()) {
19001                            mOverlay.getOverlayView().draw(canvas);
19002                        }
19003                        if (debugDraw()) {
19004                            debugDrawFocus(canvas);
19005                        }
19006                    } else {
19007                        draw(canvas);
19008                    }
19009                }
19010            } finally {
19011                renderNode.end(canvas);
19012                setDisplayListProperties(renderNode);
19013            }
19014        } else {
19015            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
19016            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
19017        }
19018        return renderNode;
19019    }
19020
19021    private void resetDisplayList() {
19022        mRenderNode.discardDisplayList();
19023        if (mBackgroundRenderNode != null) {
19024            mBackgroundRenderNode.discardDisplayList();
19025        }
19026    }
19027
19028    /**
19029     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
19030     *
19031     * @return A non-scaled bitmap representing this view or null if cache is disabled.
19032     *
19033     * @see #getDrawingCache(boolean)
19034     *
19035     * @deprecated The view drawing cache was largely made obsolete with the introduction of
19036     * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
19037     * layers are largely unnecessary and can easily result in a net loss in performance due to the
19038     * cost of creating and updating the layer. In the rare cases where caching layers are useful,
19039     * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
19040     * rendering. For software-rendered snapshots of a small part of the View hierarchy or
19041     * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
19042     * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
19043     * software-rendered usages are discouraged and have compatibility issues with hardware-only
19044     * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
19045     * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
19046     * reports or unit testing the {@link PixelCopy} API is recommended.
19047     */
19048    @Deprecated
19049    public Bitmap getDrawingCache() {
19050        return getDrawingCache(false);
19051    }
19052
19053    /**
19054     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
19055     * is null when caching is disabled. If caching is enabled and the cache is not ready,
19056     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
19057     * draw from the cache when the cache is enabled. To benefit from the cache, you must
19058     * request the drawing cache by calling this method and draw it on screen if the
19059     * returned bitmap is not null.</p>
19060     *
19061     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
19062     * this method will create a bitmap of the same size as this view. Because this bitmap
19063     * will be drawn scaled by the parent ViewGroup, the result on screen might show
19064     * scaling artifacts. To avoid such artifacts, you should call this method by setting
19065     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
19066     * size than the view. This implies that your application must be able to handle this
19067     * size.</p>
19068     *
19069     * @param autoScale Indicates whether the generated bitmap should be scaled based on
19070     *        the current density of the screen when the application is in compatibility
19071     *        mode.
19072     *
19073     * @return A bitmap representing this view or null if cache is disabled.
19074     *
19075     * @see #setDrawingCacheEnabled(boolean)
19076     * @see #isDrawingCacheEnabled()
19077     * @see #buildDrawingCache(boolean)
19078     * @see #destroyDrawingCache()
19079     *
19080     * @deprecated The view drawing cache was largely made obsolete with the introduction of
19081     * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
19082     * layers are largely unnecessary and can easily result in a net loss in performance due to the
19083     * cost of creating and updating the layer. In the rare cases where caching layers are useful,
19084     * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
19085     * rendering. For software-rendered snapshots of a small part of the View hierarchy or
19086     * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
19087     * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
19088     * software-rendered usages are discouraged and have compatibility issues with hardware-only
19089     * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
19090     * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
19091     * reports or unit testing the {@link PixelCopy} API is recommended.
19092     */
19093    @Deprecated
19094    public Bitmap getDrawingCache(boolean autoScale) {
19095        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
19096            return null;
19097        }
19098        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
19099            buildDrawingCache(autoScale);
19100        }
19101        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
19102    }
19103
19104    /**
19105     * <p>Frees the resources used by the drawing cache. If you call
19106     * {@link #buildDrawingCache()} manually without calling
19107     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
19108     * should cleanup the cache with this method afterwards.</p>
19109     *
19110     * @see #setDrawingCacheEnabled(boolean)
19111     * @see #buildDrawingCache()
19112     * @see #getDrawingCache()
19113     *
19114     * @deprecated The view drawing cache was largely made obsolete with the introduction of
19115     * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
19116     * layers are largely unnecessary and can easily result in a net loss in performance due to the
19117     * cost of creating and updating the layer. In the rare cases where caching layers are useful,
19118     * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
19119     * rendering. For software-rendered snapshots of a small part of the View hierarchy or
19120     * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
19121     * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
19122     * software-rendered usages are discouraged and have compatibility issues with hardware-only
19123     * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
19124     * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
19125     * reports or unit testing the {@link PixelCopy} API is recommended.
19126     */
19127    @Deprecated
19128    public void destroyDrawingCache() {
19129        if (mDrawingCache != null) {
19130            mDrawingCache.recycle();
19131            mDrawingCache = null;
19132        }
19133        if (mUnscaledDrawingCache != null) {
19134            mUnscaledDrawingCache.recycle();
19135            mUnscaledDrawingCache = null;
19136        }
19137    }
19138
19139    /**
19140     * Setting a solid background color for the drawing cache's bitmaps will improve
19141     * performance and memory usage. Note, though that this should only be used if this
19142     * view will always be drawn on top of a solid color.
19143     *
19144     * @param color The background color to use for the drawing cache's bitmap
19145     *
19146     * @see #setDrawingCacheEnabled(boolean)
19147     * @see #buildDrawingCache()
19148     * @see #getDrawingCache()
19149     *
19150     * @deprecated The view drawing cache was largely made obsolete with the introduction of
19151     * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
19152     * layers are largely unnecessary and can easily result in a net loss in performance due to the
19153     * cost of creating and updating the layer. In the rare cases where caching layers are useful,
19154     * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
19155     * rendering. For software-rendered snapshots of a small part of the View hierarchy or
19156     * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
19157     * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
19158     * software-rendered usages are discouraged and have compatibility issues with hardware-only
19159     * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
19160     * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
19161     * reports or unit testing the {@link PixelCopy} API is recommended.
19162     */
19163    @Deprecated
19164    public void setDrawingCacheBackgroundColor(@ColorInt int color) {
19165        if (color != mDrawingCacheBackgroundColor) {
19166            mDrawingCacheBackgroundColor = color;
19167            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
19168        }
19169    }
19170
19171    /**
19172     * @see #setDrawingCacheBackgroundColor(int)
19173     *
19174     * @return The background color to used for the drawing cache's bitmap
19175     *
19176     * @deprecated The view drawing cache was largely made obsolete with the introduction of
19177     * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
19178     * layers are largely unnecessary and can easily result in a net loss in performance due to the
19179     * cost of creating and updating the layer. In the rare cases where caching layers are useful,
19180     * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
19181     * rendering. For software-rendered snapshots of a small part of the View hierarchy or
19182     * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
19183     * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
19184     * software-rendered usages are discouraged and have compatibility issues with hardware-only
19185     * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
19186     * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
19187     * reports or unit testing the {@link PixelCopy} API is recommended.
19188     */
19189    @Deprecated
19190    @ColorInt
19191    public int getDrawingCacheBackgroundColor() {
19192        return mDrawingCacheBackgroundColor;
19193    }
19194
19195    /**
19196     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
19197     *
19198     * @see #buildDrawingCache(boolean)
19199     *
19200     * @deprecated The view drawing cache was largely made obsolete with the introduction of
19201     * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
19202     * layers are largely unnecessary and can easily result in a net loss in performance due to the
19203     * cost of creating and updating the layer. In the rare cases where caching layers are useful,
19204     * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
19205     * rendering. For software-rendered snapshots of a small part of the View hierarchy or
19206     * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
19207     * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
19208     * software-rendered usages are discouraged and have compatibility issues with hardware-only
19209     * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
19210     * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
19211     * reports or unit testing the {@link PixelCopy} API is recommended.
19212     */
19213    @Deprecated
19214    public void buildDrawingCache() {
19215        buildDrawingCache(false);
19216    }
19217
19218    /**
19219     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
19220     *
19221     * <p>If you call {@link #buildDrawingCache()} manually without calling
19222     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
19223     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
19224     *
19225     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
19226     * this method will create a bitmap of the same size as this view. Because this bitmap
19227     * will be drawn scaled by the parent ViewGroup, the result on screen might show
19228     * scaling artifacts. To avoid such artifacts, you should call this method by setting
19229     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
19230     * size than the view. This implies that your application must be able to handle this
19231     * size.</p>
19232     *
19233     * <p>You should avoid calling this method when hardware acceleration is enabled. If
19234     * you do not need the drawing cache bitmap, calling this method will increase memory
19235     * usage and cause the view to be rendered in software once, thus negatively impacting
19236     * performance.</p>
19237     *
19238     * @see #getDrawingCache()
19239     * @see #destroyDrawingCache()
19240     *
19241     * @deprecated The view drawing cache was largely made obsolete with the introduction of
19242     * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
19243     * layers are largely unnecessary and can easily result in a net loss in performance due to the
19244     * cost of creating and updating the layer. In the rare cases where caching layers are useful,
19245     * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
19246     * rendering. For software-rendered snapshots of a small part of the View hierarchy or
19247     * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
19248     * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
19249     * software-rendered usages are discouraged and have compatibility issues with hardware-only
19250     * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
19251     * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
19252     * reports or unit testing the {@link PixelCopy} API is recommended.
19253     */
19254    @Deprecated
19255    public void buildDrawingCache(boolean autoScale) {
19256        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
19257                mDrawingCache == null : mUnscaledDrawingCache == null)) {
19258            if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) {
19259                Trace.traceBegin(Trace.TRACE_TAG_VIEW,
19260                        "buildDrawingCache/SW Layer for " + getClass().getSimpleName());
19261            }
19262            try {
19263                buildDrawingCacheImpl(autoScale);
19264            } finally {
19265                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
19266            }
19267        }
19268    }
19269
19270    /**
19271     * private, internal implementation of buildDrawingCache, used to enable tracing
19272     */
19273    private void buildDrawingCacheImpl(boolean autoScale) {
19274        mCachingFailed = false;
19275
19276        int width = mRight - mLeft;
19277        int height = mBottom - mTop;
19278
19279        final AttachInfo attachInfo = mAttachInfo;
19280        final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
19281
19282        if (autoScale && scalingRequired) {
19283            width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
19284            height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
19285        }
19286
19287        final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
19288        final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
19289        final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
19290
19291        final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
19292        final long drawingCacheSize =
19293                ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
19294        if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
19295            if (width > 0 && height > 0) {
19296                Log.w(VIEW_LOG_TAG, getClass().getSimpleName() + " not displayed because it is"
19297                        + " too large to fit into a software layer (or drawing cache), needs "
19298                        + projectedBitmapSize + " bytes, only "
19299                        + drawingCacheSize + " available");
19300            }
19301            destroyDrawingCache();
19302            mCachingFailed = true;
19303            return;
19304        }
19305
19306        boolean clear = true;
19307        Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
19308
19309        if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
19310            Bitmap.Config quality;
19311            if (!opaque) {
19312                // Never pick ARGB_4444 because it looks awful
19313                // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
19314                switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
19315                    case DRAWING_CACHE_QUALITY_AUTO:
19316                    case DRAWING_CACHE_QUALITY_LOW:
19317                    case DRAWING_CACHE_QUALITY_HIGH:
19318                    default:
19319                        quality = Bitmap.Config.ARGB_8888;
19320                        break;
19321                }
19322            } else {
19323                // Optimization for translucent windows
19324                // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
19325                quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
19326            }
19327
19328            // Try to cleanup memory
19329            if (bitmap != null) bitmap.recycle();
19330
19331            try {
19332                bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
19333                        width, height, quality);
19334                bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
19335                if (autoScale) {
19336                    mDrawingCache = bitmap;
19337                } else {
19338                    mUnscaledDrawingCache = bitmap;
19339                }
19340                if (opaque && use32BitCache) bitmap.setHasAlpha(false);
19341            } catch (OutOfMemoryError e) {
19342                // If there is not enough memory to create the bitmap cache, just
19343                // ignore the issue as bitmap caches are not required to draw the
19344                // view hierarchy
19345                if (autoScale) {
19346                    mDrawingCache = null;
19347                } else {
19348                    mUnscaledDrawingCache = null;
19349                }
19350                mCachingFailed = true;
19351                return;
19352            }
19353
19354            clear = drawingCacheBackgroundColor != 0;
19355        }
19356
19357        Canvas canvas;
19358        if (attachInfo != null) {
19359            canvas = attachInfo.mCanvas;
19360            if (canvas == null) {
19361                canvas = new Canvas();
19362            }
19363            canvas.setBitmap(bitmap);
19364            // Temporarily clobber the cached Canvas in case one of our children
19365            // is also using a drawing cache. Without this, the children would
19366            // steal the canvas by attaching their own bitmap to it and bad, bad
19367            // thing would happen (invisible views, corrupted drawings, etc.)
19368            attachInfo.mCanvas = null;
19369        } else {
19370            // This case should hopefully never or seldom happen
19371            canvas = new Canvas(bitmap);
19372        }
19373
19374        if (clear) {
19375            bitmap.eraseColor(drawingCacheBackgroundColor);
19376        }
19377
19378        computeScroll();
19379        final int restoreCount = canvas.save();
19380
19381        if (autoScale && scalingRequired) {
19382            final float scale = attachInfo.mApplicationScale;
19383            canvas.scale(scale, scale);
19384        }
19385
19386        canvas.translate(-mScrollX, -mScrollY);
19387
19388        mPrivateFlags |= PFLAG_DRAWN;
19389        if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
19390                mLayerType != LAYER_TYPE_NONE) {
19391            mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
19392        }
19393
19394        // Fast path for layouts with no backgrounds
19395        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
19396            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
19397            dispatchDraw(canvas);
19398            drawAutofilledHighlight(canvas);
19399            if (mOverlay != null && !mOverlay.isEmpty()) {
19400                mOverlay.getOverlayView().draw(canvas);
19401            }
19402        } else {
19403            draw(canvas);
19404        }
19405
19406        canvas.restoreToCount(restoreCount);
19407        canvas.setBitmap(null);
19408
19409        if (attachInfo != null) {
19410            // Restore the cached Canvas for our siblings
19411            attachInfo.mCanvas = canvas;
19412        }
19413    }
19414
19415    /**
19416     * Create a snapshot of the view into a bitmap.  We should probably make
19417     * some form of this public, but should think about the API.
19418     *
19419     * @hide
19420     */
19421    public Bitmap createSnapshot(ViewDebug.CanvasProvider canvasProvider, boolean skipChildren) {
19422        int width = mRight - mLeft;
19423        int height = mBottom - mTop;
19424
19425        final AttachInfo attachInfo = mAttachInfo;
19426        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
19427        width = (int) ((width * scale) + 0.5f);
19428        height = (int) ((height * scale) + 0.5f);
19429
19430        Canvas oldCanvas = null;
19431        try {
19432            Canvas canvas = canvasProvider.getCanvas(this,
19433                    width > 0 ? width : 1, height > 0 ? height : 1);
19434
19435            if (attachInfo != null) {
19436                oldCanvas = attachInfo.mCanvas;
19437                // Temporarily clobber the cached Canvas in case one of our children
19438                // is also using a drawing cache. Without this, the children would
19439                // steal the canvas by attaching their own bitmap to it and bad, bad
19440                // things would happen (invisible views, corrupted drawings, etc.)
19441                attachInfo.mCanvas = null;
19442            }
19443
19444            computeScroll();
19445            final int restoreCount = canvas.save();
19446            canvas.scale(scale, scale);
19447            canvas.translate(-mScrollX, -mScrollY);
19448
19449            // Temporarily remove the dirty mask
19450            int flags = mPrivateFlags;
19451            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
19452
19453            // Fast path for layouts with no backgrounds
19454            if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
19455                dispatchDraw(canvas);
19456                drawAutofilledHighlight(canvas);
19457                if (mOverlay != null && !mOverlay.isEmpty()) {
19458                    mOverlay.getOverlayView().draw(canvas);
19459                }
19460            } else {
19461                draw(canvas);
19462            }
19463
19464            mPrivateFlags = flags;
19465            canvas.restoreToCount(restoreCount);
19466            return canvasProvider.createBitmap();
19467        } finally {
19468            if (oldCanvas != null) {
19469                attachInfo.mCanvas = oldCanvas;
19470            }
19471        }
19472    }
19473
19474    /**
19475     * Indicates whether this View is currently in edit mode. A View is usually
19476     * in edit mode when displayed within a developer tool. For instance, if
19477     * this View is being drawn by a visual user interface builder, this method
19478     * should return true.
19479     *
19480     * Subclasses should check the return value of this method to provide
19481     * different behaviors if their normal behavior might interfere with the
19482     * host environment. For instance: the class spawns a thread in its
19483     * constructor, the drawing code relies on device-specific features, etc.
19484     *
19485     * This method is usually checked in the drawing code of custom widgets.
19486     *
19487     * @return True if this View is in edit mode, false otherwise.
19488     */
19489    public boolean isInEditMode() {
19490        return false;
19491    }
19492
19493    /**
19494     * If the View draws content inside its padding and enables fading edges,
19495     * it needs to support padding offsets. Padding offsets are added to the
19496     * fading edges to extend the length of the fade so that it covers pixels
19497     * drawn inside the padding.
19498     *
19499     * Subclasses of this class should override this method if they need
19500     * to draw content inside the padding.
19501     *
19502     * @return True if padding offset must be applied, false otherwise.
19503     *
19504     * @see #getLeftPaddingOffset()
19505     * @see #getRightPaddingOffset()
19506     * @see #getTopPaddingOffset()
19507     * @see #getBottomPaddingOffset()
19508     *
19509     * @since CURRENT
19510     */
19511    protected boolean isPaddingOffsetRequired() {
19512        return false;
19513    }
19514
19515    /**
19516     * Amount by which to extend the left fading region. Called only when
19517     * {@link #isPaddingOffsetRequired()} returns true.
19518     *
19519     * @return The left padding offset in pixels.
19520     *
19521     * @see #isPaddingOffsetRequired()
19522     *
19523     * @since CURRENT
19524     */
19525    protected int getLeftPaddingOffset() {
19526        return 0;
19527    }
19528
19529    /**
19530     * Amount by which to extend the right fading region. Called only when
19531     * {@link #isPaddingOffsetRequired()} returns true.
19532     *
19533     * @return The right padding offset in pixels.
19534     *
19535     * @see #isPaddingOffsetRequired()
19536     *
19537     * @since CURRENT
19538     */
19539    protected int getRightPaddingOffset() {
19540        return 0;
19541    }
19542
19543    /**
19544     * Amount by which to extend the top fading region. Called only when
19545     * {@link #isPaddingOffsetRequired()} returns true.
19546     *
19547     * @return The top padding offset in pixels.
19548     *
19549     * @see #isPaddingOffsetRequired()
19550     *
19551     * @since CURRENT
19552     */
19553    protected int getTopPaddingOffset() {
19554        return 0;
19555    }
19556
19557    /**
19558     * Amount by which to extend the bottom fading region. Called only when
19559     * {@link #isPaddingOffsetRequired()} returns true.
19560     *
19561     * @return The bottom padding offset in pixels.
19562     *
19563     * @see #isPaddingOffsetRequired()
19564     *
19565     * @since CURRENT
19566     */
19567    protected int getBottomPaddingOffset() {
19568        return 0;
19569    }
19570
19571    /**
19572     * @hide
19573     * @param offsetRequired
19574     */
19575    protected int getFadeTop(boolean offsetRequired) {
19576        int top = mPaddingTop;
19577        if (offsetRequired) top += getTopPaddingOffset();
19578        return top;
19579    }
19580
19581    /**
19582     * @hide
19583     * @param offsetRequired
19584     */
19585    protected int getFadeHeight(boolean offsetRequired) {
19586        int padding = mPaddingTop;
19587        if (offsetRequired) padding += getTopPaddingOffset();
19588        return mBottom - mTop - mPaddingBottom - padding;
19589    }
19590
19591    /**
19592     * <p>Indicates whether this view is attached to a hardware accelerated
19593     * window or not.</p>
19594     *
19595     * <p>Even if this method returns true, it does not mean that every call
19596     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
19597     * accelerated {@link android.graphics.Canvas}. For instance, if this view
19598     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
19599     * window is hardware accelerated,
19600     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
19601     * return false, and this method will return true.</p>
19602     *
19603     * @return True if the view is attached to a window and the window is
19604     *         hardware accelerated; false in any other case.
19605     */
19606    @ViewDebug.ExportedProperty(category = "drawing")
19607    public boolean isHardwareAccelerated() {
19608        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
19609    }
19610
19611    /**
19612     * Sets a rectangular area on this view to which the view will be clipped
19613     * when it is drawn. Setting the value to null will remove the clip bounds
19614     * and the view will draw normally, using its full bounds.
19615     *
19616     * @param clipBounds The rectangular area, in the local coordinates of
19617     * this view, to which future drawing operations will be clipped.
19618     */
19619    public void setClipBounds(Rect clipBounds) {
19620        if (clipBounds == mClipBounds
19621                || (clipBounds != null && clipBounds.equals(mClipBounds))) {
19622            return;
19623        }
19624        if (clipBounds != null) {
19625            if (mClipBounds == null) {
19626                mClipBounds = new Rect(clipBounds);
19627            } else {
19628                mClipBounds.set(clipBounds);
19629            }
19630        } else {
19631            mClipBounds = null;
19632        }
19633        mRenderNode.setClipBounds(mClipBounds);
19634        invalidateViewProperty(false, false);
19635    }
19636
19637    /**
19638     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
19639     *
19640     * @return A copy of the current clip bounds if clip bounds are set,
19641     * otherwise null.
19642     */
19643    public Rect getClipBounds() {
19644        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
19645    }
19646
19647
19648    /**
19649     * Populates an output rectangle with the clip bounds of the view,
19650     * returning {@code true} if successful or {@code false} if the view's
19651     * clip bounds are {@code null}.
19652     *
19653     * @param outRect rectangle in which to place the clip bounds of the view
19654     * @return {@code true} if successful or {@code false} if the view's
19655     *         clip bounds are {@code null}
19656     */
19657    public boolean getClipBounds(Rect outRect) {
19658        if (mClipBounds != null) {
19659            outRect.set(mClipBounds);
19660            return true;
19661        }
19662        return false;
19663    }
19664
19665    /**
19666     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
19667     * case of an active Animation being run on the view.
19668     */
19669    private boolean applyLegacyAnimation(ViewGroup parent, long drawingTime,
19670            Animation a, boolean scalingRequired) {
19671        Transformation invalidationTransform;
19672        final int flags = parent.mGroupFlags;
19673        final boolean initialized = a.isInitialized();
19674        if (!initialized) {
19675            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
19676            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
19677            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
19678            onAnimationStart();
19679        }
19680
19681        final Transformation t = parent.getChildTransformation();
19682        boolean more = a.getTransformation(drawingTime, t, 1f);
19683        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
19684            if (parent.mInvalidationTransformation == null) {
19685                parent.mInvalidationTransformation = new Transformation();
19686            }
19687            invalidationTransform = parent.mInvalidationTransformation;
19688            a.getTransformation(drawingTime, invalidationTransform, 1f);
19689        } else {
19690            invalidationTransform = t;
19691        }
19692
19693        if (more) {
19694            if (!a.willChangeBounds()) {
19695                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
19696                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
19697                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
19698                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
19699                    // The child need to draw an animation, potentially offscreen, so
19700                    // make sure we do not cancel invalidate requests
19701                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
19702                    parent.invalidate(mLeft, mTop, mRight, mBottom);
19703                }
19704            } else {
19705                if (parent.mInvalidateRegion == null) {
19706                    parent.mInvalidateRegion = new RectF();
19707                }
19708                final RectF region = parent.mInvalidateRegion;
19709                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
19710                        invalidationTransform);
19711
19712                // The child need to draw an animation, potentially offscreen, so
19713                // make sure we do not cancel invalidate requests
19714                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
19715
19716                final int left = mLeft + (int) region.left;
19717                final int top = mTop + (int) region.top;
19718                parent.invalidate(left, top, left + (int) (region.width() + .5f),
19719                        top + (int) (region.height() + .5f));
19720            }
19721        }
19722        return more;
19723    }
19724
19725    /**
19726     * This method is called by getDisplayList() when a display list is recorded for a View.
19727     * It pushes any properties to the RenderNode that aren't managed by the RenderNode.
19728     */
19729    void setDisplayListProperties(RenderNode renderNode) {
19730        if (renderNode != null) {
19731            renderNode.setHasOverlappingRendering(getHasOverlappingRendering());
19732            renderNode.setClipToBounds(mParent instanceof ViewGroup
19733                    && ((ViewGroup) mParent).getClipChildren());
19734
19735            float alpha = 1;
19736            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
19737                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
19738                ViewGroup parentVG = (ViewGroup) mParent;
19739                final Transformation t = parentVG.getChildTransformation();
19740                if (parentVG.getChildStaticTransformation(this, t)) {
19741                    final int transformType = t.getTransformationType();
19742                    if (transformType != Transformation.TYPE_IDENTITY) {
19743                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
19744                            alpha = t.getAlpha();
19745                        }
19746                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
19747                            renderNode.setStaticMatrix(t.getMatrix());
19748                        }
19749                    }
19750                }
19751            }
19752            if (mTransformationInfo != null) {
19753                alpha *= getFinalAlpha();
19754                if (alpha < 1) {
19755                    final int multipliedAlpha = (int) (255 * alpha);
19756                    if (onSetAlpha(multipliedAlpha)) {
19757                        alpha = 1;
19758                    }
19759                }
19760                renderNode.setAlpha(alpha);
19761            } else if (alpha < 1) {
19762                renderNode.setAlpha(alpha);
19763            }
19764        }
19765    }
19766
19767    /**
19768     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
19769     *
19770     * This is where the View specializes rendering behavior based on layer type,
19771     * and hardware acceleration.
19772     */
19773    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
19774        final boolean hardwareAcceleratedCanvas = canvas.isHardwareAccelerated();
19775        /* If an attached view draws to a HW canvas, it may use its RenderNode + DisplayList.
19776         *
19777         * If a view is dettached, its DisplayList shouldn't exist. If the canvas isn't
19778         * HW accelerated, it can't handle drawing RenderNodes.
19779         */
19780        boolean drawingWithRenderNode = mAttachInfo != null
19781                && mAttachInfo.mHardwareAccelerated
19782                && hardwareAcceleratedCanvas;
19783
19784        boolean more = false;
19785        final boolean childHasIdentityMatrix = hasIdentityMatrix();
19786        final int parentFlags = parent.mGroupFlags;
19787
19788        if ((parentFlags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) != 0) {
19789            parent.getChildTransformation().clear();
19790            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
19791        }
19792
19793        Transformation transformToApply = null;
19794        boolean concatMatrix = false;
19795        final boolean scalingRequired = mAttachInfo != null && mAttachInfo.mScalingRequired;
19796        final Animation a = getAnimation();
19797        if (a != null) {
19798            more = applyLegacyAnimation(parent, drawingTime, a, scalingRequired);
19799            concatMatrix = a.willChangeTransformationMatrix();
19800            if (concatMatrix) {
19801                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
19802            }
19803            transformToApply = parent.getChildTransformation();
19804        } else {
19805            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) {
19806                // No longer animating: clear out old animation matrix
19807                mRenderNode.setAnimationMatrix(null);
19808                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
19809            }
19810            if (!drawingWithRenderNode
19811                    && (parentFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
19812                final Transformation t = parent.getChildTransformation();
19813                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
19814                if (hasTransform) {
19815                    final int transformType = t.getTransformationType();
19816                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
19817                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
19818                }
19819            }
19820        }
19821
19822        concatMatrix |= !childHasIdentityMatrix;
19823
19824        // Sets the flag as early as possible to allow draw() implementations
19825        // to call invalidate() successfully when doing animations
19826        mPrivateFlags |= PFLAG_DRAWN;
19827
19828        if (!concatMatrix &&
19829                (parentFlags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
19830                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
19831                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
19832                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
19833            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
19834            return more;
19835        }
19836        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
19837
19838        if (hardwareAcceleratedCanvas) {
19839            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
19840            // retain the flag's value temporarily in the mRecreateDisplayList flag
19841            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) != 0;
19842            mPrivateFlags &= ~PFLAG_INVALIDATED;
19843        }
19844
19845        RenderNode renderNode = null;
19846        Bitmap cache = null;
19847        int layerType = getLayerType(); // TODO: signify cache state with just 'cache' local
19848        if (layerType == LAYER_TYPE_SOFTWARE || !drawingWithRenderNode) {
19849             if (layerType != LAYER_TYPE_NONE) {
19850                 // If not drawing with RenderNode, treat HW layers as SW
19851                 layerType = LAYER_TYPE_SOFTWARE;
19852                 buildDrawingCache(true);
19853            }
19854            cache = getDrawingCache(true);
19855        }
19856
19857        if (drawingWithRenderNode) {
19858            // Delay getting the display list until animation-driven alpha values are
19859            // set up and possibly passed on to the view
19860            renderNode = updateDisplayListIfDirty();
19861            if (!renderNode.isValid()) {
19862                // Uncommon, but possible. If a view is removed from the hierarchy during the call
19863                // to getDisplayList(), the display list will be marked invalid and we should not
19864                // try to use it again.
19865                renderNode = null;
19866                drawingWithRenderNode = false;
19867            }
19868        }
19869
19870        int sx = 0;
19871        int sy = 0;
19872        if (!drawingWithRenderNode) {
19873            computeScroll();
19874            sx = mScrollX;
19875            sy = mScrollY;
19876        }
19877
19878        final boolean drawingWithDrawingCache = cache != null && !drawingWithRenderNode;
19879        final boolean offsetForScroll = cache == null && !drawingWithRenderNode;
19880
19881        int restoreTo = -1;
19882        if (!drawingWithRenderNode || transformToApply != null) {
19883            restoreTo = canvas.save();
19884        }
19885        if (offsetForScroll) {
19886            canvas.translate(mLeft - sx, mTop - sy);
19887        } else {
19888            if (!drawingWithRenderNode) {
19889                canvas.translate(mLeft, mTop);
19890            }
19891            if (scalingRequired) {
19892                if (drawingWithRenderNode) {
19893                    // TODO: Might not need this if we put everything inside the DL
19894                    restoreTo = canvas.save();
19895                }
19896                // mAttachInfo cannot be null, otherwise scalingRequired == false
19897                final float scale = 1.0f / mAttachInfo.mApplicationScale;
19898                canvas.scale(scale, scale);
19899            }
19900        }
19901
19902        float alpha = drawingWithRenderNode ? 1 : (getAlpha() * getTransitionAlpha());
19903        if (transformToApply != null
19904                || alpha < 1
19905                || !hasIdentityMatrix()
19906                || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
19907            if (transformToApply != null || !childHasIdentityMatrix) {
19908                int transX = 0;
19909                int transY = 0;
19910
19911                if (offsetForScroll) {
19912                    transX = -sx;
19913                    transY = -sy;
19914                }
19915
19916                if (transformToApply != null) {
19917                    if (concatMatrix) {
19918                        if (drawingWithRenderNode) {
19919                            renderNode.setAnimationMatrix(transformToApply.getMatrix());
19920                        } else {
19921                            // Undo the scroll translation, apply the transformation matrix,
19922                            // then redo the scroll translate to get the correct result.
19923                            canvas.translate(-transX, -transY);
19924                            canvas.concat(transformToApply.getMatrix());
19925                            canvas.translate(transX, transY);
19926                        }
19927                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
19928                    }
19929
19930                    float transformAlpha = transformToApply.getAlpha();
19931                    if (transformAlpha < 1) {
19932                        alpha *= transformAlpha;
19933                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
19934                    }
19935                }
19936
19937                if (!childHasIdentityMatrix && !drawingWithRenderNode) {
19938                    canvas.translate(-transX, -transY);
19939                    canvas.concat(getMatrix());
19940                    canvas.translate(transX, transY);
19941                }
19942            }
19943
19944            // Deal with alpha if it is or used to be <1
19945            if (alpha < 1 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
19946                if (alpha < 1) {
19947                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
19948                } else {
19949                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
19950                }
19951                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
19952                if (!drawingWithDrawingCache) {
19953                    final int multipliedAlpha = (int) (255 * alpha);
19954                    if (!onSetAlpha(multipliedAlpha)) {
19955                        if (drawingWithRenderNode) {
19956                            renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha());
19957                        } else if (layerType == LAYER_TYPE_NONE) {
19958                            canvas.saveLayerAlpha(sx, sy, sx + getWidth(), sy + getHeight(),
19959                                    multipliedAlpha);
19960                        }
19961                    } else {
19962                        // Alpha is handled by the child directly, clobber the layer's alpha
19963                        mPrivateFlags |= PFLAG_ALPHA_SET;
19964                    }
19965                }
19966            }
19967        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
19968            onSetAlpha(255);
19969            mPrivateFlags &= ~PFLAG_ALPHA_SET;
19970        }
19971
19972        if (!drawingWithRenderNode) {
19973            // apply clips directly, since RenderNode won't do it for this draw
19974            if ((parentFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 && cache == null) {
19975                if (offsetForScroll) {
19976                    canvas.clipRect(sx, sy, sx + getWidth(), sy + getHeight());
19977                } else {
19978                    if (!scalingRequired || cache == null) {
19979                        canvas.clipRect(0, 0, getWidth(), getHeight());
19980                    } else {
19981                        canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
19982                    }
19983                }
19984            }
19985
19986            if (mClipBounds != null) {
19987                // clip bounds ignore scroll
19988                canvas.clipRect(mClipBounds);
19989            }
19990        }
19991
19992        if (!drawingWithDrawingCache) {
19993            if (drawingWithRenderNode) {
19994                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
19995                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
19996            } else {
19997                // Fast path for layouts with no backgrounds
19998                if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
19999                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
20000                    dispatchDraw(canvas);
20001                } else {
20002                    draw(canvas);
20003                }
20004            }
20005        } else if (cache != null) {
20006            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
20007            if (layerType == LAYER_TYPE_NONE || mLayerPaint == null) {
20008                // no layer paint, use temporary paint to draw bitmap
20009                Paint cachePaint = parent.mCachePaint;
20010                if (cachePaint == null) {
20011                    cachePaint = new Paint();
20012                    cachePaint.setDither(false);
20013                    parent.mCachePaint = cachePaint;
20014                }
20015                cachePaint.setAlpha((int) (alpha * 255));
20016                canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
20017            } else {
20018                // use layer paint to draw the bitmap, merging the two alphas, but also restore
20019                int layerPaintAlpha = mLayerPaint.getAlpha();
20020                if (alpha < 1) {
20021                    mLayerPaint.setAlpha((int) (alpha * layerPaintAlpha));
20022                }
20023                canvas.drawBitmap(cache, 0.0f, 0.0f, mLayerPaint);
20024                if (alpha < 1) {
20025                    mLayerPaint.setAlpha(layerPaintAlpha);
20026                }
20027            }
20028        }
20029
20030        if (restoreTo >= 0) {
20031            canvas.restoreToCount(restoreTo);
20032        }
20033
20034        if (a != null && !more) {
20035            if (!hardwareAcceleratedCanvas && !a.getFillAfter()) {
20036                onSetAlpha(255);
20037            }
20038            parent.finishAnimatingView(this, a);
20039        }
20040
20041        if (more && hardwareAcceleratedCanvas) {
20042            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
20043                // alpha animations should cause the child to recreate its display list
20044                invalidate(true);
20045            }
20046        }
20047
20048        mRecreateDisplayList = false;
20049
20050        return more;
20051    }
20052
20053    static Paint getDebugPaint() {
20054        if (sDebugPaint == null) {
20055            sDebugPaint = new Paint();
20056            sDebugPaint.setAntiAlias(false);
20057        }
20058        return sDebugPaint;
20059    }
20060
20061    final int dipsToPixels(int dips) {
20062        float scale = getContext().getResources().getDisplayMetrics().density;
20063        return (int) (dips * scale + 0.5f);
20064    }
20065
20066    final private void debugDrawFocus(Canvas canvas) {
20067        if (isFocused()) {
20068            final int cornerSquareSize = dipsToPixels(DEBUG_CORNERS_SIZE_DIP);
20069            final int l = mScrollX;
20070            final int r = l + mRight - mLeft;
20071            final int t = mScrollY;
20072            final int b = t + mBottom - mTop;
20073
20074            final Paint paint = getDebugPaint();
20075            paint.setColor(DEBUG_CORNERS_COLOR);
20076
20077            // Draw squares in corners.
20078            paint.setStyle(Paint.Style.FILL);
20079            canvas.drawRect(l, t, l + cornerSquareSize, t + cornerSquareSize, paint);
20080            canvas.drawRect(r - cornerSquareSize, t, r, t + cornerSquareSize, paint);
20081            canvas.drawRect(l, b - cornerSquareSize, l + cornerSquareSize, b, paint);
20082            canvas.drawRect(r - cornerSquareSize, b - cornerSquareSize, r, b, paint);
20083
20084            // Draw big X across the view.
20085            paint.setStyle(Paint.Style.STROKE);
20086            canvas.drawLine(l, t, r, b, paint);
20087            canvas.drawLine(l, b, r, t, paint);
20088        }
20089    }
20090
20091    /**
20092     * Manually render this view (and all of its children) to the given Canvas.
20093     * The view must have already done a full layout before this function is
20094     * called.  When implementing a view, implement
20095     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
20096     * If you do need to override this method, call the superclass version.
20097     *
20098     * @param canvas The Canvas to which the View is rendered.
20099     */
20100    @CallSuper
20101    public void draw(Canvas canvas) {
20102        final int privateFlags = mPrivateFlags;
20103        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
20104                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
20105        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
20106
20107        /*
20108         * Draw traversal performs several drawing steps which must be executed
20109         * in the appropriate order:
20110         *
20111         *      1. Draw the background
20112         *      2. If necessary, save the canvas' layers to prepare for fading
20113         *      3. Draw view's content
20114         *      4. Draw children
20115         *      5. If necessary, draw the fading edges and restore layers
20116         *      6. Draw decorations (scrollbars for instance)
20117         */
20118
20119        // Step 1, draw the background, if needed
20120        int saveCount;
20121
20122        if (!dirtyOpaque) {
20123            drawBackground(canvas);
20124        }
20125
20126        // skip step 2 & 5 if possible (common case)
20127        final int viewFlags = mViewFlags;
20128        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
20129        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
20130        if (!verticalEdges && !horizontalEdges) {
20131            // Step 3, draw the content
20132            if (!dirtyOpaque) onDraw(canvas);
20133
20134            // Step 4, draw the children
20135            dispatchDraw(canvas);
20136
20137            drawAutofilledHighlight(canvas);
20138
20139            // Overlay is part of the content and draws beneath Foreground
20140            if (mOverlay != null && !mOverlay.isEmpty()) {
20141                mOverlay.getOverlayView().dispatchDraw(canvas);
20142            }
20143
20144            // Step 6, draw decorations (foreground, scrollbars)
20145            onDrawForeground(canvas);
20146
20147            // Step 7, draw the default focus highlight
20148            drawDefaultFocusHighlight(canvas);
20149
20150            if (debugDraw()) {
20151                debugDrawFocus(canvas);
20152            }
20153
20154            // we're done...
20155            return;
20156        }
20157
20158        /*
20159         * Here we do the full fledged routine...
20160         * (this is an uncommon case where speed matters less,
20161         * this is why we repeat some of the tests that have been
20162         * done above)
20163         */
20164
20165        boolean drawTop = false;
20166        boolean drawBottom = false;
20167        boolean drawLeft = false;
20168        boolean drawRight = false;
20169
20170        float topFadeStrength = 0.0f;
20171        float bottomFadeStrength = 0.0f;
20172        float leftFadeStrength = 0.0f;
20173        float rightFadeStrength = 0.0f;
20174
20175        // Step 2, save the canvas' layers
20176        int paddingLeft = mPaddingLeft;
20177
20178        final boolean offsetRequired = isPaddingOffsetRequired();
20179        if (offsetRequired) {
20180            paddingLeft += getLeftPaddingOffset();
20181        }
20182
20183        int left = mScrollX + paddingLeft;
20184        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
20185        int top = mScrollY + getFadeTop(offsetRequired);
20186        int bottom = top + getFadeHeight(offsetRequired);
20187
20188        if (offsetRequired) {
20189            right += getRightPaddingOffset();
20190            bottom += getBottomPaddingOffset();
20191        }
20192
20193        final ScrollabilityCache scrollabilityCache = mScrollCache;
20194        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
20195        int length = (int) fadeHeight;
20196
20197        // clip the fade length if top and bottom fades overlap
20198        // overlapping fades produce odd-looking artifacts
20199        if (verticalEdges && (top + length > bottom - length)) {
20200            length = (bottom - top) / 2;
20201        }
20202
20203        // also clip horizontal fades if necessary
20204        if (horizontalEdges && (left + length > right - length)) {
20205            length = (right - left) / 2;
20206        }
20207
20208        if (verticalEdges) {
20209            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
20210            drawTop = topFadeStrength * fadeHeight > 1.0f;
20211            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
20212            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
20213        }
20214
20215        if (horizontalEdges) {
20216            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
20217            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
20218            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
20219            drawRight = rightFadeStrength * fadeHeight > 1.0f;
20220        }
20221
20222        saveCount = canvas.getSaveCount();
20223
20224        int solidColor = getSolidColor();
20225        if (solidColor == 0) {
20226            if (drawTop) {
20227                canvas.saveUnclippedLayer(left, top, right, top + length);
20228            }
20229
20230            if (drawBottom) {
20231                canvas.saveUnclippedLayer(left, bottom - length, right, bottom);
20232            }
20233
20234            if (drawLeft) {
20235                canvas.saveUnclippedLayer(left, top, left + length, bottom);
20236            }
20237
20238            if (drawRight) {
20239                canvas.saveUnclippedLayer(right - length, top, right, bottom);
20240            }
20241        } else {
20242            scrollabilityCache.setFadeColor(solidColor);
20243        }
20244
20245        // Step 3, draw the content
20246        if (!dirtyOpaque) onDraw(canvas);
20247
20248        // Step 4, draw the children
20249        dispatchDraw(canvas);
20250
20251        // Step 5, draw the fade effect and restore layers
20252        final Paint p = scrollabilityCache.paint;
20253        final Matrix matrix = scrollabilityCache.matrix;
20254        final Shader fade = scrollabilityCache.shader;
20255
20256        if (drawTop) {
20257            matrix.setScale(1, fadeHeight * topFadeStrength);
20258            matrix.postTranslate(left, top);
20259            fade.setLocalMatrix(matrix);
20260            p.setShader(fade);
20261            canvas.drawRect(left, top, right, top + length, p);
20262        }
20263
20264        if (drawBottom) {
20265            matrix.setScale(1, fadeHeight * bottomFadeStrength);
20266            matrix.postRotate(180);
20267            matrix.postTranslate(left, bottom);
20268            fade.setLocalMatrix(matrix);
20269            p.setShader(fade);
20270            canvas.drawRect(left, bottom - length, right, bottom, p);
20271        }
20272
20273        if (drawLeft) {
20274            matrix.setScale(1, fadeHeight * leftFadeStrength);
20275            matrix.postRotate(-90);
20276            matrix.postTranslate(left, top);
20277            fade.setLocalMatrix(matrix);
20278            p.setShader(fade);
20279            canvas.drawRect(left, top, left + length, bottom, p);
20280        }
20281
20282        if (drawRight) {
20283            matrix.setScale(1, fadeHeight * rightFadeStrength);
20284            matrix.postRotate(90);
20285            matrix.postTranslate(right, top);
20286            fade.setLocalMatrix(matrix);
20287            p.setShader(fade);
20288            canvas.drawRect(right - length, top, right, bottom, p);
20289        }
20290
20291        canvas.restoreToCount(saveCount);
20292
20293        drawAutofilledHighlight(canvas);
20294
20295        // Overlay is part of the content and draws beneath Foreground
20296        if (mOverlay != null && !mOverlay.isEmpty()) {
20297            mOverlay.getOverlayView().dispatchDraw(canvas);
20298        }
20299
20300        // Step 6, draw decorations (foreground, scrollbars)
20301        onDrawForeground(canvas);
20302
20303        if (debugDraw()) {
20304            debugDrawFocus(canvas);
20305        }
20306    }
20307
20308    /**
20309     * Draws the background onto the specified canvas.
20310     *
20311     * @param canvas Canvas on which to draw the background
20312     */
20313    private void drawBackground(Canvas canvas) {
20314        final Drawable background = mBackground;
20315        if (background == null) {
20316            return;
20317        }
20318
20319        setBackgroundBounds();
20320
20321        // Attempt to use a display list if requested.
20322        if (canvas.isHardwareAccelerated() && mAttachInfo != null
20323                && mAttachInfo.mThreadedRenderer != null) {
20324            mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode);
20325
20326            final RenderNode renderNode = mBackgroundRenderNode;
20327            if (renderNode != null && renderNode.isValid()) {
20328                setBackgroundRenderNodeProperties(renderNode);
20329                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
20330                return;
20331            }
20332        }
20333
20334        final int scrollX = mScrollX;
20335        final int scrollY = mScrollY;
20336        if ((scrollX | scrollY) == 0) {
20337            background.draw(canvas);
20338        } else {
20339            canvas.translate(scrollX, scrollY);
20340            background.draw(canvas);
20341            canvas.translate(-scrollX, -scrollY);
20342        }
20343    }
20344
20345    /**
20346     * Sets the correct background bounds and rebuilds the outline, if needed.
20347     * <p/>
20348     * This is called by LayoutLib.
20349     */
20350    void setBackgroundBounds() {
20351        if (mBackgroundSizeChanged && mBackground != null) {
20352            mBackground.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
20353            mBackgroundSizeChanged = false;
20354            rebuildOutline();
20355        }
20356    }
20357
20358    private void setBackgroundRenderNodeProperties(RenderNode renderNode) {
20359        renderNode.setTranslationX(mScrollX);
20360        renderNode.setTranslationY(mScrollY);
20361    }
20362
20363    /**
20364     * Creates a new display list or updates the existing display list for the
20365     * specified Drawable.
20366     *
20367     * @param drawable Drawable for which to create a display list
20368     * @param renderNode Existing RenderNode, or {@code null}
20369     * @return A valid display list for the specified drawable
20370     */
20371    private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) {
20372        if (renderNode == null) {
20373            renderNode = RenderNode.create(drawable.getClass().getName(), this);
20374        }
20375
20376        final Rect bounds = drawable.getBounds();
20377        final int width = bounds.width();
20378        final int height = bounds.height();
20379        final DisplayListCanvas canvas = renderNode.start(width, height);
20380
20381        // Reverse left/top translation done by drawable canvas, which will
20382        // instead be applied by rendernode's LTRB bounds below. This way, the
20383        // drawable's bounds match with its rendernode bounds and its content
20384        // will lie within those bounds in the rendernode tree.
20385        canvas.translate(-bounds.left, -bounds.top);
20386
20387        try {
20388            drawable.draw(canvas);
20389        } finally {
20390            renderNode.end(canvas);
20391        }
20392
20393        // Set up drawable properties that are view-independent.
20394        renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
20395        renderNode.setProjectBackwards(drawable.isProjected());
20396        renderNode.setProjectionReceiver(true);
20397        renderNode.setClipToBounds(false);
20398        return renderNode;
20399    }
20400
20401    /**
20402     * Returns the overlay for this view, creating it if it does not yet exist.
20403     * Adding drawables to the overlay will cause them to be displayed whenever
20404     * the view itself is redrawn. Objects in the overlay should be actively
20405     * managed: remove them when they should not be displayed anymore. The
20406     * overlay will always have the same size as its host view.
20407     *
20408     * <p>Note: Overlays do not currently work correctly with {@link
20409     * SurfaceView} or {@link TextureView}; contents in overlays for these
20410     * types of views may not display correctly.</p>
20411     *
20412     * @return The ViewOverlay object for this view.
20413     * @see ViewOverlay
20414     */
20415    public ViewOverlay getOverlay() {
20416        if (mOverlay == null) {
20417            mOverlay = new ViewOverlay(mContext, this);
20418        }
20419        return mOverlay;
20420    }
20421
20422    /**
20423     * Override this if your view is known to always be drawn on top of a solid color background,
20424     * and needs to draw fading edges. Returning a non-zero color enables the view system to
20425     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
20426     * should be set to 0xFF.
20427     *
20428     * @see #setVerticalFadingEdgeEnabled(boolean)
20429     * @see #setHorizontalFadingEdgeEnabled(boolean)
20430     *
20431     * @return The known solid color background for this view, or 0 if the color may vary
20432     */
20433    @ViewDebug.ExportedProperty(category = "drawing")
20434    @ColorInt
20435    public int getSolidColor() {
20436        return 0;
20437    }
20438
20439    /**
20440     * Build a human readable string representation of the specified view flags.
20441     *
20442     * @param flags the view flags to convert to a string
20443     * @return a String representing the supplied flags
20444     */
20445    private static String printFlags(int flags) {
20446        String output = "";
20447        int numFlags = 0;
20448        if ((flags & FOCUSABLE) == FOCUSABLE) {
20449            output += "TAKES_FOCUS";
20450            numFlags++;
20451        }
20452
20453        switch (flags & VISIBILITY_MASK) {
20454        case INVISIBLE:
20455            if (numFlags > 0) {
20456                output += " ";
20457            }
20458            output += "INVISIBLE";
20459            // USELESS HERE numFlags++;
20460            break;
20461        case GONE:
20462            if (numFlags > 0) {
20463                output += " ";
20464            }
20465            output += "GONE";
20466            // USELESS HERE numFlags++;
20467            break;
20468        default:
20469            break;
20470        }
20471        return output;
20472    }
20473
20474    /**
20475     * Build a human readable string representation of the specified private
20476     * view flags.
20477     *
20478     * @param privateFlags the private view flags to convert to a string
20479     * @return a String representing the supplied flags
20480     */
20481    private static String printPrivateFlags(int privateFlags) {
20482        String output = "";
20483        int numFlags = 0;
20484
20485        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
20486            output += "WANTS_FOCUS";
20487            numFlags++;
20488        }
20489
20490        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
20491            if (numFlags > 0) {
20492                output += " ";
20493            }
20494            output += "FOCUSED";
20495            numFlags++;
20496        }
20497
20498        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
20499            if (numFlags > 0) {
20500                output += " ";
20501            }
20502            output += "SELECTED";
20503            numFlags++;
20504        }
20505
20506        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
20507            if (numFlags > 0) {
20508                output += " ";
20509            }
20510            output += "IS_ROOT_NAMESPACE";
20511            numFlags++;
20512        }
20513
20514        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
20515            if (numFlags > 0) {
20516                output += " ";
20517            }
20518            output += "HAS_BOUNDS";
20519            numFlags++;
20520        }
20521
20522        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
20523            if (numFlags > 0) {
20524                output += " ";
20525            }
20526            output += "DRAWN";
20527            // USELESS HERE numFlags++;
20528        }
20529        return output;
20530    }
20531
20532    /**
20533     * <p>Indicates whether or not this view's layout will be requested during
20534     * the next hierarchy layout pass.</p>
20535     *
20536     * @return true if the layout will be forced during next layout pass
20537     */
20538    public boolean isLayoutRequested() {
20539        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
20540    }
20541
20542    /**
20543     * Return true if o is a ViewGroup that is laying out using optical bounds.
20544     * @hide
20545     */
20546    public static boolean isLayoutModeOptical(Object o) {
20547        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
20548    }
20549
20550    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
20551        Insets parentInsets = mParent instanceof View ?
20552                ((View) mParent).getOpticalInsets() : Insets.NONE;
20553        Insets childInsets = getOpticalInsets();
20554        return setFrame(
20555                left   + parentInsets.left - childInsets.left,
20556                top    + parentInsets.top  - childInsets.top,
20557                right  + parentInsets.left + childInsets.right,
20558                bottom + parentInsets.top  + childInsets.bottom);
20559    }
20560
20561    /**
20562     * Assign a size and position to a view and all of its
20563     * descendants
20564     *
20565     * <p>This is the second phase of the layout mechanism.
20566     * (The first is measuring). In this phase, each parent calls
20567     * layout on all of its children to position them.
20568     * This is typically done using the child measurements
20569     * that were stored in the measure pass().</p>
20570     *
20571     * <p>Derived classes should not override this method.
20572     * Derived classes with children should override
20573     * onLayout. In that method, they should
20574     * call layout on each of their children.</p>
20575     *
20576     * @param l Left position, relative to parent
20577     * @param t Top position, relative to parent
20578     * @param r Right position, relative to parent
20579     * @param b Bottom position, relative to parent
20580     */
20581    @SuppressWarnings({"unchecked"})
20582    public void layout(int l, int t, int r, int b) {
20583        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
20584            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
20585            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
20586        }
20587
20588        int oldL = mLeft;
20589        int oldT = mTop;
20590        int oldB = mBottom;
20591        int oldR = mRight;
20592
20593        boolean changed = isLayoutModeOptical(mParent) ?
20594                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
20595
20596        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
20597            onLayout(changed, l, t, r, b);
20598
20599            if (shouldDrawRoundScrollbar()) {
20600                if(mRoundScrollbarRenderer == null) {
20601                    mRoundScrollbarRenderer = new RoundScrollbarRenderer(this);
20602                }
20603            } else {
20604                mRoundScrollbarRenderer = null;
20605            }
20606
20607            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
20608
20609            ListenerInfo li = mListenerInfo;
20610            if (li != null && li.mOnLayoutChangeListeners != null) {
20611                ArrayList<OnLayoutChangeListener> listenersCopy =
20612                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
20613                int numListeners = listenersCopy.size();
20614                for (int i = 0; i < numListeners; ++i) {
20615                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
20616                }
20617            }
20618        }
20619
20620        final boolean wasLayoutValid = isLayoutValid();
20621
20622        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
20623        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
20624
20625        if (!wasLayoutValid && isFocused()) {
20626            mPrivateFlags &= ~PFLAG_WANTS_FOCUS;
20627            if (canTakeFocus()) {
20628                // We have a robust focus, so parents should no longer be wanting focus.
20629                clearParentsWantFocus();
20630            } else if (!getViewRootImpl().isInLayout()) {
20631                // This is a weird case. Most-likely the user, rather than ViewRootImpl, called
20632                // layout. In this case, there's no guarantee that parent layouts will be evaluated
20633                // and thus the safest action is to clear focus here.
20634                clearFocusInternal(null, /* propagate */ true, /* refocus */ false);
20635                clearParentsWantFocus();
20636            } else if (!hasParentWantsFocus()) {
20637                // original requestFocus was likely on this view directly, so just clear focus
20638                clearFocusInternal(null, /* propagate */ true, /* refocus */ false);
20639            }
20640            // otherwise, we let parents handle re-assigning focus during their layout passes.
20641        } else if ((mPrivateFlags & PFLAG_WANTS_FOCUS) != 0) {
20642            mPrivateFlags &= ~PFLAG_WANTS_FOCUS;
20643            View focused = findFocus();
20644            if (focused != null) {
20645                // Try to restore focus as close as possible to our starting focus.
20646                if (!restoreDefaultFocus() && !hasParentWantsFocus()) {
20647                    // Give up and clear focus once we've reached the top-most parent which wants
20648                    // focus.
20649                    focused.clearFocusInternal(null, /* propagate */ true, /* refocus */ false);
20650                }
20651            }
20652        }
20653
20654        if ((mPrivateFlags3 & PFLAG3_NOTIFY_AUTOFILL_ENTER_ON_LAYOUT) != 0) {
20655            mPrivateFlags3 &= ~PFLAG3_NOTIFY_AUTOFILL_ENTER_ON_LAYOUT;
20656            notifyEnterOrExitForAutoFillIfNeeded(true);
20657        }
20658    }
20659
20660    private boolean hasParentWantsFocus() {
20661        ViewParent parent = mParent;
20662        while (parent instanceof ViewGroup) {
20663            ViewGroup pv = (ViewGroup) parent;
20664            if ((pv.mPrivateFlags & PFLAG_WANTS_FOCUS) != 0) {
20665                return true;
20666            }
20667            parent = pv.mParent;
20668        }
20669        return false;
20670    }
20671
20672    /**
20673     * Called from layout when this view should
20674     * assign a size and position to each of its children.
20675     *
20676     * Derived classes with children should override
20677     * this method and call layout on each of
20678     * their children.
20679     * @param changed This is a new size or position for this view
20680     * @param left Left position, relative to parent
20681     * @param top Top position, relative to parent
20682     * @param right Right position, relative to parent
20683     * @param bottom Bottom position, relative to parent
20684     */
20685    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
20686    }
20687
20688    /**
20689     * Assign a size and position to this view.
20690     *
20691     * This is called from layout.
20692     *
20693     * @param left Left position, relative to parent
20694     * @param top Top position, relative to parent
20695     * @param right Right position, relative to parent
20696     * @param bottom Bottom position, relative to parent
20697     * @return true if the new size and position are different than the
20698     *         previous ones
20699     * {@hide}
20700     */
20701    protected boolean setFrame(int left, int top, int right, int bottom) {
20702        boolean changed = false;
20703
20704        if (DBG) {
20705            Log.d(VIEW_LOG_TAG, this + " View.setFrame(" + left + "," + top + ","
20706                    + right + "," + bottom + ")");
20707        }
20708
20709        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
20710            changed = true;
20711
20712            // Remember our drawn bit
20713            int drawn = mPrivateFlags & PFLAG_DRAWN;
20714
20715            int oldWidth = mRight - mLeft;
20716            int oldHeight = mBottom - mTop;
20717            int newWidth = right - left;
20718            int newHeight = bottom - top;
20719            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
20720
20721            // Invalidate our old position
20722            invalidate(sizeChanged);
20723
20724            mLeft = left;
20725            mTop = top;
20726            mRight = right;
20727            mBottom = bottom;
20728            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
20729
20730            mPrivateFlags |= PFLAG_HAS_BOUNDS;
20731
20732
20733            if (sizeChanged) {
20734                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
20735            }
20736
20737            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) {
20738                // If we are visible, force the DRAWN bit to on so that
20739                // this invalidate will go through (at least to our parent).
20740                // This is because someone may have invalidated this view
20741                // before this call to setFrame came in, thereby clearing
20742                // the DRAWN bit.
20743                mPrivateFlags |= PFLAG_DRAWN;
20744                invalidate(sizeChanged);
20745                // parent display list may need to be recreated based on a change in the bounds
20746                // of any child
20747                invalidateParentCaches();
20748            }
20749
20750            // Reset drawn bit to original value (invalidate turns it off)
20751            mPrivateFlags |= drawn;
20752
20753            mBackgroundSizeChanged = true;
20754            mDefaultFocusHighlightSizeChanged = true;
20755            if (mForegroundInfo != null) {
20756                mForegroundInfo.mBoundsChanged = true;
20757            }
20758
20759            notifySubtreeAccessibilityStateChangedIfNeeded();
20760        }
20761        return changed;
20762    }
20763
20764    /**
20765     * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}.
20766     * @hide
20767     */
20768    public void setLeftTopRightBottom(int left, int top, int right, int bottom) {
20769        setFrame(left, top, right, bottom);
20770    }
20771
20772    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
20773        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
20774        if (mOverlay != null) {
20775            mOverlay.getOverlayView().setRight(newWidth);
20776            mOverlay.getOverlayView().setBottom(newHeight);
20777        }
20778        // If this isn't laid out yet, focus assignment will be handled during the "deferment/
20779        // backtracking" of requestFocus during layout, so don't touch focus here.
20780        if (!sCanFocusZeroSized && isLayoutValid()) {
20781            if (newWidth <= 0 || newHeight <= 0) {
20782                if (hasFocus()) {
20783                    clearFocus();
20784                    if (mParent instanceof ViewGroup) {
20785                        ((ViewGroup) mParent).clearFocusedInCluster();
20786                    }
20787                }
20788                clearAccessibilityFocus();
20789            } else if (oldWidth <= 0 || oldHeight <= 0) {
20790                if (mParent != null && canTakeFocus()) {
20791                    mParent.focusableViewAvailable(this);
20792                }
20793            }
20794        }
20795        rebuildOutline();
20796    }
20797
20798    /**
20799     * Finalize inflating a view from XML.  This is called as the last phase
20800     * of inflation, after all child views have been added.
20801     *
20802     * <p>Even if the subclass overrides onFinishInflate, they should always be
20803     * sure to call the super method, so that we get called.
20804     */
20805    @CallSuper
20806    protected void onFinishInflate() {
20807    }
20808
20809    /**
20810     * Returns the resources associated with this view.
20811     *
20812     * @return Resources object.
20813     */
20814    public Resources getResources() {
20815        return mResources;
20816    }
20817
20818    /**
20819     * Invalidates the specified Drawable.
20820     *
20821     * @param drawable the drawable to invalidate
20822     */
20823    @Override
20824    public void invalidateDrawable(@NonNull Drawable drawable) {
20825        if (verifyDrawable(drawable)) {
20826            final Rect dirty = drawable.getDirtyBounds();
20827            final int scrollX = mScrollX;
20828            final int scrollY = mScrollY;
20829
20830            invalidate(dirty.left + scrollX, dirty.top + scrollY,
20831                    dirty.right + scrollX, dirty.bottom + scrollY);
20832            rebuildOutline();
20833        }
20834    }
20835
20836    /**
20837     * Schedules an action on a drawable to occur at a specified time.
20838     *
20839     * @param who the recipient of the action
20840     * @param what the action to run on the drawable
20841     * @param when the time at which the action must occur. Uses the
20842     *        {@link SystemClock#uptimeMillis} timebase.
20843     */
20844    @Override
20845    public void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when) {
20846        if (verifyDrawable(who) && what != null) {
20847            final long delay = when - SystemClock.uptimeMillis();
20848            if (mAttachInfo != null) {
20849                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
20850                        Choreographer.CALLBACK_ANIMATION, what, who,
20851                        Choreographer.subtractFrameDelay(delay));
20852            } else {
20853                // Postpone the runnable until we know
20854                // on which thread it needs to run.
20855                getRunQueue().postDelayed(what, delay);
20856            }
20857        }
20858    }
20859
20860    /**
20861     * Cancels a scheduled action on a drawable.
20862     *
20863     * @param who the recipient of the action
20864     * @param what the action to cancel
20865     */
20866    @Override
20867    public void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what) {
20868        if (verifyDrawable(who) && what != null) {
20869            if (mAttachInfo != null) {
20870                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
20871                        Choreographer.CALLBACK_ANIMATION, what, who);
20872            }
20873            getRunQueue().removeCallbacks(what);
20874        }
20875    }
20876
20877    /**
20878     * Unschedule any events associated with the given Drawable.  This can be
20879     * used when selecting a new Drawable into a view, so that the previous
20880     * one is completely unscheduled.
20881     *
20882     * @param who The Drawable to unschedule.
20883     *
20884     * @see #drawableStateChanged
20885     */
20886    public void unscheduleDrawable(Drawable who) {
20887        if (mAttachInfo != null && who != null) {
20888            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
20889                    Choreographer.CALLBACK_ANIMATION, null, who);
20890        }
20891    }
20892
20893    /**
20894     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
20895     * that the View directionality can and will be resolved before its Drawables.
20896     *
20897     * Will call {@link View#onResolveDrawables} when resolution is done.
20898     *
20899     * @hide
20900     */
20901    protected void resolveDrawables() {
20902        // Drawables resolution may need to happen before resolving the layout direction (which is
20903        // done only during the measure() call).
20904        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
20905        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
20906        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
20907        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
20908        // direction to be resolved as its resolved value will be the same as its raw value.
20909        if (!isLayoutDirectionResolved() &&
20910                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
20911            return;
20912        }
20913
20914        final int layoutDirection = isLayoutDirectionResolved() ?
20915                getLayoutDirection() : getRawLayoutDirection();
20916
20917        if (mBackground != null) {
20918            mBackground.setLayoutDirection(layoutDirection);
20919        }
20920        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
20921            mForegroundInfo.mDrawable.setLayoutDirection(layoutDirection);
20922        }
20923        if (mDefaultFocusHighlight != null) {
20924            mDefaultFocusHighlight.setLayoutDirection(layoutDirection);
20925        }
20926        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
20927        onResolveDrawables(layoutDirection);
20928    }
20929
20930    boolean areDrawablesResolved() {
20931        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
20932    }
20933
20934    /**
20935     * Called when layout direction has been resolved.
20936     *
20937     * The default implementation does nothing.
20938     *
20939     * @param layoutDirection The resolved layout direction.
20940     *
20941     * @see #LAYOUT_DIRECTION_LTR
20942     * @see #LAYOUT_DIRECTION_RTL
20943     *
20944     * @hide
20945     */
20946    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
20947    }
20948
20949    /**
20950     * @hide
20951     */
20952    protected void resetResolvedDrawables() {
20953        resetResolvedDrawablesInternal();
20954    }
20955
20956    void resetResolvedDrawablesInternal() {
20957        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
20958    }
20959
20960    /**
20961     * If your view subclass is displaying its own Drawable objects, it should
20962     * override this function and return true for any Drawable it is
20963     * displaying.  This allows animations for those drawables to be
20964     * scheduled.
20965     *
20966     * <p>Be sure to call through to the super class when overriding this
20967     * function.
20968     *
20969     * @param who The Drawable to verify.  Return true if it is one you are
20970     *            displaying, else return the result of calling through to the
20971     *            super class.
20972     *
20973     * @return boolean If true than the Drawable is being displayed in the
20974     *         view; else false and it is not allowed to animate.
20975     *
20976     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
20977     * @see #drawableStateChanged()
20978     */
20979    @CallSuper
20980    protected boolean verifyDrawable(@NonNull Drawable who) {
20981        // Avoid verifying the scroll bar drawable so that we don't end up in
20982        // an invalidation loop. This effectively prevents the scroll bar
20983        // drawable from triggering invalidations and scheduling runnables.
20984        return who == mBackground || (mForegroundInfo != null && mForegroundInfo.mDrawable == who)
20985                || (mDefaultFocusHighlight == who);
20986    }
20987
20988    /**
20989     * This function is called whenever the state of the view changes in such
20990     * a way that it impacts the state of drawables being shown.
20991     * <p>
20992     * If the View has a StateListAnimator, it will also be called to run necessary state
20993     * change animations.
20994     * <p>
20995     * Be sure to call through to the superclass when overriding this function.
20996     *
20997     * @see Drawable#setState(int[])
20998     */
20999    @CallSuper
21000    protected void drawableStateChanged() {
21001        final int[] state = getDrawableState();
21002        boolean changed = false;
21003
21004        final Drawable bg = mBackground;
21005        if (bg != null && bg.isStateful()) {
21006            changed |= bg.setState(state);
21007        }
21008
21009        final Drawable hl = mDefaultFocusHighlight;
21010        if (hl != null && hl.isStateful()) {
21011            changed |= hl.setState(state);
21012        }
21013
21014        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
21015        if (fg != null && fg.isStateful()) {
21016            changed |= fg.setState(state);
21017        }
21018
21019        if (mScrollCache != null) {
21020            final Drawable scrollBar = mScrollCache.scrollBar;
21021            if (scrollBar != null && scrollBar.isStateful()) {
21022                changed |= scrollBar.setState(state)
21023                        && mScrollCache.state != ScrollabilityCache.OFF;
21024            }
21025        }
21026
21027        if (mStateListAnimator != null) {
21028            mStateListAnimator.setState(state);
21029        }
21030
21031        if (changed) {
21032            invalidate();
21033        }
21034    }
21035
21036    /**
21037     * This function is called whenever the view hotspot changes and needs to
21038     * be propagated to drawables or child views managed by the view.
21039     * <p>
21040     * Dispatching to child views is handled by
21041     * {@link #dispatchDrawableHotspotChanged(float, float)}.
21042     * <p>
21043     * Be sure to call through to the superclass when overriding this function.
21044     *
21045     * @param x hotspot x coordinate
21046     * @param y hotspot y coordinate
21047     */
21048    @CallSuper
21049    public void drawableHotspotChanged(float x, float y) {
21050        if (mBackground != null) {
21051            mBackground.setHotspot(x, y);
21052        }
21053        if (mDefaultFocusHighlight != null) {
21054            mDefaultFocusHighlight.setHotspot(x, y);
21055        }
21056        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
21057            mForegroundInfo.mDrawable.setHotspot(x, y);
21058        }
21059
21060        dispatchDrawableHotspotChanged(x, y);
21061    }
21062
21063    /**
21064     * Dispatches drawableHotspotChanged to all of this View's children.
21065     *
21066     * @param x hotspot x coordinate
21067     * @param y hotspot y coordinate
21068     * @see #drawableHotspotChanged(float, float)
21069     */
21070    public void dispatchDrawableHotspotChanged(float x, float y) {
21071    }
21072
21073    /**
21074     * Call this to force a view to update its drawable state. This will cause
21075     * drawableStateChanged to be called on this view. Views that are interested
21076     * in the new state should call getDrawableState.
21077     *
21078     * @see #drawableStateChanged
21079     * @see #getDrawableState
21080     */
21081    public void refreshDrawableState() {
21082        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
21083        drawableStateChanged();
21084
21085        ViewParent parent = mParent;
21086        if (parent != null) {
21087            parent.childDrawableStateChanged(this);
21088        }
21089    }
21090
21091    /**
21092     * Create a default focus highlight if it doesn't exist.
21093     * @return a default focus highlight.
21094     */
21095    private Drawable getDefaultFocusHighlightDrawable() {
21096        if (mDefaultFocusHighlightCache == null) {
21097            if (mContext != null) {
21098                final int[] attrs = new int[] { android.R.attr.selectableItemBackground };
21099                final TypedArray ta = mContext.obtainStyledAttributes(attrs);
21100                mDefaultFocusHighlightCache = ta.getDrawable(0);
21101                ta.recycle();
21102            }
21103        }
21104        return mDefaultFocusHighlightCache;
21105    }
21106
21107    /**
21108     * Set the current default focus highlight.
21109     * @param highlight the highlight drawable, or {@code null} if it's no longer needed.
21110     */
21111    private void setDefaultFocusHighlight(Drawable highlight) {
21112        mDefaultFocusHighlight = highlight;
21113        mDefaultFocusHighlightSizeChanged = true;
21114        if (highlight != null) {
21115            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
21116                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
21117            }
21118            highlight.setLayoutDirection(getLayoutDirection());
21119            if (highlight.isStateful()) {
21120                highlight.setState(getDrawableState());
21121            }
21122            if (isAttachedToWindow()) {
21123                highlight.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
21124            }
21125            // Set callback last, since the view may still be initializing.
21126            highlight.setCallback(this);
21127        } else if ((mViewFlags & WILL_NOT_DRAW) != 0 && mBackground == null
21128                && (mForegroundInfo == null || mForegroundInfo.mDrawable == null)) {
21129            mPrivateFlags |= PFLAG_SKIP_DRAW;
21130        }
21131        invalidate();
21132    }
21133
21134    /**
21135     * Check whether we need to draw a default focus highlight when this view gets focused,
21136     * which requires:
21137     * <ul>
21138     *     <li>In both background and foreground, {@link android.R.attr#state_focused}
21139     *         is not defined.</li>
21140     *     <li>This view is not in touch mode.</li>
21141     *     <li>This view doesn't opt out for a default focus highlight, via
21142     *         {@link #setDefaultFocusHighlightEnabled(boolean)}.</li>
21143     *     <li>This view is attached to window.</li>
21144     * </ul>
21145     * @return {@code true} if a default focus highlight is needed.
21146     * @hide
21147     */
21148    @TestApi
21149    public boolean isDefaultFocusHighlightNeeded(Drawable background, Drawable foreground) {
21150        final boolean lackFocusState = (background == null || !background.isStateful()
21151                || !background.hasFocusStateSpecified())
21152                && (foreground == null || !foreground.isStateful()
21153                || !foreground.hasFocusStateSpecified());
21154        return !isInTouchMode() && getDefaultFocusHighlightEnabled() && lackFocusState
21155                && isAttachedToWindow() && sUseDefaultFocusHighlight;
21156    }
21157
21158    /**
21159     * When this view is focused, switches on/off the default focused highlight.
21160     * <p>
21161     * This always happens when this view is focused, and only at this moment the default focus
21162     * highlight can be visible.
21163     */
21164    private void switchDefaultFocusHighlight() {
21165        if (isFocused()) {
21166            final boolean needed = isDefaultFocusHighlightNeeded(mBackground,
21167                    mForegroundInfo == null ? null : mForegroundInfo.mDrawable);
21168            final boolean active = mDefaultFocusHighlight != null;
21169            if (needed && !active) {
21170                setDefaultFocusHighlight(getDefaultFocusHighlightDrawable());
21171            } else if (!needed && active) {
21172                // The highlight is no longer needed, so tear it down.
21173                setDefaultFocusHighlight(null);
21174            }
21175        }
21176    }
21177
21178    /**
21179     * Draw the default focus highlight onto the canvas.
21180     * @param canvas the canvas where we're drawing the highlight.
21181     */
21182    private void drawDefaultFocusHighlight(Canvas canvas) {
21183        if (mDefaultFocusHighlight != null) {
21184            if (mDefaultFocusHighlightSizeChanged) {
21185                mDefaultFocusHighlightSizeChanged = false;
21186                final int l = mScrollX;
21187                final int r = l + mRight - mLeft;
21188                final int t = mScrollY;
21189                final int b = t + mBottom - mTop;
21190                mDefaultFocusHighlight.setBounds(l, t, r, b);
21191            }
21192            mDefaultFocusHighlight.draw(canvas);
21193        }
21194    }
21195
21196    /**
21197     * Return an array of resource IDs of the drawable states representing the
21198     * current state of the view.
21199     *
21200     * @return The current drawable state
21201     *
21202     * @see Drawable#setState(int[])
21203     * @see #drawableStateChanged()
21204     * @see #onCreateDrawableState(int)
21205     */
21206    public final int[] getDrawableState() {
21207        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
21208            return mDrawableState;
21209        } else {
21210            mDrawableState = onCreateDrawableState(0);
21211            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
21212            return mDrawableState;
21213        }
21214    }
21215
21216    /**
21217     * Generate the new {@link android.graphics.drawable.Drawable} state for
21218     * this view. This is called by the view
21219     * system when the cached Drawable state is determined to be invalid.  To
21220     * retrieve the current state, you should use {@link #getDrawableState}.
21221     *
21222     * @param extraSpace if non-zero, this is the number of extra entries you
21223     * would like in the returned array in which you can place your own
21224     * states.
21225     *
21226     * @return Returns an array holding the current {@link Drawable} state of
21227     * the view.
21228     *
21229     * @see #mergeDrawableStates(int[], int[])
21230     */
21231    protected int[] onCreateDrawableState(int extraSpace) {
21232        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
21233                mParent instanceof View) {
21234            return ((View) mParent).onCreateDrawableState(extraSpace);
21235        }
21236
21237        int[] drawableState;
21238
21239        int privateFlags = mPrivateFlags;
21240
21241        int viewStateIndex = 0;
21242        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= StateSet.VIEW_STATE_PRESSED;
21243        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= StateSet.VIEW_STATE_ENABLED;
21244        if (isFocused()) viewStateIndex |= StateSet.VIEW_STATE_FOCUSED;
21245        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= StateSet.VIEW_STATE_SELECTED;
21246        if (hasWindowFocus()) viewStateIndex |= StateSet.VIEW_STATE_WINDOW_FOCUSED;
21247        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= StateSet.VIEW_STATE_ACTIVATED;
21248        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
21249                ThreadedRenderer.isAvailable()) {
21250            // This is set if HW acceleration is requested, even if the current
21251            // process doesn't allow it.  This is just to allow app preview
21252            // windows to better match their app.
21253            viewStateIndex |= StateSet.VIEW_STATE_ACCELERATED;
21254        }
21255        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= StateSet.VIEW_STATE_HOVERED;
21256
21257        final int privateFlags2 = mPrivateFlags2;
21258        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) {
21259            viewStateIndex |= StateSet.VIEW_STATE_DRAG_CAN_ACCEPT;
21260        }
21261        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) {
21262            viewStateIndex |= StateSet.VIEW_STATE_DRAG_HOVERED;
21263        }
21264
21265        drawableState = StateSet.get(viewStateIndex);
21266
21267        //noinspection ConstantIfStatement
21268        if (false) {
21269            Log.i("View", "drawableStateIndex=" + viewStateIndex);
21270            Log.i("View", toString()
21271                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
21272                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
21273                    + " fo=" + hasFocus()
21274                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
21275                    + " wf=" + hasWindowFocus()
21276                    + ": " + Arrays.toString(drawableState));
21277        }
21278
21279        if (extraSpace == 0) {
21280            return drawableState;
21281        }
21282
21283        final int[] fullState;
21284        if (drawableState != null) {
21285            fullState = new int[drawableState.length + extraSpace];
21286            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
21287        } else {
21288            fullState = new int[extraSpace];
21289        }
21290
21291        return fullState;
21292    }
21293
21294    /**
21295     * Merge your own state values in <var>additionalState</var> into the base
21296     * state values <var>baseState</var> that were returned by
21297     * {@link #onCreateDrawableState(int)}.
21298     *
21299     * @param baseState The base state values returned by
21300     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
21301     * own additional state values.
21302     *
21303     * @param additionalState The additional state values you would like
21304     * added to <var>baseState</var>; this array is not modified.
21305     *
21306     * @return As a convenience, the <var>baseState</var> array you originally
21307     * passed into the function is returned.
21308     *
21309     * @see #onCreateDrawableState(int)
21310     */
21311    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
21312        final int N = baseState.length;
21313        int i = N - 1;
21314        while (i >= 0 && baseState[i] == 0) {
21315            i--;
21316        }
21317        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
21318        return baseState;
21319    }
21320
21321    /**
21322     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
21323     * on all Drawable objects associated with this view.
21324     * <p>
21325     * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator
21326     * attached to this view.
21327     */
21328    @CallSuper
21329    public void jumpDrawablesToCurrentState() {
21330        if (mBackground != null) {
21331            mBackground.jumpToCurrentState();
21332        }
21333        if (mStateListAnimator != null) {
21334            mStateListAnimator.jumpToCurrentState();
21335        }
21336        if (mDefaultFocusHighlight != null) {
21337            mDefaultFocusHighlight.jumpToCurrentState();
21338        }
21339        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
21340            mForegroundInfo.mDrawable.jumpToCurrentState();
21341        }
21342    }
21343
21344    /**
21345     * Sets the background color for this view.
21346     * @param color the color of the background
21347     */
21348    @RemotableViewMethod
21349    public void setBackgroundColor(@ColorInt int color) {
21350        if (mBackground instanceof ColorDrawable) {
21351            ((ColorDrawable) mBackground.mutate()).setColor(color);
21352            computeOpaqueFlags();
21353            mBackgroundResource = 0;
21354        } else {
21355            setBackground(new ColorDrawable(color));
21356        }
21357    }
21358
21359    /**
21360     * Set the background to a given resource. The resource should refer to
21361     * a Drawable object or 0 to remove the background.
21362     * @param resid The identifier of the resource.
21363     *
21364     * @attr ref android.R.styleable#View_background
21365     */
21366    @RemotableViewMethod
21367    public void setBackgroundResource(@DrawableRes int resid) {
21368        if (resid != 0 && resid == mBackgroundResource) {
21369            return;
21370        }
21371
21372        Drawable d = null;
21373        if (resid != 0) {
21374            d = mContext.getDrawable(resid);
21375        }
21376        setBackground(d);
21377
21378        mBackgroundResource = resid;
21379    }
21380
21381    /**
21382     * Set the background to a given Drawable, or remove the background. If the
21383     * background has padding, this View's padding is set to the background's
21384     * padding. However, when a background is removed, this View's padding isn't
21385     * touched. If setting the padding is desired, please use
21386     * {@link #setPadding(int, int, int, int)}.
21387     *
21388     * @param background The Drawable to use as the background, or null to remove the
21389     *        background
21390     */
21391    public void setBackground(Drawable background) {
21392        //noinspection deprecation
21393        setBackgroundDrawable(background);
21394    }
21395
21396    /**
21397     * @deprecated use {@link #setBackground(Drawable)} instead
21398     */
21399    @Deprecated
21400    public void setBackgroundDrawable(Drawable background) {
21401        computeOpaqueFlags();
21402
21403        if (background == mBackground) {
21404            return;
21405        }
21406
21407        boolean requestLayout = false;
21408
21409        mBackgroundResource = 0;
21410
21411        /*
21412         * Regardless of whether we're setting a new background or not, we want
21413         * to clear the previous drawable. setVisible first while we still have the callback set.
21414         */
21415        if (mBackground != null) {
21416            if (isAttachedToWindow()) {
21417                mBackground.setVisible(false, false);
21418            }
21419            mBackground.setCallback(null);
21420            unscheduleDrawable(mBackground);
21421        }
21422
21423        if (background != null) {
21424            Rect padding = sThreadLocal.get();
21425            if (padding == null) {
21426                padding = new Rect();
21427                sThreadLocal.set(padding);
21428            }
21429            resetResolvedDrawablesInternal();
21430            background.setLayoutDirection(getLayoutDirection());
21431            if (background.getPadding(padding)) {
21432                resetResolvedPaddingInternal();
21433                switch (background.getLayoutDirection()) {
21434                    case LAYOUT_DIRECTION_RTL:
21435                        mUserPaddingLeftInitial = padding.right;
21436                        mUserPaddingRightInitial = padding.left;
21437                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
21438                        break;
21439                    case LAYOUT_DIRECTION_LTR:
21440                    default:
21441                        mUserPaddingLeftInitial = padding.left;
21442                        mUserPaddingRightInitial = padding.right;
21443                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
21444                }
21445                mLeftPaddingDefined = false;
21446                mRightPaddingDefined = false;
21447            }
21448
21449            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
21450            // if it has a different minimum size, we should layout again
21451            if (mBackground == null
21452                    || mBackground.getMinimumHeight() != background.getMinimumHeight()
21453                    || mBackground.getMinimumWidth() != background.getMinimumWidth()) {
21454                requestLayout = true;
21455            }
21456
21457            // Set mBackground before we set this as the callback and start making other
21458            // background drawable state change calls. In particular, the setVisible call below
21459            // can result in drawables attempting to start animations or otherwise invalidate,
21460            // which requires the view set as the callback (us) to recognize the drawable as
21461            // belonging to it as per verifyDrawable.
21462            mBackground = background;
21463            if (background.isStateful()) {
21464                background.setState(getDrawableState());
21465            }
21466            if (isAttachedToWindow()) {
21467                background.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
21468            }
21469
21470            applyBackgroundTint();
21471
21472            // Set callback last, since the view may still be initializing.
21473            background.setCallback(this);
21474
21475            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
21476                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
21477                requestLayout = true;
21478            }
21479        } else {
21480            /* Remove the background */
21481            mBackground = null;
21482            if ((mViewFlags & WILL_NOT_DRAW) != 0
21483                    && (mDefaultFocusHighlight == null)
21484                    && (mForegroundInfo == null || mForegroundInfo.mDrawable == null)) {
21485                mPrivateFlags |= PFLAG_SKIP_DRAW;
21486            }
21487
21488            /*
21489             * When the background is set, we try to apply its padding to this
21490             * View. When the background is removed, we don't touch this View's
21491             * padding. This is noted in the Javadocs. Hence, we don't need to
21492             * requestLayout(), the invalidate() below is sufficient.
21493             */
21494
21495            // The old background's minimum size could have affected this
21496            // View's layout, so let's requestLayout
21497            requestLayout = true;
21498        }
21499
21500        computeOpaqueFlags();
21501
21502        if (requestLayout) {
21503            requestLayout();
21504        }
21505
21506        mBackgroundSizeChanged = true;
21507        invalidate(true);
21508        invalidateOutline();
21509    }
21510
21511    /**
21512     * Gets the background drawable
21513     *
21514     * @return The drawable used as the background for this view, if any.
21515     *
21516     * @see #setBackground(Drawable)
21517     *
21518     * @attr ref android.R.styleable#View_background
21519     */
21520    public Drawable getBackground() {
21521        return mBackground;
21522    }
21523
21524    /**
21525     * Applies a tint to the background drawable. Does not modify the current tint
21526     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
21527     * <p>
21528     * Subsequent calls to {@link #setBackground(Drawable)} will automatically
21529     * mutate the drawable and apply the specified tint and tint mode using
21530     * {@link Drawable#setTintList(ColorStateList)}.
21531     *
21532     * @param tint the tint to apply, may be {@code null} to clear tint
21533     *
21534     * @attr ref android.R.styleable#View_backgroundTint
21535     * @see #getBackgroundTintList()
21536     * @see Drawable#setTintList(ColorStateList)
21537     */
21538    public void setBackgroundTintList(@Nullable ColorStateList tint) {
21539        if (mBackgroundTint == null) {
21540            mBackgroundTint = new TintInfo();
21541        }
21542        mBackgroundTint.mTintList = tint;
21543        mBackgroundTint.mHasTintList = true;
21544
21545        applyBackgroundTint();
21546    }
21547
21548    /**
21549     * Return the tint applied to the background drawable, if specified.
21550     *
21551     * @return the tint applied to the background drawable
21552     * @attr ref android.R.styleable#View_backgroundTint
21553     * @see #setBackgroundTintList(ColorStateList)
21554     */
21555    @Nullable
21556    public ColorStateList getBackgroundTintList() {
21557        return mBackgroundTint != null ? mBackgroundTint.mTintList : null;
21558    }
21559
21560    /**
21561     * Specifies the blending mode used to apply the tint specified by
21562     * {@link #setBackgroundTintList(ColorStateList)}} to the background
21563     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
21564     *
21565     * @param tintMode the blending mode used to apply the tint, may be
21566     *                 {@code null} to clear tint
21567     * @attr ref android.R.styleable#View_backgroundTintMode
21568     * @see #getBackgroundTintMode()
21569     * @see Drawable#setTintMode(PorterDuff.Mode)
21570     */
21571    public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) {
21572        if (mBackgroundTint == null) {
21573            mBackgroundTint = new TintInfo();
21574        }
21575        mBackgroundTint.mTintMode = tintMode;
21576        mBackgroundTint.mHasTintMode = true;
21577
21578        applyBackgroundTint();
21579    }
21580
21581    /**
21582     * Return the blending mode used to apply the tint to the background
21583     * drawable, if specified.
21584     *
21585     * @return the blending mode used to apply the tint to the background
21586     *         drawable
21587     * @attr ref android.R.styleable#View_backgroundTintMode
21588     * @see #setBackgroundTintMode(PorterDuff.Mode)
21589     */
21590    @Nullable
21591    public PorterDuff.Mode getBackgroundTintMode() {
21592        return mBackgroundTint != null ? mBackgroundTint.mTintMode : null;
21593    }
21594
21595    private void applyBackgroundTint() {
21596        if (mBackground != null && mBackgroundTint != null) {
21597            final TintInfo tintInfo = mBackgroundTint;
21598            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
21599                mBackground = mBackground.mutate();
21600
21601                if (tintInfo.mHasTintList) {
21602                    mBackground.setTintList(tintInfo.mTintList);
21603                }
21604
21605                if (tintInfo.mHasTintMode) {
21606                    mBackground.setTintMode(tintInfo.mTintMode);
21607                }
21608
21609                // The drawable (or one of its children) may not have been
21610                // stateful before applying the tint, so let's try again.
21611                if (mBackground.isStateful()) {
21612                    mBackground.setState(getDrawableState());
21613                }
21614            }
21615        }
21616    }
21617
21618    /**
21619     * Returns the drawable used as the foreground of this View. The
21620     * foreground drawable, if non-null, is always drawn on top of the view's content.
21621     *
21622     * @return a Drawable or null if no foreground was set
21623     *
21624     * @see #onDrawForeground(Canvas)
21625     */
21626    public Drawable getForeground() {
21627        return mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
21628    }
21629
21630    /**
21631     * Supply a Drawable that is to be rendered on top of all of the content in the view.
21632     *
21633     * @param foreground the Drawable to be drawn on top of the children
21634     *
21635     * @attr ref android.R.styleable#View_foreground
21636     */
21637    public void setForeground(Drawable foreground) {
21638        if (mForegroundInfo == null) {
21639            if (foreground == null) {
21640                // Nothing to do.
21641                return;
21642            }
21643            mForegroundInfo = new ForegroundInfo();
21644        }
21645
21646        if (foreground == mForegroundInfo.mDrawable) {
21647            // Nothing to do
21648            return;
21649        }
21650
21651        if (mForegroundInfo.mDrawable != null) {
21652            if (isAttachedToWindow()) {
21653                mForegroundInfo.mDrawable.setVisible(false, false);
21654            }
21655            mForegroundInfo.mDrawable.setCallback(null);
21656            unscheduleDrawable(mForegroundInfo.mDrawable);
21657        }
21658
21659        mForegroundInfo.mDrawable = foreground;
21660        mForegroundInfo.mBoundsChanged = true;
21661        if (foreground != null) {
21662            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
21663                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
21664            }
21665            foreground.setLayoutDirection(getLayoutDirection());
21666            if (foreground.isStateful()) {
21667                foreground.setState(getDrawableState());
21668            }
21669            applyForegroundTint();
21670            if (isAttachedToWindow()) {
21671                foreground.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
21672            }
21673            // Set callback last, since the view may still be initializing.
21674            foreground.setCallback(this);
21675        } else if ((mViewFlags & WILL_NOT_DRAW) != 0 && mBackground == null
21676                && (mDefaultFocusHighlight == null)) {
21677            mPrivateFlags |= PFLAG_SKIP_DRAW;
21678        }
21679        requestLayout();
21680        invalidate();
21681    }
21682
21683    /**
21684     * Magic bit used to support features of framework-internal window decor implementation details.
21685     * This used to live exclusively in FrameLayout.
21686     *
21687     * @return true if the foreground should draw inside the padding region or false
21688     *         if it should draw inset by the view's padding
21689     * @hide internal use only; only used by FrameLayout and internal screen layouts.
21690     */
21691    public boolean isForegroundInsidePadding() {
21692        return mForegroundInfo != null ? mForegroundInfo.mInsidePadding : true;
21693    }
21694
21695    /**
21696     * Describes how the foreground is positioned.
21697     *
21698     * @return foreground gravity.
21699     *
21700     * @see #setForegroundGravity(int)
21701     *
21702     * @attr ref android.R.styleable#View_foregroundGravity
21703     */
21704    public int getForegroundGravity() {
21705        return mForegroundInfo != null ? mForegroundInfo.mGravity
21706                : Gravity.START | Gravity.TOP;
21707    }
21708
21709    /**
21710     * Describes how the foreground is positioned. Defaults to START and TOP.
21711     *
21712     * @param gravity see {@link android.view.Gravity}
21713     *
21714     * @see #getForegroundGravity()
21715     *
21716     * @attr ref android.R.styleable#View_foregroundGravity
21717     */
21718    public void setForegroundGravity(int gravity) {
21719        if (mForegroundInfo == null) {
21720            mForegroundInfo = new ForegroundInfo();
21721        }
21722
21723        if (mForegroundInfo.mGravity != gravity) {
21724            if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) {
21725                gravity |= Gravity.START;
21726            }
21727
21728            if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) {
21729                gravity |= Gravity.TOP;
21730            }
21731
21732            mForegroundInfo.mGravity = gravity;
21733            requestLayout();
21734        }
21735    }
21736
21737    /**
21738     * Applies a tint to the foreground drawable. Does not modify the current tint
21739     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
21740     * <p>
21741     * Subsequent calls to {@link #setForeground(Drawable)} will automatically
21742     * mutate the drawable and apply the specified tint and tint mode using
21743     * {@link Drawable#setTintList(ColorStateList)}.
21744     *
21745     * @param tint the tint to apply, may be {@code null} to clear tint
21746     *
21747     * @attr ref android.R.styleable#View_foregroundTint
21748     * @see #getForegroundTintList()
21749     * @see Drawable#setTintList(ColorStateList)
21750     */
21751    public void setForegroundTintList(@Nullable ColorStateList tint) {
21752        if (mForegroundInfo == null) {
21753            mForegroundInfo = new ForegroundInfo();
21754        }
21755        if (mForegroundInfo.mTintInfo == null) {
21756            mForegroundInfo.mTintInfo = new TintInfo();
21757        }
21758        mForegroundInfo.mTintInfo.mTintList = tint;
21759        mForegroundInfo.mTintInfo.mHasTintList = true;
21760
21761        applyForegroundTint();
21762    }
21763
21764    /**
21765     * Return the tint applied to the foreground drawable, if specified.
21766     *
21767     * @return the tint applied to the foreground drawable
21768     * @attr ref android.R.styleable#View_foregroundTint
21769     * @see #setForegroundTintList(ColorStateList)
21770     */
21771    @Nullable
21772    public ColorStateList getForegroundTintList() {
21773        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
21774                ? mForegroundInfo.mTintInfo.mTintList : null;
21775    }
21776
21777    /**
21778     * Specifies the blending mode used to apply the tint specified by
21779     * {@link #setForegroundTintList(ColorStateList)}} to the background
21780     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
21781     *
21782     * @param tintMode the blending mode used to apply the tint, may be
21783     *                 {@code null} to clear tint
21784     * @attr ref android.R.styleable#View_foregroundTintMode
21785     * @see #getForegroundTintMode()
21786     * @see Drawable#setTintMode(PorterDuff.Mode)
21787     */
21788    public void setForegroundTintMode(@Nullable PorterDuff.Mode tintMode) {
21789        if (mForegroundInfo == null) {
21790            mForegroundInfo = new ForegroundInfo();
21791        }
21792        if (mForegroundInfo.mTintInfo == null) {
21793            mForegroundInfo.mTintInfo = new TintInfo();
21794        }
21795        mForegroundInfo.mTintInfo.mTintMode = tintMode;
21796        mForegroundInfo.mTintInfo.mHasTintMode = true;
21797
21798        applyForegroundTint();
21799    }
21800
21801    /**
21802     * Return the blending mode used to apply the tint to the foreground
21803     * drawable, if specified.
21804     *
21805     * @return the blending mode used to apply the tint to the foreground
21806     *         drawable
21807     * @attr ref android.R.styleable#View_foregroundTintMode
21808     * @see #setForegroundTintMode(PorterDuff.Mode)
21809     */
21810    @Nullable
21811    public PorterDuff.Mode getForegroundTintMode() {
21812        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
21813                ? mForegroundInfo.mTintInfo.mTintMode : null;
21814    }
21815
21816    private void applyForegroundTint() {
21817        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
21818                && mForegroundInfo.mTintInfo != null) {
21819            final TintInfo tintInfo = mForegroundInfo.mTintInfo;
21820            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
21821                mForegroundInfo.mDrawable = mForegroundInfo.mDrawable.mutate();
21822
21823                if (tintInfo.mHasTintList) {
21824                    mForegroundInfo.mDrawable.setTintList(tintInfo.mTintList);
21825                }
21826
21827                if (tintInfo.mHasTintMode) {
21828                    mForegroundInfo.mDrawable.setTintMode(tintInfo.mTintMode);
21829                }
21830
21831                // The drawable (or one of its children) may not have been
21832                // stateful before applying the tint, so let's try again.
21833                if (mForegroundInfo.mDrawable.isStateful()) {
21834                    mForegroundInfo.mDrawable.setState(getDrawableState());
21835                }
21836            }
21837        }
21838    }
21839
21840    /**
21841     * Get the drawable to be overlayed when a view is autofilled
21842     *
21843     * @return The drawable
21844     *
21845     * @throws IllegalStateException if the drawable could not be found.
21846     */
21847    @Nullable private Drawable getAutofilledDrawable() {
21848        if (mAttachInfo == null) {
21849            return null;
21850        }
21851        // Lazily load the isAutofilled drawable.
21852        if (mAttachInfo.mAutofilledDrawable == null) {
21853            Context rootContext = getRootView().getContext();
21854            TypedArray a = rootContext.getTheme().obtainStyledAttributes(AUTOFILL_HIGHLIGHT_ATTR);
21855            int attributeResourceId = a.getResourceId(0, 0);
21856            mAttachInfo.mAutofilledDrawable = rootContext.getDrawable(attributeResourceId);
21857            a.recycle();
21858        }
21859
21860        return mAttachInfo.mAutofilledDrawable;
21861    }
21862
21863    /**
21864     * Draw {@link View#isAutofilled()} highlight over view if the view is autofilled.
21865     *
21866     * @param canvas The canvas to draw on
21867     */
21868    private void drawAutofilledHighlight(@NonNull Canvas canvas) {
21869        if (isAutofilled()) {
21870            Drawable autofilledHighlight = getAutofilledDrawable();
21871
21872            if (autofilledHighlight != null) {
21873                autofilledHighlight.setBounds(0, 0, getWidth(), getHeight());
21874                autofilledHighlight.draw(canvas);
21875            }
21876        }
21877    }
21878
21879    /**
21880     * Draw any foreground content for this view.
21881     *
21882     * <p>Foreground content may consist of scroll bars, a {@link #setForeground foreground}
21883     * drawable or other view-specific decorations. The foreground is drawn on top of the
21884     * primary view content.</p>
21885     *
21886     * @param canvas canvas to draw into
21887     */
21888    public void onDrawForeground(Canvas canvas) {
21889        onDrawScrollIndicators(canvas);
21890        onDrawScrollBars(canvas);
21891
21892        final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
21893        if (foreground != null) {
21894            if (mForegroundInfo.mBoundsChanged) {
21895                mForegroundInfo.mBoundsChanged = false;
21896                final Rect selfBounds = mForegroundInfo.mSelfBounds;
21897                final Rect overlayBounds = mForegroundInfo.mOverlayBounds;
21898
21899                if (mForegroundInfo.mInsidePadding) {
21900                    selfBounds.set(0, 0, getWidth(), getHeight());
21901                } else {
21902                    selfBounds.set(getPaddingLeft(), getPaddingTop(),
21903                            getWidth() - getPaddingRight(), getHeight() - getPaddingBottom());
21904                }
21905
21906                final int ld = getLayoutDirection();
21907                Gravity.apply(mForegroundInfo.mGravity, foreground.getIntrinsicWidth(),
21908                        foreground.getIntrinsicHeight(), selfBounds, overlayBounds, ld);
21909                foreground.setBounds(overlayBounds);
21910            }
21911
21912            foreground.draw(canvas);
21913        }
21914    }
21915
21916    /**
21917     * Sets the padding. The view may add on the space required to display
21918     * the scrollbars, depending on the style and visibility of the scrollbars.
21919     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
21920     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
21921     * from the values set in this call.
21922     *
21923     * @attr ref android.R.styleable#View_padding
21924     * @attr ref android.R.styleable#View_paddingBottom
21925     * @attr ref android.R.styleable#View_paddingLeft
21926     * @attr ref android.R.styleable#View_paddingRight
21927     * @attr ref android.R.styleable#View_paddingTop
21928     * @param left the left padding in pixels
21929     * @param top the top padding in pixels
21930     * @param right the right padding in pixels
21931     * @param bottom the bottom padding in pixels
21932     */
21933    public void setPadding(int left, int top, int right, int bottom) {
21934        resetResolvedPaddingInternal();
21935
21936        mUserPaddingStart = UNDEFINED_PADDING;
21937        mUserPaddingEnd = UNDEFINED_PADDING;
21938
21939        mUserPaddingLeftInitial = left;
21940        mUserPaddingRightInitial = right;
21941
21942        mLeftPaddingDefined = true;
21943        mRightPaddingDefined = true;
21944
21945        internalSetPadding(left, top, right, bottom);
21946    }
21947
21948    /**
21949     * @hide
21950     */
21951    protected void internalSetPadding(int left, int top, int right, int bottom) {
21952        mUserPaddingLeft = left;
21953        mUserPaddingRight = right;
21954        mUserPaddingBottom = bottom;
21955
21956        final int viewFlags = mViewFlags;
21957        boolean changed = false;
21958
21959        // Common case is there are no scroll bars.
21960        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
21961            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
21962                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
21963                        ? 0 : getVerticalScrollbarWidth();
21964                switch (mVerticalScrollbarPosition) {
21965                    case SCROLLBAR_POSITION_DEFAULT:
21966                        if (isLayoutRtl()) {
21967                            left += offset;
21968                        } else {
21969                            right += offset;
21970                        }
21971                        break;
21972                    case SCROLLBAR_POSITION_RIGHT:
21973                        right += offset;
21974                        break;
21975                    case SCROLLBAR_POSITION_LEFT:
21976                        left += offset;
21977                        break;
21978                }
21979            }
21980            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
21981                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
21982                        ? 0 : getHorizontalScrollbarHeight();
21983            }
21984        }
21985
21986        if (mPaddingLeft != left) {
21987            changed = true;
21988            mPaddingLeft = left;
21989        }
21990        if (mPaddingTop != top) {
21991            changed = true;
21992            mPaddingTop = top;
21993        }
21994        if (mPaddingRight != right) {
21995            changed = true;
21996            mPaddingRight = right;
21997        }
21998        if (mPaddingBottom != bottom) {
21999            changed = true;
22000            mPaddingBottom = bottom;
22001        }
22002
22003        if (changed) {
22004            requestLayout();
22005            invalidateOutline();
22006        }
22007    }
22008
22009    /**
22010     * Sets the relative padding. The view may add on the space required to display
22011     * the scrollbars, depending on the style and visibility of the scrollbars.
22012     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
22013     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
22014     * from the values set in this call.
22015     *
22016     * @attr ref android.R.styleable#View_padding
22017     * @attr ref android.R.styleable#View_paddingBottom
22018     * @attr ref android.R.styleable#View_paddingStart
22019     * @attr ref android.R.styleable#View_paddingEnd
22020     * @attr ref android.R.styleable#View_paddingTop
22021     * @param start the start padding in pixels
22022     * @param top the top padding in pixels
22023     * @param end the end padding in pixels
22024     * @param bottom the bottom padding in pixels
22025     */
22026    public void setPaddingRelative(int start, int top, int end, int bottom) {
22027        resetResolvedPaddingInternal();
22028
22029        mUserPaddingStart = start;
22030        mUserPaddingEnd = end;
22031        mLeftPaddingDefined = true;
22032        mRightPaddingDefined = true;
22033
22034        switch(getLayoutDirection()) {
22035            case LAYOUT_DIRECTION_RTL:
22036                mUserPaddingLeftInitial = end;
22037                mUserPaddingRightInitial = start;
22038                internalSetPadding(end, top, start, bottom);
22039                break;
22040            case LAYOUT_DIRECTION_LTR:
22041            default:
22042                mUserPaddingLeftInitial = start;
22043                mUserPaddingRightInitial = end;
22044                internalSetPadding(start, top, end, bottom);
22045        }
22046    }
22047
22048    /**
22049     * Returns the top padding of this view.
22050     *
22051     * @return the top padding in pixels
22052     */
22053    public int getPaddingTop() {
22054        return mPaddingTop;
22055    }
22056
22057    /**
22058     * Returns the bottom padding of this view. If there are inset and enabled
22059     * scrollbars, this value may include the space required to display the
22060     * scrollbars as well.
22061     *
22062     * @return the bottom padding in pixels
22063     */
22064    public int getPaddingBottom() {
22065        return mPaddingBottom;
22066    }
22067
22068    /**
22069     * Returns the left padding of this view. If there are inset and enabled
22070     * scrollbars, this value may include the space required to display the
22071     * scrollbars as well.
22072     *
22073     * @return the left padding in pixels
22074     */
22075    public int getPaddingLeft() {
22076        if (!isPaddingResolved()) {
22077            resolvePadding();
22078        }
22079        return mPaddingLeft;
22080    }
22081
22082    /**
22083     * Returns the start padding of this view depending on its resolved layout direction.
22084     * If there are inset and enabled scrollbars, this value may include the space
22085     * required to display the scrollbars as well.
22086     *
22087     * @return the start padding in pixels
22088     */
22089    public int getPaddingStart() {
22090        if (!isPaddingResolved()) {
22091            resolvePadding();
22092        }
22093        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
22094                mPaddingRight : mPaddingLeft;
22095    }
22096
22097    /**
22098     * Returns the right padding of this view. If there are inset and enabled
22099     * scrollbars, this value may include the space required to display the
22100     * scrollbars as well.
22101     *
22102     * @return the right padding in pixels
22103     */
22104    public int getPaddingRight() {
22105        if (!isPaddingResolved()) {
22106            resolvePadding();
22107        }
22108        return mPaddingRight;
22109    }
22110
22111    /**
22112     * Returns the end padding of this view depending on its resolved layout direction.
22113     * If there are inset and enabled scrollbars, this value may include the space
22114     * required to display the scrollbars as well.
22115     *
22116     * @return the end padding in pixels
22117     */
22118    public int getPaddingEnd() {
22119        if (!isPaddingResolved()) {
22120            resolvePadding();
22121        }
22122        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
22123                mPaddingLeft : mPaddingRight;
22124    }
22125
22126    /**
22127     * Return if the padding has been set through relative values
22128     * {@link #setPaddingRelative(int, int, int, int)} or through
22129     * @attr ref android.R.styleable#View_paddingStart or
22130     * @attr ref android.R.styleable#View_paddingEnd
22131     *
22132     * @return true if the padding is relative or false if it is not.
22133     */
22134    public boolean isPaddingRelative() {
22135        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
22136    }
22137
22138    Insets computeOpticalInsets() {
22139        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
22140    }
22141
22142    /**
22143     * @hide
22144     */
22145    public void resetPaddingToInitialValues() {
22146        if (isRtlCompatibilityMode()) {
22147            mPaddingLeft = mUserPaddingLeftInitial;
22148            mPaddingRight = mUserPaddingRightInitial;
22149            return;
22150        }
22151        if (isLayoutRtl()) {
22152            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
22153            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
22154        } else {
22155            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
22156            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
22157        }
22158    }
22159
22160    /**
22161     * @hide
22162     */
22163    public Insets getOpticalInsets() {
22164        if (mLayoutInsets == null) {
22165            mLayoutInsets = computeOpticalInsets();
22166        }
22167        return mLayoutInsets;
22168    }
22169
22170    /**
22171     * Set this view's optical insets.
22172     *
22173     * <p>This method should be treated similarly to setMeasuredDimension and not as a general
22174     * property. Views that compute their own optical insets should call it as part of measurement.
22175     * This method does not request layout. If you are setting optical insets outside of
22176     * measure/layout itself you will want to call requestLayout() yourself.
22177     * </p>
22178     * @hide
22179     */
22180    public void setOpticalInsets(Insets insets) {
22181        mLayoutInsets = insets;
22182    }
22183
22184    /**
22185     * Changes the selection state of this view. A view can be selected or not.
22186     * Note that selection is not the same as focus. Views are typically
22187     * selected in the context of an AdapterView like ListView or GridView;
22188     * the selected view is the view that is highlighted.
22189     *
22190     * @param selected true if the view must be selected, false otherwise
22191     */
22192    public void setSelected(boolean selected) {
22193        //noinspection DoubleNegation
22194        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
22195            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
22196            if (!selected) resetPressedState();
22197            invalidate(true);
22198            refreshDrawableState();
22199            dispatchSetSelected(selected);
22200            if (selected) {
22201                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
22202            } else {
22203                notifyViewAccessibilityStateChangedIfNeeded(
22204                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
22205            }
22206        }
22207    }
22208
22209    /**
22210     * Dispatch setSelected to all of this View's children.
22211     *
22212     * @see #setSelected(boolean)
22213     *
22214     * @param selected The new selected state
22215     */
22216    protected void dispatchSetSelected(boolean selected) {
22217    }
22218
22219    /**
22220     * Indicates the selection state of this view.
22221     *
22222     * @return true if the view is selected, false otherwise
22223     */
22224    @ViewDebug.ExportedProperty
22225    public boolean isSelected() {
22226        return (mPrivateFlags & PFLAG_SELECTED) != 0;
22227    }
22228
22229    /**
22230     * Changes the activated state of this view. A view can be activated or not.
22231     * Note that activation is not the same as selection.  Selection is
22232     * a transient property, representing the view (hierarchy) the user is
22233     * currently interacting with.  Activation is a longer-term state that the
22234     * user can move views in and out of.  For example, in a list view with
22235     * single or multiple selection enabled, the views in the current selection
22236     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
22237     * here.)  The activated state is propagated down to children of the view it
22238     * is set on.
22239     *
22240     * @param activated true if the view must be activated, false otherwise
22241     */
22242    public void setActivated(boolean activated) {
22243        //noinspection DoubleNegation
22244        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
22245            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
22246            invalidate(true);
22247            refreshDrawableState();
22248            dispatchSetActivated(activated);
22249        }
22250    }
22251
22252    /**
22253     * Dispatch setActivated to all of this View's children.
22254     *
22255     * @see #setActivated(boolean)
22256     *
22257     * @param activated The new activated state
22258     */
22259    protected void dispatchSetActivated(boolean activated) {
22260    }
22261
22262    /**
22263     * Indicates the activation state of this view.
22264     *
22265     * @return true if the view is activated, false otherwise
22266     */
22267    @ViewDebug.ExportedProperty
22268    public boolean isActivated() {
22269        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
22270    }
22271
22272    /**
22273     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
22274     * observer can be used to get notifications when global events, like
22275     * layout, happen.
22276     *
22277     * The returned ViewTreeObserver observer is not guaranteed to remain
22278     * valid for the lifetime of this View. If the caller of this method keeps
22279     * a long-lived reference to ViewTreeObserver, it should always check for
22280     * the return value of {@link ViewTreeObserver#isAlive()}.
22281     *
22282     * @return The ViewTreeObserver for this view's hierarchy.
22283     */
22284    public ViewTreeObserver getViewTreeObserver() {
22285        if (mAttachInfo != null) {
22286            return mAttachInfo.mTreeObserver;
22287        }
22288        if (mFloatingTreeObserver == null) {
22289            mFloatingTreeObserver = new ViewTreeObserver(mContext);
22290        }
22291        return mFloatingTreeObserver;
22292    }
22293
22294    /**
22295     * <p>Finds the topmost view in the current view hierarchy.</p>
22296     *
22297     * @return the topmost view containing this view
22298     */
22299    public View getRootView() {
22300        if (mAttachInfo != null) {
22301            final View v = mAttachInfo.mRootView;
22302            if (v != null) {
22303                return v;
22304            }
22305        }
22306
22307        View parent = this;
22308
22309        while (parent.mParent != null && parent.mParent instanceof View) {
22310            parent = (View) parent.mParent;
22311        }
22312
22313        return parent;
22314    }
22315
22316    /**
22317     * Transforms a motion event from view-local coordinates to on-screen
22318     * coordinates.
22319     *
22320     * @param ev the view-local motion event
22321     * @return false if the transformation could not be applied
22322     * @hide
22323     */
22324    public boolean toGlobalMotionEvent(MotionEvent ev) {
22325        final AttachInfo info = mAttachInfo;
22326        if (info == null) {
22327            return false;
22328        }
22329
22330        final Matrix m = info.mTmpMatrix;
22331        m.set(Matrix.IDENTITY_MATRIX);
22332        transformMatrixToGlobal(m);
22333        ev.transform(m);
22334        return true;
22335    }
22336
22337    /**
22338     * Transforms a motion event from on-screen coordinates to view-local
22339     * coordinates.
22340     *
22341     * @param ev the on-screen motion event
22342     * @return false if the transformation could not be applied
22343     * @hide
22344     */
22345    public boolean toLocalMotionEvent(MotionEvent ev) {
22346        final AttachInfo info = mAttachInfo;
22347        if (info == null) {
22348            return false;
22349        }
22350
22351        final Matrix m = info.mTmpMatrix;
22352        m.set(Matrix.IDENTITY_MATRIX);
22353        transformMatrixToLocal(m);
22354        ev.transform(m);
22355        return true;
22356    }
22357
22358    /**
22359     * Modifies the input matrix such that it maps view-local coordinates to
22360     * on-screen coordinates.
22361     *
22362     * @param m input matrix to modify
22363     * @hide
22364     */
22365    public void transformMatrixToGlobal(Matrix m) {
22366        final ViewParent parent = mParent;
22367        if (parent instanceof View) {
22368            final View vp = (View) parent;
22369            vp.transformMatrixToGlobal(m);
22370            m.preTranslate(-vp.mScrollX, -vp.mScrollY);
22371        } else if (parent instanceof ViewRootImpl) {
22372            final ViewRootImpl vr = (ViewRootImpl) parent;
22373            vr.transformMatrixToGlobal(m);
22374            m.preTranslate(0, -vr.mCurScrollY);
22375        }
22376
22377        m.preTranslate(mLeft, mTop);
22378
22379        if (!hasIdentityMatrix()) {
22380            m.preConcat(getMatrix());
22381        }
22382    }
22383
22384    /**
22385     * Modifies the input matrix such that it maps on-screen coordinates to
22386     * view-local coordinates.
22387     *
22388     * @param m input matrix to modify
22389     * @hide
22390     */
22391    public void transformMatrixToLocal(Matrix m) {
22392        final ViewParent parent = mParent;
22393        if (parent instanceof View) {
22394            final View vp = (View) parent;
22395            vp.transformMatrixToLocal(m);
22396            m.postTranslate(vp.mScrollX, vp.mScrollY);
22397        } else if (parent instanceof ViewRootImpl) {
22398            final ViewRootImpl vr = (ViewRootImpl) parent;
22399            vr.transformMatrixToLocal(m);
22400            m.postTranslate(0, vr.mCurScrollY);
22401        }
22402
22403        m.postTranslate(-mLeft, -mTop);
22404
22405        if (!hasIdentityMatrix()) {
22406            m.postConcat(getInverseMatrix());
22407        }
22408    }
22409
22410    /**
22411     * @hide
22412     */
22413    @ViewDebug.ExportedProperty(category = "layout", indexMapping = {
22414            @ViewDebug.IntToString(from = 0, to = "x"),
22415            @ViewDebug.IntToString(from = 1, to = "y")
22416    })
22417    public int[] getLocationOnScreen() {
22418        int[] location = new int[2];
22419        getLocationOnScreen(location);
22420        return location;
22421    }
22422
22423    /**
22424     * <p>Computes the coordinates of this view on the screen. The argument
22425     * must be an array of two integers. After the method returns, the array
22426     * contains the x and y location in that order.</p>
22427     *
22428     * @param outLocation an array of two integers in which to hold the coordinates
22429     */
22430    public void getLocationOnScreen(@Size(2) int[] outLocation) {
22431        getLocationInWindow(outLocation);
22432
22433        final AttachInfo info = mAttachInfo;
22434        if (info != null) {
22435            outLocation[0] += info.mWindowLeft;
22436            outLocation[1] += info.mWindowTop;
22437        }
22438    }
22439
22440    /**
22441     * <p>Computes the coordinates of this view in its window. The argument
22442     * must be an array of two integers. After the method returns, the array
22443     * contains the x and y location in that order.</p>
22444     *
22445     * @param outLocation an array of two integers in which to hold the coordinates
22446     */
22447    public void getLocationInWindow(@Size(2) int[] outLocation) {
22448        if (outLocation == null || outLocation.length < 2) {
22449            throw new IllegalArgumentException("outLocation must be an array of two integers");
22450        }
22451
22452        outLocation[0] = 0;
22453        outLocation[1] = 0;
22454
22455        transformFromViewToWindowSpace(outLocation);
22456    }
22457
22458    /** @hide */
22459    public void transformFromViewToWindowSpace(@Size(2) int[] inOutLocation) {
22460        if (inOutLocation == null || inOutLocation.length < 2) {
22461            throw new IllegalArgumentException("inOutLocation must be an array of two integers");
22462        }
22463
22464        if (mAttachInfo == null) {
22465            // When the view is not attached to a window, this method does not make sense
22466            inOutLocation[0] = inOutLocation[1] = 0;
22467            return;
22468        }
22469
22470        float position[] = mAttachInfo.mTmpTransformLocation;
22471        position[0] = inOutLocation[0];
22472        position[1] = inOutLocation[1];
22473
22474        if (!hasIdentityMatrix()) {
22475            getMatrix().mapPoints(position);
22476        }
22477
22478        position[0] += mLeft;
22479        position[1] += mTop;
22480
22481        ViewParent viewParent = mParent;
22482        while (viewParent instanceof View) {
22483            final View view = (View) viewParent;
22484
22485            position[0] -= view.mScrollX;
22486            position[1] -= view.mScrollY;
22487
22488            if (!view.hasIdentityMatrix()) {
22489                view.getMatrix().mapPoints(position);
22490            }
22491
22492            position[0] += view.mLeft;
22493            position[1] += view.mTop;
22494
22495            viewParent = view.mParent;
22496         }
22497
22498        if (viewParent instanceof ViewRootImpl) {
22499            // *cough*
22500            final ViewRootImpl vr = (ViewRootImpl) viewParent;
22501            position[1] -= vr.mCurScrollY;
22502        }
22503
22504        inOutLocation[0] = Math.round(position[0]);
22505        inOutLocation[1] = Math.round(position[1]);
22506    }
22507
22508    /**
22509     * @param id the id of the view to be found
22510     * @return the view of the specified id, null if cannot be found
22511     * @hide
22512     */
22513    protected <T extends View> T findViewTraversal(@IdRes int id) {
22514        if (id == mID) {
22515            return (T) this;
22516        }
22517        return null;
22518    }
22519
22520    /**
22521     * @param tag the tag of the view to be found
22522     * @return the view of specified tag, null if cannot be found
22523     * @hide
22524     */
22525    protected <T extends View> T findViewWithTagTraversal(Object tag) {
22526        if (tag != null && tag.equals(mTag)) {
22527            return (T) this;
22528        }
22529        return null;
22530    }
22531
22532    /**
22533     * @param predicate The predicate to evaluate.
22534     * @param childToSkip If not null, ignores this child during the recursive traversal.
22535     * @return The first view that matches the predicate or null.
22536     * @hide
22537     */
22538    protected <T extends View> T findViewByPredicateTraversal(Predicate<View> predicate,
22539            View childToSkip) {
22540        if (predicate.test(this)) {
22541            return (T) this;
22542        }
22543        return null;
22544    }
22545
22546    /**
22547     * Finds the first descendant view with the given ID, the view itself if
22548     * the ID matches {@link #getId()}, or {@code null} if the ID is invalid
22549     * (< 0) or there is no matching view in the hierarchy.
22550     * <p>
22551     * <strong>Note:</strong> In most cases -- depending on compiler support --
22552     * the resulting view is automatically cast to the target class type. If
22553     * the target class type is unconstrained, an explicit cast may be
22554     * necessary.
22555     *
22556     * @param id the ID to search for
22557     * @return a view with given ID if found, or {@code null} otherwise
22558     * @see View#requireViewById(int)
22559     */
22560    @Nullable
22561    public final <T extends View> T findViewById(@IdRes int id) {
22562        if (id == NO_ID) {
22563            return null;
22564        }
22565        return findViewTraversal(id);
22566    }
22567
22568    /**
22569     * Finds the first descendant view with the given ID, the view itself if the ID matches
22570     * {@link #getId()}, or throws an IllegalArgumentException if the ID is invalid or there is no
22571     * matching view in the hierarchy.
22572     * <p>
22573     * <strong>Note:</strong> In most cases -- depending on compiler support --
22574     * the resulting view is automatically cast to the target class type. If
22575     * the target class type is unconstrained, an explicit cast may be
22576     * necessary.
22577     *
22578     * @param id the ID to search for
22579     * @return a view with given ID
22580     * @see View#findViewById(int)
22581     */
22582    @NonNull
22583    public final <T extends View> T requireViewById(@IdRes int id) {
22584        T view = findViewById(id);
22585        if (view == null) {
22586            throw new IllegalArgumentException("ID does not reference a View inside this View");
22587        }
22588        return view;
22589    }
22590
22591    /**
22592     * Finds a view by its unuque and stable accessibility id.
22593     *
22594     * @param accessibilityId The searched accessibility id.
22595     * @return The found view.
22596     */
22597    final <T extends View> T findViewByAccessibilityId(int accessibilityId) {
22598        if (accessibilityId < 0) {
22599            return null;
22600        }
22601        T view = findViewByAccessibilityIdTraversal(accessibilityId);
22602        if (view != null) {
22603            return view.includeForAccessibility() ? view : null;
22604        }
22605        return null;
22606    }
22607
22608    /**
22609     * Performs the traversal to find a view by its unique and stable accessibility id.
22610     *
22611     * <strong>Note:</strong>This method does not stop at the root namespace
22612     * boundary since the user can touch the screen at an arbitrary location
22613     * potentially crossing the root namespace boundary which will send an
22614     * accessibility event to accessibility services and they should be able
22615     * to obtain the event source. Also accessibility ids are guaranteed to be
22616     * unique in the window.
22617     *
22618     * @param accessibilityId The accessibility id.
22619     * @return The found view.
22620     * @hide
22621     */
22622    public <T extends View> T findViewByAccessibilityIdTraversal(int accessibilityId) {
22623        if (getAccessibilityViewId() == accessibilityId) {
22624            return (T) this;
22625        }
22626        return null;
22627    }
22628
22629    /**
22630     * Performs the traversal to find a view by its autofill id.
22631     *
22632     * <strong>Note:</strong>This method does not stop at the root namespace
22633     * boundary.
22634     *
22635     * @param autofillId The autofill id.
22636     * @return The found view.
22637     * @hide
22638     */
22639    public <T extends View> T findViewByAutofillIdTraversal(int autofillId) {
22640        if (getAutofillViewId() == autofillId) {
22641            return (T) this;
22642        }
22643        return null;
22644    }
22645
22646    /**
22647     * Look for a child view with the given tag.  If this view has the given
22648     * tag, return this view.
22649     *
22650     * @param tag The tag to search for, using "tag.equals(getTag())".
22651     * @return The View that has the given tag in the hierarchy or null
22652     */
22653    public final <T extends View> T findViewWithTag(Object tag) {
22654        if (tag == null) {
22655            return null;
22656        }
22657        return findViewWithTagTraversal(tag);
22658    }
22659
22660    /**
22661     * Look for a child view that matches the specified predicate.
22662     * If this view matches the predicate, return this view.
22663     *
22664     * @param predicate The predicate to evaluate.
22665     * @return The first view that matches the predicate or null.
22666     * @hide
22667     */
22668    public final <T extends View> T findViewByPredicate(Predicate<View> predicate) {
22669        return findViewByPredicateTraversal(predicate, null);
22670    }
22671
22672    /**
22673     * Look for a child view that matches the specified predicate,
22674     * starting with the specified view and its descendents and then
22675     * recusively searching the ancestors and siblings of that view
22676     * until this view is reached.
22677     *
22678     * This method is useful in cases where the predicate does not match
22679     * a single unique view (perhaps multiple views use the same id)
22680     * and we are trying to find the view that is "closest" in scope to the
22681     * starting view.
22682     *
22683     * @param start The view to start from.
22684     * @param predicate The predicate to evaluate.
22685     * @return The first view that matches the predicate or null.
22686     * @hide
22687     */
22688    public final <T extends View> T findViewByPredicateInsideOut(
22689            View start, Predicate<View> predicate) {
22690        View childToSkip = null;
22691        for (;;) {
22692            T view = start.findViewByPredicateTraversal(predicate, childToSkip);
22693            if (view != null || start == this) {
22694                return view;
22695            }
22696
22697            ViewParent parent = start.getParent();
22698            if (parent == null || !(parent instanceof View)) {
22699                return null;
22700            }
22701
22702            childToSkip = start;
22703            start = (View) parent;
22704        }
22705    }
22706
22707    /**
22708     * Sets the identifier for this view. The identifier does not have to be
22709     * unique in this view's hierarchy. The identifier should be a positive
22710     * number.
22711     *
22712     * @see #NO_ID
22713     * @see #getId()
22714     * @see #findViewById(int)
22715     *
22716     * @param id a number used to identify the view
22717     *
22718     * @attr ref android.R.styleable#View_id
22719     */
22720    public void setId(@IdRes int id) {
22721        mID = id;
22722        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
22723            mID = generateViewId();
22724        }
22725    }
22726
22727    /**
22728     * {@hide}
22729     *
22730     * @param isRoot true if the view belongs to the root namespace, false
22731     *        otherwise
22732     */
22733    public void setIsRootNamespace(boolean isRoot) {
22734        if (isRoot) {
22735            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
22736        } else {
22737            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
22738        }
22739    }
22740
22741    /**
22742     * {@hide}
22743     *
22744     * @return true if the view belongs to the root namespace, false otherwise
22745     */
22746    public boolean isRootNamespace() {
22747        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
22748    }
22749
22750    /**
22751     * Returns this view's identifier.
22752     *
22753     * @return a positive integer used to identify the view or {@link #NO_ID}
22754     *         if the view has no ID
22755     *
22756     * @see #setId(int)
22757     * @see #findViewById(int)
22758     * @attr ref android.R.styleable#View_id
22759     */
22760    @IdRes
22761    @ViewDebug.CapturedViewProperty
22762    public int getId() {
22763        return mID;
22764    }
22765
22766    /**
22767     * Returns this view's tag.
22768     *
22769     * @return the Object stored in this view as a tag, or {@code null} if not
22770     *         set
22771     *
22772     * @see #setTag(Object)
22773     * @see #getTag(int)
22774     */
22775    @ViewDebug.ExportedProperty
22776    public Object getTag() {
22777        return mTag;
22778    }
22779
22780    /**
22781     * Sets the tag associated with this view. A tag can be used to mark
22782     * a view in its hierarchy and does not have to be unique within the
22783     * hierarchy. Tags can also be used to store data within a view without
22784     * resorting to another data structure.
22785     *
22786     * @param tag an Object to tag the view with
22787     *
22788     * @see #getTag()
22789     * @see #setTag(int, Object)
22790     */
22791    public void setTag(final Object tag) {
22792        mTag = tag;
22793    }
22794
22795    /**
22796     * Returns the tag associated with this view and the specified key.
22797     *
22798     * @param key The key identifying the tag
22799     *
22800     * @return the Object stored in this view as a tag, or {@code null} if not
22801     *         set
22802     *
22803     * @see #setTag(int, Object)
22804     * @see #getTag()
22805     */
22806    public Object getTag(int key) {
22807        if (mKeyedTags != null) return mKeyedTags.get(key);
22808        return null;
22809    }
22810
22811    /**
22812     * Sets a tag associated with this view and a key. A tag can be used
22813     * to mark a view in its hierarchy and does not have to be unique within
22814     * the hierarchy. Tags can also be used to store data within a view
22815     * without resorting to another data structure.
22816     *
22817     * The specified key should be an id declared in the resources of the
22818     * application to ensure it is unique (see the <a
22819     * href="{@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
22820     * Keys identified as belonging to
22821     * the Android framework or not associated with any package will cause
22822     * an {@link IllegalArgumentException} to be thrown.
22823     *
22824     * @param key The key identifying the tag
22825     * @param tag An Object to tag the view with
22826     *
22827     * @throws IllegalArgumentException If they specified key is not valid
22828     *
22829     * @see #setTag(Object)
22830     * @see #getTag(int)
22831     */
22832    public void setTag(int key, final Object tag) {
22833        // If the package id is 0x00 or 0x01, it's either an undefined package
22834        // or a framework id
22835        if ((key >>> 24) < 2) {
22836            throw new IllegalArgumentException("The key must be an application-specific "
22837                    + "resource id.");
22838        }
22839
22840        setKeyedTag(key, tag);
22841    }
22842
22843    /**
22844     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
22845     * framework id.
22846     *
22847     * @hide
22848     */
22849    public void setTagInternal(int key, Object tag) {
22850        if ((key >>> 24) != 0x1) {
22851            throw new IllegalArgumentException("The key must be a framework-specific "
22852                    + "resource id.");
22853        }
22854
22855        setKeyedTag(key, tag);
22856    }
22857
22858    private void setKeyedTag(int key, Object tag) {
22859        if (mKeyedTags == null) {
22860            mKeyedTags = new SparseArray<Object>(2);
22861        }
22862
22863        mKeyedTags.put(key, tag);
22864    }
22865
22866    /**
22867     * Prints information about this view in the log output, with the tag
22868     * {@link #VIEW_LOG_TAG}.
22869     *
22870     * @hide
22871     */
22872    public void debug() {
22873        debug(0);
22874    }
22875
22876    /**
22877     * Prints information about this view in the log output, with the tag
22878     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
22879     * indentation defined by the <code>depth</code>.
22880     *
22881     * @param depth the indentation level
22882     *
22883     * @hide
22884     */
22885    protected void debug(int depth) {
22886        String output = debugIndent(depth - 1);
22887
22888        output += "+ " + this;
22889        int id = getId();
22890        if (id != -1) {
22891            output += " (id=" + id + ")";
22892        }
22893        Object tag = getTag();
22894        if (tag != null) {
22895            output += " (tag=" + tag + ")";
22896        }
22897        Log.d(VIEW_LOG_TAG, output);
22898
22899        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
22900            output = debugIndent(depth) + " FOCUSED";
22901            Log.d(VIEW_LOG_TAG, output);
22902        }
22903
22904        output = debugIndent(depth);
22905        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
22906                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
22907                + "} ";
22908        Log.d(VIEW_LOG_TAG, output);
22909
22910        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
22911                || mPaddingBottom != 0) {
22912            output = debugIndent(depth);
22913            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
22914                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
22915            Log.d(VIEW_LOG_TAG, output);
22916        }
22917
22918        output = debugIndent(depth);
22919        output += "mMeasureWidth=" + mMeasuredWidth +
22920                " mMeasureHeight=" + mMeasuredHeight;
22921        Log.d(VIEW_LOG_TAG, output);
22922
22923        output = debugIndent(depth);
22924        if (mLayoutParams == null) {
22925            output += "BAD! no layout params";
22926        } else {
22927            output = mLayoutParams.debug(output);
22928        }
22929        Log.d(VIEW_LOG_TAG, output);
22930
22931        output = debugIndent(depth);
22932        output += "flags={";
22933        output += View.printFlags(mViewFlags);
22934        output += "}";
22935        Log.d(VIEW_LOG_TAG, output);
22936
22937        output = debugIndent(depth);
22938        output += "privateFlags={";
22939        output += View.printPrivateFlags(mPrivateFlags);
22940        output += "}";
22941        Log.d(VIEW_LOG_TAG, output);
22942    }
22943
22944    /**
22945     * Creates a string of whitespaces used for indentation.
22946     *
22947     * @param depth the indentation level
22948     * @return a String containing (depth * 2 + 3) * 2 white spaces
22949     *
22950     * @hide
22951     */
22952    protected static String debugIndent(int depth) {
22953        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
22954        for (int i = 0; i < (depth * 2) + 3; i++) {
22955            spaces.append(' ').append(' ');
22956        }
22957        return spaces.toString();
22958    }
22959
22960    /**
22961     * <p>Return the offset of the widget's text baseline from the widget's top
22962     * boundary. If this widget does not support baseline alignment, this
22963     * method returns -1. </p>
22964     *
22965     * @return the offset of the baseline within the widget's bounds or -1
22966     *         if baseline alignment is not supported
22967     */
22968    @ViewDebug.ExportedProperty(category = "layout")
22969    public int getBaseline() {
22970        return -1;
22971    }
22972
22973    /**
22974     * Returns whether the view hierarchy is currently undergoing a layout pass. This
22975     * information is useful to avoid situations such as calling {@link #requestLayout()} during
22976     * a layout pass.
22977     *
22978     * @return whether the view hierarchy is currently undergoing a layout pass
22979     */
22980    public boolean isInLayout() {
22981        ViewRootImpl viewRoot = getViewRootImpl();
22982        return (viewRoot != null && viewRoot.isInLayout());
22983    }
22984
22985    /**
22986     * Call this when something has changed which has invalidated the
22987     * layout of this view. This will schedule a layout pass of the view
22988     * tree. This should not be called while the view hierarchy is currently in a layout
22989     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
22990     * end of the current layout pass (and then layout will run again) or after the current
22991     * frame is drawn and the next layout occurs.
22992     *
22993     * <p>Subclasses which override this method should call the superclass method to
22994     * handle possible request-during-layout errors correctly.</p>
22995     */
22996    @CallSuper
22997    public void requestLayout() {
22998        if (mMeasureCache != null) mMeasureCache.clear();
22999
23000        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
23001            // Only trigger request-during-layout logic if this is the view requesting it,
23002            // not the views in its parent hierarchy
23003            ViewRootImpl viewRoot = getViewRootImpl();
23004            if (viewRoot != null && viewRoot.isInLayout()) {
23005                if (!viewRoot.requestLayoutDuringLayout(this)) {
23006                    return;
23007                }
23008            }
23009            mAttachInfo.mViewRequestingLayout = this;
23010        }
23011
23012        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
23013        mPrivateFlags |= PFLAG_INVALIDATED;
23014
23015        if (mParent != null && !mParent.isLayoutRequested()) {
23016            mParent.requestLayout();
23017        }
23018        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
23019            mAttachInfo.mViewRequestingLayout = null;
23020        }
23021    }
23022
23023    /**
23024     * Forces this view to be laid out during the next layout pass.
23025     * This method does not call requestLayout() or forceLayout()
23026     * on the parent.
23027     */
23028    public void forceLayout() {
23029        if (mMeasureCache != null) mMeasureCache.clear();
23030
23031        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
23032        mPrivateFlags |= PFLAG_INVALIDATED;
23033    }
23034
23035    /**
23036     * <p>
23037     * This is called to find out how big a view should be. The parent
23038     * supplies constraint information in the width and height parameters.
23039     * </p>
23040     *
23041     * <p>
23042     * The actual measurement work of a view is performed in
23043     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
23044     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
23045     * </p>
23046     *
23047     *
23048     * @param widthMeasureSpec Horizontal space requirements as imposed by the
23049     *        parent
23050     * @param heightMeasureSpec Vertical space requirements as imposed by the
23051     *        parent
23052     *
23053     * @see #onMeasure(int, int)
23054     */
23055    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
23056        boolean optical = isLayoutModeOptical(this);
23057        if (optical != isLayoutModeOptical(mParent)) {
23058            Insets insets = getOpticalInsets();
23059            int oWidth  = insets.left + insets.right;
23060            int oHeight = insets.top  + insets.bottom;
23061            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
23062            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
23063        }
23064
23065        // Suppress sign extension for the low bytes
23066        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
23067        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
23068
23069        final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
23070
23071        // Optimize layout by avoiding an extra EXACTLY pass when the view is
23072        // already measured as the correct size. In API 23 and below, this
23073        // extra pass is required to make LinearLayout re-distribute weight.
23074        final boolean specChanged = widthMeasureSpec != mOldWidthMeasureSpec
23075                || heightMeasureSpec != mOldHeightMeasureSpec;
23076        final boolean isSpecExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY
23077                && MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY;
23078        final boolean matchesSpecSize = getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec)
23079                && getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec);
23080        final boolean needsLayout = specChanged
23081                && (sAlwaysRemeasureExactly || !isSpecExactly || !matchesSpecSize);
23082
23083        if (forceLayout || needsLayout) {
23084            // first clears the measured dimension flag
23085            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
23086
23087            resolveRtlPropertiesIfNeeded();
23088
23089            int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key);
23090            if (cacheIndex < 0 || sIgnoreMeasureCache) {
23091                // measure ourselves, this should set the measured dimension flag back
23092                onMeasure(widthMeasureSpec, heightMeasureSpec);
23093                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
23094            } else {
23095                long value = mMeasureCache.valueAt(cacheIndex);
23096                // Casting a long to int drops the high 32 bits, no mask needed
23097                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
23098                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
23099            }
23100
23101            // flag not set, setMeasuredDimension() was not invoked, we raise
23102            // an exception to warn the developer
23103            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
23104                throw new IllegalStateException("View with id " + getId() + ": "
23105                        + getClass().getName() + "#onMeasure() did not set the"
23106                        + " measured dimension by calling"
23107                        + " setMeasuredDimension()");
23108            }
23109
23110            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
23111        }
23112
23113        mOldWidthMeasureSpec = widthMeasureSpec;
23114        mOldHeightMeasureSpec = heightMeasureSpec;
23115
23116        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
23117                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
23118    }
23119
23120    /**
23121     * <p>
23122     * Measure the view and its content to determine the measured width and the
23123     * measured height. This method is invoked by {@link #measure(int, int)} and
23124     * should be overridden by subclasses to provide accurate and efficient
23125     * measurement of their contents.
23126     * </p>
23127     *
23128     * <p>
23129     * <strong>CONTRACT:</strong> When overriding this method, you
23130     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
23131     * measured width and height of this view. Failure to do so will trigger an
23132     * <code>IllegalStateException</code>, thrown by
23133     * {@link #measure(int, int)}. Calling the superclass'
23134     * {@link #onMeasure(int, int)} is a valid use.
23135     * </p>
23136     *
23137     * <p>
23138     * The base class implementation of measure defaults to the background size,
23139     * unless a larger size is allowed by the MeasureSpec. Subclasses should
23140     * override {@link #onMeasure(int, int)} to provide better measurements of
23141     * their content.
23142     * </p>
23143     *
23144     * <p>
23145     * If this method is overridden, it is the subclass's responsibility to make
23146     * sure the measured height and width are at least the view's minimum height
23147     * and width ({@link #getSuggestedMinimumHeight()} and
23148     * {@link #getSuggestedMinimumWidth()}).
23149     * </p>
23150     *
23151     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
23152     *                         The requirements are encoded with
23153     *                         {@link android.view.View.MeasureSpec}.
23154     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
23155     *                         The requirements are encoded with
23156     *                         {@link android.view.View.MeasureSpec}.
23157     *
23158     * @see #getMeasuredWidth()
23159     * @see #getMeasuredHeight()
23160     * @see #setMeasuredDimension(int, int)
23161     * @see #getSuggestedMinimumHeight()
23162     * @see #getSuggestedMinimumWidth()
23163     * @see android.view.View.MeasureSpec#getMode(int)
23164     * @see android.view.View.MeasureSpec#getSize(int)
23165     */
23166    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
23167        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
23168                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
23169    }
23170
23171    /**
23172     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
23173     * measured width and measured height. Failing to do so will trigger an
23174     * exception at measurement time.</p>
23175     *
23176     * @param measuredWidth The measured width of this view.  May be a complex
23177     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
23178     * {@link #MEASURED_STATE_TOO_SMALL}.
23179     * @param measuredHeight The measured height of this view.  May be a complex
23180     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
23181     * {@link #MEASURED_STATE_TOO_SMALL}.
23182     */
23183    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
23184        boolean optical = isLayoutModeOptical(this);
23185        if (optical != isLayoutModeOptical(mParent)) {
23186            Insets insets = getOpticalInsets();
23187            int opticalWidth  = insets.left + insets.right;
23188            int opticalHeight = insets.top  + insets.bottom;
23189
23190            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
23191            measuredHeight += optical ? opticalHeight : -opticalHeight;
23192        }
23193        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
23194    }
23195
23196    /**
23197     * Sets the measured dimension without extra processing for things like optical bounds.
23198     * Useful for reapplying consistent values that have already been cooked with adjustments
23199     * for optical bounds, etc. such as those from the measurement cache.
23200     *
23201     * @param measuredWidth The measured width of this view.  May be a complex
23202     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
23203     * {@link #MEASURED_STATE_TOO_SMALL}.
23204     * @param measuredHeight The measured height of this view.  May be a complex
23205     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
23206     * {@link #MEASURED_STATE_TOO_SMALL}.
23207     */
23208    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
23209        mMeasuredWidth = measuredWidth;
23210        mMeasuredHeight = measuredHeight;
23211
23212        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
23213    }
23214
23215    /**
23216     * Merge two states as returned by {@link #getMeasuredState()}.
23217     * @param curState The current state as returned from a view or the result
23218     * of combining multiple views.
23219     * @param newState The new view state to combine.
23220     * @return Returns a new integer reflecting the combination of the two
23221     * states.
23222     */
23223    public static int combineMeasuredStates(int curState, int newState) {
23224        return curState | newState;
23225    }
23226
23227    /**
23228     * Version of {@link #resolveSizeAndState(int, int, int)}
23229     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
23230     */
23231    public static int resolveSize(int size, int measureSpec) {
23232        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
23233    }
23234
23235    /**
23236     * Utility to reconcile a desired size and state, with constraints imposed
23237     * by a MeasureSpec. Will take the desired size, unless a different size
23238     * is imposed by the constraints. The returned value is a compound integer,
23239     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
23240     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the
23241     * resulting size is smaller than the size the view wants to be.
23242     *
23243     * @param size How big the view wants to be.
23244     * @param measureSpec Constraints imposed by the parent.
23245     * @param childMeasuredState Size information bit mask for the view's
23246     *                           children.
23247     * @return Size information bit mask as defined by
23248     *         {@link #MEASURED_SIZE_MASK} and
23249     *         {@link #MEASURED_STATE_TOO_SMALL}.
23250     */
23251    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
23252        final int specMode = MeasureSpec.getMode(measureSpec);
23253        final int specSize = MeasureSpec.getSize(measureSpec);
23254        final int result;
23255        switch (specMode) {
23256            case MeasureSpec.AT_MOST:
23257                if (specSize < size) {
23258                    result = specSize | MEASURED_STATE_TOO_SMALL;
23259                } else {
23260                    result = size;
23261                }
23262                break;
23263            case MeasureSpec.EXACTLY:
23264                result = specSize;
23265                break;
23266            case MeasureSpec.UNSPECIFIED:
23267            default:
23268                result = size;
23269        }
23270        return result | (childMeasuredState & MEASURED_STATE_MASK);
23271    }
23272
23273    /**
23274     * Utility to return a default size. Uses the supplied size if the
23275     * MeasureSpec imposed no constraints. Will get larger if allowed
23276     * by the MeasureSpec.
23277     *
23278     * @param size Default size for this view
23279     * @param measureSpec Constraints imposed by the parent
23280     * @return The size this view should be.
23281     */
23282    public static int getDefaultSize(int size, int measureSpec) {
23283        int result = size;
23284        int specMode = MeasureSpec.getMode(measureSpec);
23285        int specSize = MeasureSpec.getSize(measureSpec);
23286
23287        switch (specMode) {
23288        case MeasureSpec.UNSPECIFIED:
23289            result = size;
23290            break;
23291        case MeasureSpec.AT_MOST:
23292        case MeasureSpec.EXACTLY:
23293            result = specSize;
23294            break;
23295        }
23296        return result;
23297    }
23298
23299    /**
23300     * Returns the suggested minimum height that the view should use. This
23301     * returns the maximum of the view's minimum height
23302     * and the background's minimum height
23303     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
23304     * <p>
23305     * When being used in {@link #onMeasure(int, int)}, the caller should still
23306     * ensure the returned height is within the requirements of the parent.
23307     *
23308     * @return The suggested minimum height of the view.
23309     */
23310    protected int getSuggestedMinimumHeight() {
23311        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
23312
23313    }
23314
23315    /**
23316     * Returns the suggested minimum width that the view should use. This
23317     * returns the maximum of the view's minimum width
23318     * and the background's minimum width
23319     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
23320     * <p>
23321     * When being used in {@link #onMeasure(int, int)}, the caller should still
23322     * ensure the returned width is within the requirements of the parent.
23323     *
23324     * @return The suggested minimum width of the view.
23325     */
23326    protected int getSuggestedMinimumWidth() {
23327        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
23328    }
23329
23330    /**
23331     * Returns the minimum height of the view.
23332     *
23333     * @return the minimum height the view will try to be, in pixels
23334     *
23335     * @see #setMinimumHeight(int)
23336     *
23337     * @attr ref android.R.styleable#View_minHeight
23338     */
23339    public int getMinimumHeight() {
23340        return mMinHeight;
23341    }
23342
23343    /**
23344     * Sets the minimum height of the view. It is not guaranteed the view will
23345     * be able to achieve this minimum height (for example, if its parent layout
23346     * constrains it with less available height).
23347     *
23348     * @param minHeight The minimum height the view will try to be, in pixels
23349     *
23350     * @see #getMinimumHeight()
23351     *
23352     * @attr ref android.R.styleable#View_minHeight
23353     */
23354    @RemotableViewMethod
23355    public void setMinimumHeight(int minHeight) {
23356        mMinHeight = minHeight;
23357        requestLayout();
23358    }
23359
23360    /**
23361     * Returns the minimum width of the view.
23362     *
23363     * @return the minimum width the view will try to be, in pixels
23364     *
23365     * @see #setMinimumWidth(int)
23366     *
23367     * @attr ref android.R.styleable#View_minWidth
23368     */
23369    public int getMinimumWidth() {
23370        return mMinWidth;
23371    }
23372
23373    /**
23374     * Sets the minimum width of the view. It is not guaranteed the view will
23375     * be able to achieve this minimum width (for example, if its parent layout
23376     * constrains it with less available width).
23377     *
23378     * @param minWidth The minimum width the view will try to be, in pixels
23379     *
23380     * @see #getMinimumWidth()
23381     *
23382     * @attr ref android.R.styleable#View_minWidth
23383     */
23384    public void setMinimumWidth(int minWidth) {
23385        mMinWidth = minWidth;
23386        requestLayout();
23387
23388    }
23389
23390    /**
23391     * Get the animation currently associated with this view.
23392     *
23393     * @return The animation that is currently playing or
23394     *         scheduled to play for this view.
23395     */
23396    public Animation getAnimation() {
23397        return mCurrentAnimation;
23398    }
23399
23400    /**
23401     * Start the specified animation now.
23402     *
23403     * @param animation the animation to start now
23404     */
23405    public void startAnimation(Animation animation) {
23406        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
23407        setAnimation(animation);
23408        invalidateParentCaches();
23409        invalidate(true);
23410    }
23411
23412    /**
23413     * Cancels any animations for this view.
23414     */
23415    public void clearAnimation() {
23416        if (mCurrentAnimation != null) {
23417            mCurrentAnimation.detach();
23418        }
23419        mCurrentAnimation = null;
23420        invalidateParentIfNeeded();
23421    }
23422
23423    /**
23424     * Sets the next animation to play for this view.
23425     * If you want the animation to play immediately, use
23426     * {@link #startAnimation(android.view.animation.Animation)} instead.
23427     * This method provides allows fine-grained
23428     * control over the start time and invalidation, but you
23429     * must make sure that 1) the animation has a start time set, and
23430     * 2) the view's parent (which controls animations on its children)
23431     * will be invalidated when the animation is supposed to
23432     * start.
23433     *
23434     * @param animation The next animation, or null.
23435     */
23436    public void setAnimation(Animation animation) {
23437        mCurrentAnimation = animation;
23438
23439        if (animation != null) {
23440            // If the screen is off assume the animation start time is now instead of
23441            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
23442            // would cause the animation to start when the screen turns back on
23443            if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF
23444                    && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
23445                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
23446            }
23447            animation.reset();
23448        }
23449    }
23450
23451    /**
23452     * Invoked by a parent ViewGroup to notify the start of the animation
23453     * currently associated with this view. If you override this method,
23454     * always call super.onAnimationStart();
23455     *
23456     * @see #setAnimation(android.view.animation.Animation)
23457     * @see #getAnimation()
23458     */
23459    @CallSuper
23460    protected void onAnimationStart() {
23461        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
23462    }
23463
23464    /**
23465     * Invoked by a parent ViewGroup to notify the end of the animation
23466     * currently associated with this view. If you override this method,
23467     * always call super.onAnimationEnd();
23468     *
23469     * @see #setAnimation(android.view.animation.Animation)
23470     * @see #getAnimation()
23471     */
23472    @CallSuper
23473    protected void onAnimationEnd() {
23474        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
23475    }
23476
23477    /**
23478     * Invoked if there is a Transform that involves alpha. Subclass that can
23479     * draw themselves with the specified alpha should return true, and then
23480     * respect that alpha when their onDraw() is called. If this returns false
23481     * then the view may be redirected to draw into an offscreen buffer to
23482     * fulfill the request, which will look fine, but may be slower than if the
23483     * subclass handles it internally. The default implementation returns false.
23484     *
23485     * @param alpha The alpha (0..255) to apply to the view's drawing
23486     * @return true if the view can draw with the specified alpha.
23487     */
23488    protected boolean onSetAlpha(int alpha) {
23489        return false;
23490    }
23491
23492    /**
23493     * This is used by the RootView to perform an optimization when
23494     * the view hierarchy contains one or several SurfaceView.
23495     * SurfaceView is always considered transparent, but its children are not,
23496     * therefore all View objects remove themselves from the global transparent
23497     * region (passed as a parameter to this function).
23498     *
23499     * @param region The transparent region for this ViewAncestor (window).
23500     *
23501     * @return Returns true if the effective visibility of the view at this
23502     * point is opaque, regardless of the transparent region; returns false
23503     * if it is possible for underlying windows to be seen behind the view.
23504     *
23505     * {@hide}
23506     */
23507    public boolean gatherTransparentRegion(Region region) {
23508        final AttachInfo attachInfo = mAttachInfo;
23509        if (region != null && attachInfo != null) {
23510            final int pflags = mPrivateFlags;
23511            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
23512                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
23513                // remove it from the transparent region.
23514                final int[] location = attachInfo.mTransparentLocation;
23515                getLocationInWindow(location);
23516                // When a view has Z value, then it will be better to leave some area below the view
23517                // for drawing shadow. The shadow outset is proportional to the Z value. Note that
23518                // the bottom part needs more offset than the left, top and right parts due to the
23519                // spot light effects.
23520                int shadowOffset = getZ() > 0 ? (int) getZ() : 0;
23521                region.op(location[0] - shadowOffset, location[1] - shadowOffset,
23522                        location[0] + mRight - mLeft + shadowOffset,
23523                        location[1] + mBottom - mTop + (shadowOffset * 3), Region.Op.DIFFERENCE);
23524            } else {
23525                if (mBackground != null && mBackground.getOpacity() != PixelFormat.TRANSPARENT) {
23526                    // The SKIP_DRAW flag IS set and the background drawable exists, we remove
23527                    // the background drawable's non-transparent parts from this transparent region.
23528                    applyDrawableToTransparentRegion(mBackground, region);
23529                }
23530                if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
23531                        && mForegroundInfo.mDrawable.getOpacity() != PixelFormat.TRANSPARENT) {
23532                    // Similarly, we remove the foreground drawable's non-transparent parts.
23533                    applyDrawableToTransparentRegion(mForegroundInfo.mDrawable, region);
23534                }
23535                if (mDefaultFocusHighlight != null
23536                        && mDefaultFocusHighlight.getOpacity() != PixelFormat.TRANSPARENT) {
23537                    // Similarly, we remove the default focus highlight's non-transparent parts.
23538                    applyDrawableToTransparentRegion(mDefaultFocusHighlight, region);
23539                }
23540            }
23541        }
23542        return true;
23543    }
23544
23545    /**
23546     * Play a sound effect for this view.
23547     *
23548     * <p>The framework will play sound effects for some built in actions, such as
23549     * clicking, but you may wish to play these effects in your widget,
23550     * for instance, for internal navigation.
23551     *
23552     * <p>The sound effect will only be played if sound effects are enabled by the user, and
23553     * {@link #isSoundEffectsEnabled()} is true.
23554     *
23555     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
23556     */
23557    public void playSoundEffect(int soundConstant) {
23558        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
23559            return;
23560        }
23561        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
23562    }
23563
23564    /**
23565     * BZZZTT!!1!
23566     *
23567     * <p>Provide haptic feedback to the user for this view.
23568     *
23569     * <p>The framework will provide haptic feedback for some built in actions,
23570     * such as long presses, but you may wish to provide feedback for your
23571     * own widget.
23572     *
23573     * <p>The feedback will only be performed if
23574     * {@link #isHapticFeedbackEnabled()} is true.
23575     *
23576     * @param feedbackConstant One of the constants defined in
23577     * {@link HapticFeedbackConstants}
23578     */
23579    public boolean performHapticFeedback(int feedbackConstant) {
23580        return performHapticFeedback(feedbackConstant, 0);
23581    }
23582
23583    /**
23584     * BZZZTT!!1!
23585     *
23586     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
23587     *
23588     * @param feedbackConstant One of the constants defined in
23589     * {@link HapticFeedbackConstants}
23590     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
23591     */
23592    public boolean performHapticFeedback(int feedbackConstant, int flags) {
23593        if (mAttachInfo == null) {
23594            return false;
23595        }
23596        //noinspection SimplifiableIfStatement
23597        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
23598                && !isHapticFeedbackEnabled()) {
23599            return false;
23600        }
23601        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
23602                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
23603    }
23604
23605    /**
23606     * Request that the visibility of the status bar or other screen/window
23607     * decorations be changed.
23608     *
23609     * <p>This method is used to put the over device UI into temporary modes
23610     * where the user's attention is focused more on the application content,
23611     * by dimming or hiding surrounding system affordances.  This is typically
23612     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
23613     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
23614     * to be placed behind the action bar (and with these flags other system
23615     * affordances) so that smooth transitions between hiding and showing them
23616     * can be done.
23617     *
23618     * <p>Two representative examples of the use of system UI visibility is
23619     * implementing a content browsing application (like a magazine reader)
23620     * and a video playing application.
23621     *
23622     * <p>The first code shows a typical implementation of a View in a content
23623     * browsing application.  In this implementation, the application goes
23624     * into a content-oriented mode by hiding the status bar and action bar,
23625     * and putting the navigation elements into lights out mode.  The user can
23626     * then interact with content while in this mode.  Such an application should
23627     * provide an easy way for the user to toggle out of the mode (such as to
23628     * check information in the status bar or access notifications).  In the
23629     * implementation here, this is done simply by tapping on the content.
23630     *
23631     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
23632     *      content}
23633     *
23634     * <p>This second code sample shows a typical implementation of a View
23635     * in a video playing application.  In this situation, while the video is
23636     * playing the application would like to go into a complete full-screen mode,
23637     * to use as much of the display as possible for the video.  When in this state
23638     * the user can not interact with the application; the system intercepts
23639     * touching on the screen to pop the UI out of full screen mode.  See
23640     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
23641     *
23642     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
23643     *      content}
23644     *
23645     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
23646     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
23647     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
23648     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
23649     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
23650     */
23651    public void setSystemUiVisibility(int visibility) {
23652        if (visibility != mSystemUiVisibility) {
23653            mSystemUiVisibility = visibility;
23654            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
23655                mParent.recomputeViewAttributes(this);
23656            }
23657        }
23658    }
23659
23660    /**
23661     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
23662     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
23663     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
23664     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
23665     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
23666     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
23667     */
23668    public int getSystemUiVisibility() {
23669        return mSystemUiVisibility;
23670    }
23671
23672    /**
23673     * Returns the current system UI visibility that is currently set for
23674     * the entire window.  This is the combination of the
23675     * {@link #setSystemUiVisibility(int)} values supplied by all of the
23676     * views in the window.
23677     */
23678    public int getWindowSystemUiVisibility() {
23679        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
23680    }
23681
23682    /**
23683     * Override to find out when the window's requested system UI visibility
23684     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
23685     * This is different from the callbacks received through
23686     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
23687     * in that this is only telling you about the local request of the window,
23688     * not the actual values applied by the system.
23689     */
23690    public void onWindowSystemUiVisibilityChanged(int visible) {
23691    }
23692
23693    /**
23694     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
23695     * the view hierarchy.
23696     */
23697    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
23698        onWindowSystemUiVisibilityChanged(visible);
23699    }
23700
23701    /**
23702     * Set a listener to receive callbacks when the visibility of the system bar changes.
23703     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
23704     */
23705    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
23706        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
23707        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
23708            mParent.recomputeViewAttributes(this);
23709        }
23710    }
23711
23712    /**
23713     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
23714     * the view hierarchy.
23715     */
23716    public void dispatchSystemUiVisibilityChanged(int visibility) {
23717        ListenerInfo li = mListenerInfo;
23718        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
23719            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
23720                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
23721        }
23722    }
23723
23724    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
23725        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
23726        if (val != mSystemUiVisibility) {
23727            setSystemUiVisibility(val);
23728            return true;
23729        }
23730        return false;
23731    }
23732
23733    /** @hide */
23734    public void setDisabledSystemUiVisibility(int flags) {
23735        if (mAttachInfo != null) {
23736            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
23737                mAttachInfo.mDisabledSystemUiVisibility = flags;
23738                if (mParent != null) {
23739                    mParent.recomputeViewAttributes(this);
23740                }
23741            }
23742        }
23743    }
23744
23745    /**
23746     * Creates an image that the system displays during the drag and drop
23747     * operation. This is called a &quot;drag shadow&quot;. The default implementation
23748     * for a DragShadowBuilder based on a View returns an image that has exactly the same
23749     * appearance as the given View. The default also positions the center of the drag shadow
23750     * directly under the touch point. If no View is provided (the constructor with no parameters
23751     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
23752     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overridden, then the
23753     * default is an invisible drag shadow.
23754     * <p>
23755     * You are not required to use the View you provide to the constructor as the basis of the
23756     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
23757     * anything you want as the drag shadow.
23758     * </p>
23759     * <p>
23760     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
23761     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
23762     *  size and position of the drag shadow. It uses this data to construct a
23763     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
23764     *  so that your application can draw the shadow image in the Canvas.
23765     * </p>
23766     *
23767     * <div class="special reference">
23768     * <h3>Developer Guides</h3>
23769     * <p>For a guide to implementing drag and drop features, read the
23770     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
23771     * </div>
23772     */
23773    public static class DragShadowBuilder {
23774        private final WeakReference<View> mView;
23775
23776        /**
23777         * Constructs a shadow image builder based on a View. By default, the resulting drag
23778         * shadow will have the same appearance and dimensions as the View, with the touch point
23779         * over the center of the View.
23780         * @param view A View. Any View in scope can be used.
23781         */
23782        public DragShadowBuilder(View view) {
23783            mView = new WeakReference<View>(view);
23784        }
23785
23786        /**
23787         * Construct a shadow builder object with no associated View.  This
23788         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
23789         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
23790         * to supply the drag shadow's dimensions and appearance without
23791         * reference to any View object.
23792         */
23793        public DragShadowBuilder() {
23794            mView = new WeakReference<View>(null);
23795        }
23796
23797        /**
23798         * Returns the View object that had been passed to the
23799         * {@link #View.DragShadowBuilder(View)}
23800         * constructor.  If that View parameter was {@code null} or if the
23801         * {@link #View.DragShadowBuilder()}
23802         * constructor was used to instantiate the builder object, this method will return
23803         * null.
23804         *
23805         * @return The View object associate with this builder object.
23806         */
23807        @SuppressWarnings({"JavadocReference"})
23808        final public View getView() {
23809            return mView.get();
23810        }
23811
23812        /**
23813         * Provides the metrics for the shadow image. These include the dimensions of
23814         * the shadow image, and the point within that shadow that should
23815         * be centered under the touch location while dragging.
23816         * <p>
23817         * The default implementation sets the dimensions of the shadow to be the
23818         * same as the dimensions of the View itself and centers the shadow under
23819         * the touch point.
23820         * </p>
23821         *
23822         * @param outShadowSize A {@link android.graphics.Point} containing the width and height
23823         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
23824         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
23825         * image.
23826         *
23827         * @param outShadowTouchPoint A {@link android.graphics.Point} for the position within the
23828         * shadow image that should be underneath the touch point during the drag and drop
23829         * operation. Your application must set {@link android.graphics.Point#x} to the
23830         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
23831         */
23832        public void onProvideShadowMetrics(Point outShadowSize, Point outShadowTouchPoint) {
23833            final View view = mView.get();
23834            if (view != null) {
23835                outShadowSize.set(view.getWidth(), view.getHeight());
23836                outShadowTouchPoint.set(outShadowSize.x / 2, outShadowSize.y / 2);
23837            } else {
23838                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
23839            }
23840        }
23841
23842        /**
23843         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
23844         * based on the dimensions it received from the
23845         * {@link #onProvideShadowMetrics(Point, Point)} callback.
23846         *
23847         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
23848         */
23849        public void onDrawShadow(Canvas canvas) {
23850            final View view = mView.get();
23851            if (view != null) {
23852                view.draw(canvas);
23853            } else {
23854                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
23855            }
23856        }
23857    }
23858
23859    /**
23860     * @deprecated Use {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)
23861     * startDragAndDrop()} for newer platform versions.
23862     */
23863    @Deprecated
23864    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
23865                                   Object myLocalState, int flags) {
23866        return startDragAndDrop(data, shadowBuilder, myLocalState, flags);
23867    }
23868
23869    /**
23870     * Starts a drag and drop operation. When your application calls this method, it passes a
23871     * {@link android.view.View.DragShadowBuilder} object to the system. The
23872     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
23873     * to get metrics for the drag shadow, and then calls the object's
23874     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
23875     * <p>
23876     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
23877     *  drag events to all the View objects in your application that are currently visible. It does
23878     *  this either by calling the View object's drag listener (an implementation of
23879     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
23880     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
23881     *  Both are passed a {@link android.view.DragEvent} object that has a
23882     *  {@link android.view.DragEvent#getAction()} value of
23883     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
23884     * </p>
23885     * <p>
23886     * Your application can invoke {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object,
23887     * int) startDragAndDrop()} on any attached View object. The View object does not need to be
23888     * the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to be related
23889     * to the View the user selected for dragging.
23890     * </p>
23891     * @param data A {@link android.content.ClipData} object pointing to the data to be
23892     * transferred by the drag and drop operation.
23893     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
23894     * drag shadow.
23895     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
23896     * drop operation. When dispatching drag events to views in the same activity this object
23897     * will be available through {@link android.view.DragEvent#getLocalState()}. Views in other
23898     * activities will not have access to this data ({@link android.view.DragEvent#getLocalState()}
23899     * will return null).
23900     * <p>
23901     * myLocalState is a lightweight mechanism for the sending information from the dragged View
23902     * to the target Views. For example, it can contain flags that differentiate between a
23903     * a copy operation and a move operation.
23904     * </p>
23905     * @param flags Flags that control the drag and drop operation. This can be set to 0 for no
23906     * flags, or any combination of the following:
23907     *     <ul>
23908     *         <li>{@link #DRAG_FLAG_GLOBAL}</li>
23909     *         <li>{@link #DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION}</li>
23910     *         <li>{@link #DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION}</li>
23911     *         <li>{@link #DRAG_FLAG_GLOBAL_URI_READ}</li>
23912     *         <li>{@link #DRAG_FLAG_GLOBAL_URI_WRITE}</li>
23913     *         <li>{@link #DRAG_FLAG_OPAQUE}</li>
23914     *     </ul>
23915     * @return {@code true} if the method completes successfully, or
23916     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
23917     * do a drag, and so no drag operation is in progress.
23918     */
23919    public final boolean startDragAndDrop(ClipData data, DragShadowBuilder shadowBuilder,
23920            Object myLocalState, int flags) {
23921        if (ViewDebug.DEBUG_DRAG) {
23922            Log.d(VIEW_LOG_TAG, "startDragAndDrop: data=" + data + " flags=" + flags);
23923        }
23924        if (mAttachInfo == null) {
23925            Log.w(VIEW_LOG_TAG, "startDragAndDrop called on a detached view.");
23926            return false;
23927        }
23928
23929        if (data != null) {
23930            data.prepareToLeaveProcess((flags & View.DRAG_FLAG_GLOBAL) != 0);
23931        }
23932
23933        Point shadowSize = new Point();
23934        Point shadowTouchPoint = new Point();
23935        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
23936
23937        if ((shadowSize.x < 0) || (shadowSize.y < 0)
23938                || (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
23939            throw new IllegalStateException("Drag shadow dimensions must not be negative");
23940        }
23941
23942        // Create 1x1 surface when zero surface size is specified because SurfaceControl.Builder
23943        // does not accept zero size surface.
23944        if (shadowSize.x == 0  || shadowSize.y == 0) {
23945            if (!sAcceptZeroSizeDragShadow) {
23946                throw new IllegalStateException("Drag shadow dimensions must be positive");
23947            }
23948            shadowSize.x = 1;
23949            shadowSize.y = 1;
23950        }
23951
23952        if (ViewDebug.DEBUG_DRAG) {
23953            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
23954                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
23955        }
23956        if (mAttachInfo.mDragSurface != null) {
23957            mAttachInfo.mDragSurface.release();
23958        }
23959        mAttachInfo.mDragSurface = new Surface();
23960        mAttachInfo.mDragToken = null;
23961
23962        final ViewRootImpl root = mAttachInfo.mViewRootImpl;
23963        final SurfaceSession session = new SurfaceSession(root.mSurface);
23964        final SurfaceControl surface = new SurfaceControl.Builder(session)
23965                .setName("drag surface")
23966                .setSize(shadowSize.x, shadowSize.y)
23967                .setFormat(PixelFormat.TRANSLUCENT)
23968                .build();
23969        try {
23970            mAttachInfo.mDragSurface.copyFrom(surface);
23971            final Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null);
23972            try {
23973                canvas.drawColor(0, PorterDuff.Mode.CLEAR);
23974                shadowBuilder.onDrawShadow(canvas);
23975            } finally {
23976                mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas);
23977            }
23978
23979            // Cache the local state object for delivery with DragEvents
23980            root.setLocalDragState(myLocalState);
23981
23982            // repurpose 'shadowSize' for the last touch point
23983            root.getLastTouchPoint(shadowSize);
23984
23985            mAttachInfo.mDragToken = mAttachInfo.mSession.performDrag(
23986                    mAttachInfo.mWindow, flags, surface, root.getLastTouchSource(),
23987                    shadowSize.x, shadowSize.y, shadowTouchPoint.x, shadowTouchPoint.y, data);
23988            if (ViewDebug.DEBUG_DRAG) {
23989                Log.d(VIEW_LOG_TAG, "performDrag returned " + mAttachInfo.mDragToken);
23990            }
23991
23992            return mAttachInfo.mDragToken != null;
23993        } catch (Exception e) {
23994            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
23995            return false;
23996        } finally {
23997            if (mAttachInfo.mDragToken == null) {
23998                mAttachInfo.mDragSurface.destroy();
23999                mAttachInfo.mDragSurface = null;
24000                root.setLocalDragState(null);
24001            }
24002            session.kill();
24003        }
24004    }
24005
24006    /**
24007     * Cancels an ongoing drag and drop operation.
24008     * <p>
24009     * A {@link android.view.DragEvent} object with
24010     * {@link android.view.DragEvent#getAction()} value of
24011     * {@link android.view.DragEvent#ACTION_DRAG_ENDED} and
24012     * {@link android.view.DragEvent#getResult()} value of {@code false}
24013     * will be sent to every
24014     * View that received {@link android.view.DragEvent#ACTION_DRAG_STARTED}
24015     * even if they are not currently visible.
24016     * </p>
24017     * <p>
24018     * This method can be called on any View in the same window as the View on which
24019     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int) startDragAndDrop}
24020     * was called.
24021     * </p>
24022     */
24023    public final void cancelDragAndDrop() {
24024        if (ViewDebug.DEBUG_DRAG) {
24025            Log.d(VIEW_LOG_TAG, "cancelDragAndDrop");
24026        }
24027        if (mAttachInfo == null) {
24028            Log.w(VIEW_LOG_TAG, "cancelDragAndDrop called on a detached view.");
24029            return;
24030        }
24031        if (mAttachInfo.mDragToken != null) {
24032            try {
24033                mAttachInfo.mSession.cancelDragAndDrop(mAttachInfo.mDragToken);
24034            } catch (Exception e) {
24035                Log.e(VIEW_LOG_TAG, "Unable to cancel drag", e);
24036            }
24037            mAttachInfo.mDragToken = null;
24038        } else {
24039            Log.e(VIEW_LOG_TAG, "No active drag to cancel");
24040        }
24041    }
24042
24043    /**
24044     * Updates the drag shadow for the ongoing drag and drop operation.
24045     *
24046     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
24047     * new drag shadow.
24048     */
24049    public final void updateDragShadow(DragShadowBuilder shadowBuilder) {
24050        if (ViewDebug.DEBUG_DRAG) {
24051            Log.d(VIEW_LOG_TAG, "updateDragShadow");
24052        }
24053        if (mAttachInfo == null) {
24054            Log.w(VIEW_LOG_TAG, "updateDragShadow called on a detached view.");
24055            return;
24056        }
24057        if (mAttachInfo.mDragToken != null) {
24058            try {
24059                Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null);
24060                try {
24061                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
24062                    shadowBuilder.onDrawShadow(canvas);
24063                } finally {
24064                    mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas);
24065                }
24066            } catch (Exception e) {
24067                Log.e(VIEW_LOG_TAG, "Unable to update drag shadow", e);
24068            }
24069        } else {
24070            Log.e(VIEW_LOG_TAG, "No active drag");
24071        }
24072    }
24073
24074    /**
24075     * Starts a move from {startX, startY}, the amount of the movement will be the offset
24076     * between {startX, startY} and the new cursor positon.
24077     * @param startX horizontal coordinate where the move started.
24078     * @param startY vertical coordinate where the move started.
24079     * @return whether moving was started successfully.
24080     * @hide
24081     */
24082    public final boolean startMovingTask(float startX, float startY) {
24083        if (ViewDebug.DEBUG_POSITIONING) {
24084            Log.d(VIEW_LOG_TAG, "startMovingTask: {" + startX + "," + startY + "}");
24085        }
24086        try {
24087            return mAttachInfo.mSession.startMovingTask(mAttachInfo.mWindow, startX, startY);
24088        } catch (RemoteException e) {
24089            Log.e(VIEW_LOG_TAG, "Unable to start moving", e);
24090        }
24091        return false;
24092    }
24093
24094    /**
24095     * Handles drag events sent by the system following a call to
24096     * {@link android.view.View#startDragAndDrop(ClipData,DragShadowBuilder,Object,int)
24097     * startDragAndDrop()}.
24098     *<p>
24099     * When the system calls this method, it passes a
24100     * {@link android.view.DragEvent} object. A call to
24101     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
24102     * in DragEvent. The method uses these to determine what is happening in the drag and drop
24103     * operation.
24104     * @param event The {@link android.view.DragEvent} sent by the system.
24105     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
24106     * in DragEvent, indicating the type of drag event represented by this object.
24107     * @return {@code true} if the method was successful, otherwise {@code false}.
24108     * <p>
24109     *  The method should return {@code true} in response to an action type of
24110     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
24111     *  operation.
24112     * </p>
24113     * <p>
24114     *  The method should also return {@code true} in response to an action type of
24115     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
24116     *  {@code false} if it didn't.
24117     * </p>
24118     * <p>
24119     *  For all other events, the return value is ignored.
24120     * </p>
24121     */
24122    public boolean onDragEvent(DragEvent event) {
24123        return false;
24124    }
24125
24126    // Dispatches ACTION_DRAG_ENTERED and ACTION_DRAG_EXITED events for pre-Nougat apps.
24127    boolean dispatchDragEnterExitInPreN(DragEvent event) {
24128        return callDragEventHandler(event);
24129    }
24130
24131    /**
24132     * Detects if this View is enabled and has a drag event listener.
24133     * If both are true, then it calls the drag event listener with the
24134     * {@link android.view.DragEvent} it received. If the drag event listener returns
24135     * {@code true}, then dispatchDragEvent() returns {@code true}.
24136     * <p>
24137     * For all other cases, the method calls the
24138     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
24139     * method and returns its result.
24140     * </p>
24141     * <p>
24142     * This ensures that a drag event is always consumed, even if the View does not have a drag
24143     * event listener. However, if the View has a listener and the listener returns true, then
24144     * onDragEvent() is not called.
24145     * </p>
24146     */
24147    public boolean dispatchDragEvent(DragEvent event) {
24148        event.mEventHandlerWasCalled = true;
24149        if (event.mAction == DragEvent.ACTION_DRAG_LOCATION ||
24150            event.mAction == DragEvent.ACTION_DROP) {
24151            // About to deliver an event with coordinates to this view. Notify that now this view
24152            // has drag focus. This will send exit/enter events as needed.
24153            getViewRootImpl().setDragFocus(this, event);
24154        }
24155        return callDragEventHandler(event);
24156    }
24157
24158    final boolean callDragEventHandler(DragEvent event) {
24159        final boolean result;
24160
24161        ListenerInfo li = mListenerInfo;
24162        //noinspection SimplifiableIfStatement
24163        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
24164                && li.mOnDragListener.onDrag(this, event)) {
24165            result = true;
24166        } else {
24167            result = onDragEvent(event);
24168        }
24169
24170        switch (event.mAction) {
24171            case DragEvent.ACTION_DRAG_ENTERED: {
24172                mPrivateFlags2 |= View.PFLAG2_DRAG_HOVERED;
24173                refreshDrawableState();
24174            } break;
24175            case DragEvent.ACTION_DRAG_EXITED: {
24176                mPrivateFlags2 &= ~View.PFLAG2_DRAG_HOVERED;
24177                refreshDrawableState();
24178            } break;
24179            case DragEvent.ACTION_DRAG_ENDED: {
24180                mPrivateFlags2 &= ~View.DRAG_MASK;
24181                refreshDrawableState();
24182            } break;
24183        }
24184
24185        return result;
24186    }
24187
24188    boolean canAcceptDrag() {
24189        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
24190    }
24191
24192    /**
24193     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
24194     * it is ever exposed at all.
24195     * @hide
24196     */
24197    public void onCloseSystemDialogs(String reason) {
24198    }
24199
24200    /**
24201     * Given a Drawable whose bounds have been set to draw into this view,
24202     * update a Region being computed for
24203     * {@link #gatherTransparentRegion(android.graphics.Region)} so
24204     * that any non-transparent parts of the Drawable are removed from the
24205     * given transparent region.
24206     *
24207     * @param dr The Drawable whose transparency is to be applied to the region.
24208     * @param region A Region holding the current transparency information,
24209     * where any parts of the region that are set are considered to be
24210     * transparent.  On return, this region will be modified to have the
24211     * transparency information reduced by the corresponding parts of the
24212     * Drawable that are not transparent.
24213     * {@hide}
24214     */
24215    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
24216        if (DBG) {
24217            Log.i("View", "Getting transparent region for: " + this);
24218        }
24219        final Region r = dr.getTransparentRegion();
24220        final Rect db = dr.getBounds();
24221        final AttachInfo attachInfo = mAttachInfo;
24222        if (r != null && attachInfo != null) {
24223            final int w = getRight()-getLeft();
24224            final int h = getBottom()-getTop();
24225            if (db.left > 0) {
24226                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
24227                r.op(0, 0, db.left, h, Region.Op.UNION);
24228            }
24229            if (db.right < w) {
24230                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
24231                r.op(db.right, 0, w, h, Region.Op.UNION);
24232            }
24233            if (db.top > 0) {
24234                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
24235                r.op(0, 0, w, db.top, Region.Op.UNION);
24236            }
24237            if (db.bottom < h) {
24238                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
24239                r.op(0, db.bottom, w, h, Region.Op.UNION);
24240            }
24241            final int[] location = attachInfo.mTransparentLocation;
24242            getLocationInWindow(location);
24243            r.translate(location[0], location[1]);
24244            region.op(r, Region.Op.INTERSECT);
24245        } else {
24246            region.op(db, Region.Op.DIFFERENCE);
24247        }
24248    }
24249
24250    private void checkForLongClick(int delayOffset, float x, float y) {
24251        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE || (mViewFlags & TOOLTIP) == TOOLTIP) {
24252            mHasPerformedLongPress = false;
24253
24254            if (mPendingCheckForLongPress == null) {
24255                mPendingCheckForLongPress = new CheckForLongPress();
24256            }
24257            mPendingCheckForLongPress.setAnchor(x, y);
24258            mPendingCheckForLongPress.rememberWindowAttachCount();
24259            mPendingCheckForLongPress.rememberPressedState();
24260            postDelayed(mPendingCheckForLongPress,
24261                    ViewConfiguration.getLongPressTimeout() - delayOffset);
24262        }
24263    }
24264
24265    /**
24266     * Inflate a view from an XML resource.  This convenience method wraps the {@link
24267     * LayoutInflater} class, which provides a full range of options for view inflation.
24268     *
24269     * @param context The Context object for your activity or application.
24270     * @param resource The resource ID to inflate
24271     * @param root A view group that will be the parent.  Used to properly inflate the
24272     * layout_* parameters.
24273     * @see LayoutInflater
24274     */
24275    public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
24276        LayoutInflater factory = LayoutInflater.from(context);
24277        return factory.inflate(resource, root);
24278    }
24279
24280    /**
24281     * Scroll the view with standard behavior for scrolling beyond the normal
24282     * content boundaries. Views that call this method should override
24283     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
24284     * results of an over-scroll operation.
24285     *
24286     * Views can use this method to handle any touch or fling-based scrolling.
24287     *
24288     * @param deltaX Change in X in pixels
24289     * @param deltaY Change in Y in pixels
24290     * @param scrollX Current X scroll value in pixels before applying deltaX
24291     * @param scrollY Current Y scroll value in pixels before applying deltaY
24292     * @param scrollRangeX Maximum content scroll range along the X axis
24293     * @param scrollRangeY Maximum content scroll range along the Y axis
24294     * @param maxOverScrollX Number of pixels to overscroll by in either direction
24295     *          along the X axis.
24296     * @param maxOverScrollY Number of pixels to overscroll by in either direction
24297     *          along the Y axis.
24298     * @param isTouchEvent true if this scroll operation is the result of a touch event.
24299     * @return true if scrolling was clamped to an over-scroll boundary along either
24300     *          axis, false otherwise.
24301     */
24302    @SuppressWarnings({"UnusedParameters"})
24303    protected boolean overScrollBy(int deltaX, int deltaY,
24304            int scrollX, int scrollY,
24305            int scrollRangeX, int scrollRangeY,
24306            int maxOverScrollX, int maxOverScrollY,
24307            boolean isTouchEvent) {
24308        final int overScrollMode = mOverScrollMode;
24309        final boolean canScrollHorizontal =
24310                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
24311        final boolean canScrollVertical =
24312                computeVerticalScrollRange() > computeVerticalScrollExtent();
24313        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
24314                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
24315        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
24316                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
24317
24318        int newScrollX = scrollX + deltaX;
24319        if (!overScrollHorizontal) {
24320            maxOverScrollX = 0;
24321        }
24322
24323        int newScrollY = scrollY + deltaY;
24324        if (!overScrollVertical) {
24325            maxOverScrollY = 0;
24326        }
24327
24328        // Clamp values if at the limits and record
24329        final int left = -maxOverScrollX;
24330        final int right = maxOverScrollX + scrollRangeX;
24331        final int top = -maxOverScrollY;
24332        final int bottom = maxOverScrollY + scrollRangeY;
24333
24334        boolean clampedX = false;
24335        if (newScrollX > right) {
24336            newScrollX = right;
24337            clampedX = true;
24338        } else if (newScrollX < left) {
24339            newScrollX = left;
24340            clampedX = true;
24341        }
24342
24343        boolean clampedY = false;
24344        if (newScrollY > bottom) {
24345            newScrollY = bottom;
24346            clampedY = true;
24347        } else if (newScrollY < top) {
24348            newScrollY = top;
24349            clampedY = true;
24350        }
24351
24352        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
24353
24354        return clampedX || clampedY;
24355    }
24356
24357    /**
24358     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
24359     * respond to the results of an over-scroll operation.
24360     *
24361     * @param scrollX New X scroll value in pixels
24362     * @param scrollY New Y scroll value in pixels
24363     * @param clampedX True if scrollX was clamped to an over-scroll boundary
24364     * @param clampedY True if scrollY was clamped to an over-scroll boundary
24365     */
24366    protected void onOverScrolled(int scrollX, int scrollY,
24367            boolean clampedX, boolean clampedY) {
24368        // Intentionally empty.
24369    }
24370
24371    /**
24372     * Returns the over-scroll mode for this view. The result will be
24373     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
24374     * (allow over-scrolling only if the view content is larger than the container),
24375     * or {@link #OVER_SCROLL_NEVER}.
24376     *
24377     * @return This view's over-scroll mode.
24378     */
24379    public int getOverScrollMode() {
24380        return mOverScrollMode;
24381    }
24382
24383    /**
24384     * Set the over-scroll mode for this view. Valid over-scroll modes are
24385     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
24386     * (allow over-scrolling only if the view content is larger than the container),
24387     * or {@link #OVER_SCROLL_NEVER}.
24388     *
24389     * Setting the over-scroll mode of a view will have an effect only if the
24390     * view is capable of scrolling.
24391     *
24392     * @param overScrollMode The new over-scroll mode for this view.
24393     */
24394    public void setOverScrollMode(int overScrollMode) {
24395        if (overScrollMode != OVER_SCROLL_ALWAYS &&
24396                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
24397                overScrollMode != OVER_SCROLL_NEVER) {
24398            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
24399        }
24400        mOverScrollMode = overScrollMode;
24401    }
24402
24403    /**
24404     * Enable or disable nested scrolling for this view.
24405     *
24406     * <p>If this property is set to true the view will be permitted to initiate nested
24407     * scrolling operations with a compatible parent view in the current hierarchy. If this
24408     * view does not implement nested scrolling this will have no effect. Disabling nested scrolling
24409     * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping}
24410     * the nested scroll.</p>
24411     *
24412     * @param enabled true to enable nested scrolling, false to disable
24413     *
24414     * @see #isNestedScrollingEnabled()
24415     */
24416    public void setNestedScrollingEnabled(boolean enabled) {
24417        if (enabled) {
24418            mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED;
24419        } else {
24420            stopNestedScroll();
24421            mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED;
24422        }
24423    }
24424
24425    /**
24426     * Returns true if nested scrolling is enabled for this view.
24427     *
24428     * <p>If nested scrolling is enabled and this View class implementation supports it,
24429     * this view will act as a nested scrolling child view when applicable, forwarding data
24430     * about the scroll operation in progress to a compatible and cooperating nested scrolling
24431     * parent.</p>
24432     *
24433     * @return true if nested scrolling is enabled
24434     *
24435     * @see #setNestedScrollingEnabled(boolean)
24436     */
24437    public boolean isNestedScrollingEnabled() {
24438        return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) ==
24439                PFLAG3_NESTED_SCROLLING_ENABLED;
24440    }
24441
24442    /**
24443     * Begin a nestable scroll operation along the given axes.
24444     *
24445     * <p>A view starting a nested scroll promises to abide by the following contract:</p>
24446     *
24447     * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case
24448     * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}.
24449     * In the case of touch scrolling the nested scroll will be terminated automatically in
24450     * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}.
24451     * In the event of programmatic scrolling the caller must explicitly call
24452     * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p>
24453     *
24454     * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found.
24455     * If it returns false the caller may ignore the rest of this contract until the next scroll.
24456     * Calling startNestedScroll while a nested scroll is already in progress will return true.</p>
24457     *
24458     * <p>At each incremental step of the scroll the caller should invoke
24459     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll}
24460     * once it has calculated the requested scrolling delta. If it returns true the nested scrolling
24461     * parent at least partially consumed the scroll and the caller should adjust the amount it
24462     * scrolls by.</p>
24463     *
24464     * <p>After applying the remainder of the scroll delta the caller should invoke
24465     * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing
24466     * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat
24467     * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}.
24468     * </p>
24469     *
24470     * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or
24471     *             {@link #SCROLL_AXIS_VERTICAL}.
24472     * @return true if a cooperative parent was found and nested scrolling has been enabled for
24473     *         the current gesture.
24474     *
24475     * @see #stopNestedScroll()
24476     * @see #dispatchNestedPreScroll(int, int, int[], int[])
24477     * @see #dispatchNestedScroll(int, int, int, int, int[])
24478     */
24479    public boolean startNestedScroll(int axes) {
24480        if (hasNestedScrollingParent()) {
24481            // Already in progress
24482            return true;
24483        }
24484        if (isNestedScrollingEnabled()) {
24485            ViewParent p = getParent();
24486            View child = this;
24487            while (p != null) {
24488                try {
24489                    if (p.onStartNestedScroll(child, this, axes)) {
24490                        mNestedScrollingParent = p;
24491                        p.onNestedScrollAccepted(child, this, axes);
24492                        return true;
24493                    }
24494                } catch (AbstractMethodError e) {
24495                    Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " +
24496                            "method onStartNestedScroll", e);
24497                    // Allow the search upward to continue
24498                }
24499                if (p instanceof View) {
24500                    child = (View) p;
24501                }
24502                p = p.getParent();
24503            }
24504        }
24505        return false;
24506    }
24507
24508    /**
24509     * Stop a nested scroll in progress.
24510     *
24511     * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p>
24512     *
24513     * @see #startNestedScroll(int)
24514     */
24515    public void stopNestedScroll() {
24516        if (mNestedScrollingParent != null) {
24517            mNestedScrollingParent.onStopNestedScroll(this);
24518            mNestedScrollingParent = null;
24519        }
24520    }
24521
24522    /**
24523     * Returns true if this view has a nested scrolling parent.
24524     *
24525     * <p>The presence of a nested scrolling parent indicates that this view has initiated
24526     * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p>
24527     *
24528     * @return whether this view has a nested scrolling parent
24529     */
24530    public boolean hasNestedScrollingParent() {
24531        return mNestedScrollingParent != null;
24532    }
24533
24534    /**
24535     * Dispatch one step of a nested scroll in progress.
24536     *
24537     * <p>Implementations of views that support nested scrolling should call this to report
24538     * info about a scroll in progress to the current nested scrolling parent. If a nested scroll
24539     * is not currently in progress or nested scrolling is not
24540     * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p>
24541     *
24542     * <p>Compatible View implementations should also call
24543     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before
24544     * consuming a component of the scroll event themselves.</p>
24545     *
24546     * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step
24547     * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step
24548     * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view
24549     * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view
24550     * @param offsetInWindow Optional. If not null, on return this will contain the offset
24551     *                       in local view coordinates of this view from before this operation
24552     *                       to after it completes. View implementations may use this to adjust
24553     *                       expected input coordinate tracking.
24554     * @return true if the event was dispatched, false if it could not be dispatched.
24555     * @see #dispatchNestedPreScroll(int, int, int[], int[])
24556     */
24557    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed,
24558            int dxUnconsumed, int dyUnconsumed, @Nullable @Size(2) int[] offsetInWindow) {
24559        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
24560            if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) {
24561                int startX = 0;
24562                int startY = 0;
24563                if (offsetInWindow != null) {
24564                    getLocationInWindow(offsetInWindow);
24565                    startX = offsetInWindow[0];
24566                    startY = offsetInWindow[1];
24567                }
24568
24569                mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed,
24570                        dxUnconsumed, dyUnconsumed);
24571
24572                if (offsetInWindow != null) {
24573                    getLocationInWindow(offsetInWindow);
24574                    offsetInWindow[0] -= startX;
24575                    offsetInWindow[1] -= startY;
24576                }
24577                return true;
24578            } else if (offsetInWindow != null) {
24579                // No motion, no dispatch. Keep offsetInWindow up to date.
24580                offsetInWindow[0] = 0;
24581                offsetInWindow[1] = 0;
24582            }
24583        }
24584        return false;
24585    }
24586
24587    /**
24588     * Dispatch one step of a nested scroll in progress before this view consumes any portion of it.
24589     *
24590     * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch.
24591     * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested
24592     * scrolling operation to consume some or all of the scroll operation before the child view
24593     * consumes it.</p>
24594     *
24595     * @param dx Horizontal scroll distance in pixels
24596     * @param dy Vertical scroll distance in pixels
24597     * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx
24598     *                 and consumed[1] the consumed dy.
24599     * @param offsetInWindow Optional. If not null, on return this will contain the offset
24600     *                       in local view coordinates of this view from before this operation
24601     *                       to after it completes. View implementations may use this to adjust
24602     *                       expected input coordinate tracking.
24603     * @return true if the parent consumed some or all of the scroll delta
24604     * @see #dispatchNestedScroll(int, int, int, int, int[])
24605     */
24606    public boolean dispatchNestedPreScroll(int dx, int dy,
24607            @Nullable @Size(2) int[] consumed, @Nullable @Size(2) int[] offsetInWindow) {
24608        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
24609            if (dx != 0 || dy != 0) {
24610                int startX = 0;
24611                int startY = 0;
24612                if (offsetInWindow != null) {
24613                    getLocationInWindow(offsetInWindow);
24614                    startX = offsetInWindow[0];
24615                    startY = offsetInWindow[1];
24616                }
24617
24618                if (consumed == null) {
24619                    if (mTempNestedScrollConsumed == null) {
24620                        mTempNestedScrollConsumed = new int[2];
24621                    }
24622                    consumed = mTempNestedScrollConsumed;
24623                }
24624                consumed[0] = 0;
24625                consumed[1] = 0;
24626                mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed);
24627
24628                if (offsetInWindow != null) {
24629                    getLocationInWindow(offsetInWindow);
24630                    offsetInWindow[0] -= startX;
24631                    offsetInWindow[1] -= startY;
24632                }
24633                return consumed[0] != 0 || consumed[1] != 0;
24634            } else if (offsetInWindow != null) {
24635                offsetInWindow[0] = 0;
24636                offsetInWindow[1] = 0;
24637            }
24638        }
24639        return false;
24640    }
24641
24642    /**
24643     * Dispatch a fling to a nested scrolling parent.
24644     *
24645     * <p>This method should be used to indicate that a nested scrolling child has detected
24646     * suitable conditions for a fling. Generally this means that a touch scroll has ended with a
24647     * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds
24648     * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity}
24649     * along a scrollable axis.</p>
24650     *
24651     * <p>If a nested scrolling child view would normally fling but it is at the edge of
24652     * its own content, it can use this method to delegate the fling to its nested scrolling
24653     * parent instead. The parent may optionally consume the fling or observe a child fling.</p>
24654     *
24655     * @param velocityX Horizontal fling velocity in pixels per second
24656     * @param velocityY Vertical fling velocity in pixels per second
24657     * @param consumed true if the child consumed the fling, false otherwise
24658     * @return true if the nested scrolling parent consumed or otherwise reacted to the fling
24659     */
24660    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
24661        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
24662            return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed);
24663        }
24664        return false;
24665    }
24666
24667    /**
24668     * Dispatch a fling to a nested scrolling parent before it is processed by this view.
24669     *
24670     * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch
24671     * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code>
24672     * offsets an opportunity for the parent view in a nested fling to fully consume the fling
24673     * before the child view consumes it. If this method returns <code>true</code>, a nested
24674     * parent view consumed the fling and this view should not scroll as a result.</p>
24675     *
24676     * <p>For a better user experience, only one view in a nested scrolling chain should consume
24677     * the fling at a time. If a parent view consumed the fling this method will return false.
24678     * Custom view implementations should account for this in two ways:</p>
24679     *
24680     * <ul>
24681     *     <li>If a custom view is paged and needs to settle to a fixed page-point, do not
24682     *     call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid
24683     *     position regardless.</li>
24684     *     <li>If a nested parent does consume the fling, this view should not scroll at all,
24685     *     even to settle back to a valid idle position.</li>
24686     * </ul>
24687     *
24688     * <p>Views should also not offer fling velocities to nested parent views along an axis
24689     * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView}
24690     * should not offer a horizontal fling velocity to its parents since scrolling along that
24691     * axis is not permitted and carrying velocity along that motion does not make sense.</p>
24692     *
24693     * @param velocityX Horizontal fling velocity in pixels per second
24694     * @param velocityY Vertical fling velocity in pixels per second
24695     * @return true if a nested scrolling parent consumed the fling
24696     */
24697    public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
24698        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
24699            return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY);
24700        }
24701        return false;
24702    }
24703
24704    /**
24705     * Gets a scale factor that determines the distance the view should scroll
24706     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
24707     * @return The vertical scroll scale factor.
24708     * @hide
24709     */
24710    protected float getVerticalScrollFactor() {
24711        if (mVerticalScrollFactor == 0) {
24712            TypedValue outValue = new TypedValue();
24713            if (!mContext.getTheme().resolveAttribute(
24714                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
24715                throw new IllegalStateException(
24716                        "Expected theme to define listPreferredItemHeight.");
24717            }
24718            mVerticalScrollFactor = outValue.getDimension(
24719                    mContext.getResources().getDisplayMetrics());
24720        }
24721        return mVerticalScrollFactor;
24722    }
24723
24724    /**
24725     * Gets a scale factor that determines the distance the view should scroll
24726     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
24727     * @return The horizontal scroll scale factor.
24728     * @hide
24729     */
24730    protected float getHorizontalScrollFactor() {
24731        // TODO: Should use something else.
24732        return getVerticalScrollFactor();
24733    }
24734
24735    /**
24736     * Return the value specifying the text direction or policy that was set with
24737     * {@link #setTextDirection(int)}.
24738     *
24739     * @return the defined text direction. It can be one of:
24740     *
24741     * {@link #TEXT_DIRECTION_INHERIT},
24742     * {@link #TEXT_DIRECTION_FIRST_STRONG},
24743     * {@link #TEXT_DIRECTION_ANY_RTL},
24744     * {@link #TEXT_DIRECTION_LTR},
24745     * {@link #TEXT_DIRECTION_RTL},
24746     * {@link #TEXT_DIRECTION_LOCALE},
24747     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
24748     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
24749     *
24750     * @attr ref android.R.styleable#View_textDirection
24751     *
24752     * @hide
24753     */
24754    @ViewDebug.ExportedProperty(category = "text", mapping = {
24755            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
24756            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
24757            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
24758            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
24759            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
24760            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
24761            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
24762            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
24763    })
24764    public int getRawTextDirection() {
24765        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
24766    }
24767
24768    /**
24769     * Set the text direction.
24770     *
24771     * @param textDirection the direction to set. Should be one of:
24772     *
24773     * {@link #TEXT_DIRECTION_INHERIT},
24774     * {@link #TEXT_DIRECTION_FIRST_STRONG},
24775     * {@link #TEXT_DIRECTION_ANY_RTL},
24776     * {@link #TEXT_DIRECTION_LTR},
24777     * {@link #TEXT_DIRECTION_RTL},
24778     * {@link #TEXT_DIRECTION_LOCALE}
24779     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
24780     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL},
24781     *
24782     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
24783     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
24784     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
24785     *
24786     * @attr ref android.R.styleable#View_textDirection
24787     */
24788    public void setTextDirection(int textDirection) {
24789        if (getRawTextDirection() != textDirection) {
24790            // Reset the current text direction and the resolved one
24791            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
24792            resetResolvedTextDirection();
24793            // Set the new text direction
24794            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
24795            // Do resolution
24796            resolveTextDirection();
24797            // Notify change
24798            onRtlPropertiesChanged(getLayoutDirection());
24799            // Refresh
24800            requestLayout();
24801            invalidate(true);
24802        }
24803    }
24804
24805    /**
24806     * Return the resolved text direction.
24807     *
24808     * @return the resolved text direction. Returns one of:
24809     *
24810     * {@link #TEXT_DIRECTION_FIRST_STRONG},
24811     * {@link #TEXT_DIRECTION_ANY_RTL},
24812     * {@link #TEXT_DIRECTION_LTR},
24813     * {@link #TEXT_DIRECTION_RTL},
24814     * {@link #TEXT_DIRECTION_LOCALE},
24815     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
24816     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
24817     *
24818     * @attr ref android.R.styleable#View_textDirection
24819     */
24820    @ViewDebug.ExportedProperty(category = "text", mapping = {
24821            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
24822            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
24823            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
24824            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
24825            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
24826            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
24827            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
24828            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
24829    })
24830    public int getTextDirection() {
24831        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
24832    }
24833
24834    /**
24835     * Resolve the text direction.
24836     *
24837     * @return true if resolution has been done, false otherwise.
24838     *
24839     * @hide
24840     */
24841    public boolean resolveTextDirection() {
24842        // Reset any previous text direction resolution
24843        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
24844
24845        if (hasRtlSupport()) {
24846            // Set resolved text direction flag depending on text direction flag
24847            final int textDirection = getRawTextDirection();
24848            switch(textDirection) {
24849                case TEXT_DIRECTION_INHERIT:
24850                    if (!canResolveTextDirection()) {
24851                        // We cannot do the resolution if there is no parent, so use the default one
24852                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
24853                        // Resolution will need to happen again later
24854                        return false;
24855                    }
24856
24857                    // Parent has not yet resolved, so we still return the default
24858                    try {
24859                        if (!mParent.isTextDirectionResolved()) {
24860                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
24861                            // Resolution will need to happen again later
24862                            return false;
24863                        }
24864                    } catch (AbstractMethodError e) {
24865                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
24866                                " does not fully implement ViewParent", e);
24867                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
24868                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
24869                        return true;
24870                    }
24871
24872                    // Set current resolved direction to the same value as the parent's one
24873                    int parentResolvedDirection;
24874                    try {
24875                        parentResolvedDirection = mParent.getTextDirection();
24876                    } catch (AbstractMethodError e) {
24877                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
24878                                " does not fully implement ViewParent", e);
24879                        parentResolvedDirection = TEXT_DIRECTION_LTR;
24880                    }
24881                    switch (parentResolvedDirection) {
24882                        case TEXT_DIRECTION_FIRST_STRONG:
24883                        case TEXT_DIRECTION_ANY_RTL:
24884                        case TEXT_DIRECTION_LTR:
24885                        case TEXT_DIRECTION_RTL:
24886                        case TEXT_DIRECTION_LOCALE:
24887                        case TEXT_DIRECTION_FIRST_STRONG_LTR:
24888                        case TEXT_DIRECTION_FIRST_STRONG_RTL:
24889                            mPrivateFlags2 |=
24890                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
24891                            break;
24892                        default:
24893                            // Default resolved direction is "first strong" heuristic
24894                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
24895                    }
24896                    break;
24897                case TEXT_DIRECTION_FIRST_STRONG:
24898                case TEXT_DIRECTION_ANY_RTL:
24899                case TEXT_DIRECTION_LTR:
24900                case TEXT_DIRECTION_RTL:
24901                case TEXT_DIRECTION_LOCALE:
24902                case TEXT_DIRECTION_FIRST_STRONG_LTR:
24903                case TEXT_DIRECTION_FIRST_STRONG_RTL:
24904                    // Resolved direction is the same as text direction
24905                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
24906                    break;
24907                default:
24908                    // Default resolved direction is "first strong" heuristic
24909                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
24910            }
24911        } else {
24912            // Default resolved direction is "first strong" heuristic
24913            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
24914        }
24915
24916        // Set to resolved
24917        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
24918        return true;
24919    }
24920
24921    /**
24922     * Check if text direction resolution can be done.
24923     *
24924     * @return true if text direction resolution can be done otherwise return false.
24925     */
24926    public boolean canResolveTextDirection() {
24927        switch (getRawTextDirection()) {
24928            case TEXT_DIRECTION_INHERIT:
24929                if (mParent != null) {
24930                    try {
24931                        return mParent.canResolveTextDirection();
24932                    } catch (AbstractMethodError e) {
24933                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
24934                                " does not fully implement ViewParent", e);
24935                    }
24936                }
24937                return false;
24938
24939            default:
24940                return true;
24941        }
24942    }
24943
24944    /**
24945     * Reset resolved text direction. Text direction will be resolved during a call to
24946     * {@link #onMeasure(int, int)}.
24947     *
24948     * @hide
24949     */
24950    public void resetResolvedTextDirection() {
24951        // Reset any previous text direction resolution
24952        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
24953        // Set to default value
24954        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
24955    }
24956
24957    /**
24958     * @return true if text direction is inherited.
24959     *
24960     * @hide
24961     */
24962    public boolean isTextDirectionInherited() {
24963        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
24964    }
24965
24966    /**
24967     * @return true if text direction is resolved.
24968     */
24969    public boolean isTextDirectionResolved() {
24970        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
24971    }
24972
24973    /**
24974     * Return the value specifying the text alignment or policy that was set with
24975     * {@link #setTextAlignment(int)}.
24976     *
24977     * @return the defined text alignment. It can be one of:
24978     *
24979     * {@link #TEXT_ALIGNMENT_INHERIT},
24980     * {@link #TEXT_ALIGNMENT_GRAVITY},
24981     * {@link #TEXT_ALIGNMENT_CENTER},
24982     * {@link #TEXT_ALIGNMENT_TEXT_START},
24983     * {@link #TEXT_ALIGNMENT_TEXT_END},
24984     * {@link #TEXT_ALIGNMENT_VIEW_START},
24985     * {@link #TEXT_ALIGNMENT_VIEW_END}
24986     *
24987     * @attr ref android.R.styleable#View_textAlignment
24988     *
24989     * @hide
24990     */
24991    @ViewDebug.ExportedProperty(category = "text", mapping = {
24992            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
24993            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
24994            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
24995            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
24996            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
24997            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
24998            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
24999    })
25000    @TextAlignment
25001    public int getRawTextAlignment() {
25002        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
25003    }
25004
25005    /**
25006     * Set the text alignment.
25007     *
25008     * @param textAlignment The text alignment to set. Should be one of
25009     *
25010     * {@link #TEXT_ALIGNMENT_INHERIT},
25011     * {@link #TEXT_ALIGNMENT_GRAVITY},
25012     * {@link #TEXT_ALIGNMENT_CENTER},
25013     * {@link #TEXT_ALIGNMENT_TEXT_START},
25014     * {@link #TEXT_ALIGNMENT_TEXT_END},
25015     * {@link #TEXT_ALIGNMENT_VIEW_START},
25016     * {@link #TEXT_ALIGNMENT_VIEW_END}
25017     *
25018     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
25019     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
25020     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
25021     *
25022     * @attr ref android.R.styleable#View_textAlignment
25023     */
25024    public void setTextAlignment(@TextAlignment int textAlignment) {
25025        if (textAlignment != getRawTextAlignment()) {
25026            // Reset the current and resolved text alignment
25027            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
25028            resetResolvedTextAlignment();
25029            // Set the new text alignment
25030            mPrivateFlags2 |=
25031                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
25032            // Do resolution
25033            resolveTextAlignment();
25034            // Notify change
25035            onRtlPropertiesChanged(getLayoutDirection());
25036            // Refresh
25037            requestLayout();
25038            invalidate(true);
25039        }
25040    }
25041
25042    /**
25043     * Return the resolved text alignment.
25044     *
25045     * @return the resolved text alignment. Returns one of:
25046     *
25047     * {@link #TEXT_ALIGNMENT_GRAVITY},
25048     * {@link #TEXT_ALIGNMENT_CENTER},
25049     * {@link #TEXT_ALIGNMENT_TEXT_START},
25050     * {@link #TEXT_ALIGNMENT_TEXT_END},
25051     * {@link #TEXT_ALIGNMENT_VIEW_START},
25052     * {@link #TEXT_ALIGNMENT_VIEW_END}
25053     *
25054     * @attr ref android.R.styleable#View_textAlignment
25055     */
25056    @ViewDebug.ExportedProperty(category = "text", mapping = {
25057            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
25058            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
25059            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
25060            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
25061            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
25062            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
25063            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
25064    })
25065    @TextAlignment
25066    public int getTextAlignment() {
25067        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
25068                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
25069    }
25070
25071    /**
25072     * Resolve the text alignment.
25073     *
25074     * @return true if resolution has been done, false otherwise.
25075     *
25076     * @hide
25077     */
25078    public boolean resolveTextAlignment() {
25079        // Reset any previous text alignment resolution
25080        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
25081
25082        if (hasRtlSupport()) {
25083            // Set resolved text alignment flag depending on text alignment flag
25084            final int textAlignment = getRawTextAlignment();
25085            switch (textAlignment) {
25086                case TEXT_ALIGNMENT_INHERIT:
25087                    // Check if we can resolve the text alignment
25088                    if (!canResolveTextAlignment()) {
25089                        // We cannot do the resolution if there is no parent so use the default
25090                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
25091                        // Resolution will need to happen again later
25092                        return false;
25093                    }
25094
25095                    // Parent has not yet resolved, so we still return the default
25096                    try {
25097                        if (!mParent.isTextAlignmentResolved()) {
25098                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
25099                            // Resolution will need to happen again later
25100                            return false;
25101                        }
25102                    } catch (AbstractMethodError e) {
25103                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
25104                                " does not fully implement ViewParent", e);
25105                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
25106                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
25107                        return true;
25108                    }
25109
25110                    int parentResolvedTextAlignment;
25111                    try {
25112                        parentResolvedTextAlignment = mParent.getTextAlignment();
25113                    } catch (AbstractMethodError e) {
25114                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
25115                                " does not fully implement ViewParent", e);
25116                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
25117                    }
25118                    switch (parentResolvedTextAlignment) {
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 the parent resolved
25126                            // text alignment
25127                            mPrivateFlags2 |=
25128                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
25129                            break;
25130                        default:
25131                            // Use default resolved text alignment
25132                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
25133                    }
25134                    break;
25135                case TEXT_ALIGNMENT_GRAVITY:
25136                case TEXT_ALIGNMENT_TEXT_START:
25137                case TEXT_ALIGNMENT_TEXT_END:
25138                case TEXT_ALIGNMENT_CENTER:
25139                case TEXT_ALIGNMENT_VIEW_START:
25140                case TEXT_ALIGNMENT_VIEW_END:
25141                    // Resolved text alignment is the same as text alignment
25142                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
25143                    break;
25144                default:
25145                    // Use default resolved text alignment
25146                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
25147            }
25148        } else {
25149            // Use default resolved text alignment
25150            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
25151        }
25152
25153        // Set the resolved
25154        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
25155        return true;
25156    }
25157
25158    /**
25159     * Check if text alignment resolution can be done.
25160     *
25161     * @return true if text alignment resolution can be done otherwise return false.
25162     */
25163    public boolean canResolveTextAlignment() {
25164        switch (getRawTextAlignment()) {
25165            case TEXT_DIRECTION_INHERIT:
25166                if (mParent != null) {
25167                    try {
25168                        return mParent.canResolveTextAlignment();
25169                    } catch (AbstractMethodError e) {
25170                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
25171                                " does not fully implement ViewParent", e);
25172                    }
25173                }
25174                return false;
25175
25176            default:
25177                return true;
25178        }
25179    }
25180
25181    /**
25182     * Reset resolved text alignment. Text alignment will be resolved during a call to
25183     * {@link #onMeasure(int, int)}.
25184     *
25185     * @hide
25186     */
25187    public void resetResolvedTextAlignment() {
25188        // Reset any previous text alignment resolution
25189        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
25190        // Set to default
25191        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
25192    }
25193
25194    /**
25195     * @return true if text alignment is inherited.
25196     *
25197     * @hide
25198     */
25199    public boolean isTextAlignmentInherited() {
25200        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
25201    }
25202
25203    /**
25204     * @return true if text alignment is resolved.
25205     */
25206    public boolean isTextAlignmentResolved() {
25207        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
25208    }
25209
25210    /**
25211     * Generate a value suitable for use in {@link #setId(int)}.
25212     * This value will not collide with ID values generated at build time by aapt for R.id.
25213     *
25214     * @return a generated ID value
25215     */
25216    public static int generateViewId() {
25217        for (;;) {
25218            final int result = sNextGeneratedId.get();
25219            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
25220            int newValue = result + 1;
25221            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
25222            if (sNextGeneratedId.compareAndSet(result, newValue)) {
25223                return result;
25224            }
25225        }
25226    }
25227
25228    private static boolean isViewIdGenerated(int id) {
25229        return (id & 0xFF000000) == 0 && (id & 0x00FFFFFF) != 0;
25230    }
25231
25232    /**
25233     * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions.
25234     * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and
25235     *                           a normal View or a ViewGroup with
25236     *                           {@link android.view.ViewGroup#isTransitionGroup()} true.
25237     * @hide
25238     */
25239    public void captureTransitioningViews(List<View> transitioningViews) {
25240        if (getVisibility() == View.VISIBLE) {
25241            transitioningViews.add(this);
25242        }
25243    }
25244
25245    /**
25246     * Adds all Views that have {@link #getTransitionName()} non-null to namedElements.
25247     * @param namedElements Will contain all Views in the hierarchy having a transitionName.
25248     * @hide
25249     */
25250    public void findNamedViews(Map<String, View> namedElements) {
25251        if (getVisibility() == VISIBLE || mGhostView != null) {
25252            String transitionName = getTransitionName();
25253            if (transitionName != null) {
25254                namedElements.put(transitionName, this);
25255            }
25256        }
25257    }
25258
25259    /**
25260     * Returns the pointer icon for the motion event, or null if it doesn't specify the icon.
25261     * The default implementation does not care the location or event types, but some subclasses
25262     * may use it (such as WebViews).
25263     * @param event The MotionEvent from a mouse
25264     * @param pointerIndex The index of the pointer for which to retrieve the {@link PointerIcon}.
25265     *                     This will be between 0 and {@link MotionEvent#getPointerCount()}.
25266     * @see PointerIcon
25267     */
25268    public PointerIcon onResolvePointerIcon(MotionEvent event, int pointerIndex) {
25269        final float x = event.getX(pointerIndex);
25270        final float y = event.getY(pointerIndex);
25271        if (isDraggingScrollBar() || isOnScrollbarThumb(x, y)) {
25272            return PointerIcon.getSystemIcon(mContext, PointerIcon.TYPE_ARROW);
25273        }
25274        return mPointerIcon;
25275    }
25276
25277    /**
25278     * Set the pointer icon for the current view.
25279     * Passing {@code null} will restore the pointer icon to its default value.
25280     * @param pointerIcon A PointerIcon instance which will be shown when the mouse hovers.
25281     */
25282    public void setPointerIcon(PointerIcon pointerIcon) {
25283        mPointerIcon = pointerIcon;
25284        if (mAttachInfo == null || mAttachInfo.mHandlingPointerEvent) {
25285            return;
25286        }
25287        try {
25288            mAttachInfo.mSession.updatePointerIcon(mAttachInfo.mWindow);
25289        } catch (RemoteException e) {
25290        }
25291    }
25292
25293    /**
25294     * Gets the pointer icon for the current view.
25295     */
25296    public PointerIcon getPointerIcon() {
25297        return mPointerIcon;
25298    }
25299
25300    /**
25301     * Checks pointer capture status.
25302     *
25303     * @return true if the view has pointer capture.
25304     * @see #requestPointerCapture()
25305     * @see #hasPointerCapture()
25306     */
25307    public boolean hasPointerCapture() {
25308        final ViewRootImpl viewRootImpl = getViewRootImpl();
25309        if (viewRootImpl == null) {
25310            return false;
25311        }
25312        return viewRootImpl.hasPointerCapture();
25313    }
25314
25315    /**
25316     * Requests pointer capture mode.
25317     * <p>
25318     * When the window has pointer capture, the mouse pointer icon will disappear and will not
25319     * change its position. Further mouse will be dispatched with the source
25320     * {@link InputDevice#SOURCE_MOUSE_RELATIVE}, and relative position changes will be available
25321     * through {@link MotionEvent#getX} and {@link MotionEvent#getY}. Non-mouse events
25322     * (touchscreens, or stylus) will not be affected.
25323     * <p>
25324     * If the window already has pointer capture, this call does nothing.
25325     * <p>
25326     * The capture may be released through {@link #releasePointerCapture()}, or will be lost
25327     * automatically when the window loses focus.
25328     *
25329     * @see #releasePointerCapture()
25330     * @see #hasPointerCapture()
25331     */
25332    public void requestPointerCapture() {
25333        final ViewRootImpl viewRootImpl = getViewRootImpl();
25334        if (viewRootImpl != null) {
25335            viewRootImpl.requestPointerCapture(true);
25336        }
25337    }
25338
25339
25340    /**
25341     * Releases the pointer capture.
25342     * <p>
25343     * If the window does not have pointer capture, this call will do nothing.
25344     * @see #requestPointerCapture()
25345     * @see #hasPointerCapture()
25346     */
25347    public void releasePointerCapture() {
25348        final ViewRootImpl viewRootImpl = getViewRootImpl();
25349        if (viewRootImpl != null) {
25350            viewRootImpl.requestPointerCapture(false);
25351        }
25352    }
25353
25354    /**
25355     * Called when the window has just acquired or lost pointer capture.
25356     *
25357     * @param hasCapture True if the view now has pointerCapture, false otherwise.
25358     */
25359    @CallSuper
25360    public void onPointerCaptureChange(boolean hasCapture) {
25361    }
25362
25363    /**
25364     * @see #onPointerCaptureChange
25365     */
25366    public void dispatchPointerCaptureChanged(boolean hasCapture) {
25367        onPointerCaptureChange(hasCapture);
25368    }
25369
25370    /**
25371     * Implement this method to handle captured pointer events
25372     *
25373     * @param event The captured pointer event.
25374     * @return True if the event was handled, false otherwise.
25375     * @see #requestPointerCapture()
25376     */
25377    public boolean onCapturedPointerEvent(MotionEvent event) {
25378        return false;
25379    }
25380
25381    /**
25382     * Interface definition for a callback to be invoked when a captured pointer event
25383     * is being dispatched this view. The callback will be invoked before the event is
25384     * given to the view.
25385     */
25386    public interface OnCapturedPointerListener {
25387        /**
25388         * Called when a captured pointer event is dispatched to a view.
25389         * @param view The view this event has been dispatched to.
25390         * @param event The captured event.
25391         * @return True if the listener has consumed the event, false otherwise.
25392         */
25393        boolean onCapturedPointer(View view, MotionEvent event);
25394    }
25395
25396    /**
25397     * Set a listener to receive callbacks when the pointer capture state of a view changes.
25398     * @param l  The {@link OnCapturedPointerListener} to receive callbacks.
25399     */
25400    public void setOnCapturedPointerListener(OnCapturedPointerListener l) {
25401        getListenerInfo().mOnCapturedPointerListener = l;
25402    }
25403
25404    // Properties
25405    //
25406    /**
25407     * A Property wrapper around the <code>alpha</code> functionality handled by the
25408     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
25409     */
25410    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
25411        @Override
25412        public void setValue(View object, float value) {
25413            object.setAlpha(value);
25414        }
25415
25416        @Override
25417        public Float get(View object) {
25418            return object.getAlpha();
25419        }
25420    };
25421
25422    /**
25423     * A Property wrapper around the <code>translationX</code> functionality handled by the
25424     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
25425     */
25426    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
25427        @Override
25428        public void setValue(View object, float value) {
25429            object.setTranslationX(value);
25430        }
25431
25432                @Override
25433        public Float get(View object) {
25434            return object.getTranslationX();
25435        }
25436    };
25437
25438    /**
25439     * A Property wrapper around the <code>translationY</code> functionality handled by the
25440     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
25441     */
25442    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
25443        @Override
25444        public void setValue(View object, float value) {
25445            object.setTranslationY(value);
25446        }
25447
25448        @Override
25449        public Float get(View object) {
25450            return object.getTranslationY();
25451        }
25452    };
25453
25454    /**
25455     * A Property wrapper around the <code>translationZ</code> functionality handled by the
25456     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
25457     */
25458    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
25459        @Override
25460        public void setValue(View object, float value) {
25461            object.setTranslationZ(value);
25462        }
25463
25464        @Override
25465        public Float get(View object) {
25466            return object.getTranslationZ();
25467        }
25468    };
25469
25470    /**
25471     * A Property wrapper around the <code>x</code> functionality handled by the
25472     * {@link View#setX(float)} and {@link View#getX()} methods.
25473     */
25474    public static final Property<View, Float> X = new FloatProperty<View>("x") {
25475        @Override
25476        public void setValue(View object, float value) {
25477            object.setX(value);
25478        }
25479
25480        @Override
25481        public Float get(View object) {
25482            return object.getX();
25483        }
25484    };
25485
25486    /**
25487     * A Property wrapper around the <code>y</code> functionality handled by the
25488     * {@link View#setY(float)} and {@link View#getY()} methods.
25489     */
25490    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
25491        @Override
25492        public void setValue(View object, float value) {
25493            object.setY(value);
25494        }
25495
25496        @Override
25497        public Float get(View object) {
25498            return object.getY();
25499        }
25500    };
25501
25502    /**
25503     * A Property wrapper around the <code>z</code> functionality handled by the
25504     * {@link View#setZ(float)} and {@link View#getZ()} methods.
25505     */
25506    public static final Property<View, Float> Z = new FloatProperty<View>("z") {
25507        @Override
25508        public void setValue(View object, float value) {
25509            object.setZ(value);
25510        }
25511
25512        @Override
25513        public Float get(View object) {
25514            return object.getZ();
25515        }
25516    };
25517
25518    /**
25519     * A Property wrapper around the <code>rotation</code> functionality handled by the
25520     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
25521     */
25522    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
25523        @Override
25524        public void setValue(View object, float value) {
25525            object.setRotation(value);
25526        }
25527
25528        @Override
25529        public Float get(View object) {
25530            return object.getRotation();
25531        }
25532    };
25533
25534    /**
25535     * A Property wrapper around the <code>rotationX</code> functionality handled by the
25536     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
25537     */
25538    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
25539        @Override
25540        public void setValue(View object, float value) {
25541            object.setRotationX(value);
25542        }
25543
25544        @Override
25545        public Float get(View object) {
25546            return object.getRotationX();
25547        }
25548    };
25549
25550    /**
25551     * A Property wrapper around the <code>rotationY</code> functionality handled by the
25552     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
25553     */
25554    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
25555        @Override
25556        public void setValue(View object, float value) {
25557            object.setRotationY(value);
25558        }
25559
25560        @Override
25561        public Float get(View object) {
25562            return object.getRotationY();
25563        }
25564    };
25565
25566    /**
25567     * A Property wrapper around the <code>scaleX</code> functionality handled by the
25568     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
25569     */
25570    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
25571        @Override
25572        public void setValue(View object, float value) {
25573            object.setScaleX(value);
25574        }
25575
25576        @Override
25577        public Float get(View object) {
25578            return object.getScaleX();
25579        }
25580    };
25581
25582    /**
25583     * A Property wrapper around the <code>scaleY</code> functionality handled by the
25584     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
25585     */
25586    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
25587        @Override
25588        public void setValue(View object, float value) {
25589            object.setScaleY(value);
25590        }
25591
25592        @Override
25593        public Float get(View object) {
25594            return object.getScaleY();
25595        }
25596    };
25597
25598    /**
25599     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
25600     * Each MeasureSpec represents a requirement for either the width or the height.
25601     * A MeasureSpec is comprised of a size and a mode. There are three possible
25602     * modes:
25603     * <dl>
25604     * <dt>UNSPECIFIED</dt>
25605     * <dd>
25606     * The parent has not imposed any constraint on the child. It can be whatever size
25607     * it wants.
25608     * </dd>
25609     *
25610     * <dt>EXACTLY</dt>
25611     * <dd>
25612     * The parent has determined an exact size for the child. The child is going to be
25613     * given those bounds regardless of how big it wants to be.
25614     * </dd>
25615     *
25616     * <dt>AT_MOST</dt>
25617     * <dd>
25618     * The child can be as large as it wants up to the specified size.
25619     * </dd>
25620     * </dl>
25621     *
25622     * MeasureSpecs are implemented as ints to reduce object allocation. This class
25623     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
25624     */
25625    public static class MeasureSpec {
25626        private static final int MODE_SHIFT = 30;
25627        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
25628
25629        /** @hide */
25630        @IntDef({UNSPECIFIED, EXACTLY, AT_MOST})
25631        @Retention(RetentionPolicy.SOURCE)
25632        public @interface MeasureSpecMode {}
25633
25634        /**
25635         * Measure specification mode: The parent has not imposed any constraint
25636         * on the child. It can be whatever size it wants.
25637         */
25638        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
25639
25640        /**
25641         * Measure specification mode: The parent has determined an exact size
25642         * for the child. The child is going to be given those bounds regardless
25643         * of how big it wants to be.
25644         */
25645        public static final int EXACTLY     = 1 << MODE_SHIFT;
25646
25647        /**
25648         * Measure specification mode: The child can be as large as it wants up
25649         * to the specified size.
25650         */
25651        public static final int AT_MOST     = 2 << MODE_SHIFT;
25652
25653        /**
25654         * Creates a measure specification based on the supplied size and mode.
25655         *
25656         * The mode must always be one of the following:
25657         * <ul>
25658         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
25659         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
25660         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
25661         * </ul>
25662         *
25663         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
25664         * implementation was such that the order of arguments did not matter
25665         * and overflow in either value could impact the resulting MeasureSpec.
25666         * {@link android.widget.RelativeLayout} was affected by this bug.
25667         * Apps targeting API levels greater than 17 will get the fixed, more strict
25668         * behavior.</p>
25669         *
25670         * @param size the size of the measure specification
25671         * @param mode the mode of the measure specification
25672         * @return the measure specification based on size and mode
25673         */
25674        public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size,
25675                                          @MeasureSpecMode int mode) {
25676            if (sUseBrokenMakeMeasureSpec) {
25677                return size + mode;
25678            } else {
25679                return (size & ~MODE_MASK) | (mode & MODE_MASK);
25680            }
25681        }
25682
25683        /**
25684         * Like {@link #makeMeasureSpec(int, int)}, but any spec with a mode of UNSPECIFIED
25685         * will automatically get a size of 0. Older apps expect this.
25686         *
25687         * @hide internal use only for compatibility with system widgets and older apps
25688         */
25689        public static int makeSafeMeasureSpec(int size, int mode) {
25690            if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) {
25691                return 0;
25692            }
25693            return makeMeasureSpec(size, mode);
25694        }
25695
25696        /**
25697         * Extracts the mode from the supplied measure specification.
25698         *
25699         * @param measureSpec the measure specification to extract the mode from
25700         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
25701         *         {@link android.view.View.MeasureSpec#AT_MOST} or
25702         *         {@link android.view.View.MeasureSpec#EXACTLY}
25703         */
25704        @MeasureSpecMode
25705        public static int getMode(int measureSpec) {
25706            //noinspection ResourceType
25707            return (measureSpec & MODE_MASK);
25708        }
25709
25710        /**
25711         * Extracts the size from the supplied measure specification.
25712         *
25713         * @param measureSpec the measure specification to extract the size from
25714         * @return the size in pixels defined in the supplied measure specification
25715         */
25716        public static int getSize(int measureSpec) {
25717            return (measureSpec & ~MODE_MASK);
25718        }
25719
25720        static int adjust(int measureSpec, int delta) {
25721            final int mode = getMode(measureSpec);
25722            int size = getSize(measureSpec);
25723            if (mode == UNSPECIFIED) {
25724                // No need to adjust size for UNSPECIFIED mode.
25725                return makeMeasureSpec(size, UNSPECIFIED);
25726            }
25727            size += delta;
25728            if (size < 0) {
25729                Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
25730                        ") spec: " + toString(measureSpec) + " delta: " + delta);
25731                size = 0;
25732            }
25733            return makeMeasureSpec(size, mode);
25734        }
25735
25736        /**
25737         * Returns a String representation of the specified measure
25738         * specification.
25739         *
25740         * @param measureSpec the measure specification to convert to a String
25741         * @return a String with the following format: "MeasureSpec: MODE SIZE"
25742         */
25743        public static String toString(int measureSpec) {
25744            int mode = getMode(measureSpec);
25745            int size = getSize(measureSpec);
25746
25747            StringBuilder sb = new StringBuilder("MeasureSpec: ");
25748
25749            if (mode == UNSPECIFIED)
25750                sb.append("UNSPECIFIED ");
25751            else if (mode == EXACTLY)
25752                sb.append("EXACTLY ");
25753            else if (mode == AT_MOST)
25754                sb.append("AT_MOST ");
25755            else
25756                sb.append(mode).append(" ");
25757
25758            sb.append(size);
25759            return sb.toString();
25760        }
25761    }
25762
25763    private final class CheckForLongPress implements Runnable {
25764        private int mOriginalWindowAttachCount;
25765        private float mX;
25766        private float mY;
25767        private boolean mOriginalPressedState;
25768
25769        @Override
25770        public void run() {
25771            if ((mOriginalPressedState == isPressed()) && (mParent != null)
25772                    && mOriginalWindowAttachCount == mWindowAttachCount) {
25773                if (performLongClick(mX, mY)) {
25774                    mHasPerformedLongPress = true;
25775                }
25776            }
25777        }
25778
25779        public void setAnchor(float x, float y) {
25780            mX = x;
25781            mY = y;
25782        }
25783
25784        public void rememberWindowAttachCount() {
25785            mOriginalWindowAttachCount = mWindowAttachCount;
25786        }
25787
25788        public void rememberPressedState() {
25789            mOriginalPressedState = isPressed();
25790        }
25791    }
25792
25793    private final class CheckForTap implements Runnable {
25794        public float x;
25795        public float y;
25796
25797        @Override
25798        public void run() {
25799            mPrivateFlags &= ~PFLAG_PREPRESSED;
25800            setPressed(true, x, y);
25801            checkForLongClick(ViewConfiguration.getTapTimeout(), x, y);
25802        }
25803    }
25804
25805    private final class PerformClick implements Runnable {
25806        @Override
25807        public void run() {
25808            performClickInternal();
25809        }
25810    }
25811
25812    /**
25813     * This method returns a ViewPropertyAnimator object, which can be used to animate
25814     * specific properties on this View.
25815     *
25816     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
25817     */
25818    public ViewPropertyAnimator animate() {
25819        if (mAnimator == null) {
25820            mAnimator = new ViewPropertyAnimator(this);
25821        }
25822        return mAnimator;
25823    }
25824
25825    /**
25826     * Sets the name of the View to be used to identify Views in Transitions.
25827     * Names should be unique in the View hierarchy.
25828     *
25829     * @param transitionName The name of the View to uniquely identify it for Transitions.
25830     */
25831    public final void setTransitionName(String transitionName) {
25832        mTransitionName = transitionName;
25833    }
25834
25835    /**
25836     * Returns the name of the View to be used to identify Views in Transitions.
25837     * Names should be unique in the View hierarchy.
25838     *
25839     * <p>This returns null if the View has not been given a name.</p>
25840     *
25841     * @return The name used of the View to be used to identify Views in Transitions or null
25842     * if no name has been given.
25843     */
25844    @ViewDebug.ExportedProperty
25845    public String getTransitionName() {
25846        return mTransitionName;
25847    }
25848
25849    /**
25850     * @hide
25851     */
25852    public void requestKeyboardShortcuts(List<KeyboardShortcutGroup> data, int deviceId) {
25853        // Do nothing.
25854    }
25855
25856    /**
25857     * Interface definition for a callback to be invoked when a hardware key event is
25858     * dispatched to this view. The callback will be invoked before the key event is
25859     * given to the view. This is only useful for hardware keyboards; a software input
25860     * method has no obligation to trigger this listener.
25861     */
25862    public interface OnKeyListener {
25863        /**
25864         * Called when a hardware key is dispatched to a view. This allows listeners to
25865         * get a chance to respond before the target view.
25866         * <p>Key presses in software keyboards will generally NOT trigger this method,
25867         * although some may elect to do so in some situations. Do not assume a
25868         * software input method has to be key-based; even if it is, it may use key presses
25869         * in a different way than you expect, so there is no way to reliably catch soft
25870         * input key presses.
25871         *
25872         * @param v The view the key has been dispatched to.
25873         * @param keyCode The code for the physical key that was pressed
25874         * @param event The KeyEvent object containing full information about
25875         *        the event.
25876         * @return True if the listener has consumed the event, false otherwise.
25877         */
25878        boolean onKey(View v, int keyCode, KeyEvent event);
25879    }
25880
25881    /**
25882     * Interface definition for a callback to be invoked when a hardware key event is
25883     * dispatched to this view during the fallback phase. This means no view in the hierarchy
25884     * has handled this event.
25885     */
25886    public interface OnKeyFallbackListener {
25887        /**
25888         * Called when a hardware key is dispatched to a view in the fallback phase. This allows
25889         * listeners to respond to events after the view hierarchy has had a chance to respond.
25890         * <p>Key presses in software keyboards will generally NOT trigger this method,
25891         * although some may elect to do so in some situations. Do not assume a
25892         * software input method has to be key-based; even if it is, it may use key presses
25893         * in a different way than you expect, so there is no way to reliably catch soft
25894         * input key presses.
25895         *
25896         * @param v The view the key has been dispatched to.
25897         * @param event The KeyEvent object containing full information about
25898         *        the event.
25899         * @return True if the listener has consumed the event, false otherwise.
25900         */
25901        boolean onKeyFallback(View v, KeyEvent event);
25902    }
25903
25904    /**
25905     * Interface definition for a callback to be invoked when a touch event is
25906     * dispatched to this view. The callback will be invoked before the touch
25907     * event is given to the view.
25908     */
25909    public interface OnTouchListener {
25910        /**
25911         * Called when a touch event is dispatched to a view. This allows listeners to
25912         * get a chance to respond before the target view.
25913         *
25914         * @param v The view the touch event has been dispatched to.
25915         * @param event The MotionEvent object containing full information about
25916         *        the event.
25917         * @return True if the listener has consumed the event, false otherwise.
25918         */
25919        boolean onTouch(View v, MotionEvent event);
25920    }
25921
25922    /**
25923     * Interface definition for a callback to be invoked when a hover event is
25924     * dispatched to this view. The callback will be invoked before the hover
25925     * event is given to the view.
25926     */
25927    public interface OnHoverListener {
25928        /**
25929         * Called when a hover event is dispatched to a view. This allows listeners to
25930         * get a chance to respond before the target view.
25931         *
25932         * @param v The view the hover event has been dispatched to.
25933         * @param event The MotionEvent object containing full information about
25934         *        the event.
25935         * @return True if the listener has consumed the event, false otherwise.
25936         */
25937        boolean onHover(View v, MotionEvent event);
25938    }
25939
25940    /**
25941     * Interface definition for a callback to be invoked when a generic motion event is
25942     * dispatched to this view. The callback will be invoked before the generic motion
25943     * event is given to the view.
25944     */
25945    public interface OnGenericMotionListener {
25946        /**
25947         * Called when a generic motion event is dispatched to a view. This allows listeners to
25948         * get a chance to respond before the target view.
25949         *
25950         * @param v The view the generic motion event has been dispatched to.
25951         * @param event The MotionEvent object containing full information about
25952         *        the event.
25953         * @return True if the listener has consumed the event, false otherwise.
25954         */
25955        boolean onGenericMotion(View v, MotionEvent event);
25956    }
25957
25958    /**
25959     * Interface definition for a callback to be invoked when a view has been clicked and held.
25960     */
25961    public interface OnLongClickListener {
25962        /**
25963         * Called when a view has been clicked and held.
25964         *
25965         * @param v The view that was clicked and held.
25966         *
25967         * @return true if the callback consumed the long click, false otherwise.
25968         */
25969        boolean onLongClick(View v);
25970    }
25971
25972    /**
25973     * Interface definition for a callback to be invoked when a drag is being dispatched
25974     * to this view.  The callback will be invoked before the hosting view's own
25975     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
25976     * onDrag(event) behavior, it should return 'false' from this callback.
25977     *
25978     * <div class="special reference">
25979     * <h3>Developer Guides</h3>
25980     * <p>For a guide to implementing drag and drop features, read the
25981     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
25982     * </div>
25983     */
25984    public interface OnDragListener {
25985        /**
25986         * Called when a drag event is dispatched to a view. This allows listeners
25987         * to get a chance to override base View behavior.
25988         *
25989         * @param v The View that received the drag event.
25990         * @param event The {@link android.view.DragEvent} object for the drag event.
25991         * @return {@code true} if the drag event was handled successfully, or {@code false}
25992         * if the drag event was not handled. Note that {@code false} will trigger the View
25993         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
25994         */
25995        boolean onDrag(View v, DragEvent event);
25996    }
25997
25998    /**
25999     * Interface definition for a callback to be invoked when the focus state of
26000     * a view changed.
26001     */
26002    public interface OnFocusChangeListener {
26003        /**
26004         * Called when the focus state of a view has changed.
26005         *
26006         * @param v The view whose state has changed.
26007         * @param hasFocus The new focus state of v.
26008         */
26009        void onFocusChange(View v, boolean hasFocus);
26010    }
26011
26012    /**
26013     * Interface definition for a callback to be invoked when a view is clicked.
26014     */
26015    public interface OnClickListener {
26016        /**
26017         * Called when a view has been clicked.
26018         *
26019         * @param v The view that was clicked.
26020         */
26021        void onClick(View v);
26022    }
26023
26024    /**
26025     * Interface definition for a callback to be invoked when a view is context clicked.
26026     */
26027    public interface OnContextClickListener {
26028        /**
26029         * Called when a view is context clicked.
26030         *
26031         * @param v The view that has been context clicked.
26032         * @return true if the callback consumed the context click, false otherwise.
26033         */
26034        boolean onContextClick(View v);
26035    }
26036
26037    /**
26038     * Interface definition for a callback to be invoked when the context menu
26039     * for this view is being built.
26040     */
26041    public interface OnCreateContextMenuListener {
26042        /**
26043         * Called when the context menu for this view is being built. It is not
26044         * safe to hold onto the menu after this method returns.
26045         *
26046         * @param menu The context menu that is being built
26047         * @param v The view for which the context menu is being built
26048         * @param menuInfo Extra information about the item for which the
26049         *            context menu should be shown. This information will vary
26050         *            depending on the class of v.
26051         */
26052        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
26053    }
26054
26055    /**
26056     * Interface definition for a callback to be invoked when the status bar changes
26057     * visibility.  This reports <strong>global</strong> changes to the system UI
26058     * state, not what the application is requesting.
26059     *
26060     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
26061     */
26062    public interface OnSystemUiVisibilityChangeListener {
26063        /**
26064         * Called when the status bar changes visibility because of a call to
26065         * {@link View#setSystemUiVisibility(int)}.
26066         *
26067         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
26068         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
26069         * This tells you the <strong>global</strong> state of these UI visibility
26070         * flags, not what your app is currently applying.
26071         */
26072        public void onSystemUiVisibilityChange(int visibility);
26073    }
26074
26075    /**
26076     * Interface definition for a callback to be invoked when this view is attached
26077     * or detached from its window.
26078     */
26079    public interface OnAttachStateChangeListener {
26080        /**
26081         * Called when the view is attached to a window.
26082         * @param v The view that was attached
26083         */
26084        public void onViewAttachedToWindow(View v);
26085        /**
26086         * Called when the view is detached from a window.
26087         * @param v The view that was detached
26088         */
26089        public void onViewDetachedFromWindow(View v);
26090    }
26091
26092    /**
26093     * Listener for applying window insets on a view in a custom way.
26094     *
26095     * <p>Apps may choose to implement this interface if they want to apply custom policy
26096     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
26097     * is set, its
26098     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
26099     * method will be called instead of the View's own
26100     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
26101     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
26102     * the View's normal behavior as part of its own.</p>
26103     */
26104    public interface OnApplyWindowInsetsListener {
26105        /**
26106         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
26107         * on a View, this listener method will be called instead of the view's own
26108         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
26109         *
26110         * @param v The view applying window insets
26111         * @param insets The insets to apply
26112         * @return The insets supplied, minus any insets that were consumed
26113         */
26114        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
26115    }
26116
26117    private final class UnsetPressedState implements Runnable {
26118        @Override
26119        public void run() {
26120            setPressed(false);
26121        }
26122    }
26123
26124    /**
26125     * When a view becomes invisible checks if autofill considers the view invisible too. This
26126     * happens after the regular removal operation to make sure the operation is finished by the
26127     * time this is called.
26128     */
26129    private static class VisibilityChangeForAutofillHandler extends Handler {
26130        private final AutofillManager mAfm;
26131        private final View mView;
26132
26133        private VisibilityChangeForAutofillHandler(@NonNull AutofillManager afm,
26134                @NonNull View view) {
26135            mAfm = afm;
26136            mView = view;
26137        }
26138
26139        @Override
26140        public void handleMessage(Message msg) {
26141            mAfm.notifyViewVisibilityChanged(mView, mView.isShown());
26142        }
26143    }
26144
26145    /**
26146     * Base class for derived classes that want to save and restore their own
26147     * state in {@link android.view.View#onSaveInstanceState()}.
26148     */
26149    public static class BaseSavedState extends AbsSavedState {
26150        static final int START_ACTIVITY_REQUESTED_WHO_SAVED = 0b1;
26151        static final int IS_AUTOFILLED = 0b10;
26152        static final int AUTOFILL_ID = 0b100;
26153
26154        // Flags that describe what data in this state is valid
26155        int mSavedData;
26156        String mStartActivityRequestWhoSaved;
26157        boolean mIsAutofilled;
26158        int mAutofillViewId;
26159
26160        /**
26161         * Constructor used when reading from a parcel. Reads the state of the superclass.
26162         *
26163         * @param source parcel to read from
26164         */
26165        public BaseSavedState(Parcel source) {
26166            this(source, null);
26167        }
26168
26169        /**
26170         * Constructor used when reading from a parcel using a given class loader.
26171         * Reads the state of the superclass.
26172         *
26173         * @param source parcel to read from
26174         * @param loader ClassLoader to use for reading
26175         */
26176        public BaseSavedState(Parcel source, ClassLoader loader) {
26177            super(source, loader);
26178            mSavedData = source.readInt();
26179            mStartActivityRequestWhoSaved = source.readString();
26180            mIsAutofilled = source.readBoolean();
26181            mAutofillViewId = source.readInt();
26182        }
26183
26184        /**
26185         * Constructor called by derived classes when creating their SavedState objects
26186         *
26187         * @param superState The state of the superclass of this view
26188         */
26189        public BaseSavedState(Parcelable superState) {
26190            super(superState);
26191        }
26192
26193        @Override
26194        public void writeToParcel(Parcel out, int flags) {
26195            super.writeToParcel(out, flags);
26196
26197            out.writeInt(mSavedData);
26198            out.writeString(mStartActivityRequestWhoSaved);
26199            out.writeBoolean(mIsAutofilled);
26200            out.writeInt(mAutofillViewId);
26201        }
26202
26203        public static final Parcelable.Creator<BaseSavedState> CREATOR
26204                = new Parcelable.ClassLoaderCreator<BaseSavedState>() {
26205            @Override
26206            public BaseSavedState createFromParcel(Parcel in) {
26207                return new BaseSavedState(in);
26208            }
26209
26210            @Override
26211            public BaseSavedState createFromParcel(Parcel in, ClassLoader loader) {
26212                return new BaseSavedState(in, loader);
26213            }
26214
26215            @Override
26216            public BaseSavedState[] newArray(int size) {
26217                return new BaseSavedState[size];
26218            }
26219        };
26220    }
26221
26222    /**
26223     * A set of information given to a view when it is attached to its parent
26224     * window.
26225     */
26226    final static class AttachInfo {
26227        interface Callbacks {
26228            void playSoundEffect(int effectId);
26229            boolean performHapticFeedback(int effectId, boolean always);
26230        }
26231
26232        /**
26233         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
26234         * to a Handler. This class contains the target (View) to invalidate and
26235         * the coordinates of the dirty rectangle.
26236         *
26237         * For performance purposes, this class also implements a pool of up to
26238         * POOL_LIMIT objects that get reused. This reduces memory allocations
26239         * whenever possible.
26240         */
26241        static class InvalidateInfo {
26242            private static final int POOL_LIMIT = 10;
26243
26244            private static final SynchronizedPool<InvalidateInfo> sPool =
26245                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
26246
26247            View target;
26248
26249            int left;
26250            int top;
26251            int right;
26252            int bottom;
26253
26254            public static InvalidateInfo obtain() {
26255                InvalidateInfo instance = sPool.acquire();
26256                return (instance != null) ? instance : new InvalidateInfo();
26257            }
26258
26259            public void recycle() {
26260                target = null;
26261                sPool.release(this);
26262            }
26263        }
26264
26265        final IWindowSession mSession;
26266
26267        final IWindow mWindow;
26268
26269        final IBinder mWindowToken;
26270
26271        Display mDisplay;
26272
26273        final Callbacks mRootCallbacks;
26274
26275        IWindowId mIWindowId;
26276        WindowId mWindowId;
26277
26278        /**
26279         * The top view of the hierarchy.
26280         */
26281        View mRootView;
26282
26283        IBinder mPanelParentWindowToken;
26284
26285        boolean mHardwareAccelerated;
26286        boolean mHardwareAccelerationRequested;
26287        ThreadedRenderer mThreadedRenderer;
26288        List<RenderNode> mPendingAnimatingRenderNodes;
26289
26290        /**
26291         * The state of the display to which the window is attached, as reported
26292         * by {@link Display#getState()}.  Note that the display state constants
26293         * declared by {@link Display} do not exactly line up with the screen state
26294         * constants declared by {@link View} (there are more display states than
26295         * screen states).
26296         */
26297        int mDisplayState = Display.STATE_UNKNOWN;
26298
26299        /**
26300         * Scale factor used by the compatibility mode
26301         */
26302        float mApplicationScale;
26303
26304        /**
26305         * Indicates whether the application is in compatibility mode
26306         */
26307        boolean mScalingRequired;
26308
26309        /**
26310         * Left position of this view's window
26311         */
26312        int mWindowLeft;
26313
26314        /**
26315         * Top position of this view's window
26316         */
26317        int mWindowTop;
26318
26319        /**
26320         * Indicates whether views need to use 32-bit drawing caches
26321         */
26322        boolean mUse32BitDrawingCache;
26323
26324        /**
26325         * For windows that are full-screen but using insets to layout inside
26326         * of the screen areas, these are the current insets to appear inside
26327         * the overscan area of the display.
26328         */
26329        final Rect mOverscanInsets = new Rect();
26330
26331        /**
26332         * For windows that are full-screen but using insets to layout inside
26333         * of the screen decorations, these are the current insets for the
26334         * content of the window.
26335         */
26336        final Rect mContentInsets = new Rect();
26337
26338        /**
26339         * For windows that are full-screen but using insets to layout inside
26340         * of the screen decorations, these are the current insets for the
26341         * actual visible parts of the window.
26342         */
26343        final Rect mVisibleInsets = new Rect();
26344
26345        /**
26346         * For windows that are full-screen but using insets to layout inside
26347         * of the screen decorations, these are the current insets for the
26348         * stable system windows.
26349         */
26350        final Rect mStableInsets = new Rect();
26351
26352        final DisplayCutout.ParcelableWrapper mDisplayCutout =
26353                new DisplayCutout.ParcelableWrapper(DisplayCutout.NO_CUTOUT);
26354
26355        /**
26356         * For windows that include areas that are not covered by real surface these are the outsets
26357         * for real surface.
26358         */
26359        final Rect mOutsets = new Rect();
26360
26361        /**
26362         * In multi-window we force show the navigation bar. Because we don't want that the surface
26363         * size changes in this mode, we instead have a flag whether the navigation bar size should
26364         * always be consumed, so the app is treated like there is no virtual navigation bar at all.
26365         */
26366        boolean mAlwaysConsumeNavBar;
26367
26368        /**
26369         * The internal insets given by this window.  This value is
26370         * supplied by the client (through
26371         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
26372         * be given to the window manager when changed to be used in laying
26373         * out windows behind it.
26374         */
26375        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
26376                = new ViewTreeObserver.InternalInsetsInfo();
26377
26378        /**
26379         * Set to true when mGivenInternalInsets is non-empty.
26380         */
26381        boolean mHasNonEmptyGivenInternalInsets;
26382
26383        /**
26384         * All views in the window's hierarchy that serve as scroll containers,
26385         * used to determine if the window can be resized or must be panned
26386         * to adjust for a soft input area.
26387         */
26388        final ArrayList<View> mScrollContainers = new ArrayList<View>();
26389
26390        final KeyEvent.DispatcherState mKeyDispatchState
26391                = new KeyEvent.DispatcherState();
26392
26393        /**
26394         * Indicates whether the view's window currently has the focus.
26395         */
26396        boolean mHasWindowFocus;
26397
26398        /**
26399         * The current visibility of the window.
26400         */
26401        int mWindowVisibility;
26402
26403        /**
26404         * Indicates the time at which drawing started to occur.
26405         */
26406        long mDrawingTime;
26407
26408        /**
26409         * Indicates whether or not ignoring the DIRTY_MASK flags.
26410         */
26411        boolean mIgnoreDirtyState;
26412
26413        /**
26414         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
26415         * to avoid clearing that flag prematurely.
26416         */
26417        boolean mSetIgnoreDirtyState = false;
26418
26419        /**
26420         * Indicates whether the view's window is currently in touch mode.
26421         */
26422        boolean mInTouchMode;
26423
26424        /**
26425         * Indicates whether the view has requested unbuffered input dispatching for the current
26426         * event stream.
26427         */
26428        boolean mUnbufferedDispatchRequested;
26429
26430        /**
26431         * Indicates that ViewAncestor should trigger a global layout change
26432         * the next time it performs a traversal
26433         */
26434        boolean mRecomputeGlobalAttributes;
26435
26436        /**
26437         * Always report new attributes at next traversal.
26438         */
26439        boolean mForceReportNewAttributes;
26440
26441        /**
26442         * Set during a traveral if any views want to keep the screen on.
26443         */
26444        boolean mKeepScreenOn;
26445
26446        /**
26447         * Set during a traveral if the light center needs to be updated.
26448         */
26449        boolean mNeedsUpdateLightCenter;
26450
26451        /**
26452         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
26453         */
26454        int mSystemUiVisibility;
26455
26456        /**
26457         * Hack to force certain system UI visibility flags to be cleared.
26458         */
26459        int mDisabledSystemUiVisibility;
26460
26461        /**
26462         * Last global system UI visibility reported by the window manager.
26463         */
26464        int mGlobalSystemUiVisibility = -1;
26465
26466        /**
26467         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
26468         * attached.
26469         */
26470        boolean mHasSystemUiListeners;
26471
26472        /**
26473         * Set if the window has requested to extend into the overscan region
26474         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
26475         */
26476        boolean mOverscanRequested;
26477
26478        /**
26479         * Set if the visibility of any views has changed.
26480         */
26481        boolean mViewVisibilityChanged;
26482
26483        /**
26484         * Set to true if a view has been scrolled.
26485         */
26486        boolean mViewScrollChanged;
26487
26488        /**
26489         * Set to true if a pointer event is currently being handled.
26490         */
26491        boolean mHandlingPointerEvent;
26492
26493        /**
26494         * Global to the view hierarchy used as a temporary for dealing with
26495         * x/y points in the transparent region computations.
26496         */
26497        final int[] mTransparentLocation = new int[2];
26498
26499        /**
26500         * Global to the view hierarchy used as a temporary for dealing with
26501         * x/y points in the ViewGroup.invalidateChild implementation.
26502         */
26503        final int[] mInvalidateChildLocation = new int[2];
26504
26505        /**
26506         * Global to the view hierarchy used as a temporary for dealing with
26507         * computing absolute on-screen location.
26508         */
26509        final int[] mTmpLocation = new int[2];
26510
26511        /**
26512         * Global to the view hierarchy used as a temporary for dealing with
26513         * x/y location when view is transformed.
26514         */
26515        final float[] mTmpTransformLocation = new float[2];
26516
26517        /**
26518         * The view tree observer used to dispatch global events like
26519         * layout, pre-draw, touch mode change, etc.
26520         */
26521        final ViewTreeObserver mTreeObserver;
26522
26523        /**
26524         * A Canvas used by the view hierarchy to perform bitmap caching.
26525         */
26526        Canvas mCanvas;
26527
26528        /**
26529         * The view root impl.
26530         */
26531        final ViewRootImpl mViewRootImpl;
26532
26533        /**
26534         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
26535         * handler can be used to pump events in the UI events queue.
26536         */
26537        final Handler mHandler;
26538
26539        /**
26540         * Temporary for use in computing invalidate rectangles while
26541         * calling up the hierarchy.
26542         */
26543        final Rect mTmpInvalRect = new Rect();
26544
26545        /**
26546         * Temporary for use in computing hit areas with transformed views
26547         */
26548        final RectF mTmpTransformRect = new RectF();
26549
26550        /**
26551         * Temporary for use in computing hit areas with transformed views
26552         */
26553        final RectF mTmpTransformRect1 = new RectF();
26554
26555        /**
26556         * Temporary list of rectanges.
26557         */
26558        final List<RectF> mTmpRectList = new ArrayList<>();
26559
26560        /**
26561         * Temporary for use in transforming invalidation rect
26562         */
26563        final Matrix mTmpMatrix = new Matrix();
26564
26565        /**
26566         * Temporary for use in transforming invalidation rect
26567         */
26568        final Transformation mTmpTransformation = new Transformation();
26569
26570        /**
26571         * Temporary for use in querying outlines from OutlineProviders
26572         */
26573        final Outline mTmpOutline = new Outline();
26574
26575        /**
26576         * Temporary list for use in collecting focusable descendents of a view.
26577         */
26578        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
26579
26580        /**
26581         * The id of the window for accessibility purposes.
26582         */
26583        int mAccessibilityWindowId = AccessibilityWindowInfo.UNDEFINED_WINDOW_ID;
26584
26585        /**
26586         * Flags related to accessibility processing.
26587         *
26588         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
26589         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
26590         */
26591        int mAccessibilityFetchFlags;
26592
26593        /**
26594         * The drawable for highlighting accessibility focus.
26595         */
26596        Drawable mAccessibilityFocusDrawable;
26597
26598        /**
26599         * The drawable for highlighting autofilled views.
26600         *
26601         * @see #isAutofilled()
26602         */
26603        Drawable mAutofilledDrawable;
26604
26605        /**
26606         * Show where the margins, bounds and layout bounds are for each view.
26607         */
26608        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
26609
26610        /**
26611         * Point used to compute visible regions.
26612         */
26613        final Point mPoint = new Point();
26614
26615        /**
26616         * Used to track which View originated a requestLayout() call, used when
26617         * requestLayout() is called during layout.
26618         */
26619        View mViewRequestingLayout;
26620
26621        /**
26622         * Used to track views that need (at least) a partial relayout at their current size
26623         * during the next traversal.
26624         */
26625        List<View> mPartialLayoutViews = new ArrayList<>();
26626
26627        /**
26628         * Swapped with mPartialLayoutViews during layout to avoid concurrent
26629         * modification. Lazily assigned during ViewRootImpl layout.
26630         */
26631        List<View> mEmptyPartialLayoutViews;
26632
26633        /**
26634         * Used to track the identity of the current drag operation.
26635         */
26636        IBinder mDragToken;
26637
26638        /**
26639         * The drag shadow surface for the current drag operation.
26640         */
26641        public Surface mDragSurface;
26642
26643
26644        /**
26645         * The view that currently has a tooltip displayed.
26646         */
26647        View mTooltipHost;
26648
26649        /**
26650         * Creates a new set of attachment information with the specified
26651         * events handler and thread.
26652         *
26653         * @param handler the events handler the view must use
26654         */
26655        AttachInfo(IWindowSession session, IWindow window, Display display,
26656                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer,
26657                Context context) {
26658            mSession = session;
26659            mWindow = window;
26660            mWindowToken = window.asBinder();
26661            mDisplay = display;
26662            mViewRootImpl = viewRootImpl;
26663            mHandler = handler;
26664            mRootCallbacks = effectPlayer;
26665            mTreeObserver = new ViewTreeObserver(context);
26666        }
26667    }
26668
26669    /**
26670     * <p>ScrollabilityCache holds various fields used by a View when scrolling
26671     * is supported. This avoids keeping too many unused fields in most
26672     * instances of View.</p>
26673     */
26674    private static class ScrollabilityCache implements Runnable {
26675
26676        /**
26677         * Scrollbars are not visible
26678         */
26679        public static final int OFF = 0;
26680
26681        /**
26682         * Scrollbars are visible
26683         */
26684        public static final int ON = 1;
26685
26686        /**
26687         * Scrollbars are fading away
26688         */
26689        public static final int FADING = 2;
26690
26691        public boolean fadeScrollBars;
26692
26693        public int fadingEdgeLength;
26694        public int scrollBarDefaultDelayBeforeFade;
26695        public int scrollBarFadeDuration;
26696
26697        public int scrollBarSize;
26698        public int scrollBarMinTouchTarget;
26699        public ScrollBarDrawable scrollBar;
26700        public float[] interpolatorValues;
26701        public View host;
26702
26703        public final Paint paint;
26704        public final Matrix matrix;
26705        public Shader shader;
26706
26707        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
26708
26709        private static final float[] OPAQUE = { 255 };
26710        private static final float[] TRANSPARENT = { 0.0f };
26711
26712        /**
26713         * When fading should start. This time moves into the future every time
26714         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
26715         */
26716        public long fadeStartTime;
26717
26718
26719        /**
26720         * The current state of the scrollbars: ON, OFF, or FADING
26721         */
26722        public int state = OFF;
26723
26724        private int mLastColor;
26725
26726        public final Rect mScrollBarBounds = new Rect();
26727        public final Rect mScrollBarTouchBounds = new Rect();
26728
26729        public static final int NOT_DRAGGING = 0;
26730        public static final int DRAGGING_VERTICAL_SCROLL_BAR = 1;
26731        public static final int DRAGGING_HORIZONTAL_SCROLL_BAR = 2;
26732        public int mScrollBarDraggingState = NOT_DRAGGING;
26733
26734        public float mScrollBarDraggingPos = 0;
26735
26736        public ScrollabilityCache(ViewConfiguration configuration, View host) {
26737            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
26738            scrollBarSize = configuration.getScaledScrollBarSize();
26739            scrollBarMinTouchTarget = configuration.getScaledMinScrollbarTouchTarget();
26740            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
26741            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
26742
26743            paint = new Paint();
26744            matrix = new Matrix();
26745            // use use a height of 1, and then wack the matrix each time we
26746            // actually use it.
26747            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
26748            paint.setShader(shader);
26749            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
26750
26751            this.host = host;
26752        }
26753
26754        public void setFadeColor(int color) {
26755            if (color != mLastColor) {
26756                mLastColor = color;
26757
26758                if (color != 0) {
26759                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
26760                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
26761                    paint.setShader(shader);
26762                    // Restore the default transfer mode (src_over)
26763                    paint.setXfermode(null);
26764                } else {
26765                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
26766                    paint.setShader(shader);
26767                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
26768                }
26769            }
26770        }
26771
26772        public void run() {
26773            long now = AnimationUtils.currentAnimationTimeMillis();
26774            if (now >= fadeStartTime) {
26775
26776                // the animation fades the scrollbars out by changing
26777                // the opacity (alpha) from fully opaque to fully
26778                // transparent
26779                int nextFrame = (int) now;
26780                int framesCount = 0;
26781
26782                Interpolator interpolator = scrollBarInterpolator;
26783
26784                // Start opaque
26785                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
26786
26787                // End transparent
26788                nextFrame += scrollBarFadeDuration;
26789                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
26790
26791                state = FADING;
26792
26793                // Kick off the fade animation
26794                host.invalidate(true);
26795            }
26796        }
26797    }
26798
26799    /**
26800     * Resuable callback for sending
26801     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
26802     */
26803    private class SendViewScrolledAccessibilityEvent implements Runnable {
26804        public volatile boolean mIsPending;
26805        public int mDeltaX;
26806        public int mDeltaY;
26807
26808        public void post(int dx, int dy) {
26809            mDeltaX += dx;
26810            mDeltaY += dy;
26811            if (!mIsPending) {
26812                mIsPending = true;
26813                postDelayed(this, ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
26814            }
26815        }
26816
26817        @Override
26818        public void run() {
26819            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
26820                AccessibilityEvent event = AccessibilityEvent.obtain(
26821                        AccessibilityEvent.TYPE_VIEW_SCROLLED);
26822                event.setScrollDeltaX(mDeltaX);
26823                event.setScrollDeltaY(mDeltaY);
26824                sendAccessibilityEventUnchecked(event);
26825            }
26826            reset();
26827        }
26828
26829        private void reset() {
26830            mIsPending = false;
26831            mDeltaX = 0;
26832            mDeltaY = 0;
26833        }
26834    }
26835
26836    /**
26837     * Remove the pending callback for sending a
26838     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
26839     */
26840    private void cancel(@Nullable SendViewScrolledAccessibilityEvent callback) {
26841        if (callback == null || !callback.mIsPending) return;
26842        removeCallbacks(callback);
26843        callback.reset();
26844    }
26845
26846    /**
26847     * <p>
26848     * This class represents a delegate that can be registered in a {@link View}
26849     * to enhance accessibility support via composition rather via inheritance.
26850     * It is specifically targeted to widget developers that extend basic View
26851     * classes i.e. classes in package android.view, that would like their
26852     * applications to be backwards compatible.
26853     * </p>
26854     * <div class="special reference">
26855     * <h3>Developer Guides</h3>
26856     * <p>For more information about making applications accessible, read the
26857     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
26858     * developer guide.</p>
26859     * </div>
26860     * <p>
26861     * A scenario in which a developer would like to use an accessibility delegate
26862     * is overriding a method introduced in a later API version than the minimal API
26863     * version supported by the application. For example, the method
26864     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
26865     * in API version 4 when the accessibility APIs were first introduced. If a
26866     * developer would like his application to run on API version 4 devices (assuming
26867     * all other APIs used by the application are version 4 or lower) and take advantage
26868     * of this method, instead of overriding the method which would break the application's
26869     * backwards compatibility, he can override the corresponding method in this
26870     * delegate and register the delegate in the target View if the API version of
26871     * the system is high enough, i.e. the API version is the same as or higher than the API
26872     * version that introduced
26873     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
26874     * </p>
26875     * <p>
26876     * Here is an example implementation:
26877     * </p>
26878     * <code><pre><p>
26879     * if (Build.VERSION.SDK_INT >= 14) {
26880     *     // If the API version is equal of higher than the version in
26881     *     // which onInitializeAccessibilityNodeInfo was introduced we
26882     *     // register a delegate with a customized implementation.
26883     *     View view = findViewById(R.id.view_id);
26884     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
26885     *         public void onInitializeAccessibilityNodeInfo(View host,
26886     *                 AccessibilityNodeInfo info) {
26887     *             // Let the default implementation populate the info.
26888     *             super.onInitializeAccessibilityNodeInfo(host, info);
26889     *             // Set some other information.
26890     *             info.setEnabled(host.isEnabled());
26891     *         }
26892     *     });
26893     * }
26894     * </code></pre></p>
26895     * <p>
26896     * This delegate contains methods that correspond to the accessibility methods
26897     * in View. If a delegate has been specified the implementation in View hands
26898     * off handling to the corresponding method in this delegate. The default
26899     * implementation the delegate methods behaves exactly as the corresponding
26900     * method in View for the case of no accessibility delegate been set. Hence,
26901     * to customize the behavior of a View method, clients can override only the
26902     * corresponding delegate method without altering the behavior of the rest
26903     * accessibility related methods of the host view.
26904     * </p>
26905     * <p>
26906     * <strong>Note:</strong> On platform versions prior to
26907     * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on
26908     * views in the {@code android.widget.*} package are called <i>before</i>
26909     * host methods. This prevents certain properties such as class name from
26910     * being modified by overriding
26911     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)},
26912     * as any changes will be overwritten by the host class.
26913     * <p>
26914     * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate
26915     * methods are called <i>after</i> host methods, which all properties to be
26916     * modified without being overwritten by the host class.
26917     */
26918    public static class AccessibilityDelegate {
26919
26920        /**
26921         * Sends an accessibility event of the given type. If accessibility is not
26922         * enabled this method has no effect.
26923         * <p>
26924         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
26925         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
26926         * been set.
26927         * </p>
26928         *
26929         * @param host The View hosting the delegate.
26930         * @param eventType The type of the event to send.
26931         *
26932         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
26933         */
26934        public void sendAccessibilityEvent(View host, int eventType) {
26935            host.sendAccessibilityEventInternal(eventType);
26936        }
26937
26938        /**
26939         * Performs the specified accessibility action on the view. For
26940         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
26941         * <p>
26942         * The default implementation behaves as
26943         * {@link View#performAccessibilityAction(int, Bundle)
26944         *  View#performAccessibilityAction(int, Bundle)} for the case of
26945         *  no accessibility delegate been set.
26946         * </p>
26947         *
26948         * @param action The action to perform.
26949         * @return Whether the action was performed.
26950         *
26951         * @see View#performAccessibilityAction(int, Bundle)
26952         *      View#performAccessibilityAction(int, Bundle)
26953         */
26954        public boolean performAccessibilityAction(View host, int action, Bundle args) {
26955            return host.performAccessibilityActionInternal(action, args);
26956        }
26957
26958        /**
26959         * Sends an accessibility event. This method behaves exactly as
26960         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
26961         * empty {@link AccessibilityEvent} and does not perform a check whether
26962         * accessibility is enabled.
26963         * <p>
26964         * The default implementation behaves as
26965         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
26966         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
26967         * the case of no accessibility delegate been set.
26968         * </p>
26969         *
26970         * @param host The View hosting the delegate.
26971         * @param event The event to send.
26972         *
26973         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
26974         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
26975         */
26976        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
26977            host.sendAccessibilityEventUncheckedInternal(event);
26978        }
26979
26980        /**
26981         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
26982         * to its children for adding their text content to the event.
26983         * <p>
26984         * The default implementation behaves as
26985         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
26986         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
26987         * the case of no accessibility delegate been set.
26988         * </p>
26989         *
26990         * @param host The View hosting the delegate.
26991         * @param event The event.
26992         * @return True if the event population was completed.
26993         *
26994         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
26995         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
26996         */
26997        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
26998            return host.dispatchPopulateAccessibilityEventInternal(event);
26999        }
27000
27001        /**
27002         * Gives a chance to the host View to populate the accessibility event with its
27003         * text content.
27004         * <p>
27005         * The default implementation behaves as
27006         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
27007         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
27008         * the case of no accessibility delegate been set.
27009         * </p>
27010         *
27011         * @param host The View hosting the delegate.
27012         * @param event The accessibility event which to populate.
27013         *
27014         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
27015         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
27016         */
27017        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
27018            host.onPopulateAccessibilityEventInternal(event);
27019        }
27020
27021        /**
27022         * Initializes an {@link AccessibilityEvent} with information about the
27023         * the host View which is the event source.
27024         * <p>
27025         * The default implementation behaves as
27026         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
27027         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
27028         * the case of no accessibility delegate been set.
27029         * </p>
27030         *
27031         * @param host The View hosting the delegate.
27032         * @param event The event to initialize.
27033         *
27034         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
27035         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
27036         */
27037        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
27038            host.onInitializeAccessibilityEventInternal(event);
27039        }
27040
27041        /**
27042         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
27043         * <p>
27044         * The default implementation behaves as
27045         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
27046         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
27047         * the case of no accessibility delegate been set.
27048         * </p>
27049         *
27050         * @param host The View hosting the delegate.
27051         * @param info The instance to initialize.
27052         *
27053         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
27054         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
27055         */
27056        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
27057            host.onInitializeAccessibilityNodeInfoInternal(info);
27058        }
27059
27060        /**
27061         * Adds extra data to an {@link AccessibilityNodeInfo} based on an explicit request for the
27062         * additional data.
27063         * <p>
27064         * This method only needs to be implemented if the View offers to provide additional data.
27065         * </p>
27066         * <p>
27067         * The default implementation behaves as
27068         * {@link View#addExtraDataToAccessibilityNodeInfo(AccessibilityNodeInfo, String, Bundle)
27069         * for the case where no accessibility delegate is set.
27070         * </p>
27071         *
27072         * @param host The View hosting the delegate. Never {@code null}.
27073         * @param info The info to which to add the extra data. Never {@code null}.
27074         * @param extraDataKey A key specifying the type of extra data to add to the info. The
27075         *                     extra data should be added to the {@link Bundle} returned by
27076         *                     the info's {@link AccessibilityNodeInfo#getExtras} method.  Never
27077         *                     {@code null}.
27078         * @param arguments A {@link Bundle} holding any arguments relevant for this request.
27079         *                  May be {@code null} if the if the service provided no arguments.
27080         *
27081         * @see AccessibilityNodeInfo#setExtraAvailableData
27082         */
27083        public void addExtraDataToAccessibilityNodeInfo(@NonNull View host,
27084                @NonNull AccessibilityNodeInfo info, @NonNull String extraDataKey,
27085                @Nullable Bundle arguments) {
27086            host.addExtraDataToAccessibilityNodeInfo(info, extraDataKey, arguments);
27087        }
27088
27089        /**
27090         * Called when a child of the host View has requested sending an
27091         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
27092         * to augment the event.
27093         * <p>
27094         * The default implementation behaves as
27095         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
27096         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
27097         * the case of no accessibility delegate been set.
27098         * </p>
27099         *
27100         * @param host The View hosting the delegate.
27101         * @param child The child which requests sending the event.
27102         * @param event The event to be sent.
27103         * @return True if the event should be sent
27104         *
27105         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
27106         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
27107         */
27108        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
27109                AccessibilityEvent event) {
27110            return host.onRequestSendAccessibilityEventInternal(child, event);
27111        }
27112
27113        /**
27114         * Gets the provider for managing a virtual view hierarchy rooted at this View
27115         * and reported to {@link android.accessibilityservice.AccessibilityService}s
27116         * that explore the window content.
27117         * <p>
27118         * The default implementation behaves as
27119         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
27120         * the case of no accessibility delegate been set.
27121         * </p>
27122         *
27123         * @return The provider.
27124         *
27125         * @see AccessibilityNodeProvider
27126         */
27127        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
27128            return null;
27129        }
27130
27131        /**
27132         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
27133         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
27134         * This method is responsible for obtaining an accessibility node info from a
27135         * pool of reusable instances and calling
27136         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
27137         * view to initialize the former.
27138         * <p>
27139         * <strong>Note:</strong> The client is responsible for recycling the obtained
27140         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
27141         * creation.
27142         * </p>
27143         * <p>
27144         * The default implementation behaves as
27145         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
27146         * the case of no accessibility delegate been set.
27147         * </p>
27148         * @return A populated {@link AccessibilityNodeInfo}.
27149         *
27150         * @see AccessibilityNodeInfo
27151         *
27152         * @hide
27153         */
27154        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
27155            return host.createAccessibilityNodeInfoInternal();
27156        }
27157    }
27158
27159    private static class MatchIdPredicate implements Predicate<View> {
27160        public int mId;
27161
27162        @Override
27163        public boolean test(View view) {
27164            return (view.mID == mId);
27165        }
27166    }
27167
27168    private static class MatchLabelForPredicate implements Predicate<View> {
27169        private int mLabeledId;
27170
27171        @Override
27172        public boolean test(View view) {
27173            return (view.mLabelForId == mLabeledId);
27174        }
27175    }
27176
27177    /**
27178     * Dump all private flags in readable format, useful for documentation and
27179     * sanity checking.
27180     */
27181    private static void dumpFlags() {
27182        final HashMap<String, String> found = Maps.newHashMap();
27183        try {
27184            for (Field field : View.class.getDeclaredFields()) {
27185                final int modifiers = field.getModifiers();
27186                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
27187                    if (field.getType().equals(int.class)) {
27188                        final int value = field.getInt(null);
27189                        dumpFlag(found, field.getName(), value);
27190                    } else if (field.getType().equals(int[].class)) {
27191                        final int[] values = (int[]) field.get(null);
27192                        for (int i = 0; i < values.length; i++) {
27193                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
27194                        }
27195                    }
27196                }
27197            }
27198        } catch (IllegalAccessException e) {
27199            throw new RuntimeException(e);
27200        }
27201
27202        final ArrayList<String> keys = Lists.newArrayList();
27203        keys.addAll(found.keySet());
27204        Collections.sort(keys);
27205        for (String key : keys) {
27206            Log.d(VIEW_LOG_TAG, found.get(key));
27207        }
27208    }
27209
27210    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
27211        // Sort flags by prefix, then by bits, always keeping unique keys
27212        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
27213        final int prefix = name.indexOf('_');
27214        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
27215        final String output = bits + " " + name;
27216        found.put(key, output);
27217    }
27218
27219    /** {@hide} */
27220    public void encode(@NonNull ViewHierarchyEncoder stream) {
27221        stream.beginObject(this);
27222        encodeProperties(stream);
27223        stream.endObject();
27224    }
27225
27226    /** {@hide} */
27227    @CallSuper
27228    protected void encodeProperties(@NonNull ViewHierarchyEncoder stream) {
27229        Object resolveId = ViewDebug.resolveId(getContext(), mID);
27230        if (resolveId instanceof String) {
27231            stream.addProperty("id", (String) resolveId);
27232        } else {
27233            stream.addProperty("id", mID);
27234        }
27235
27236        stream.addProperty("misc:transformation.alpha",
27237                mTransformationInfo != null ? mTransformationInfo.mAlpha : 0);
27238        stream.addProperty("misc:transitionName", getTransitionName());
27239
27240        // layout
27241        stream.addProperty("layout:left", mLeft);
27242        stream.addProperty("layout:right", mRight);
27243        stream.addProperty("layout:top", mTop);
27244        stream.addProperty("layout:bottom", mBottom);
27245        stream.addProperty("layout:width", getWidth());
27246        stream.addProperty("layout:height", getHeight());
27247        stream.addProperty("layout:layoutDirection", getLayoutDirection());
27248        stream.addProperty("layout:layoutRtl", isLayoutRtl());
27249        stream.addProperty("layout:hasTransientState", hasTransientState());
27250        stream.addProperty("layout:baseline", getBaseline());
27251
27252        // layout params
27253        ViewGroup.LayoutParams layoutParams = getLayoutParams();
27254        if (layoutParams != null) {
27255            stream.addPropertyKey("layoutParams");
27256            layoutParams.encode(stream);
27257        }
27258
27259        // scrolling
27260        stream.addProperty("scrolling:scrollX", mScrollX);
27261        stream.addProperty("scrolling:scrollY", mScrollY);
27262
27263        // padding
27264        stream.addProperty("padding:paddingLeft", mPaddingLeft);
27265        stream.addProperty("padding:paddingRight", mPaddingRight);
27266        stream.addProperty("padding:paddingTop", mPaddingTop);
27267        stream.addProperty("padding:paddingBottom", mPaddingBottom);
27268        stream.addProperty("padding:userPaddingRight", mUserPaddingRight);
27269        stream.addProperty("padding:userPaddingLeft", mUserPaddingLeft);
27270        stream.addProperty("padding:userPaddingBottom", mUserPaddingBottom);
27271        stream.addProperty("padding:userPaddingStart", mUserPaddingStart);
27272        stream.addProperty("padding:userPaddingEnd", mUserPaddingEnd);
27273
27274        // measurement
27275        stream.addProperty("measurement:minHeight", mMinHeight);
27276        stream.addProperty("measurement:minWidth", mMinWidth);
27277        stream.addProperty("measurement:measuredWidth", mMeasuredWidth);
27278        stream.addProperty("measurement:measuredHeight", mMeasuredHeight);
27279
27280        // drawing
27281        stream.addProperty("drawing:elevation", getElevation());
27282        stream.addProperty("drawing:translationX", getTranslationX());
27283        stream.addProperty("drawing:translationY", getTranslationY());
27284        stream.addProperty("drawing:translationZ", getTranslationZ());
27285        stream.addProperty("drawing:rotation", getRotation());
27286        stream.addProperty("drawing:rotationX", getRotationX());
27287        stream.addProperty("drawing:rotationY", getRotationY());
27288        stream.addProperty("drawing:scaleX", getScaleX());
27289        stream.addProperty("drawing:scaleY", getScaleY());
27290        stream.addProperty("drawing:pivotX", getPivotX());
27291        stream.addProperty("drawing:pivotY", getPivotY());
27292        stream.addProperty("drawing:clipBounds",
27293                mClipBounds == null ? null : mClipBounds.toString());
27294        stream.addProperty("drawing:opaque", isOpaque());
27295        stream.addProperty("drawing:alpha", getAlpha());
27296        stream.addProperty("drawing:transitionAlpha", getTransitionAlpha());
27297        stream.addProperty("drawing:shadow", hasShadow());
27298        stream.addProperty("drawing:solidColor", getSolidColor());
27299        stream.addProperty("drawing:layerType", mLayerType);
27300        stream.addProperty("drawing:willNotDraw", willNotDraw());
27301        stream.addProperty("drawing:hardwareAccelerated", isHardwareAccelerated());
27302        stream.addProperty("drawing:willNotCacheDrawing", willNotCacheDrawing());
27303        stream.addProperty("drawing:drawingCacheEnabled", isDrawingCacheEnabled());
27304        stream.addProperty("drawing:overlappingRendering", hasOverlappingRendering());
27305        stream.addProperty("drawing:outlineAmbientShadowColor", getOutlineAmbientShadowColor());
27306        stream.addProperty("drawing:outlineSpotShadowColor", getOutlineSpotShadowColor());
27307
27308        // focus
27309        stream.addProperty("focus:hasFocus", hasFocus());
27310        stream.addProperty("focus:isFocused", isFocused());
27311        stream.addProperty("focus:focusable", getFocusable());
27312        stream.addProperty("focus:isFocusable", isFocusable());
27313        stream.addProperty("focus:isFocusableInTouchMode", isFocusableInTouchMode());
27314
27315        stream.addProperty("misc:clickable", isClickable());
27316        stream.addProperty("misc:pressed", isPressed());
27317        stream.addProperty("misc:selected", isSelected());
27318        stream.addProperty("misc:touchMode", isInTouchMode());
27319        stream.addProperty("misc:hovered", isHovered());
27320        stream.addProperty("misc:activated", isActivated());
27321
27322        stream.addProperty("misc:visibility", getVisibility());
27323        stream.addProperty("misc:fitsSystemWindows", getFitsSystemWindows());
27324        stream.addProperty("misc:filterTouchesWhenObscured", getFilterTouchesWhenObscured());
27325
27326        stream.addProperty("misc:enabled", isEnabled());
27327        stream.addProperty("misc:soundEffectsEnabled", isSoundEffectsEnabled());
27328        stream.addProperty("misc:hapticFeedbackEnabled", isHapticFeedbackEnabled());
27329
27330        // theme attributes
27331        Resources.Theme theme = getContext().getTheme();
27332        if (theme != null) {
27333            stream.addPropertyKey("theme");
27334            theme.encode(stream);
27335        }
27336
27337        // view attribute information
27338        int n = mAttributes != null ? mAttributes.length : 0;
27339        stream.addProperty("meta:__attrCount__", n/2);
27340        for (int i = 0; i < n; i += 2) {
27341            stream.addProperty("meta:__attr__" + mAttributes[i], mAttributes[i+1]);
27342        }
27343
27344        stream.addProperty("misc:scrollBarStyle", getScrollBarStyle());
27345
27346        // text
27347        stream.addProperty("text:textDirection", getTextDirection());
27348        stream.addProperty("text:textAlignment", getTextAlignment());
27349
27350        // accessibility
27351        CharSequence contentDescription = getContentDescription();
27352        stream.addProperty("accessibility:contentDescription",
27353                contentDescription == null ? "" : contentDescription.toString());
27354        stream.addProperty("accessibility:labelFor", getLabelFor());
27355        stream.addProperty("accessibility:importantForAccessibility", getImportantForAccessibility());
27356    }
27357
27358    /**
27359     * Determine if this view is rendered on a round wearable device and is the main view
27360     * on the screen.
27361     */
27362    boolean shouldDrawRoundScrollbar() {
27363        if (!mResources.getConfiguration().isScreenRound() || mAttachInfo == null) {
27364            return false;
27365        }
27366
27367        final View rootView = getRootView();
27368        final WindowInsets insets = getRootWindowInsets();
27369
27370        int height = getHeight();
27371        int width = getWidth();
27372        int displayHeight = rootView.getHeight();
27373        int displayWidth = rootView.getWidth();
27374
27375        if (height != displayHeight || width != displayWidth) {
27376            return false;
27377        }
27378
27379        getLocationInWindow(mAttachInfo.mTmpLocation);
27380        return mAttachInfo.mTmpLocation[0] == insets.getStableInsetLeft()
27381                && mAttachInfo.mTmpLocation[1] == insets.getStableInsetTop();
27382    }
27383
27384    /**
27385     * Sets the tooltip text which will be displayed in a small popup next to the view.
27386     * <p>
27387     * The tooltip will be displayed:
27388     * <ul>
27389     * <li>On long click, unless it is handled otherwise (by OnLongClickListener or a context
27390     * menu). </li>
27391     * <li>On hover, after a brief delay since the pointer has stopped moving </li>
27392     * </ul>
27393     * <p>
27394     * <strong>Note:</strong> Do not override this method, as it will have no
27395     * effect on the text displayed in the tooltip.
27396     *
27397     * @param tooltipText the tooltip text, or null if no tooltip is required
27398     * @see #getTooltipText()
27399     * @attr ref android.R.styleable#View_tooltipText
27400     */
27401    public void setTooltipText(@Nullable CharSequence tooltipText) {
27402        if (TextUtils.isEmpty(tooltipText)) {
27403            setFlags(0, TOOLTIP);
27404            hideTooltip();
27405            mTooltipInfo = null;
27406        } else {
27407            setFlags(TOOLTIP, TOOLTIP);
27408            if (mTooltipInfo == null) {
27409                mTooltipInfo = new TooltipInfo();
27410                mTooltipInfo.mShowTooltipRunnable = this::showHoverTooltip;
27411                mTooltipInfo.mHideTooltipRunnable = this::hideTooltip;
27412                mTooltipInfo.mHoverSlop = ViewConfiguration.get(mContext).getScaledHoverSlop();
27413                mTooltipInfo.clearAnchorPos();
27414            }
27415            mTooltipInfo.mTooltipText = tooltipText;
27416        }
27417    }
27418
27419    /**
27420     * @hide Binary compatibility stub. To be removed when we finalize O APIs.
27421     */
27422    public void setTooltip(@Nullable CharSequence tooltipText) {
27423        setTooltipText(tooltipText);
27424    }
27425
27426    /**
27427     * Returns the view's tooltip text.
27428     *
27429     * <strong>Note:</strong> Do not override this method, as it will have no
27430     * effect on the text displayed in the tooltip. You must call
27431     * {@link #setTooltipText(CharSequence)} to modify the tooltip text.
27432     *
27433     * @return the tooltip text
27434     * @see #setTooltipText(CharSequence)
27435     * @attr ref android.R.styleable#View_tooltipText
27436     */
27437    @Nullable
27438    public CharSequence getTooltipText() {
27439        return mTooltipInfo != null ? mTooltipInfo.mTooltipText : null;
27440    }
27441
27442    /**
27443     * @hide Binary compatibility stub. To be removed when we finalize O APIs.
27444     */
27445    @Nullable
27446    public CharSequence getTooltip() {
27447        return getTooltipText();
27448    }
27449
27450    private boolean showTooltip(int x, int y, boolean fromLongClick) {
27451        if (mAttachInfo == null || mTooltipInfo == null) {
27452            return false;
27453        }
27454        if (fromLongClick && (mViewFlags & ENABLED_MASK) != ENABLED) {
27455            return false;
27456        }
27457        if (TextUtils.isEmpty(mTooltipInfo.mTooltipText)) {
27458            return false;
27459        }
27460        hideTooltip();
27461        mTooltipInfo.mTooltipFromLongClick = fromLongClick;
27462        mTooltipInfo.mTooltipPopup = new TooltipPopup(getContext());
27463        final boolean fromTouch = (mPrivateFlags3 & PFLAG3_FINGER_DOWN) == PFLAG3_FINGER_DOWN;
27464        mTooltipInfo.mTooltipPopup.show(this, x, y, fromTouch, mTooltipInfo.mTooltipText);
27465        mAttachInfo.mTooltipHost = this;
27466        // The available accessibility actions have changed
27467        notifyViewAccessibilityStateChangedIfNeeded(CONTENT_CHANGE_TYPE_UNDEFINED);
27468        return true;
27469    }
27470
27471    void hideTooltip() {
27472        if (mTooltipInfo == null) {
27473            return;
27474        }
27475        removeCallbacks(mTooltipInfo.mShowTooltipRunnable);
27476        if (mTooltipInfo.mTooltipPopup == null) {
27477            return;
27478        }
27479        mTooltipInfo.mTooltipPopup.hide();
27480        mTooltipInfo.mTooltipPopup = null;
27481        mTooltipInfo.mTooltipFromLongClick = false;
27482        mTooltipInfo.clearAnchorPos();
27483        if (mAttachInfo != null) {
27484            mAttachInfo.mTooltipHost = null;
27485        }
27486        // The available accessibility actions have changed
27487        notifyViewAccessibilityStateChangedIfNeeded(CONTENT_CHANGE_TYPE_UNDEFINED);
27488    }
27489
27490    private boolean showLongClickTooltip(int x, int y) {
27491        removeCallbacks(mTooltipInfo.mShowTooltipRunnable);
27492        removeCallbacks(mTooltipInfo.mHideTooltipRunnable);
27493        return showTooltip(x, y, true);
27494    }
27495
27496    private boolean showHoverTooltip() {
27497        return showTooltip(mTooltipInfo.mAnchorX, mTooltipInfo.mAnchorY, false);
27498    }
27499
27500    boolean dispatchTooltipHoverEvent(MotionEvent event) {
27501        if (mTooltipInfo == null) {
27502            return false;
27503        }
27504        switch(event.getAction()) {
27505            case MotionEvent.ACTION_HOVER_MOVE:
27506                if ((mViewFlags & TOOLTIP) != TOOLTIP) {
27507                    break;
27508                }
27509                if (!mTooltipInfo.mTooltipFromLongClick && mTooltipInfo.updateAnchorPos(event)) {
27510                    if (mTooltipInfo.mTooltipPopup == null) {
27511                        // Schedule showing the tooltip after a timeout.
27512                        removeCallbacks(mTooltipInfo.mShowTooltipRunnable);
27513                        postDelayed(mTooltipInfo.mShowTooltipRunnable,
27514                                ViewConfiguration.getHoverTooltipShowTimeout());
27515                    }
27516
27517                    // Hide hover-triggered tooltip after a period of inactivity.
27518                    // Match the timeout used by NativeInputManager to hide the mouse pointer
27519                    // (depends on SYSTEM_UI_FLAG_LOW_PROFILE being set).
27520                    final int timeout;
27521                    if ((getWindowSystemUiVisibility() & SYSTEM_UI_FLAG_LOW_PROFILE)
27522                            == SYSTEM_UI_FLAG_LOW_PROFILE) {
27523                        timeout = ViewConfiguration.getHoverTooltipHideShortTimeout();
27524                    } else {
27525                        timeout = ViewConfiguration.getHoverTooltipHideTimeout();
27526                    }
27527                    removeCallbacks(mTooltipInfo.mHideTooltipRunnable);
27528                    postDelayed(mTooltipInfo.mHideTooltipRunnable, timeout);
27529                }
27530                return true;
27531
27532            case MotionEvent.ACTION_HOVER_EXIT:
27533                mTooltipInfo.clearAnchorPos();
27534                if (!mTooltipInfo.mTooltipFromLongClick) {
27535                    hideTooltip();
27536                }
27537                break;
27538        }
27539        return false;
27540    }
27541
27542    void handleTooltipKey(KeyEvent event) {
27543        switch (event.getAction()) {
27544            case KeyEvent.ACTION_DOWN:
27545                if (event.getRepeatCount() == 0) {
27546                    hideTooltip();
27547                }
27548                break;
27549
27550            case KeyEvent.ACTION_UP:
27551                handleTooltipUp();
27552                break;
27553        }
27554    }
27555
27556    private void handleTooltipUp() {
27557        if (mTooltipInfo == null || mTooltipInfo.mTooltipPopup == null) {
27558            return;
27559        }
27560        removeCallbacks(mTooltipInfo.mHideTooltipRunnable);
27561        postDelayed(mTooltipInfo.mHideTooltipRunnable,
27562                ViewConfiguration.getLongPressTooltipHideTimeout());
27563    }
27564
27565    private int getFocusableAttribute(TypedArray attributes) {
27566        TypedValue val = new TypedValue();
27567        if (attributes.getValue(com.android.internal.R.styleable.View_focusable, val)) {
27568            if (val.type == TypedValue.TYPE_INT_BOOLEAN) {
27569                return (val.data == 0 ? NOT_FOCUSABLE : FOCUSABLE);
27570            } else {
27571                return val.data;
27572            }
27573        } else {
27574            return FOCUSABLE_AUTO;
27575        }
27576    }
27577
27578    /**
27579     * @return The content view of the tooltip popup currently being shown, or null if the tooltip
27580     * is not showing.
27581     * @hide
27582     */
27583    @TestApi
27584    public View getTooltipView() {
27585        if (mTooltipInfo == null || mTooltipInfo.mTooltipPopup == null) {
27586            return null;
27587        }
27588        return mTooltipInfo.mTooltipPopup.getContentView();
27589    }
27590
27591    /**
27592     * @return {@code true} if the default focus highlight is enabled, {@code false} otherwies.
27593     * @hide
27594     */
27595    @TestApi
27596    public static boolean isDefaultFocusHighlightEnabled() {
27597        return sUseDefaultFocusHighlight;
27598    }
27599
27600  /**
27601     * Allows this view to handle {@link KeyEvent}s which weren't handled by normal dispatch. This
27602     * occurs after the normal view hierarchy dispatch, but before the window callback. By default,
27603     * this will dispatch into all the listeners registered via
27604     * {@link #addKeyFallbackListener(OnKeyFallbackListener)} in last-in-first-out order (most
27605     * recently added will receive events first).
27606     *
27607     * @param event A not-previously-handled event.
27608     * @return {@code true} if the event was handled, {@code false} otherwise.
27609     * @see #addKeyFallbackListener
27610     */
27611    public boolean onKeyFallback(@NonNull KeyEvent event) {
27612        if (mListenerInfo != null && mListenerInfo.mKeyFallbackListeners != null) {
27613            for (int i = mListenerInfo.mKeyFallbackListeners.size() - 1; i >= 0; --i) {
27614                if (mListenerInfo.mKeyFallbackListeners.get(i).onKeyFallback(this, event)) {
27615                    return true;
27616                }
27617            }
27618        }
27619        return false;
27620    }
27621
27622    /**
27623     * Adds a listener which will receive unhandled {@link KeyEvent}s.
27624     * @param listener the receiver of fallback {@link KeyEvent}s.
27625     * @see #onKeyFallback(KeyEvent)
27626     */
27627    public void addKeyFallbackListener(OnKeyFallbackListener listener) {
27628        ArrayList<OnKeyFallbackListener> fallbacks = getListenerInfo().mKeyFallbackListeners;
27629        if (fallbacks == null) {
27630            fallbacks = new ArrayList<>();
27631            getListenerInfo().mKeyFallbackListeners = fallbacks;
27632        }
27633        fallbacks.add(listener);
27634    }
27635
27636    /**
27637     * Removes a listener which will receive unhandled {@link KeyEvent}s.
27638     * @param listener the receiver of fallback {@link KeyEvent}s.
27639     * @see #onKeyFallback(KeyEvent)
27640     */
27641    public void removeKeyFallbackListener(OnKeyFallbackListener listener) {
27642        if (mListenerInfo != null) {
27643            if (mListenerInfo.mKeyFallbackListeners != null) {
27644                mListenerInfo.mKeyFallbackListeners.remove(listener);
27645                if (mListenerInfo.mKeyFallbackListeners.isEmpty()) {
27646                    mListenerInfo.mKeyFallbackListeners = null;
27647                }
27648            }
27649        }
27650    }
27651}
27652