View.java revision 11fa71845bead86b27600ef8712365065defece2
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_accessibilityHeading
701 * @attr ref android.R.styleable#View_alpha
702 * @attr ref android.R.styleable#View_background
703 * @attr ref android.R.styleable#View_clickable
704 * @attr ref android.R.styleable#View_contentDescription
705 * @attr ref android.R.styleable#View_drawingCacheQuality
706 * @attr ref android.R.styleable#View_duplicateParentState
707 * @attr ref android.R.styleable#View_id
708 * @attr ref android.R.styleable#View_requiresFadingEdge
709 * @attr ref android.R.styleable#View_fadeScrollbars
710 * @attr ref android.R.styleable#View_fadingEdgeLength
711 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
712 * @attr ref android.R.styleable#View_fitsSystemWindows
713 * @attr ref android.R.styleable#View_isScrollContainer
714 * @attr ref android.R.styleable#View_focusable
715 * @attr ref android.R.styleable#View_focusableInTouchMode
716 * @attr ref android.R.styleable#View_focusedByDefault
717 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
718 * @attr ref android.R.styleable#View_keepScreenOn
719 * @attr ref android.R.styleable#View_keyboardNavigationCluster
720 * @attr ref android.R.styleable#View_layerType
721 * @attr ref android.R.styleable#View_layoutDirection
722 * @attr ref android.R.styleable#View_longClickable
723 * @attr ref android.R.styleable#View_minHeight
724 * @attr ref android.R.styleable#View_minWidth
725 * @attr ref android.R.styleable#View_nextClusterForward
726 * @attr ref android.R.styleable#View_nextFocusDown
727 * @attr ref android.R.styleable#View_nextFocusLeft
728 * @attr ref android.R.styleable#View_nextFocusRight
729 * @attr ref android.R.styleable#View_nextFocusUp
730 * @attr ref android.R.styleable#View_onClick
731 * @attr ref android.R.styleable#View_outlineSpotShadowColor
732 * @attr ref android.R.styleable#View_outlineAmbientShadowColor
733 * @attr ref android.R.styleable#View_padding
734 * @attr ref android.R.styleable#View_paddingHorizontal
735 * @attr ref android.R.styleable#View_paddingVertical
736 * @attr ref android.R.styleable#View_paddingBottom
737 * @attr ref android.R.styleable#View_paddingLeft
738 * @attr ref android.R.styleable#View_paddingRight
739 * @attr ref android.R.styleable#View_paddingTop
740 * @attr ref android.R.styleable#View_paddingStart
741 * @attr ref android.R.styleable#View_paddingEnd
742 * @attr ref android.R.styleable#View_saveEnabled
743 * @attr ref android.R.styleable#View_rotation
744 * @attr ref android.R.styleable#View_rotationX
745 * @attr ref android.R.styleable#View_rotationY
746 * @attr ref android.R.styleable#View_scaleX
747 * @attr ref android.R.styleable#View_scaleY
748 * @attr ref android.R.styleable#View_scrollX
749 * @attr ref android.R.styleable#View_scrollY
750 * @attr ref android.R.styleable#View_scrollbarSize
751 * @attr ref android.R.styleable#View_scrollbarStyle
752 * @attr ref android.R.styleable#View_scrollbars
753 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
754 * @attr ref android.R.styleable#View_scrollbarFadeDuration
755 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
756 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
757 * @attr ref android.R.styleable#View_scrollbarThumbVertical
758 * @attr ref android.R.styleable#View_scrollbarTrackVertical
759 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
760 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
761 * @attr ref android.R.styleable#View_stateListAnimator
762 * @attr ref android.R.styleable#View_transitionName
763 * @attr ref android.R.styleable#View_soundEffectsEnabled
764 * @attr ref android.R.styleable#View_tag
765 * @attr ref android.R.styleable#View_textAlignment
766 * @attr ref android.R.styleable#View_textDirection
767 * @attr ref android.R.styleable#View_transformPivotX
768 * @attr ref android.R.styleable#View_transformPivotY
769 * @attr ref android.R.styleable#View_translationX
770 * @attr ref android.R.styleable#View_translationY
771 * @attr ref android.R.styleable#View_translationZ
772 * @attr ref android.R.styleable#View_visibility
773 * @attr ref android.R.styleable#View_theme
774 *
775 * @see android.view.ViewGroup
776 */
777@UiThread
778public class View implements Drawable.Callback, KeyEvent.Callback,
779        AccessibilityEventSource {
780    private static final boolean DBG = false;
781
782    /** @hide */
783    public static boolean DEBUG_DRAW = false;
784
785    /**
786     * The logging tag used by this class with android.util.Log.
787     */
788    protected static final String VIEW_LOG_TAG = "View";
789
790    /**
791     * When set to true, apps will draw debugging information about their layouts.
792     *
793     * @hide
794     */
795    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
796
797    /**
798     * When set to true, this view will save its attribute data.
799     *
800     * @hide
801     */
802    public static boolean mDebugViewAttributes = false;
803
804    /**
805     * Used to mark a View that has no ID.
806     */
807    public static final int NO_ID = -1;
808
809    /**
810     * Last ID that is given to Views that are no part of activities.
811     *
812     * {@hide}
813     */
814    public static final int LAST_APP_AUTOFILL_ID = Integer.MAX_VALUE / 2;
815
816    /**
817     * Attribute to find the autofilled highlight
818     *
819     * @see #getAutofilledDrawable()
820     */
821    private static final int[] AUTOFILL_HIGHLIGHT_ATTR =
822            new int[]{android.R.attr.autofilledHighlight};
823
824    /**
825     * Signals that compatibility booleans have been initialized according to
826     * target SDK versions.
827     */
828    private static boolean sCompatibilityDone = false;
829
830    /**
831     * Use the old (broken) way of building MeasureSpecs.
832     */
833    private static boolean sUseBrokenMakeMeasureSpec = false;
834
835    /**
836     * Always return a size of 0 for MeasureSpec values with a mode of UNSPECIFIED
837     */
838    static boolean sUseZeroUnspecifiedMeasureSpec = false;
839
840    /**
841     * Ignore any optimizations using the measure cache.
842     */
843    private static boolean sIgnoreMeasureCache = false;
844
845    /**
846     * Ignore an optimization that skips unnecessary EXACTLY layout passes.
847     */
848    private static boolean sAlwaysRemeasureExactly = false;
849
850    /**
851     * Relax constraints around whether setLayoutParams() must be called after
852     * modifying the layout params.
853     */
854    private static boolean sLayoutParamsAlwaysChanged = false;
855
856    /**
857     * Allow setForeground/setBackground to be called (and ignored) on a textureview,
858     * without throwing
859     */
860    static boolean sTextureViewIgnoresDrawableSetters = false;
861
862    /**
863     * Prior to N, some ViewGroups would not convert LayoutParams properly even though both extend
864     * MarginLayoutParams. For instance, converting LinearLayout.LayoutParams to
865     * RelativeLayout.LayoutParams would lose margin information. This is fixed on N but target API
866     * check is implemented for backwards compatibility.
867     *
868     * {@hide}
869     */
870    protected static boolean sPreserveMarginParamsInLayoutParamConversion;
871
872    /**
873     * Prior to N, when drag enters into child of a view that has already received an
874     * ACTION_DRAG_ENTERED event, the parent doesn't get a ACTION_DRAG_EXITED event.
875     * ACTION_DRAG_LOCATION and ACTION_DROP were delivered to the parent of a view that returned
876     * false from its event handler for these events.
877     * Starting from N, the parent will get ACTION_DRAG_EXITED event before the child gets its
878     * ACTION_DRAG_ENTERED. ACTION_DRAG_LOCATION and ACTION_DROP are never propagated to the parent.
879     * sCascadedDragDrop is true for pre-N apps for backwards compatibility implementation.
880     */
881    static boolean sCascadedDragDrop;
882
883    /**
884     * Prior to O, auto-focusable didn't exist and widgets such as ListView use hasFocusable
885     * to determine things like whether or not to permit item click events. We can't break
886     * apps that do this just because more things (clickable things) are now auto-focusable
887     * and they would get different results, so give old behavior to old apps.
888     */
889    static boolean sHasFocusableExcludeAutoFocusable;
890
891    /**
892     * Prior to O, auto-focusable didn't exist and views marked as clickable weren't implicitly
893     * made focusable by default. As a result, apps could (incorrectly) change the clickable
894     * setting of views off the UI thread. Now that clickable can effect the focusable state,
895     * changing the clickable attribute off the UI thread will cause an exception (since changing
896     * the focusable state checks). In order to prevent apps from crashing, we will handle this
897     * specific case and just not notify parents on new focusables resulting from marking views
898     * clickable from outside the UI thread.
899     */
900    private static boolean sAutoFocusableOffUIThreadWontNotifyParents;
901
902    /**
903     * Prior to P things like setScaleX() allowed passing float values that were bogus such as
904     * Float.NaN. If the app is targetting P or later then passing these values will result in an
905     * exception being thrown. If the app is targetting an earlier SDK version, then we will
906     * silently clamp these values to avoid crashes elsewhere when the rendering code hits
907     * these bogus values.
908     */
909    private static boolean sThrowOnInvalidFloatProperties;
910
911    /**
912     * Prior to P, {@code #startDragAndDrop} accepts a builder which produces an empty drag shadow.
913     * Currently zero size SurfaceControl cannot be created thus we create a dummy 1x1 surface
914     * instead.
915     */
916    private static boolean sAcceptZeroSizeDragShadow;
917
918    /** @hide */
919    @IntDef({NOT_FOCUSABLE, FOCUSABLE, FOCUSABLE_AUTO})
920    @Retention(RetentionPolicy.SOURCE)
921    public @interface Focusable {}
922
923    /**
924     * This view does not want keystrokes.
925     * <p>
926     * Use with {@link #setFocusable(int)} and <a href="#attr_android:focusable">{@code
927     * android:focusable}.
928     */
929    public static final int NOT_FOCUSABLE = 0x00000000;
930
931    /**
932     * This view wants keystrokes.
933     * <p>
934     * Use with {@link #setFocusable(int)} and <a href="#attr_android:focusable">{@code
935     * android:focusable}.
936     */
937    public static final int FOCUSABLE = 0x00000001;
938
939    /**
940     * This view determines focusability automatically. This is the default.
941     * <p>
942     * Use with {@link #setFocusable(int)} and <a href="#attr_android:focusable">{@code
943     * android:focusable}.
944     */
945    public static final int FOCUSABLE_AUTO = 0x00000010;
946
947    /**
948     * Mask for use with setFlags indicating bits used for focus.
949     */
950    private static final int FOCUSABLE_MASK = 0x00000011;
951
952    /**
953     * This view will adjust its padding to fit sytem windows (e.g. status bar)
954     */
955    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
956
957    /** @hide */
958    @IntDef({VISIBLE, INVISIBLE, GONE})
959    @Retention(RetentionPolicy.SOURCE)
960    public @interface Visibility {}
961
962    /**
963     * This view is visible.
964     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
965     * android:visibility}.
966     */
967    public static final int VISIBLE = 0x00000000;
968
969    /**
970     * This view is invisible, but it still takes up space for layout purposes.
971     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
972     * android:visibility}.
973     */
974    public static final int INVISIBLE = 0x00000004;
975
976    /**
977     * This view is invisible, and it doesn't take any space for layout
978     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
979     * android:visibility}.
980     */
981    public static final int GONE = 0x00000008;
982
983    /**
984     * Mask for use with setFlags indicating bits used for visibility.
985     * {@hide}
986     */
987    static final int VISIBILITY_MASK = 0x0000000C;
988
989    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
990
991    /**
992     * Hint indicating that this view can be autofilled with an email address.
993     *
994     * <p>Can be used with either {@link #setAutofillHints(String[])} or
995     * <a href="#attr_android:autofillHint"> {@code android:autofillHint}</a> (in which case the
996     * value should be <code>{@value #AUTOFILL_HINT_EMAIL_ADDRESS}</code>).
997     *
998     * <p>See {@link #setAutofillHints(String...)} for more info about autofill hints.
999     */
1000    public static final String AUTOFILL_HINT_EMAIL_ADDRESS = "emailAddress";
1001
1002    /**
1003     * Hint indicating that this view can be autofilled with a user's real name.
1004     *
1005     * <p>Can be used with either {@link #setAutofillHints(String[])} or
1006     * <a href="#attr_android:autofillHint"> {@code android:autofillHint}</a> (in which case the
1007     * value should be <code>{@value #AUTOFILL_HINT_NAME}</code>).
1008     *
1009     * <p>See {@link #setAutofillHints(String...)} for more info about autofill hints.
1010     */
1011    public static final String AUTOFILL_HINT_NAME = "name";
1012
1013    /**
1014     * Hint indicating that this view can be autofilled with a username.
1015     *
1016     * <p>Can be used with either {@link #setAutofillHints(String[])} or
1017     * <a href="#attr_android:autofillHint"> {@code android:autofillHint}</a> (in which case the
1018     * value should be <code>{@value #AUTOFILL_HINT_USERNAME}</code>).
1019     *
1020     * <p>See {@link #setAutofillHints(String...)} for more info about autofill hints.
1021     */
1022    public static final String AUTOFILL_HINT_USERNAME = "username";
1023
1024    /**
1025     * Hint indicating that this view can be autofilled with a password.
1026     *
1027     * <p>Can be used with either {@link #setAutofillHints(String[])} or
1028     * <a href="#attr_android:autofillHint"> {@code android:autofillHint}</a> (in which case the
1029     * value should be <code>{@value #AUTOFILL_HINT_PASSWORD}</code>).
1030     *
1031     * <p>See {@link #setAutofillHints(String...)} for more info about autofill hints.
1032     */
1033    public static final String AUTOFILL_HINT_PASSWORD = "password";
1034
1035    /**
1036     * Hint indicating that this view can be autofilled with a phone number.
1037     *
1038     * <p>Can be used with either {@link #setAutofillHints(String[])} or
1039     * <a href="#attr_android:autofillHint"> {@code android:autofillHint}</a> (in which case the
1040     * value should be <code>{@value #AUTOFILL_HINT_PHONE}</code>).
1041     *
1042     * <p>See {@link #setAutofillHints(String...)} for more info about autofill hints.
1043     */
1044    public static final String AUTOFILL_HINT_PHONE = "phone";
1045
1046    /**
1047     * Hint indicating that this view can be autofilled with a postal address.
1048     *
1049     * <p>Can be used with either {@link #setAutofillHints(String[])} or
1050     * <a href="#attr_android:autofillHint"> {@code android:autofillHint}</a> (in which case the
1051     * value should be <code>{@value #AUTOFILL_HINT_POSTAL_ADDRESS}</code>).
1052     *
1053     * <p>See {@link #setAutofillHints(String...)} for more info about autofill hints.
1054     */
1055    public static final String AUTOFILL_HINT_POSTAL_ADDRESS = "postalAddress";
1056
1057    /**
1058     * Hint indicating that this view can be autofilled with a postal code.
1059     *
1060     * <p>Can be used with either {@link #setAutofillHints(String[])} or
1061     * <a href="#attr_android:autofillHint"> {@code android:autofillHint}</a> (in which case the
1062     * value should be <code>{@value #AUTOFILL_HINT_POSTAL_CODE}</code>).
1063     *
1064     * <p>See {@link #setAutofillHints(String...)} for more info about autofill hints.
1065     */
1066    public static final String AUTOFILL_HINT_POSTAL_CODE = "postalCode";
1067
1068    /**
1069     * Hint indicating that this view can be autofilled with a credit card number.
1070     *
1071     * <p>Can be used with either {@link #setAutofillHints(String[])} or
1072     * <a href="#attr_android:autofillHint"> {@code android:autofillHint}</a> (in which case the
1073     * value should be <code>{@value #AUTOFILL_HINT_CREDIT_CARD_NUMBER}</code>).
1074     *
1075     * <p>See {@link #setAutofillHints(String...)} for more info about autofill hints.
1076     */
1077    public static final String AUTOFILL_HINT_CREDIT_CARD_NUMBER = "creditCardNumber";
1078
1079    /**
1080     * Hint indicating that this view can be autofilled with a credit card security code.
1081     *
1082     * <p>Can be used with either {@link #setAutofillHints(String[])} or
1083     * <a href="#attr_android:autofillHint"> {@code android:autofillHint}</a> (in which case the
1084     * value should be <code>{@value #AUTOFILL_HINT_CREDIT_CARD_SECURITY_CODE}</code>).
1085     *
1086     * <p>See {@link #setAutofillHints(String...)} for more info about autofill hints.
1087     */
1088    public static final String AUTOFILL_HINT_CREDIT_CARD_SECURITY_CODE = "creditCardSecurityCode";
1089
1090    /**
1091     * Hint indicating that this view can be autofilled with a credit card expiration date.
1092     *
1093     * <p>It should be used when the credit card expiration date is represented by just one view;
1094     * if it is represented by more than one (for example, one view for the month and another view
1095     * for the year), then each of these views should use the hint specific for the unit
1096     * ({@link #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DAY},
1097     * {@link #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_MONTH},
1098     * or {@link #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_YEAR}).
1099     *
1100     * <p>Can be used with either {@link #setAutofillHints(String[])} or
1101     * <a href="#attr_android:autofillHint"> {@code android:autofillHint}</a> (in which case the
1102     * value should be <code>{@value #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DATE}</code>).
1103     *
1104     * <p>When annotating a view with this hint, it's recommended to use a date autofill value to
1105     * avoid ambiguity when the autofill service provides a value for it. To understand why a
1106     * value can be ambiguous, consider "April of 2020", which could be represented as either of
1107     * the following options:
1108     *
1109     * <ul>
1110     *   <li>{@code "04/2020"}
1111     *   <li>{@code "4/2020"}
1112     *   <li>{@code "2020/04"}
1113     *   <li>{@code "2020/4"}
1114     *   <li>{@code "April/2020"}
1115     *   <li>{@code "Apr/2020"}
1116     * </ul>
1117     *
1118     * <p>You define a date autofill value for the view by overriding the following methods:
1119     *
1120     * <ol>
1121     *   <li>{@link #getAutofillType()} to return {@link #AUTOFILL_TYPE_DATE}.
1122     *   <li>{@link #getAutofillValue()} to return a
1123     *       {@link AutofillValue#forDate(long) date autofillvalue}.
1124     *   <li>{@link #autofill(AutofillValue)} to expect a data autofillvalue.
1125     * </ol>
1126     *
1127     * <p>See {@link #setAutofillHints(String...)} for more info about autofill hints.
1128     */
1129    public static final String AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DATE =
1130            "creditCardExpirationDate";
1131
1132    /**
1133     * Hint indicating that this view can be autofilled with a credit card expiration month.
1134     *
1135     * <p>Can be used with either {@link #setAutofillHints(String[])} or
1136     * <a href="#attr_android:autofillHint"> {@code android:autofillHint}</a> (in which case the
1137     * value should be <code>{@value #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_MONTH}</code>).
1138     *
1139     * <p>When annotating a view with this hint, it's recommended to use a text autofill value
1140     * whose value is the numerical representation of the month, starting on {@code 1} to avoid
1141     * ambiguity when the autofill service provides a value for it. To understand why a
1142     * value can be ambiguous, consider "January", which could be represented as either of
1143     *
1144     * <ul>
1145     *   <li>{@code "1"}: recommended way.
1146     *   <li>{@code "0"}: if following the {@link Calendar#MONTH} convention.
1147     *   <li>{@code "January"}: full name, in English.
1148     *   <li>{@code "jan"}: abbreviated name, in English.
1149     *   <li>{@code "Janeiro"}: full name, in another language.
1150     * </ul>
1151     *
1152     * <p>Another recommended approach is to use a date autofill value - see
1153     * {@link #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DATE} for more details.
1154     *
1155     * <p>See {@link #setAutofillHints(String...)} for more info about autofill hints.
1156     */
1157    public static final String AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_MONTH =
1158            "creditCardExpirationMonth";
1159
1160    /**
1161     * Hint indicating that this view can be autofilled with a credit card expiration year.
1162     *
1163     * <p>Can be used with either {@link #setAutofillHints(String[])} or
1164     * <a href="#attr_android:autofillHint"> {@code android:autofillHint}</a> (in which case the
1165     * value should be <code>{@value #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_YEAR}</code>).
1166     *
1167     * <p>See {@link #setAutofillHints(String...)} for more info about autofill hints.
1168     */
1169    public static final String AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_YEAR =
1170            "creditCardExpirationYear";
1171
1172    /**
1173     * Hint indicating that this view can be autofilled with a credit card expiration day.
1174     *
1175     * <p>Can be used with either {@link #setAutofillHints(String[])} or
1176     * <a href="#attr_android:autofillHint"> {@code android:autofillHint}</a> (in which case the
1177     * value should be <code>{@value #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DAY}</code>).
1178     *
1179     * <p>See {@link #setAutofillHints(String...)} for more info about autofill hints.
1180     */
1181    public static final String AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DAY = "creditCardExpirationDay";
1182
1183    /**
1184     * Hints for the autofill services that describes the content of the view.
1185     */
1186    private @Nullable String[] mAutofillHints;
1187
1188    /**
1189     * Autofill id, lazily created on calls to {@link #getAutofillId()}.
1190     */
1191    private AutofillId mAutofillId;
1192
1193    /** @hide */
1194    @IntDef(prefix = { "AUTOFILL_TYPE_" }, value = {
1195            AUTOFILL_TYPE_NONE,
1196            AUTOFILL_TYPE_TEXT,
1197            AUTOFILL_TYPE_TOGGLE,
1198            AUTOFILL_TYPE_LIST,
1199            AUTOFILL_TYPE_DATE
1200    })
1201    @Retention(RetentionPolicy.SOURCE)
1202    public @interface AutofillType {}
1203
1204    /**
1205     * Autofill type for views that cannot be autofilled.
1206     *
1207     * <p>Typically used when the view is read-only; for example, a text label.
1208     *
1209     * @see #getAutofillType()
1210     */
1211    public static final int AUTOFILL_TYPE_NONE = 0;
1212
1213    /**
1214     * Autofill type for a text field, which is filled by a {@link CharSequence}.
1215     *
1216     * <p>{@link AutofillValue} instances for autofilling a {@link View} can be obtained through
1217     * {@link AutofillValue#forText(CharSequence)}, and the value passed to autofill a
1218     * {@link View} can be fetched through {@link AutofillValue#getTextValue()}.
1219     *
1220     * @see #getAutofillType()
1221     */
1222    public static final int AUTOFILL_TYPE_TEXT = 1;
1223
1224    /**
1225     * Autofill type for a togglable field, which is filled by a {@code boolean}.
1226     *
1227     * <p>{@link AutofillValue} instances for autofilling a {@link View} can be obtained through
1228     * {@link AutofillValue#forToggle(boolean)}, and the value passed to autofill a
1229     * {@link View} can be fetched through {@link AutofillValue#getToggleValue()}.
1230     *
1231     * @see #getAutofillType()
1232     */
1233    public static final int AUTOFILL_TYPE_TOGGLE = 2;
1234
1235    /**
1236     * Autofill type for a selection list field, which is filled by an {@code int}
1237     * representing the element index inside the list (starting at {@code 0}).
1238     *
1239     * <p>{@link AutofillValue} instances for autofilling a {@link View} can be obtained through
1240     * {@link AutofillValue#forList(int)}, and the value passed to autofill a
1241     * {@link View} can be fetched through {@link AutofillValue#getListValue()}.
1242     *
1243     * <p>The available options in the selection list are typically provided by
1244     * {@link android.app.assist.AssistStructure.ViewNode#getAutofillOptions()}.
1245     *
1246     * @see #getAutofillType()
1247     */
1248    public static final int AUTOFILL_TYPE_LIST = 3;
1249
1250
1251    /**
1252     * Autofill type for a field that contains a date, which is represented by a long representing
1253     * the number of milliseconds since the standard base time known as "the epoch", namely
1254     * January 1, 1970, 00:00:00 GMT (see {@link java.util.Date#getTime()}.
1255     *
1256     * <p>{@link AutofillValue} instances for autofilling a {@link View} can be obtained through
1257     * {@link AutofillValue#forDate(long)}, and the values passed to
1258     * autofill a {@link View} can be fetched through {@link AutofillValue#getDateValue()}.
1259     *
1260     * @see #getAutofillType()
1261     */
1262    public static final int AUTOFILL_TYPE_DATE = 4;
1263
1264    /** @hide */
1265    @IntDef(prefix = { "IMPORTANT_FOR_AUTOFILL_" }, value = {
1266            IMPORTANT_FOR_AUTOFILL_AUTO,
1267            IMPORTANT_FOR_AUTOFILL_YES,
1268            IMPORTANT_FOR_AUTOFILL_NO,
1269            IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS,
1270            IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS
1271    })
1272    @Retention(RetentionPolicy.SOURCE)
1273    public @interface AutofillImportance {}
1274
1275    /**
1276     * Automatically determine whether a view is important for autofill.
1277     *
1278     * @see #isImportantForAutofill()
1279     * @see #setImportantForAutofill(int)
1280     */
1281    public static final int IMPORTANT_FOR_AUTOFILL_AUTO = 0x0;
1282
1283    /**
1284     * The view is important for autofill, and its children (if any) will be traversed.
1285     *
1286     * @see #isImportantForAutofill()
1287     * @see #setImportantForAutofill(int)
1288     */
1289    public static final int IMPORTANT_FOR_AUTOFILL_YES = 0x1;
1290
1291    /**
1292     * The view is not important for autofill, but its children (if any) will be traversed.
1293     *
1294     * @see #isImportantForAutofill()
1295     * @see #setImportantForAutofill(int)
1296     */
1297    public static final int IMPORTANT_FOR_AUTOFILL_NO = 0x2;
1298
1299    /**
1300     * The view is important for autofill, but its children (if any) will not be traversed.
1301     *
1302     * @see #isImportantForAutofill()
1303     * @see #setImportantForAutofill(int)
1304     */
1305    public static final int IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS = 0x4;
1306
1307    /**
1308     * The view is not important for autofill, and its children (if any) will not be traversed.
1309     *
1310     * @see #isImportantForAutofill()
1311     * @see #setImportantForAutofill(int)
1312     */
1313    public static final int IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS = 0x8;
1314
1315    /** @hide */
1316    @IntDef(flag = true, prefix = { "AUTOFILL_FLAG_" }, value = {
1317            AUTOFILL_FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
1318    })
1319    @Retention(RetentionPolicy.SOURCE)
1320    public @interface AutofillFlags {}
1321
1322    /**
1323     * Flag requesting you to add views that are marked as not important for autofill
1324     * (see {@link #setImportantForAutofill(int)}) to a {@link ViewStructure}.
1325     */
1326    public static final int AUTOFILL_FLAG_INCLUDE_NOT_IMPORTANT_VIEWS = 0x1;
1327
1328    /**
1329     * This view is enabled. Interpretation varies by subclass.
1330     * Use with ENABLED_MASK when calling setFlags.
1331     * {@hide}
1332     */
1333    static final int ENABLED = 0x00000000;
1334
1335    /**
1336     * This view is disabled. Interpretation varies by subclass.
1337     * Use with ENABLED_MASK when calling setFlags.
1338     * {@hide}
1339     */
1340    static final int DISABLED = 0x00000020;
1341
1342   /**
1343    * Mask for use with setFlags indicating bits used for indicating whether
1344    * this view is enabled
1345    * {@hide}
1346    */
1347    static final int ENABLED_MASK = 0x00000020;
1348
1349    /**
1350     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
1351     * called and further optimizations will be performed. It is okay to have
1352     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
1353     * {@hide}
1354     */
1355    static final int WILL_NOT_DRAW = 0x00000080;
1356
1357    /**
1358     * Mask for use with setFlags indicating bits used for indicating whether
1359     * this view is will draw
1360     * {@hide}
1361     */
1362    static final int DRAW_MASK = 0x00000080;
1363
1364    /**
1365     * <p>This view doesn't show scrollbars.</p>
1366     * {@hide}
1367     */
1368    static final int SCROLLBARS_NONE = 0x00000000;
1369
1370    /**
1371     * <p>This view shows horizontal scrollbars.</p>
1372     * {@hide}
1373     */
1374    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
1375
1376    /**
1377     * <p>This view shows vertical scrollbars.</p>
1378     * {@hide}
1379     */
1380    static final int SCROLLBARS_VERTICAL = 0x00000200;
1381
1382    /**
1383     * <p>Mask for use with setFlags indicating bits used for indicating which
1384     * scrollbars are enabled.</p>
1385     * {@hide}
1386     */
1387    static final int SCROLLBARS_MASK = 0x00000300;
1388
1389    /**
1390     * Indicates that the view should filter touches when its window is obscured.
1391     * Refer to the class comments for more information about this security feature.
1392     * {@hide}
1393     */
1394    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
1395
1396    /**
1397     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
1398     * that they are optional and should be skipped if the window has
1399     * requested system UI flags that ignore those insets for layout.
1400     */
1401    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
1402
1403    /**
1404     * <p>This view doesn't show fading edges.</p>
1405     * {@hide}
1406     */
1407    static final int FADING_EDGE_NONE = 0x00000000;
1408
1409    /**
1410     * <p>This view shows horizontal fading edges.</p>
1411     * {@hide}
1412     */
1413    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
1414
1415    /**
1416     * <p>This view shows vertical fading edges.</p>
1417     * {@hide}
1418     */
1419    static final int FADING_EDGE_VERTICAL = 0x00002000;
1420
1421    /**
1422     * <p>Mask for use with setFlags indicating bits used for indicating which
1423     * fading edges are enabled.</p>
1424     * {@hide}
1425     */
1426    static final int FADING_EDGE_MASK = 0x00003000;
1427
1428    /**
1429     * <p>Indicates this view can be clicked. When clickable, a View reacts
1430     * to clicks by notifying the OnClickListener.<p>
1431     * {@hide}
1432     */
1433    static final int CLICKABLE = 0x00004000;
1434
1435    /**
1436     * <p>Indicates this view is caching its drawing into a bitmap.</p>
1437     * {@hide}
1438     */
1439    static final int DRAWING_CACHE_ENABLED = 0x00008000;
1440
1441    /**
1442     * <p>Indicates that no icicle should be saved for this view.<p>
1443     * {@hide}
1444     */
1445    static final int SAVE_DISABLED = 0x000010000;
1446
1447    /**
1448     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
1449     * property.</p>
1450     * {@hide}
1451     */
1452    static final int SAVE_DISABLED_MASK = 0x000010000;
1453
1454    /**
1455     * <p>Indicates that no drawing cache should ever be created for this view.<p>
1456     * {@hide}
1457     */
1458    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
1459
1460    /**
1461     * <p>Indicates this view can take / keep focus when int touch mode.</p>
1462     * {@hide}
1463     */
1464    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
1465
1466    /** @hide */
1467    @Retention(RetentionPolicy.SOURCE)
1468    @IntDef(prefix = { "DRAWING_CACHE_QUALITY_" }, value = {
1469            DRAWING_CACHE_QUALITY_LOW,
1470            DRAWING_CACHE_QUALITY_HIGH,
1471            DRAWING_CACHE_QUALITY_AUTO
1472    })
1473    public @interface DrawingCacheQuality {}
1474
1475    /**
1476     * <p>Enables low quality mode for the drawing cache.</p>
1477     *
1478     * @deprecated The view drawing cache was largely made obsolete with the introduction of
1479     * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
1480     * layers are largely unnecessary and can easily result in a net loss in performance due to the
1481     * cost of creating and updating the layer. In the rare cases where caching layers are useful,
1482     * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
1483     * rendering. For software-rendered snapshots of a small part of the View hierarchy or
1484     * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
1485     * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
1486     * software-rendered usages are discouraged and have compatibility issues with hardware-only
1487     * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
1488     * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
1489     * reports or unit testing the {@link PixelCopy} API is recommended.
1490     */
1491    @Deprecated
1492    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
1493
1494    /**
1495     * <p>Enables high quality mode for the drawing cache.</p>
1496     *
1497     * @deprecated The view drawing cache was largely made obsolete with the introduction of
1498     * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
1499     * layers are largely unnecessary and can easily result in a net loss in performance due to the
1500     * cost of creating and updating the layer. In the rare cases where caching layers are useful,
1501     * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
1502     * rendering. For software-rendered snapshots of a small part of the View hierarchy or
1503     * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
1504     * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
1505     * software-rendered usages are discouraged and have compatibility issues with hardware-only
1506     * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
1507     * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
1508     * reports or unit testing the {@link PixelCopy} API is recommended.
1509     */
1510    @Deprecated
1511    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
1512
1513    /**
1514     * <p>Enables automatic quality mode for the drawing cache.</p>
1515     *
1516     * @deprecated The view drawing cache was largely made obsolete with the introduction of
1517     * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
1518     * layers are largely unnecessary and can easily result in a net loss in performance due to the
1519     * cost of creating and updating the layer. In the rare cases where caching layers are useful,
1520     * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
1521     * rendering. For software-rendered snapshots of a small part of the View hierarchy or
1522     * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
1523     * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
1524     * software-rendered usages are discouraged and have compatibility issues with hardware-only
1525     * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
1526     * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
1527     * reports or unit testing the {@link PixelCopy} API is recommended.
1528     */
1529    @Deprecated
1530    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
1531
1532    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
1533            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
1534    };
1535
1536    /**
1537     * <p>Mask for use with setFlags indicating bits used for the cache
1538     * quality property.</p>
1539     * {@hide}
1540     */
1541    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
1542
1543    /**
1544     * <p>
1545     * Indicates this view can be long clicked. When long clickable, a View
1546     * reacts to long clicks by notifying the OnLongClickListener or showing a
1547     * context menu.
1548     * </p>
1549     * {@hide}
1550     */
1551    static final int LONG_CLICKABLE = 0x00200000;
1552
1553    /**
1554     * <p>Indicates that this view gets its drawable states from its direct parent
1555     * and ignores its original internal states.</p>
1556     *
1557     * @hide
1558     */
1559    static final int DUPLICATE_PARENT_STATE = 0x00400000;
1560
1561    /**
1562     * <p>
1563     * Indicates this view can be context clicked. When context clickable, a View reacts to a
1564     * context click (e.g. a primary stylus button press or right mouse click) by notifying the
1565     * OnContextClickListener.
1566     * </p>
1567     * {@hide}
1568     */
1569    static final int CONTEXT_CLICKABLE = 0x00800000;
1570
1571    /** @hide */
1572    @IntDef(prefix = { "SCROLLBARS_" }, value = {
1573            SCROLLBARS_INSIDE_OVERLAY,
1574            SCROLLBARS_INSIDE_INSET,
1575            SCROLLBARS_OUTSIDE_OVERLAY,
1576            SCROLLBARS_OUTSIDE_INSET
1577    })
1578    @Retention(RetentionPolicy.SOURCE)
1579    public @interface ScrollBarStyle {}
1580
1581    /**
1582     * The scrollbar style to display the scrollbars inside the content area,
1583     * without increasing the padding. The scrollbars will be overlaid with
1584     * translucency on the view's content.
1585     */
1586    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
1587
1588    /**
1589     * The scrollbar style to display the scrollbars inside the padded area,
1590     * increasing the padding of the view. The scrollbars will not overlap the
1591     * content area of the view.
1592     */
1593    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
1594
1595    /**
1596     * The scrollbar style to display the scrollbars at the edge of the view,
1597     * without increasing the padding. The scrollbars will be overlaid with
1598     * translucency.
1599     */
1600    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
1601
1602    /**
1603     * The scrollbar style to display the scrollbars at the edge of the view,
1604     * increasing the padding of the view. The scrollbars will only overlap the
1605     * background, if any.
1606     */
1607    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
1608
1609    /**
1610     * Mask to check if the scrollbar style is overlay or inset.
1611     * {@hide}
1612     */
1613    static final int SCROLLBARS_INSET_MASK = 0x01000000;
1614
1615    /**
1616     * Mask to check if the scrollbar style is inside or outside.
1617     * {@hide}
1618     */
1619    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
1620
1621    /**
1622     * Mask for scrollbar style.
1623     * {@hide}
1624     */
1625    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
1626
1627    /**
1628     * View flag indicating that the screen should remain on while the
1629     * window containing this view is visible to the user.  This effectively
1630     * takes care of automatically setting the WindowManager's
1631     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
1632     */
1633    public static final int KEEP_SCREEN_ON = 0x04000000;
1634
1635    /**
1636     * View flag indicating whether this view should have sound effects enabled
1637     * for events such as clicking and touching.
1638     */
1639    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
1640
1641    /**
1642     * View flag indicating whether this view should have haptic feedback
1643     * enabled for events such as long presses.
1644     */
1645    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
1646
1647    /**
1648     * <p>Indicates that the view hierarchy should stop saving state when
1649     * it reaches this view.  If state saving is initiated immediately at
1650     * the view, it will be allowed.
1651     * {@hide}
1652     */
1653    static final int PARENT_SAVE_DISABLED = 0x20000000;
1654
1655    /**
1656     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1657     * {@hide}
1658     */
1659    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1660
1661    private static Paint sDebugPaint;
1662
1663    /**
1664     * <p>Indicates this view can display a tooltip on hover or long press.</p>
1665     * {@hide}
1666     */
1667    static final int TOOLTIP = 0x40000000;
1668
1669    /** @hide */
1670    @IntDef(flag = true, prefix = { "FOCUSABLES_" }, value = {
1671            FOCUSABLES_ALL,
1672            FOCUSABLES_TOUCH_MODE
1673    })
1674    @Retention(RetentionPolicy.SOURCE)
1675    public @interface FocusableMode {}
1676
1677    /**
1678     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1679     * should add all focusable Views regardless if they are focusable in touch mode.
1680     */
1681    public static final int FOCUSABLES_ALL = 0x00000000;
1682
1683    /**
1684     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1685     * should add only Views focusable in touch mode.
1686     */
1687    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1688
1689    /** @hide */
1690    @IntDef(prefix = { "FOCUS_" }, value = {
1691            FOCUS_BACKWARD,
1692            FOCUS_FORWARD,
1693            FOCUS_LEFT,
1694            FOCUS_UP,
1695            FOCUS_RIGHT,
1696            FOCUS_DOWN
1697    })
1698    @Retention(RetentionPolicy.SOURCE)
1699    public @interface FocusDirection {}
1700
1701    /** @hide */
1702    @IntDef(prefix = { "FOCUS_" }, value = {
1703            FOCUS_LEFT,
1704            FOCUS_UP,
1705            FOCUS_RIGHT,
1706            FOCUS_DOWN
1707    })
1708    @Retention(RetentionPolicy.SOURCE)
1709    public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward
1710
1711    /**
1712     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1713     * item.
1714     */
1715    public static final int FOCUS_BACKWARD = 0x00000001;
1716
1717    /**
1718     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1719     * item.
1720     */
1721    public static final int FOCUS_FORWARD = 0x00000002;
1722
1723    /**
1724     * Use with {@link #focusSearch(int)}. Move focus to the left.
1725     */
1726    public static final int FOCUS_LEFT = 0x00000011;
1727
1728    /**
1729     * Use with {@link #focusSearch(int)}. Move focus up.
1730     */
1731    public static final int FOCUS_UP = 0x00000021;
1732
1733    /**
1734     * Use with {@link #focusSearch(int)}. Move focus to the right.
1735     */
1736    public static final int FOCUS_RIGHT = 0x00000042;
1737
1738    /**
1739     * Use with {@link #focusSearch(int)}. Move focus down.
1740     */
1741    public static final int FOCUS_DOWN = 0x00000082;
1742
1743    /**
1744     * Bits of {@link #getMeasuredWidthAndState()} and
1745     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1746     */
1747    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1748
1749    /**
1750     * Bits of {@link #getMeasuredWidthAndState()} and
1751     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1752     */
1753    public static final int MEASURED_STATE_MASK = 0xff000000;
1754
1755    /**
1756     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1757     * for functions that combine both width and height into a single int,
1758     * such as {@link #getMeasuredState()} and the childState argument of
1759     * {@link #resolveSizeAndState(int, int, int)}.
1760     */
1761    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1762
1763    /**
1764     * Bit of {@link #getMeasuredWidthAndState()} and
1765     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1766     * is smaller that the space the view would like to have.
1767     */
1768    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1769
1770    /**
1771     * Base View state sets
1772     */
1773    // Singles
1774    /**
1775     * Indicates the view has no states set. States are used with
1776     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1777     * view depending on its state.
1778     *
1779     * @see android.graphics.drawable.Drawable
1780     * @see #getDrawableState()
1781     */
1782    protected static final int[] EMPTY_STATE_SET;
1783    /**
1784     * Indicates the view is enabled. States are used with
1785     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1786     * view depending on its state.
1787     *
1788     * @see android.graphics.drawable.Drawable
1789     * @see #getDrawableState()
1790     */
1791    protected static final int[] ENABLED_STATE_SET;
1792    /**
1793     * Indicates the view is focused. States are used with
1794     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1795     * view depending on its state.
1796     *
1797     * @see android.graphics.drawable.Drawable
1798     * @see #getDrawableState()
1799     */
1800    protected static final int[] FOCUSED_STATE_SET;
1801    /**
1802     * Indicates the view is selected. States are used with
1803     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1804     * view depending on its state.
1805     *
1806     * @see android.graphics.drawable.Drawable
1807     * @see #getDrawableState()
1808     */
1809    protected static final int[] SELECTED_STATE_SET;
1810    /**
1811     * Indicates the view is pressed. States are used with
1812     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1813     * view depending on its state.
1814     *
1815     * @see android.graphics.drawable.Drawable
1816     * @see #getDrawableState()
1817     */
1818    protected static final int[] PRESSED_STATE_SET;
1819    /**
1820     * Indicates the view's window has focus. States are used with
1821     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1822     * view depending on its state.
1823     *
1824     * @see android.graphics.drawable.Drawable
1825     * @see #getDrawableState()
1826     */
1827    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1828    // Doubles
1829    /**
1830     * Indicates the view is enabled and has the focus.
1831     *
1832     * @see #ENABLED_STATE_SET
1833     * @see #FOCUSED_STATE_SET
1834     */
1835    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1836    /**
1837     * Indicates the view is enabled and selected.
1838     *
1839     * @see #ENABLED_STATE_SET
1840     * @see #SELECTED_STATE_SET
1841     */
1842    protected static final int[] ENABLED_SELECTED_STATE_SET;
1843    /**
1844     * Indicates the view is enabled and that its window has focus.
1845     *
1846     * @see #ENABLED_STATE_SET
1847     * @see #WINDOW_FOCUSED_STATE_SET
1848     */
1849    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1850    /**
1851     * Indicates the view is focused and selected.
1852     *
1853     * @see #FOCUSED_STATE_SET
1854     * @see #SELECTED_STATE_SET
1855     */
1856    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1857    /**
1858     * Indicates the view has the focus and that its window has the focus.
1859     *
1860     * @see #FOCUSED_STATE_SET
1861     * @see #WINDOW_FOCUSED_STATE_SET
1862     */
1863    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1864    /**
1865     * Indicates the view is selected and that its window has the focus.
1866     *
1867     * @see #SELECTED_STATE_SET
1868     * @see #WINDOW_FOCUSED_STATE_SET
1869     */
1870    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1871    // Triples
1872    /**
1873     * Indicates the view is enabled, focused and selected.
1874     *
1875     * @see #ENABLED_STATE_SET
1876     * @see #FOCUSED_STATE_SET
1877     * @see #SELECTED_STATE_SET
1878     */
1879    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1880    /**
1881     * Indicates the view is enabled, focused and its window has the focus.
1882     *
1883     * @see #ENABLED_STATE_SET
1884     * @see #FOCUSED_STATE_SET
1885     * @see #WINDOW_FOCUSED_STATE_SET
1886     */
1887    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1888    /**
1889     * Indicates the view is enabled, selected and its window has the focus.
1890     *
1891     * @see #ENABLED_STATE_SET
1892     * @see #SELECTED_STATE_SET
1893     * @see #WINDOW_FOCUSED_STATE_SET
1894     */
1895    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1896    /**
1897     * Indicates the view is focused, selected and its window has the focus.
1898     *
1899     * @see #FOCUSED_STATE_SET
1900     * @see #SELECTED_STATE_SET
1901     * @see #WINDOW_FOCUSED_STATE_SET
1902     */
1903    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1904    /**
1905     * Indicates the view is enabled, focused, selected and its window
1906     * has the focus.
1907     *
1908     * @see #ENABLED_STATE_SET
1909     * @see #FOCUSED_STATE_SET
1910     * @see #SELECTED_STATE_SET
1911     * @see #WINDOW_FOCUSED_STATE_SET
1912     */
1913    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1914    /**
1915     * Indicates the view is pressed and its window has the focus.
1916     *
1917     * @see #PRESSED_STATE_SET
1918     * @see #WINDOW_FOCUSED_STATE_SET
1919     */
1920    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1921    /**
1922     * Indicates the view is pressed and selected.
1923     *
1924     * @see #PRESSED_STATE_SET
1925     * @see #SELECTED_STATE_SET
1926     */
1927    protected static final int[] PRESSED_SELECTED_STATE_SET;
1928    /**
1929     * Indicates the view is pressed, selected and its window has the focus.
1930     *
1931     * @see #PRESSED_STATE_SET
1932     * @see #SELECTED_STATE_SET
1933     * @see #WINDOW_FOCUSED_STATE_SET
1934     */
1935    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1936    /**
1937     * Indicates the view is pressed and focused.
1938     *
1939     * @see #PRESSED_STATE_SET
1940     * @see #FOCUSED_STATE_SET
1941     */
1942    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1943    /**
1944     * Indicates the view is pressed, focused and its window has the focus.
1945     *
1946     * @see #PRESSED_STATE_SET
1947     * @see #FOCUSED_STATE_SET
1948     * @see #WINDOW_FOCUSED_STATE_SET
1949     */
1950    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1951    /**
1952     * Indicates the view is pressed, focused and selected.
1953     *
1954     * @see #PRESSED_STATE_SET
1955     * @see #SELECTED_STATE_SET
1956     * @see #FOCUSED_STATE_SET
1957     */
1958    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1959    /**
1960     * Indicates the view is pressed, focused, selected and its window has the focus.
1961     *
1962     * @see #PRESSED_STATE_SET
1963     * @see #FOCUSED_STATE_SET
1964     * @see #SELECTED_STATE_SET
1965     * @see #WINDOW_FOCUSED_STATE_SET
1966     */
1967    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1968    /**
1969     * Indicates the view is pressed and enabled.
1970     *
1971     * @see #PRESSED_STATE_SET
1972     * @see #ENABLED_STATE_SET
1973     */
1974    protected static final int[] PRESSED_ENABLED_STATE_SET;
1975    /**
1976     * Indicates the view is pressed, enabled and its window has the focus.
1977     *
1978     * @see #PRESSED_STATE_SET
1979     * @see #ENABLED_STATE_SET
1980     * @see #WINDOW_FOCUSED_STATE_SET
1981     */
1982    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1983    /**
1984     * Indicates the view is pressed, enabled and selected.
1985     *
1986     * @see #PRESSED_STATE_SET
1987     * @see #ENABLED_STATE_SET
1988     * @see #SELECTED_STATE_SET
1989     */
1990    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1991    /**
1992     * Indicates the view is pressed, enabled, selected and its window has the
1993     * focus.
1994     *
1995     * @see #PRESSED_STATE_SET
1996     * @see #ENABLED_STATE_SET
1997     * @see #SELECTED_STATE_SET
1998     * @see #WINDOW_FOCUSED_STATE_SET
1999     */
2000    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
2001    /**
2002     * Indicates the view is pressed, enabled and focused.
2003     *
2004     * @see #PRESSED_STATE_SET
2005     * @see #ENABLED_STATE_SET
2006     * @see #FOCUSED_STATE_SET
2007     */
2008    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
2009    /**
2010     * Indicates the view is pressed, enabled, focused and its window has the
2011     * focus.
2012     *
2013     * @see #PRESSED_STATE_SET
2014     * @see #ENABLED_STATE_SET
2015     * @see #FOCUSED_STATE_SET
2016     * @see #WINDOW_FOCUSED_STATE_SET
2017     */
2018    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
2019    /**
2020     * Indicates the view is pressed, enabled, focused and selected.
2021     *
2022     * @see #PRESSED_STATE_SET
2023     * @see #ENABLED_STATE_SET
2024     * @see #SELECTED_STATE_SET
2025     * @see #FOCUSED_STATE_SET
2026     */
2027    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
2028    /**
2029     * Indicates the view is pressed, enabled, focused, selected and its window
2030     * has the focus.
2031     *
2032     * @see #PRESSED_STATE_SET
2033     * @see #ENABLED_STATE_SET
2034     * @see #SELECTED_STATE_SET
2035     * @see #FOCUSED_STATE_SET
2036     * @see #WINDOW_FOCUSED_STATE_SET
2037     */
2038    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
2039
2040    static {
2041        EMPTY_STATE_SET = StateSet.get(0);
2042
2043        WINDOW_FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_WINDOW_FOCUSED);
2044
2045        SELECTED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_SELECTED);
2046        SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
2047                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED);
2048
2049        FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_FOCUSED);
2050        FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
2051                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED);
2052        FOCUSED_SELECTED_STATE_SET = StateSet.get(
2053                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED);
2054        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
2055                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
2056                        | StateSet.VIEW_STATE_FOCUSED);
2057
2058        ENABLED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_ENABLED);
2059        ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
2060                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED);
2061        ENABLED_SELECTED_STATE_SET = StateSet.get(
2062                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED);
2063        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
2064                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
2065                        | StateSet.VIEW_STATE_ENABLED);
2066        ENABLED_FOCUSED_STATE_SET = StateSet.get(
2067                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED);
2068        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
2069                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
2070                        | StateSet.VIEW_STATE_ENABLED);
2071        ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
2072                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
2073                        | StateSet.VIEW_STATE_ENABLED);
2074        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
2075                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
2076                        | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED);
2077
2078        PRESSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_PRESSED);
2079        PRESSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
2080                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_PRESSED);
2081        PRESSED_SELECTED_STATE_SET = StateSet.get(
2082                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_PRESSED);
2083        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
2084                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
2085                        | StateSet.VIEW_STATE_PRESSED);
2086        PRESSED_FOCUSED_STATE_SET = StateSet.get(
2087                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED);
2088        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
2089                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
2090                        | StateSet.VIEW_STATE_PRESSED);
2091        PRESSED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
2092                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
2093                        | StateSet.VIEW_STATE_PRESSED);
2094        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
2095                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
2096                        | StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED);
2097        PRESSED_ENABLED_STATE_SET = StateSet.get(
2098                StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
2099        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
2100                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED
2101                        | StateSet.VIEW_STATE_PRESSED);
2102        PRESSED_ENABLED_SELECTED_STATE_SET = StateSet.get(
2103                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED
2104                        | StateSet.VIEW_STATE_PRESSED);
2105        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
2106                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
2107                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
2108        PRESSED_ENABLED_FOCUSED_STATE_SET = StateSet.get(
2109                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED
2110                        | StateSet.VIEW_STATE_PRESSED);
2111        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
2112                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
2113                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
2114        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
2115                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
2116                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
2117        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
2118                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
2119                        | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED
2120                        | StateSet.VIEW_STATE_PRESSED);
2121    }
2122
2123    /**
2124     * Accessibility event types that are dispatched for text population.
2125     */
2126    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
2127            AccessibilityEvent.TYPE_VIEW_CLICKED
2128            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
2129            | AccessibilityEvent.TYPE_VIEW_SELECTED
2130            | AccessibilityEvent.TYPE_VIEW_FOCUSED
2131            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
2132            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
2133            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
2134            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
2135            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
2136            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
2137            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
2138
2139    static final int DEBUG_CORNERS_COLOR = Color.rgb(63, 127, 255);
2140
2141    static final int DEBUG_CORNERS_SIZE_DIP = 8;
2142
2143    /**
2144     * Temporary Rect currently for use in setBackground().  This will probably
2145     * be extended in the future to hold our own class with more than just
2146     * a Rect. :)
2147     */
2148    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
2149
2150    /**
2151     * Map used to store views' tags.
2152     */
2153    private SparseArray<Object> mKeyedTags;
2154
2155    /**
2156     * The next available accessibility id.
2157     */
2158    private static int sNextAccessibilityViewId;
2159
2160    /**
2161     * The animation currently associated with this view.
2162     * @hide
2163     */
2164    protected Animation mCurrentAnimation = null;
2165
2166    /**
2167     * Width as measured during measure pass.
2168     * {@hide}
2169     */
2170    @ViewDebug.ExportedProperty(category = "measurement")
2171    int mMeasuredWidth;
2172
2173    /**
2174     * Height as measured during measure pass.
2175     * {@hide}
2176     */
2177    @ViewDebug.ExportedProperty(category = "measurement")
2178    int mMeasuredHeight;
2179
2180    /**
2181     * Flag to indicate that this view was marked INVALIDATED, or had its display list
2182     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
2183     * its display list. This flag, used only when hw accelerated, allows us to clear the
2184     * flag while retaining this information until it's needed (at getDisplayList() time and
2185     * in drawChild(), when we decide to draw a view's children's display lists into our own).
2186     *
2187     * {@hide}
2188     */
2189    boolean mRecreateDisplayList = false;
2190
2191    /**
2192     * The view's identifier.
2193     * {@hide}
2194     *
2195     * @see #setId(int)
2196     * @see #getId()
2197     */
2198    @IdRes
2199    @ViewDebug.ExportedProperty(resolveId = true)
2200    int mID = NO_ID;
2201
2202    /** The ID of this view for autofill purposes.
2203     * <ul>
2204     *     <li>== {@link #NO_ID}: ID has not been assigned yet
2205     *     <li>&le; {@link #LAST_APP_AUTOFILL_ID}: View is not part of a activity. The ID is
2206     *                                                  unique in the process. This might change
2207     *                                                  over activity lifecycle events.
2208     *     <li>&gt; {@link #LAST_APP_AUTOFILL_ID}: View is part of a activity. The ID is
2209     *                                                  unique in the activity. This stays the same
2210     *                                                  over activity lifecycle events.
2211     */
2212    private int mAutofillViewId = NO_ID;
2213
2214    // ID for accessibility purposes. This ID must be unique for every window
2215    private int mAccessibilityViewId = NO_ID;
2216
2217    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
2218
2219    /**
2220     * The view's tag.
2221     * {@hide}
2222     *
2223     * @see #setTag(Object)
2224     * @see #getTag()
2225     */
2226    protected Object mTag = null;
2227
2228    // for mPrivateFlags:
2229    /** {@hide} */
2230    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
2231    /** {@hide} */
2232    static final int PFLAG_FOCUSED                     = 0x00000002;
2233    /** {@hide} */
2234    static final int PFLAG_SELECTED                    = 0x00000004;
2235    /** {@hide} */
2236    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
2237    /** {@hide} */
2238    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
2239    /** {@hide} */
2240    static final int PFLAG_DRAWN                       = 0x00000020;
2241    /**
2242     * When this flag is set, this view is running an animation on behalf of its
2243     * children and should therefore not cancel invalidate requests, even if they
2244     * lie outside of this view's bounds.
2245     *
2246     * {@hide}
2247     */
2248    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
2249    /** {@hide} */
2250    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
2251    /** {@hide} */
2252    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
2253    /** {@hide} */
2254    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
2255    /** {@hide} */
2256    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
2257    /** {@hide} */
2258    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
2259    /** {@hide} */
2260    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
2261
2262    private static final int PFLAG_PRESSED             = 0x00004000;
2263
2264    /** {@hide} */
2265    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
2266    /**
2267     * Flag used to indicate that this view should be drawn once more (and only once
2268     * more) after its animation has completed.
2269     * {@hide}
2270     */
2271    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
2272
2273    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
2274
2275    /**
2276     * Indicates that the View returned true when onSetAlpha() was called and that
2277     * the alpha must be restored.
2278     * {@hide}
2279     */
2280    static final int PFLAG_ALPHA_SET                   = 0x00040000;
2281
2282    /**
2283     * Set by {@link #setScrollContainer(boolean)}.
2284     */
2285    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
2286
2287    /**
2288     * Set by {@link #setScrollContainer(boolean)}.
2289     */
2290    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
2291
2292    /**
2293     * View flag indicating whether this view was invalidated (fully or partially.)
2294     *
2295     * @hide
2296     */
2297    static final int PFLAG_DIRTY                       = 0x00200000;
2298
2299    /**
2300     * View flag indicating whether this view was invalidated by an opaque
2301     * invalidate request.
2302     *
2303     * @hide
2304     */
2305    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
2306
2307    /**
2308     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
2309     *
2310     * @hide
2311     */
2312    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
2313
2314    /**
2315     * Indicates whether the background is opaque.
2316     *
2317     * @hide
2318     */
2319    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
2320
2321    /**
2322     * Indicates whether the scrollbars are opaque.
2323     *
2324     * @hide
2325     */
2326    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
2327
2328    /**
2329     * Indicates whether the view is opaque.
2330     *
2331     * @hide
2332     */
2333    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
2334
2335    /**
2336     * Indicates a prepressed state;
2337     * the short time between ACTION_DOWN and recognizing
2338     * a 'real' press. Prepressed is used to recognize quick taps
2339     * even when they are shorter than ViewConfiguration.getTapTimeout().
2340     *
2341     * @hide
2342     */
2343    private static final int PFLAG_PREPRESSED          = 0x02000000;
2344
2345    /**
2346     * Indicates whether the view is temporarily detached.
2347     *
2348     * @hide
2349     */
2350    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
2351
2352    /**
2353     * Indicates that we should awaken scroll bars once attached
2354     *
2355     * PLEASE NOTE: This flag is now unused as we now send onVisibilityChanged
2356     * during window attachment and it is no longer needed. Feel free to repurpose it.
2357     *
2358     * @hide
2359     */
2360    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
2361
2362    /**
2363     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
2364     * @hide
2365     */
2366    private static final int PFLAG_HOVERED             = 0x10000000;
2367
2368    /**
2369     * Flag set by {@link AutofillManager} if it needs to be notified when this view is clicked.
2370     */
2371    private static final int PFLAG_NOTIFY_AUTOFILL_MANAGER_ON_CLICK = 0x20000000;
2372
2373    /** {@hide} */
2374    static final int PFLAG_ACTIVATED                   = 0x40000000;
2375
2376    /**
2377     * Indicates that this view was specifically invalidated, not just dirtied because some
2378     * child view was invalidated. The flag is used to determine when we need to recreate
2379     * a view's display list (as opposed to just returning a reference to its existing
2380     * display list).
2381     *
2382     * @hide
2383     */
2384    static final int PFLAG_INVALIDATED                 = 0x80000000;
2385
2386    /**
2387     * Masks for mPrivateFlags2, as generated by dumpFlags():
2388     *
2389     * |-------|-------|-------|-------|
2390     *                                 1 PFLAG2_DRAG_CAN_ACCEPT
2391     *                                1  PFLAG2_DRAG_HOVERED
2392     *                              11   PFLAG2_LAYOUT_DIRECTION_MASK
2393     *                             1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
2394     *                            1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
2395     *                            11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
2396     *                           1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
2397     *                          1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
2398     *                          11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
2399     *                         1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
2400     *                         1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
2401     *                         11        PFLAG2_TEXT_DIRECTION_FLAGS[6]
2402     *                         111       PFLAG2_TEXT_DIRECTION_FLAGS[7]
2403     *                         111       PFLAG2_TEXT_DIRECTION_MASK
2404     *                        1          PFLAG2_TEXT_DIRECTION_RESOLVED
2405     *                       1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
2406     *                     111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
2407     *                    1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
2408     *                   1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
2409     *                   11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
2410     *                  1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
2411     *                  1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
2412     *                  11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
2413     *                  111              PFLAG2_TEXT_ALIGNMENT_MASK
2414     *                 1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
2415     *                1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
2416     *              111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
2417     *           111                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
2418     *         11                        PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK
2419     *       1                           PFLAG2_ACCESSIBILITY_FOCUSED
2420     *      1                            PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED
2421     *     1                             PFLAG2_VIEW_QUICK_REJECTED
2422     *    1                              PFLAG2_PADDING_RESOLVED
2423     *   1                               PFLAG2_DRAWABLE_RESOLVED
2424     *  1                                PFLAG2_HAS_TRANSIENT_STATE
2425     * |-------|-------|-------|-------|
2426     */
2427
2428    /**
2429     * Indicates that this view has reported that it can accept the current drag's content.
2430     * Cleared when the drag operation concludes.
2431     * @hide
2432     */
2433    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
2434
2435    /**
2436     * Indicates that this view is currently directly under the drag location in a
2437     * drag-and-drop operation involving content that it can accept.  Cleared when
2438     * the drag exits the view, or when the drag operation concludes.
2439     * @hide
2440     */
2441    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
2442
2443    /** @hide */
2444    @IntDef(prefix = { "LAYOUT_DIRECTION_" }, value = {
2445            LAYOUT_DIRECTION_LTR,
2446            LAYOUT_DIRECTION_RTL,
2447            LAYOUT_DIRECTION_INHERIT,
2448            LAYOUT_DIRECTION_LOCALE
2449    })
2450    @Retention(RetentionPolicy.SOURCE)
2451    // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection
2452    public @interface LayoutDir {}
2453
2454    /** @hide */
2455    @IntDef(prefix = { "LAYOUT_DIRECTION_" }, value = {
2456            LAYOUT_DIRECTION_LTR,
2457            LAYOUT_DIRECTION_RTL
2458    })
2459    @Retention(RetentionPolicy.SOURCE)
2460    public @interface ResolvedLayoutDir {}
2461
2462    /**
2463     * A flag to indicate that the layout direction of this view has not been defined yet.
2464     * @hide
2465     */
2466    public static final int LAYOUT_DIRECTION_UNDEFINED = LayoutDirection.UNDEFINED;
2467
2468    /**
2469     * Horizontal layout direction of this view is from Left to Right.
2470     * Use with {@link #setLayoutDirection}.
2471     */
2472    public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR;
2473
2474    /**
2475     * Horizontal layout direction of this view is from Right to Left.
2476     * Use with {@link #setLayoutDirection}.
2477     */
2478    public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL;
2479
2480    /**
2481     * Horizontal layout direction of this view is inherited from its parent.
2482     * Use with {@link #setLayoutDirection}.
2483     */
2484    public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT;
2485
2486    /**
2487     * Horizontal layout direction of this view is from deduced from the default language
2488     * script for the locale. Use with {@link #setLayoutDirection}.
2489     */
2490    public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE;
2491
2492    /**
2493     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2494     * @hide
2495     */
2496    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
2497
2498    /**
2499     * Mask for use with private flags indicating bits used for horizontal layout direction.
2500     * @hide
2501     */
2502    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2503
2504    /**
2505     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
2506     * right-to-left direction.
2507     * @hide
2508     */
2509    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2510
2511    /**
2512     * Indicates whether the view horizontal layout direction has been resolved.
2513     * @hide
2514     */
2515    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2516
2517    /**
2518     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
2519     * @hide
2520     */
2521    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
2522            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2523
2524    /*
2525     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
2526     * flag value.
2527     * @hide
2528     */
2529    private static final int[] LAYOUT_DIRECTION_FLAGS = {
2530            LAYOUT_DIRECTION_LTR,
2531            LAYOUT_DIRECTION_RTL,
2532            LAYOUT_DIRECTION_INHERIT,
2533            LAYOUT_DIRECTION_LOCALE
2534    };
2535
2536    /**
2537     * Default horizontal layout direction.
2538     */
2539    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
2540
2541    /**
2542     * Default horizontal layout direction.
2543     * @hide
2544     */
2545    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
2546
2547    /**
2548     * Text direction is inherited through {@link ViewGroup}
2549     */
2550    public static final int TEXT_DIRECTION_INHERIT = 0;
2551
2552    /**
2553     * Text direction is using "first strong algorithm". The first strong directional character
2554     * determines the paragraph direction. If there is no strong directional character, the
2555     * paragraph direction is the view's resolved layout direction.
2556     */
2557    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
2558
2559    /**
2560     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
2561     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
2562     * If there are neither, the paragraph direction is the view's resolved layout direction.
2563     */
2564    public static final int TEXT_DIRECTION_ANY_RTL = 2;
2565
2566    /**
2567     * Text direction is forced to LTR.
2568     */
2569    public static final int TEXT_DIRECTION_LTR = 3;
2570
2571    /**
2572     * Text direction is forced to RTL.
2573     */
2574    public static final int TEXT_DIRECTION_RTL = 4;
2575
2576    /**
2577     * Text direction is coming from the system Locale.
2578     */
2579    public static final int TEXT_DIRECTION_LOCALE = 5;
2580
2581    /**
2582     * Text direction is using "first strong algorithm". The first strong directional character
2583     * determines the paragraph direction. If there is no strong directional character, the
2584     * paragraph direction is LTR.
2585     */
2586    public static final int TEXT_DIRECTION_FIRST_STRONG_LTR = 6;
2587
2588    /**
2589     * Text direction is using "first strong algorithm". The first strong directional character
2590     * determines the paragraph direction. If there is no strong directional character, the
2591     * paragraph direction is RTL.
2592     */
2593    public static final int TEXT_DIRECTION_FIRST_STRONG_RTL = 7;
2594
2595    /**
2596     * Default text direction is inherited
2597     */
2598    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
2599
2600    /**
2601     * Default resolved text direction
2602     * @hide
2603     */
2604    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
2605
2606    /**
2607     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
2608     * @hide
2609     */
2610    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
2611
2612    /**
2613     * Mask for use with private flags indicating bits used for text direction.
2614     * @hide
2615     */
2616    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
2617            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2618
2619    /**
2620     * Array of text direction flags for mapping attribute "textDirection" to correct
2621     * flag value.
2622     * @hide
2623     */
2624    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
2625            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2626            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2627            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2628            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2629            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2630            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2631            TEXT_DIRECTION_FIRST_STRONG_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2632            TEXT_DIRECTION_FIRST_STRONG_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
2633    };
2634
2635    /**
2636     * Indicates whether the view text direction has been resolved.
2637     * @hide
2638     */
2639    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
2640            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2641
2642    /**
2643     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2644     * @hide
2645     */
2646    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
2647
2648    /**
2649     * Mask for use with private flags indicating bits used for resolved text direction.
2650     * @hide
2651     */
2652    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
2653            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2654
2655    /**
2656     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
2657     * @hide
2658     */
2659    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
2660            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2661
2662    /** @hide */
2663    @IntDef(prefix = { "TEXT_ALIGNMENT_" }, value = {
2664            TEXT_ALIGNMENT_INHERIT,
2665            TEXT_ALIGNMENT_GRAVITY,
2666            TEXT_ALIGNMENT_CENTER,
2667            TEXT_ALIGNMENT_TEXT_START,
2668            TEXT_ALIGNMENT_TEXT_END,
2669            TEXT_ALIGNMENT_VIEW_START,
2670            TEXT_ALIGNMENT_VIEW_END
2671    })
2672    @Retention(RetentionPolicy.SOURCE)
2673    public @interface TextAlignment {}
2674
2675    /**
2676     * Default text alignment. The text alignment of this View is inherited from its parent.
2677     * Use with {@link #setTextAlignment(int)}
2678     */
2679    public static final int TEXT_ALIGNMENT_INHERIT = 0;
2680
2681    /**
2682     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
2683     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
2684     *
2685     * Use with {@link #setTextAlignment(int)}
2686     */
2687    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
2688
2689    /**
2690     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2691     *
2692     * Use with {@link #setTextAlignment(int)}
2693     */
2694    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2695
2696    /**
2697     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2698     *
2699     * Use with {@link #setTextAlignment(int)}
2700     */
2701    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2702
2703    /**
2704     * Center the paragraph, e.g. ALIGN_CENTER.
2705     *
2706     * Use with {@link #setTextAlignment(int)}
2707     */
2708    public static final int TEXT_ALIGNMENT_CENTER = 4;
2709
2710    /**
2711     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2712     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2713     *
2714     * Use with {@link #setTextAlignment(int)}
2715     */
2716    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2717
2718    /**
2719     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2720     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2721     *
2722     * Use with {@link #setTextAlignment(int)}
2723     */
2724    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2725
2726    /**
2727     * Default text alignment is inherited
2728     */
2729    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2730
2731    /**
2732     * Default resolved text alignment
2733     * @hide
2734     */
2735    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2736
2737    /**
2738      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2739      * @hide
2740      */
2741    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2742
2743    /**
2744      * Mask for use with private flags indicating bits used for text alignment.
2745      * @hide
2746      */
2747    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2748
2749    /**
2750     * Array of text direction flags for mapping attribute "textAlignment" to correct
2751     * flag value.
2752     * @hide
2753     */
2754    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2755            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2756            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2757            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2758            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2759            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2760            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2761            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2762    };
2763
2764    /**
2765     * Indicates whether the view text alignment has been resolved.
2766     * @hide
2767     */
2768    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2769
2770    /**
2771     * Bit shift to get the resolved text alignment.
2772     * @hide
2773     */
2774    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2775
2776    /**
2777     * Mask for use with private flags indicating bits used for text alignment.
2778     * @hide
2779     */
2780    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2781            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2782
2783    /**
2784     * Indicates whether if the view text alignment has been resolved to gravity
2785     */
2786    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2787            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2788
2789    // Accessiblity constants for mPrivateFlags2
2790
2791    /**
2792     * Shift for the bits in {@link #mPrivateFlags2} related to the
2793     * "importantForAccessibility" attribute.
2794     */
2795    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2796
2797    /**
2798     * Automatically determine whether a view is important for accessibility.
2799     */
2800    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2801
2802    /**
2803     * The view is important for accessibility.
2804     */
2805    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2806
2807    /**
2808     * The view is not important for accessibility.
2809     */
2810    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2811
2812    /**
2813     * The view is not important for accessibility, nor are any of its
2814     * descendant views.
2815     */
2816    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004;
2817
2818    /**
2819     * The default whether the view is important for accessibility.
2820     */
2821    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2822
2823    /**
2824     * Mask for obtaining the bits which specify how to determine
2825     * whether a view is important for accessibility.
2826     */
2827    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2828        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO
2829        | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS)
2830        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2831
2832    /**
2833     * Shift for the bits in {@link #mPrivateFlags2} related to the
2834     * "accessibilityLiveRegion" attribute.
2835     */
2836    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23;
2837
2838    /**
2839     * Live region mode specifying that accessibility services should not
2840     * automatically announce changes to this view. This is the default live
2841     * region mode for most views.
2842     * <p>
2843     * Use with {@link #setAccessibilityLiveRegion(int)}.
2844     */
2845    public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000;
2846
2847    /**
2848     * Live region mode specifying that accessibility services should announce
2849     * changes to this view.
2850     * <p>
2851     * Use with {@link #setAccessibilityLiveRegion(int)}.
2852     */
2853    public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001;
2854
2855    /**
2856     * Live region mode specifying that accessibility services should interrupt
2857     * ongoing speech to immediately announce changes to this view.
2858     * <p>
2859     * Use with {@link #setAccessibilityLiveRegion(int)}.
2860     */
2861    public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002;
2862
2863    /**
2864     * The default whether the view is important for accessibility.
2865     */
2866    static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE;
2867
2868    /**
2869     * Mask for obtaining the bits which specify a view's accessibility live
2870     * region mode.
2871     */
2872    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE
2873            | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE)
2874            << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
2875
2876    /**
2877     * Flag indicating whether a view has accessibility focus.
2878     */
2879    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000;
2880
2881    /**
2882     * Flag whether the accessibility state of the subtree rooted at this view changed.
2883     */
2884    static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000;
2885
2886    /**
2887     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2888     * is used to check whether later changes to the view's transform should invalidate the
2889     * view to force the quickReject test to run again.
2890     */
2891    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2892
2893    /**
2894     * Flag indicating that start/end padding has been resolved into left/right padding
2895     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2896     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2897     * during measurement. In some special cases this is required such as when an adapter-based
2898     * view measures prospective children without attaching them to a window.
2899     */
2900    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2901
2902    /**
2903     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2904     */
2905    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2906
2907    /**
2908     * Indicates that the view is tracking some sort of transient state
2909     * that the app should not need to be aware of, but that the framework
2910     * should take special care to preserve.
2911     */
2912    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000;
2913
2914    /**
2915     * Group of bits indicating that RTL properties resolution is done.
2916     */
2917    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2918            PFLAG2_TEXT_DIRECTION_RESOLVED |
2919            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2920            PFLAG2_PADDING_RESOLVED |
2921            PFLAG2_DRAWABLE_RESOLVED;
2922
2923    // There are a couple of flags left in mPrivateFlags2
2924
2925    /* End of masks for mPrivateFlags2 */
2926
2927    /**
2928     * Masks for mPrivateFlags3, as generated by dumpFlags():
2929     *
2930     * |-------|-------|-------|-------|
2931     *                                 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM
2932     *                                1  PFLAG3_VIEW_IS_ANIMATING_ALPHA
2933     *                               1   PFLAG3_IS_LAID_OUT
2934     *                              1    PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT
2935     *                             1     PFLAG3_CALLED_SUPER
2936     *                            1      PFLAG3_APPLYING_INSETS
2937     *                           1       PFLAG3_FITTING_SYSTEM_WINDOWS
2938     *                          1        PFLAG3_NESTED_SCROLLING_ENABLED
2939     *                         1         PFLAG3_SCROLL_INDICATOR_TOP
2940     *                        1          PFLAG3_SCROLL_INDICATOR_BOTTOM
2941     *                       1           PFLAG3_SCROLL_INDICATOR_LEFT
2942     *                      1            PFLAG3_SCROLL_INDICATOR_RIGHT
2943     *                     1             PFLAG3_SCROLL_INDICATOR_START
2944     *                    1              PFLAG3_SCROLL_INDICATOR_END
2945     *                   1               PFLAG3_ASSIST_BLOCKED
2946     *                  1                PFLAG3_CLUSTER
2947     *                 1                 PFLAG3_IS_AUTOFILLED
2948     *                1                  PFLAG3_FINGER_DOWN
2949     *               1                   PFLAG3_FOCUSED_BY_DEFAULT
2950     *           1111                    PFLAG3_IMPORTANT_FOR_AUTOFILL
2951     *          1                        PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE
2952     *         1                         PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED
2953     *        1                          PFLAG3_TEMPORARY_DETACH
2954     *       1                           PFLAG3_NO_REVEAL_ON_FOCUS
2955     *      1                            PFLAG3_NOTIFY_AUTOFILL_ENTER_ON_LAYOUT
2956     *     1                             PFLAG3_SCREEN_READER_FOCUSABLE
2957     *    1                              PFLAG3_AGGREGATED_VISIBLE
2958     *   1                               PFLAG3_AUTOFILLID_EXPLICITLY_SET
2959     *  1                                PFLAG3_ACCESSIBILITY_HEADING
2960     * |-------|-------|-------|-------|
2961     */
2962
2963    /**
2964     * Flag indicating that view has a transform animation set on it. This is used to track whether
2965     * an animation is cleared between successive frames, in order to tell the associated
2966     * DisplayList to clear its animation matrix.
2967     */
2968    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2969
2970    /**
2971     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2972     * animation is cleared between successive frames, in order to tell the associated
2973     * DisplayList to restore its alpha value.
2974     */
2975    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2976
2977    /**
2978     * Flag indicating that the view has been through at least one layout since it
2979     * was last attached to a window.
2980     */
2981    static final int PFLAG3_IS_LAID_OUT = 0x4;
2982
2983    /**
2984     * Flag indicating that a call to measure() was skipped and should be done
2985     * instead when layout() is invoked.
2986     */
2987    static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8;
2988
2989    /**
2990     * Flag indicating that an overridden method correctly called down to
2991     * the superclass implementation as required by the API spec.
2992     */
2993    static final int PFLAG3_CALLED_SUPER = 0x10;
2994
2995    /**
2996     * Flag indicating that we're in the process of applying window insets.
2997     */
2998    static final int PFLAG3_APPLYING_INSETS = 0x20;
2999
3000    /**
3001     * Flag indicating that we're in the process of fitting system windows using the old method.
3002     */
3003    static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40;
3004
3005    /**
3006     * Flag indicating that nested scrolling is enabled for this view.
3007     * The view will optionally cooperate with views up its parent chain to allow for
3008     * integrated nested scrolling along the same axis.
3009     */
3010    static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80;
3011
3012    /**
3013     * Flag indicating that the bottom scroll indicator should be displayed
3014     * when this view can scroll up.
3015     */
3016    static final int PFLAG3_SCROLL_INDICATOR_TOP = 0x0100;
3017
3018    /**
3019     * Flag indicating that the bottom scroll indicator should be displayed
3020     * when this view can scroll down.
3021     */
3022    static final int PFLAG3_SCROLL_INDICATOR_BOTTOM = 0x0200;
3023
3024    /**
3025     * Flag indicating that the left scroll indicator should be displayed
3026     * when this view can scroll left.
3027     */
3028    static final int PFLAG3_SCROLL_INDICATOR_LEFT = 0x0400;
3029
3030    /**
3031     * Flag indicating that the right scroll indicator should be displayed
3032     * when this view can scroll right.
3033     */
3034    static final int PFLAG3_SCROLL_INDICATOR_RIGHT = 0x0800;
3035
3036    /**
3037     * Flag indicating that the start scroll indicator should be displayed
3038     * when this view can scroll in the start direction.
3039     */
3040    static final int PFLAG3_SCROLL_INDICATOR_START = 0x1000;
3041
3042    /**
3043     * Flag indicating that the end scroll indicator should be displayed
3044     * when this view can scroll in the end direction.
3045     */
3046    static final int PFLAG3_SCROLL_INDICATOR_END = 0x2000;
3047
3048    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
3049
3050    static final int SCROLL_INDICATORS_NONE = 0x0000;
3051
3052    /**
3053     * Mask for use with setFlags indicating bits used for indicating which
3054     * scroll indicators are enabled.
3055     */
3056    static final int SCROLL_INDICATORS_PFLAG3_MASK = PFLAG3_SCROLL_INDICATOR_TOP
3057            | PFLAG3_SCROLL_INDICATOR_BOTTOM | PFLAG3_SCROLL_INDICATOR_LEFT
3058            | PFLAG3_SCROLL_INDICATOR_RIGHT | PFLAG3_SCROLL_INDICATOR_START
3059            | PFLAG3_SCROLL_INDICATOR_END;
3060
3061    /**
3062     * Left-shift required to translate between public scroll indicator flags
3063     * and internal PFLAGS3 flags. When used as a right-shift, translates
3064     * PFLAGS3 flags to public flags.
3065     */
3066    static final int SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT = 8;
3067
3068    /** @hide */
3069    @Retention(RetentionPolicy.SOURCE)
3070    @IntDef(flag = true, prefix = { "SCROLL_INDICATOR_" }, value = {
3071            SCROLL_INDICATOR_TOP,
3072            SCROLL_INDICATOR_BOTTOM,
3073            SCROLL_INDICATOR_LEFT,
3074            SCROLL_INDICATOR_RIGHT,
3075            SCROLL_INDICATOR_START,
3076            SCROLL_INDICATOR_END,
3077    })
3078    public @interface ScrollIndicators {}
3079
3080    /**
3081     * Scroll indicator direction for the top edge of the view.
3082     *
3083     * @see #setScrollIndicators(int)
3084     * @see #setScrollIndicators(int, int)
3085     * @see #getScrollIndicators()
3086     */
3087    public static final int SCROLL_INDICATOR_TOP =
3088            PFLAG3_SCROLL_INDICATOR_TOP >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
3089
3090    /**
3091     * Scroll indicator direction for the bottom edge of the view.
3092     *
3093     * @see #setScrollIndicators(int)
3094     * @see #setScrollIndicators(int, int)
3095     * @see #getScrollIndicators()
3096     */
3097    public static final int SCROLL_INDICATOR_BOTTOM =
3098            PFLAG3_SCROLL_INDICATOR_BOTTOM >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
3099
3100    /**
3101     * Scroll indicator direction for the left edge of the view.
3102     *
3103     * @see #setScrollIndicators(int)
3104     * @see #setScrollIndicators(int, int)
3105     * @see #getScrollIndicators()
3106     */
3107    public static final int SCROLL_INDICATOR_LEFT =
3108            PFLAG3_SCROLL_INDICATOR_LEFT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
3109
3110    /**
3111     * Scroll indicator direction for the right edge of the view.
3112     *
3113     * @see #setScrollIndicators(int)
3114     * @see #setScrollIndicators(int, int)
3115     * @see #getScrollIndicators()
3116     */
3117    public static final int SCROLL_INDICATOR_RIGHT =
3118            PFLAG3_SCROLL_INDICATOR_RIGHT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
3119
3120    /**
3121     * Scroll indicator direction for the starting edge of the view.
3122     * <p>
3123     * Resolved according to the view's layout direction, see
3124     * {@link #getLayoutDirection()} for more information.
3125     *
3126     * @see #setScrollIndicators(int)
3127     * @see #setScrollIndicators(int, int)
3128     * @see #getScrollIndicators()
3129     */
3130    public static final int SCROLL_INDICATOR_START =
3131            PFLAG3_SCROLL_INDICATOR_START >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
3132
3133    /**
3134     * Scroll indicator direction for the ending edge of the view.
3135     * <p>
3136     * Resolved according to the view's layout direction, see
3137     * {@link #getLayoutDirection()} for more information.
3138     *
3139     * @see #setScrollIndicators(int)
3140     * @see #setScrollIndicators(int, int)
3141     * @see #getScrollIndicators()
3142     */
3143    public static final int SCROLL_INDICATOR_END =
3144            PFLAG3_SCROLL_INDICATOR_END >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
3145
3146    /**
3147     * <p>Indicates that we are allowing {@link ViewStructure} to traverse
3148     * into this view.<p>
3149     */
3150    static final int PFLAG3_ASSIST_BLOCKED = 0x4000;
3151
3152    /**
3153     * Flag indicating that the view is a root of a keyboard navigation cluster.
3154     *
3155     * @see #isKeyboardNavigationCluster()
3156     * @see #setKeyboardNavigationCluster(boolean)
3157     */
3158    private static final int PFLAG3_CLUSTER = 0x8000;
3159
3160    /**
3161     * Flag indicating that the view is autofilled
3162     *
3163     * @see #isAutofilled()
3164     * @see #setAutofilled(boolean)
3165     */
3166    private static final int PFLAG3_IS_AUTOFILLED = 0x10000;
3167
3168    /**
3169     * Indicates that the user is currently touching the screen.
3170     * Currently used for the tooltip positioning only.
3171     */
3172    private static final int PFLAG3_FINGER_DOWN = 0x20000;
3173
3174    /**
3175     * Flag indicating that this view is the default-focus view.
3176     *
3177     * @see #isFocusedByDefault()
3178     * @see #setFocusedByDefault(boolean)
3179     */
3180    private static final int PFLAG3_FOCUSED_BY_DEFAULT = 0x40000;
3181
3182    /**
3183     * Shift for the bits in {@link #mPrivateFlags3} related to the
3184     * "importantForAutofill" attribute.
3185     */
3186    static final int PFLAG3_IMPORTANT_FOR_AUTOFILL_SHIFT = 19;
3187
3188    /**
3189     * Mask for obtaining the bits which specify how to determine
3190     * whether a view is important for autofill.
3191     */
3192    static final int PFLAG3_IMPORTANT_FOR_AUTOFILL_MASK = (IMPORTANT_FOR_AUTOFILL_AUTO
3193            | IMPORTANT_FOR_AUTOFILL_YES | IMPORTANT_FOR_AUTOFILL_NO
3194            | IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS
3195            | IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS)
3196            << PFLAG3_IMPORTANT_FOR_AUTOFILL_SHIFT;
3197
3198    /**
3199     * Whether this view has rendered elements that overlap (see {@link
3200     * #hasOverlappingRendering()}, {@link #forceHasOverlappingRendering(boolean)}, and
3201     * {@link #getHasOverlappingRendering()} ). The value in this bit is only valid when
3202     * PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED has been set. Otherwise, the value is
3203     * determined by whatever {@link #hasOverlappingRendering()} returns.
3204     */
3205    private static final int PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE = 0x800000;
3206
3207    /**
3208     * Whether {@link #forceHasOverlappingRendering(boolean)} has been called. When true, value
3209     * in PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE is valid.
3210     */
3211    private static final int PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED = 0x1000000;
3212
3213    /**
3214     * Flag indicating that the view is temporarily detached from the parent view.
3215     *
3216     * @see #onStartTemporaryDetach()
3217     * @see #onFinishTemporaryDetach()
3218     */
3219    static final int PFLAG3_TEMPORARY_DETACH = 0x2000000;
3220
3221    /**
3222     * Flag indicating that the view does not wish to be revealed within its parent
3223     * hierarchy when it gains focus. Expressed in the negative since the historical
3224     * default behavior is to reveal on focus; this flag suppresses that behavior.
3225     *
3226     * @see #setRevealOnFocusHint(boolean)
3227     * @see #getRevealOnFocusHint()
3228     */
3229    private static final int PFLAG3_NO_REVEAL_ON_FOCUS = 0x4000000;
3230
3231    /**
3232     * Flag indicating that when layout is completed we should notify
3233     * that the view was entered for autofill purposes. To minimize
3234     * showing autofill for views not visible to the user we evaluate
3235     * user visibility which cannot be done until the view is laid out.
3236     */
3237    static final int PFLAG3_NOTIFY_AUTOFILL_ENTER_ON_LAYOUT = 0x8000000;
3238
3239    /**
3240     * Works like focusable for screen readers, but without the side effects on input focus.
3241     * @see #setScreenReaderFocusable(boolean)
3242     */
3243    private static final int PFLAG3_SCREEN_READER_FOCUSABLE = 0x10000000;
3244
3245    /**
3246     * The last aggregated visibility. Used to detect when it truly changes.
3247     */
3248    private static final int PFLAG3_AGGREGATED_VISIBLE = 0x20000000;
3249
3250    /**
3251     * Used to indicate that {@link #mAutofillId} was explicitly set through
3252     * {@link #setAutofillId(AutofillId)}.
3253     */
3254    private static final int PFLAG3_AUTOFILLID_EXPLICITLY_SET = 0x40000000;
3255
3256    /**
3257     * Indicates if the View is a heading for accessibility purposes
3258     */
3259    private static final int PFLAG3_ACCESSIBILITY_HEADING = 0x80000000;
3260
3261    /* End of masks for mPrivateFlags3 */
3262
3263    /**
3264     * Always allow a user to over-scroll this view, provided it is a
3265     * view that can scroll.
3266     *
3267     * @see #getOverScrollMode()
3268     * @see #setOverScrollMode(int)
3269     */
3270    public static final int OVER_SCROLL_ALWAYS = 0;
3271
3272    /**
3273     * Allow a user to over-scroll this view only if the content is large
3274     * enough to meaningfully scroll, provided it is a view that can scroll.
3275     *
3276     * @see #getOverScrollMode()
3277     * @see #setOverScrollMode(int)
3278     */
3279    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
3280
3281    /**
3282     * Never allow a user to over-scroll this view.
3283     *
3284     * @see #getOverScrollMode()
3285     * @see #setOverScrollMode(int)
3286     */
3287    public static final int OVER_SCROLL_NEVER = 2;
3288
3289    /**
3290     * Special constant for {@link #setSystemUiVisibility(int)}: View has
3291     * requested the system UI (status bar) to be visible (the default).
3292     *
3293     * @see #setSystemUiVisibility(int)
3294     */
3295    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
3296
3297    /**
3298     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
3299     * system UI to enter an unobtrusive "low profile" mode.
3300     *
3301     * <p>This is for use in games, book readers, video players, or any other
3302     * "immersive" application where the usual system chrome is deemed too distracting.
3303     *
3304     * <p>In low profile mode, the status bar and/or navigation icons may dim.
3305     *
3306     * @see #setSystemUiVisibility(int)
3307     */
3308    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
3309
3310    /**
3311     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
3312     * system navigation be temporarily hidden.
3313     *
3314     * <p>This is an even less obtrusive state than that called for by
3315     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
3316     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
3317     * those to disappear. This is useful (in conjunction with the
3318     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
3319     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
3320     * window flags) for displaying content using every last pixel on the display.
3321     *
3322     * <p>There is a limitation: because navigation controls are so important, the least user
3323     * interaction will cause them to reappear immediately.  When this happens, both
3324     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
3325     * so that both elements reappear at the same time.
3326     *
3327     * @see #setSystemUiVisibility(int)
3328     */
3329    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
3330
3331    /**
3332     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
3333     * into the normal fullscreen mode so that its content can take over the screen
3334     * while still allowing the user to interact with the application.
3335     *
3336     * <p>This has the same visual effect as
3337     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
3338     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
3339     * meaning that non-critical screen decorations (such as the status bar) will be
3340     * hidden while the user is in the View's window, focusing the experience on
3341     * that content.  Unlike the window flag, if you are using ActionBar in
3342     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
3343     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
3344     * hide the action bar.
3345     *
3346     * <p>This approach to going fullscreen is best used over the window flag when
3347     * it is a transient state -- that is, the application does this at certain
3348     * points in its user interaction where it wants to allow the user to focus
3349     * on content, but not as a continuous state.  For situations where the application
3350     * would like to simply stay full screen the entire time (such as a game that
3351     * wants to take over the screen), the
3352     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
3353     * is usually a better approach.  The state set here will be removed by the system
3354     * in various situations (such as the user moving to another application) like
3355     * the other system UI states.
3356     *
3357     * <p>When using this flag, the application should provide some easy facility
3358     * for the user to go out of it.  A common example would be in an e-book
3359     * reader, where tapping on the screen brings back whatever screen and UI
3360     * decorations that had been hidden while the user was immersed in reading
3361     * the book.
3362     *
3363     * @see #setSystemUiVisibility(int)
3364     */
3365    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
3366
3367    /**
3368     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
3369     * flags, we would like a stable view of the content insets given to
3370     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
3371     * will always represent the worst case that the application can expect
3372     * as a continuous state.  In the stock Android UI this is the space for
3373     * the system bar, nav bar, and status bar, but not more transient elements
3374     * such as an input method.
3375     *
3376     * The stable layout your UI sees is based on the system UI modes you can
3377     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
3378     * then you will get a stable layout for changes of the
3379     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
3380     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
3381     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
3382     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
3383     * with a stable layout.  (Note that you should avoid using
3384     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
3385     *
3386     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
3387     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
3388     * then a hidden status bar will be considered a "stable" state for purposes
3389     * here.  This allows your UI to continually hide the status bar, while still
3390     * using the system UI flags to hide the action bar while still retaining
3391     * a stable layout.  Note that changing the window fullscreen flag will never
3392     * provide a stable layout for a clean transition.
3393     *
3394     * <p>If you are using ActionBar in
3395     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
3396     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
3397     * insets it adds to those given to the application.
3398     */
3399    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
3400
3401    /**
3402     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
3403     * to be laid out as if it has requested
3404     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
3405     * allows it to avoid artifacts when switching in and out of that mode, at
3406     * the expense that some of its user interface may be covered by screen
3407     * decorations when they are shown.  You can perform layout of your inner
3408     * UI elements to account for the navigation system UI through the
3409     * {@link #fitSystemWindows(Rect)} method.
3410     */
3411    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
3412
3413    /**
3414     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
3415     * to be laid out as if it has requested
3416     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
3417     * allows it to avoid artifacts when switching in and out of that mode, at
3418     * the expense that some of its user interface may be covered by screen
3419     * decorations when they are shown.  You can perform layout of your inner
3420     * UI elements to account for non-fullscreen system UI through the
3421     * {@link #fitSystemWindows(Rect)} method.
3422     *
3423     * <p>Note: on displays that have a {@link DisplayCutout}, the window may still be placed
3424     *  differently than if {@link #SYSTEM_UI_FLAG_FULLSCREEN} was set, if the
3425     *  window's {@link WindowManager.LayoutParams#layoutInDisplayCutoutMode
3426     *  layoutInDisplayCutoutMode} is
3427     *  {@link WindowManager.LayoutParams#LAYOUT_IN_DISPLAY_CUTOUT_MODE_DEFAULT
3428     *  LAYOUT_IN_DISPLAY_CUTOUT_MODE_DEFAULT}. To avoid this, use either of the other modes.
3429     *
3430     * @see WindowManager.LayoutParams#layoutInDisplayCutoutMode
3431     * @see WindowManager.LayoutParams#LAYOUT_IN_DISPLAY_CUTOUT_MODE_DEFAULT
3432     * @see WindowManager.LayoutParams#LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS
3433     * @see WindowManager.LayoutParams#LAYOUT_IN_DISPLAY_CUTOUT_MODE_NEVER
3434     */
3435    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
3436
3437    /**
3438     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
3439     * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  If this flag is
3440     * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any
3441     * user interaction.
3442     * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only
3443     * has an effect when used in combination with that flag.</p>
3444     */
3445    public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800;
3446
3447    /**
3448     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
3449     * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation
3450     * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  Use this flag to create an immersive
3451     * experience while also hiding the system bars.  If this flag is not set,
3452     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user
3453     * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system
3454     * if the user swipes from the top of the screen.
3455     * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with
3456     * system gestures, such as swiping from the top of the screen.  These transient system bars
3457     * will overlay app’s content, may have some degree of transparency, and will automatically
3458     * hide after a short timeout.
3459     * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and
3460     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination
3461     * with one or both of those flags.</p>
3462     */
3463    public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000;
3464
3465    /**
3466     * Flag for {@link #setSystemUiVisibility(int)}: Requests the status bar to draw in a mode that
3467     * is compatible with light status bar backgrounds.
3468     *
3469     * <p>For this to take effect, the window must request
3470     * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS
3471     *         FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not
3472     * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_STATUS
3473     *         FLAG_TRANSLUCENT_STATUS}.
3474     *
3475     * @see android.R.attr#windowLightStatusBar
3476     */
3477    public static final int SYSTEM_UI_FLAG_LIGHT_STATUS_BAR = 0x00002000;
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_LEGACY1 = 0x00004000;
3484
3485    /**
3486     * This flag was previously used for a private API. DO NOT reuse it for a public API as it might
3487     * trigger undefined behavior on older platforms with apps compiled against a new SDK.
3488     */
3489    private static final int SYSTEM_UI_RESERVED_LEGACY2 = 0x00010000;
3490
3491    /**
3492     * Flag for {@link #setSystemUiVisibility(int)}: Requests the navigation bar to draw in a mode
3493     * that is compatible with light navigation bar backgrounds.
3494     *
3495     * <p>For this to take effect, the window must request
3496     * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS
3497     *         FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not
3498     * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_NAVIGATION
3499     *         FLAG_TRANSLUCENT_NAVIGATION}.
3500     *
3501     * @see android.R.attr#windowLightNavigationBar
3502     */
3503    public static final int SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR = 0x00000010;
3504
3505    /**
3506     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
3507     */
3508    @Deprecated
3509    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
3510
3511    /**
3512     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
3513     */
3514    @Deprecated
3515    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
3516
3517    /**
3518     * @hide
3519     *
3520     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3521     * out of the public fields to keep the undefined bits out of the developer's way.
3522     *
3523     * Flag to make the status bar not expandable.  Unless you also
3524     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
3525     */
3526    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
3527
3528    /**
3529     * @hide
3530     *
3531     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3532     * out of the public fields to keep the undefined bits out of the developer's way.
3533     *
3534     * Flag to hide notification icons and scrolling ticker text.
3535     */
3536    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
3537
3538    /**
3539     * @hide
3540     *
3541     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3542     * out of the public fields to keep the undefined bits out of the developer's way.
3543     *
3544     * Flag to disable incoming notification alerts.  This will not block
3545     * icons, but it will block sound, vibrating and other visual or aural notifications.
3546     */
3547    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
3548
3549    /**
3550     * @hide
3551     *
3552     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3553     * out of the public fields to keep the undefined bits out of the developer's way.
3554     *
3555     * Flag to hide only the scrolling ticker.  Note that
3556     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
3557     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
3558     */
3559    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
3560
3561    /**
3562     * @hide
3563     *
3564     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3565     * out of the public fields to keep the undefined bits out of the developer's way.
3566     *
3567     * Flag to hide the center system info area.
3568     */
3569    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
3570
3571    /**
3572     * @hide
3573     *
3574     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3575     * out of the public fields to keep the undefined bits out of the developer's way.
3576     *
3577     * Flag to hide only the home button.  Don't use this
3578     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3579     */
3580    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
3581
3582    /**
3583     * @hide
3584     *
3585     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3586     * out of the public fields to keep the undefined bits out of the developer's way.
3587     *
3588     * Flag to hide only the back button. Don't use this
3589     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3590     */
3591    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
3592
3593    /**
3594     * @hide
3595     *
3596     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3597     * out of the public fields to keep the undefined bits out of the developer's way.
3598     *
3599     * Flag to hide only the clock.  You might use this if your activity has
3600     * its own clock making the status bar's clock redundant.
3601     */
3602    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
3603
3604    /**
3605     * @hide
3606     *
3607     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3608     * out of the public fields to keep the undefined bits out of the developer's way.
3609     *
3610     * Flag to hide only the recent apps button. Don't use this
3611     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3612     */
3613    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
3614
3615    /**
3616     * @hide
3617     *
3618     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3619     * out of the public fields to keep the undefined bits out of the developer's way.
3620     *
3621     * Flag to disable the global search gesture. Don't use this
3622     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3623     */
3624    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
3625
3626    /**
3627     * @hide
3628     *
3629     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3630     * out of the public fields to keep the undefined bits out of the developer's way.
3631     *
3632     * Flag to specify that the status bar is displayed in transient mode.
3633     */
3634    public static final int STATUS_BAR_TRANSIENT = 0x04000000;
3635
3636    /**
3637     * @hide
3638     *
3639     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3640     * out of the public fields to keep the undefined bits out of the developer's way.
3641     *
3642     * Flag to specify that the navigation bar is displayed in transient mode.
3643     */
3644    public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000;
3645
3646    /**
3647     * @hide
3648     *
3649     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3650     * out of the public fields to keep the undefined bits out of the developer's way.
3651     *
3652     * Flag to specify that the hidden status bar would like to be shown.
3653     */
3654    public static final int STATUS_BAR_UNHIDE = 0x10000000;
3655
3656    /**
3657     * @hide
3658     *
3659     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3660     * out of the public fields to keep the undefined bits out of the developer's way.
3661     *
3662     * Flag to specify that the hidden navigation bar would like to be shown.
3663     */
3664    public static final int NAVIGATION_BAR_UNHIDE = 0x20000000;
3665
3666    /**
3667     * @hide
3668     *
3669     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3670     * out of the public fields to keep the undefined bits out of the developer's way.
3671     *
3672     * Flag to specify that the status bar is displayed in translucent mode.
3673     */
3674    public static final int STATUS_BAR_TRANSLUCENT = 0x40000000;
3675
3676    /**
3677     * @hide
3678     *
3679     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3680     * out of the public fields to keep the undefined bits out of the developer's way.
3681     *
3682     * Flag to specify that the navigation bar is displayed in translucent mode.
3683     */
3684    public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000;
3685
3686    /**
3687     * @hide
3688     *
3689     * Makes navigation bar transparent (but not the status bar).
3690     */
3691    public static final int NAVIGATION_BAR_TRANSPARENT = 0x00008000;
3692
3693    /**
3694     * @hide
3695     *
3696     * Makes status bar transparent (but not the navigation bar).
3697     */
3698    public static final int STATUS_BAR_TRANSPARENT = 0x00000008;
3699
3700    /**
3701     * @hide
3702     *
3703     * Makes both status bar and navigation bar transparent.
3704     */
3705    public static final int SYSTEM_UI_TRANSPARENT = NAVIGATION_BAR_TRANSPARENT
3706            | STATUS_BAR_TRANSPARENT;
3707
3708    /**
3709     * @hide
3710     */
3711    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FF7;
3712
3713    /**
3714     * These are the system UI flags that can be cleared by events outside
3715     * of an application.  Currently this is just the ability to tap on the
3716     * screen while hiding the navigation bar to have it return.
3717     * @hide
3718     */
3719    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
3720            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
3721            | SYSTEM_UI_FLAG_FULLSCREEN;
3722
3723    /**
3724     * Flags that can impact the layout in relation to system UI.
3725     */
3726    public static final int SYSTEM_UI_LAYOUT_FLAGS =
3727            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
3728            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
3729
3730    /** @hide */
3731    @IntDef(flag = true, prefix = { "FIND_VIEWS_" }, value = {
3732            FIND_VIEWS_WITH_TEXT,
3733            FIND_VIEWS_WITH_CONTENT_DESCRIPTION
3734    })
3735    @Retention(RetentionPolicy.SOURCE)
3736    public @interface FindViewFlags {}
3737
3738    /**
3739     * Find views that render the specified text.
3740     *
3741     * @see #findViewsWithText(ArrayList, CharSequence, int)
3742     */
3743    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
3744
3745    /**
3746     * Find find views that contain the specified content description.
3747     *
3748     * @see #findViewsWithText(ArrayList, CharSequence, int)
3749     */
3750    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
3751
3752    /**
3753     * Find views that contain {@link AccessibilityNodeProvider}. Such
3754     * a View is a root of virtual view hierarchy and may contain the searched
3755     * text. If this flag is set Views with providers are automatically
3756     * added and it is a responsibility of the client to call the APIs of
3757     * the provider to determine whether the virtual tree rooted at this View
3758     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
3759     * representing the virtual views with this text.
3760     *
3761     * @see #findViewsWithText(ArrayList, CharSequence, int)
3762     *
3763     * @hide
3764     */
3765    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
3766
3767    /**
3768     * The undefined cursor position.
3769     *
3770     * @hide
3771     */
3772    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
3773
3774    /**
3775     * Indicates that the screen has changed state and is now off.
3776     *
3777     * @see #onScreenStateChanged(int)
3778     */
3779    public static final int SCREEN_STATE_OFF = 0x0;
3780
3781    /**
3782     * Indicates that the screen has changed state and is now on.
3783     *
3784     * @see #onScreenStateChanged(int)
3785     */
3786    public static final int SCREEN_STATE_ON = 0x1;
3787
3788    /**
3789     * Indicates no axis of view scrolling.
3790     */
3791    public static final int SCROLL_AXIS_NONE = 0;
3792
3793    /**
3794     * Indicates scrolling along the horizontal axis.
3795     */
3796    public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0;
3797
3798    /**
3799     * Indicates scrolling along the vertical axis.
3800     */
3801    public static final int SCROLL_AXIS_VERTICAL = 1 << 1;
3802
3803    /**
3804     * Controls the over-scroll mode for this view.
3805     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
3806     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
3807     * and {@link #OVER_SCROLL_NEVER}.
3808     */
3809    private int mOverScrollMode;
3810
3811    /**
3812     * The parent this view is attached to.
3813     * {@hide}
3814     *
3815     * @see #getParent()
3816     */
3817    protected ViewParent mParent;
3818
3819    /**
3820     * {@hide}
3821     */
3822    AttachInfo mAttachInfo;
3823
3824    /**
3825     * {@hide}
3826     */
3827    @ViewDebug.ExportedProperty(flagMapping = {
3828        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
3829                name = "FORCE_LAYOUT"),
3830        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
3831                name = "LAYOUT_REQUIRED"),
3832        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
3833            name = "DRAWING_CACHE_INVALID", outputIf = false),
3834        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
3835        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
3836        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
3837        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
3838    }, formatToHexString = true)
3839
3840    /* @hide */
3841    public int mPrivateFlags;
3842    int mPrivateFlags2;
3843    int mPrivateFlags3;
3844
3845    /**
3846     * This view's request for the visibility of the status bar.
3847     * @hide
3848     */
3849    @ViewDebug.ExportedProperty(flagMapping = {
3850            @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
3851                    equals = SYSTEM_UI_FLAG_LOW_PROFILE,
3852                    name = "LOW_PROFILE"),
3853            @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
3854                    equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
3855                    name = "HIDE_NAVIGATION"),
3856            @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_FULLSCREEN,
3857                    equals = SYSTEM_UI_FLAG_FULLSCREEN,
3858                    name = "FULLSCREEN"),
3859            @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LAYOUT_STABLE,
3860                    equals = SYSTEM_UI_FLAG_LAYOUT_STABLE,
3861                    name = "LAYOUT_STABLE"),
3862            @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION,
3863                    equals = SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION,
3864                    name = "LAYOUT_HIDE_NAVIGATION"),
3865            @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN,
3866                    equals = SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN,
3867                    name = "LAYOUT_FULLSCREEN"),
3868            @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_IMMERSIVE,
3869                    equals = SYSTEM_UI_FLAG_IMMERSIVE,
3870                    name = "IMMERSIVE"),
3871            @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_IMMERSIVE_STICKY,
3872                    equals = SYSTEM_UI_FLAG_IMMERSIVE_STICKY,
3873                    name = "IMMERSIVE_STICKY"),
3874            @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LIGHT_STATUS_BAR,
3875                    equals = SYSTEM_UI_FLAG_LIGHT_STATUS_BAR,
3876                    name = "LIGHT_STATUS_BAR"),
3877            @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR,
3878                    equals = SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR,
3879                    name = "LIGHT_NAVIGATION_BAR"),
3880            @ViewDebug.FlagToString(mask = STATUS_BAR_DISABLE_EXPAND,
3881                    equals = STATUS_BAR_DISABLE_EXPAND,
3882                    name = "STATUS_BAR_DISABLE_EXPAND"),
3883            @ViewDebug.FlagToString(mask = STATUS_BAR_DISABLE_NOTIFICATION_ICONS,
3884                    equals = STATUS_BAR_DISABLE_NOTIFICATION_ICONS,
3885                    name = "STATUS_BAR_DISABLE_NOTIFICATION_ICONS"),
3886            @ViewDebug.FlagToString(mask = STATUS_BAR_DISABLE_NOTIFICATION_ALERTS,
3887                    equals = STATUS_BAR_DISABLE_NOTIFICATION_ALERTS,
3888                    name = "STATUS_BAR_DISABLE_NOTIFICATION_ALERTS"),
3889            @ViewDebug.FlagToString(mask = STATUS_BAR_DISABLE_NOTIFICATION_TICKER,
3890                    equals = STATUS_BAR_DISABLE_NOTIFICATION_TICKER,
3891                    name = "STATUS_BAR_DISABLE_NOTIFICATION_TICKER"),
3892            @ViewDebug.FlagToString(mask = STATUS_BAR_DISABLE_SYSTEM_INFO,
3893                    equals = STATUS_BAR_DISABLE_SYSTEM_INFO,
3894                    name = "STATUS_BAR_DISABLE_SYSTEM_INFO"),
3895            @ViewDebug.FlagToString(mask = STATUS_BAR_DISABLE_HOME,
3896                    equals = STATUS_BAR_DISABLE_HOME,
3897                    name = "STATUS_BAR_DISABLE_HOME"),
3898            @ViewDebug.FlagToString(mask = STATUS_BAR_DISABLE_BACK,
3899                    equals = STATUS_BAR_DISABLE_BACK,
3900                    name = "STATUS_BAR_DISABLE_BACK"),
3901            @ViewDebug.FlagToString(mask = STATUS_BAR_DISABLE_CLOCK,
3902                    equals = STATUS_BAR_DISABLE_CLOCK,
3903                    name = "STATUS_BAR_DISABLE_CLOCK"),
3904            @ViewDebug.FlagToString(mask = STATUS_BAR_DISABLE_RECENT,
3905                    equals = STATUS_BAR_DISABLE_RECENT,
3906                    name = "STATUS_BAR_DISABLE_RECENT"),
3907            @ViewDebug.FlagToString(mask = STATUS_BAR_DISABLE_SEARCH,
3908                    equals = STATUS_BAR_DISABLE_SEARCH,
3909                    name = "STATUS_BAR_DISABLE_SEARCH"),
3910            @ViewDebug.FlagToString(mask = STATUS_BAR_TRANSIENT,
3911                    equals = STATUS_BAR_TRANSIENT,
3912                    name = "STATUS_BAR_TRANSIENT"),
3913            @ViewDebug.FlagToString(mask = NAVIGATION_BAR_TRANSIENT,
3914                    equals = NAVIGATION_BAR_TRANSIENT,
3915                    name = "NAVIGATION_BAR_TRANSIENT"),
3916            @ViewDebug.FlagToString(mask = STATUS_BAR_UNHIDE,
3917                    equals = STATUS_BAR_UNHIDE,
3918                    name = "STATUS_BAR_UNHIDE"),
3919            @ViewDebug.FlagToString(mask = NAVIGATION_BAR_UNHIDE,
3920                    equals = NAVIGATION_BAR_UNHIDE,
3921                    name = "NAVIGATION_BAR_UNHIDE"),
3922            @ViewDebug.FlagToString(mask = STATUS_BAR_TRANSLUCENT,
3923                    equals = STATUS_BAR_TRANSLUCENT,
3924                    name = "STATUS_BAR_TRANSLUCENT"),
3925            @ViewDebug.FlagToString(mask = NAVIGATION_BAR_TRANSLUCENT,
3926                    equals = NAVIGATION_BAR_TRANSLUCENT,
3927                    name = "NAVIGATION_BAR_TRANSLUCENT"),
3928            @ViewDebug.FlagToString(mask = NAVIGATION_BAR_TRANSPARENT,
3929                    equals = NAVIGATION_BAR_TRANSPARENT,
3930                    name = "NAVIGATION_BAR_TRANSPARENT"),
3931            @ViewDebug.FlagToString(mask = STATUS_BAR_TRANSPARENT,
3932                    equals = STATUS_BAR_TRANSPARENT,
3933                    name = "STATUS_BAR_TRANSPARENT")
3934    }, formatToHexString = true)
3935    int mSystemUiVisibility;
3936
3937    /**
3938     * Reference count for transient state.
3939     * @see #setHasTransientState(boolean)
3940     */
3941    int mTransientStateCount = 0;
3942
3943    /**
3944     * Count of how many windows this view has been attached to.
3945     */
3946    int mWindowAttachCount;
3947
3948    /**
3949     * The layout parameters associated with this view and used by the parent
3950     * {@link android.view.ViewGroup} to determine how this view should be
3951     * laid out.
3952     * {@hide}
3953     */
3954    protected ViewGroup.LayoutParams mLayoutParams;
3955
3956    /**
3957     * The view flags hold various views states.
3958     * {@hide}
3959     */
3960    @ViewDebug.ExportedProperty(formatToHexString = true)
3961    int mViewFlags;
3962
3963    static class TransformationInfo {
3964        /**
3965         * The transform matrix for the View. This transform is calculated internally
3966         * based on the translation, rotation, and scale properties.
3967         *
3968         * Do *not* use this variable directly; instead call getMatrix(), which will
3969         * load the value from the View's RenderNode.
3970         */
3971        private final Matrix mMatrix = new Matrix();
3972
3973        /**
3974         * The inverse transform matrix for the View. This transform is calculated
3975         * internally based on the translation, rotation, and scale properties.
3976         *
3977         * Do *not* use this variable directly; instead call getInverseMatrix(),
3978         * which will load the value from the View's RenderNode.
3979         */
3980        private Matrix mInverseMatrix;
3981
3982        /**
3983         * The opacity of the View. This is a value from 0 to 1, where 0 means
3984         * completely transparent and 1 means completely opaque.
3985         */
3986        @ViewDebug.ExportedProperty
3987        float mAlpha = 1f;
3988
3989        /**
3990         * The opacity of the view as manipulated by the Fade transition. This is a hidden
3991         * property only used by transitions, which is composited with the other alpha
3992         * values to calculate the final visual alpha value.
3993         */
3994        float mTransitionAlpha = 1f;
3995    }
3996
3997    /** @hide */
3998    public TransformationInfo mTransformationInfo;
3999
4000    /**
4001     * Current clip bounds. to which all drawing of this view are constrained.
4002     */
4003    @ViewDebug.ExportedProperty(category = "drawing")
4004    Rect mClipBounds = null;
4005
4006    private boolean mLastIsOpaque;
4007
4008    /**
4009     * The distance in pixels from the left edge of this view's parent
4010     * to the left edge of this view.
4011     * {@hide}
4012     */
4013    @ViewDebug.ExportedProperty(category = "layout")
4014    protected int mLeft;
4015    /**
4016     * The distance in pixels from the left edge of this view's parent
4017     * to the right edge of this view.
4018     * {@hide}
4019     */
4020    @ViewDebug.ExportedProperty(category = "layout")
4021    protected int mRight;
4022    /**
4023     * The distance in pixels from the top edge of this view's parent
4024     * to the top edge of this view.
4025     * {@hide}
4026     */
4027    @ViewDebug.ExportedProperty(category = "layout")
4028    protected int mTop;
4029    /**
4030     * The distance in pixels from the top edge of this view's parent
4031     * to the bottom edge of this view.
4032     * {@hide}
4033     */
4034    @ViewDebug.ExportedProperty(category = "layout")
4035    protected int mBottom;
4036
4037    /**
4038     * The offset, in pixels, by which the content of this view is scrolled
4039     * horizontally.
4040     * {@hide}
4041     */
4042    @ViewDebug.ExportedProperty(category = "scrolling")
4043    protected int mScrollX;
4044    /**
4045     * The offset, in pixels, by which the content of this view is scrolled
4046     * vertically.
4047     * {@hide}
4048     */
4049    @ViewDebug.ExportedProperty(category = "scrolling")
4050    protected int mScrollY;
4051
4052    /**
4053     * The left padding in pixels, that is the distance in pixels between the
4054     * left edge of this view and the left edge of its content.
4055     * {@hide}
4056     */
4057    @ViewDebug.ExportedProperty(category = "padding")
4058    protected int mPaddingLeft = 0;
4059    /**
4060     * The right padding in pixels, that is the distance in pixels between the
4061     * right edge of this view and the right edge of its content.
4062     * {@hide}
4063     */
4064    @ViewDebug.ExportedProperty(category = "padding")
4065    protected int mPaddingRight = 0;
4066    /**
4067     * The top padding in pixels, that is the distance in pixels between the
4068     * top edge of this view and the top edge of its content.
4069     * {@hide}
4070     */
4071    @ViewDebug.ExportedProperty(category = "padding")
4072    protected int mPaddingTop;
4073    /**
4074     * The bottom padding in pixels, that is the distance in pixels between the
4075     * bottom edge of this view and the bottom edge of its content.
4076     * {@hide}
4077     */
4078    @ViewDebug.ExportedProperty(category = "padding")
4079    protected int mPaddingBottom;
4080
4081    /**
4082     * The layout insets in pixels, that is the distance in pixels between the
4083     * visible edges of this view its bounds.
4084     */
4085    private Insets mLayoutInsets;
4086
4087    /**
4088     * Briefly describes the view and is primarily used for accessibility support.
4089     */
4090    private CharSequence mContentDescription;
4091
4092    /**
4093     * If this view represents a distinct part of the window, it can have a title that labels the
4094     * area.
4095     */
4096    private CharSequence mAccessibilityPaneTitle;
4097
4098    /**
4099     * Specifies the id of a view for which this view serves as a label for
4100     * accessibility purposes.
4101     */
4102    private int mLabelForId = View.NO_ID;
4103
4104    /**
4105     * Predicate for matching labeled view id with its label for
4106     * accessibility purposes.
4107     */
4108    private MatchLabelForPredicate mMatchLabelForPredicate;
4109
4110    /**
4111     * Specifies a view before which this one is visited in accessibility traversal.
4112     */
4113    private int mAccessibilityTraversalBeforeId = NO_ID;
4114
4115    /**
4116     * Specifies a view after which this one is visited in accessibility traversal.
4117     */
4118    private int mAccessibilityTraversalAfterId = NO_ID;
4119
4120    /**
4121     * Predicate for matching a view by its id.
4122     */
4123    private MatchIdPredicate mMatchIdPredicate;
4124
4125    /**
4126     * Cache the paddingRight set by the user to append to the scrollbar's size.
4127     *
4128     * @hide
4129     */
4130    @ViewDebug.ExportedProperty(category = "padding")
4131    protected int mUserPaddingRight;
4132
4133    /**
4134     * Cache the paddingBottom set by the user to append to the scrollbar's size.
4135     *
4136     * @hide
4137     */
4138    @ViewDebug.ExportedProperty(category = "padding")
4139    protected int mUserPaddingBottom;
4140
4141    /**
4142     * Cache the paddingLeft set by the user to append to the scrollbar's size.
4143     *
4144     * @hide
4145     */
4146    @ViewDebug.ExportedProperty(category = "padding")
4147    protected int mUserPaddingLeft;
4148
4149    /**
4150     * Cache the paddingStart set by the user to append to the scrollbar's size.
4151     *
4152     */
4153    @ViewDebug.ExportedProperty(category = "padding")
4154    int mUserPaddingStart;
4155
4156    /**
4157     * Cache the paddingEnd set by the user to append to the scrollbar's size.
4158     *
4159     */
4160    @ViewDebug.ExportedProperty(category = "padding")
4161    int mUserPaddingEnd;
4162
4163    /**
4164     * Cache initial left padding.
4165     *
4166     * @hide
4167     */
4168    int mUserPaddingLeftInitial;
4169
4170    /**
4171     * Cache initial right padding.
4172     *
4173     * @hide
4174     */
4175    int mUserPaddingRightInitial;
4176
4177    /**
4178     * Default undefined padding
4179     */
4180    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
4181
4182    /**
4183     * Cache if a left padding has been defined
4184     */
4185    private boolean mLeftPaddingDefined = false;
4186
4187    /**
4188     * Cache if a right padding has been defined
4189     */
4190    private boolean mRightPaddingDefined = false;
4191
4192    /**
4193     * @hide
4194     */
4195    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
4196    /**
4197     * @hide
4198     */
4199    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
4200
4201    private LongSparseLongArray mMeasureCache;
4202
4203    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
4204    private Drawable mBackground;
4205    private TintInfo mBackgroundTint;
4206
4207    @ViewDebug.ExportedProperty(deepExport = true, prefix = "fg_")
4208    private ForegroundInfo mForegroundInfo;
4209
4210    private Drawable mScrollIndicatorDrawable;
4211
4212    /**
4213     * RenderNode used for backgrounds.
4214     * <p>
4215     * When non-null and valid, this is expected to contain an up-to-date copy
4216     * of the background drawable. It is cleared on temporary detach, and reset
4217     * on cleanup.
4218     */
4219    private RenderNode mBackgroundRenderNode;
4220
4221    private int mBackgroundResource;
4222    private boolean mBackgroundSizeChanged;
4223
4224    /** The default focus highlight.
4225     * @see #mDefaultFocusHighlightEnabled
4226     * @see Drawable#hasFocusStateSpecified()
4227     */
4228    private Drawable mDefaultFocusHighlight;
4229    private Drawable mDefaultFocusHighlightCache;
4230    private boolean mDefaultFocusHighlightSizeChanged;
4231    /**
4232     * True if the default focus highlight is needed on the target device.
4233     */
4234    private static boolean sUseDefaultFocusHighlight;
4235
4236    /**
4237     * True if zero-sized views can be focused.
4238     */
4239    private static boolean sCanFocusZeroSized;
4240
4241    /**
4242     * Always assign focus if a focusable View is available.
4243     */
4244    private static boolean sAlwaysAssignFocus;
4245
4246    private String mTransitionName;
4247
4248    static class TintInfo {
4249        ColorStateList mTintList;
4250        PorterDuff.Mode mTintMode;
4251        boolean mHasTintMode;
4252        boolean mHasTintList;
4253    }
4254
4255    private static class ForegroundInfo {
4256        private Drawable mDrawable;
4257        private TintInfo mTintInfo;
4258        private int mGravity = Gravity.FILL;
4259        private boolean mInsidePadding = true;
4260        private boolean mBoundsChanged = true;
4261        private final Rect mSelfBounds = new Rect();
4262        private final Rect mOverlayBounds = new Rect();
4263    }
4264
4265    static class ListenerInfo {
4266        /**
4267         * Listener used to dispatch focus change events.
4268         * This field should be made private, so it is hidden from the SDK.
4269         * {@hide}
4270         */
4271        protected OnFocusChangeListener mOnFocusChangeListener;
4272
4273        /**
4274         * Listeners for layout change events.
4275         */
4276        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
4277
4278        protected OnScrollChangeListener mOnScrollChangeListener;
4279
4280        /**
4281         * Listeners for attach events.
4282         */
4283        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
4284
4285        /**
4286         * Listener used to dispatch click events.
4287         * This field should be made private, so it is hidden from the SDK.
4288         * {@hide}
4289         */
4290        public OnClickListener mOnClickListener;
4291
4292        /**
4293         * Listener used to dispatch long click events.
4294         * This field should be made private, so it is hidden from the SDK.
4295         * {@hide}
4296         */
4297        protected OnLongClickListener mOnLongClickListener;
4298
4299        /**
4300         * Listener used to dispatch context click events. This field should be made private, so it
4301         * is hidden from the SDK.
4302         * {@hide}
4303         */
4304        protected OnContextClickListener mOnContextClickListener;
4305
4306        /**
4307         * Listener used to build the context menu.
4308         * This field should be made private, so it is hidden from the SDK.
4309         * {@hide}
4310         */
4311        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
4312
4313        private OnKeyListener mOnKeyListener;
4314
4315        private OnTouchListener mOnTouchListener;
4316
4317        private OnHoverListener mOnHoverListener;
4318
4319        private OnGenericMotionListener mOnGenericMotionListener;
4320
4321        private OnDragListener mOnDragListener;
4322
4323        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
4324
4325        OnApplyWindowInsetsListener mOnApplyWindowInsetsListener;
4326
4327        OnCapturedPointerListener mOnCapturedPointerListener;
4328
4329        private ArrayList<OnUnhandledKeyEventListener> mUnhandledKeyListeners;
4330    }
4331
4332    ListenerInfo mListenerInfo;
4333
4334    private static class TooltipInfo {
4335        /**
4336         * Text to be displayed in a tooltip popup.
4337         */
4338        @Nullable
4339        CharSequence mTooltipText;
4340
4341        /**
4342         * View-relative position of the tooltip anchor point.
4343         */
4344        int mAnchorX;
4345        int mAnchorY;
4346
4347        /**
4348         * The tooltip popup.
4349         */
4350        @Nullable
4351        TooltipPopup mTooltipPopup;
4352
4353        /**
4354         * Set to true if the tooltip was shown as a result of a long click.
4355         */
4356        boolean mTooltipFromLongClick;
4357
4358        /**
4359         * Keep these Runnables so that they can be used to reschedule.
4360         */
4361        Runnable mShowTooltipRunnable;
4362        Runnable mHideTooltipRunnable;
4363
4364        /**
4365         * Hover move is ignored if it is within this distance in pixels from the previous one.
4366         */
4367        int mHoverSlop;
4368
4369        /**
4370         * Update the anchor position if it significantly (that is by at least mHoverSlop)
4371         * different from the previously stored position. Ignoring insignificant changes
4372         * filters out the jitter which is typical for such input sources as stylus.
4373         *
4374         * @return True if the position has been updated.
4375         */
4376        private boolean updateAnchorPos(MotionEvent event) {
4377            final int newAnchorX = (int) event.getX();
4378            final int newAnchorY = (int) event.getY();
4379            if (Math.abs(newAnchorX - mAnchorX) <= mHoverSlop
4380                    && Math.abs(newAnchorY - mAnchorY) <= mHoverSlop) {
4381                return false;
4382            }
4383            mAnchorX = newAnchorX;
4384            mAnchorY = newAnchorY;
4385            return true;
4386        }
4387
4388        /**
4389         *  Clear the anchor position to ensure that the next change is considered significant.
4390         */
4391        private void clearAnchorPos() {
4392            mAnchorX = Integer.MAX_VALUE;
4393            mAnchorY = Integer.MAX_VALUE;
4394        }
4395    }
4396
4397    TooltipInfo mTooltipInfo;
4398
4399    // Temporary values used to hold (x,y) coordinates when delegating from the
4400    // two-arg performLongClick() method to the legacy no-arg version.
4401    private float mLongClickX = Float.NaN;
4402    private float mLongClickY = Float.NaN;
4403
4404    /**
4405     * The application environment this view lives in.
4406     * This field should be made private, so it is hidden from the SDK.
4407     * {@hide}
4408     */
4409    @ViewDebug.ExportedProperty(deepExport = true)
4410    protected Context mContext;
4411
4412    private final Resources mResources;
4413
4414    private ScrollabilityCache mScrollCache;
4415
4416    private int[] mDrawableState = null;
4417
4418    ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND;
4419
4420    /**
4421     * Animator that automatically runs based on state changes.
4422     */
4423    private StateListAnimator mStateListAnimator;
4424
4425    /**
4426     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
4427     * the user may specify which view to go to next.
4428     */
4429    private int mNextFocusLeftId = View.NO_ID;
4430
4431    /**
4432     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
4433     * the user may specify which view to go to next.
4434     */
4435    private int mNextFocusRightId = View.NO_ID;
4436
4437    /**
4438     * When this view has focus and the next focus is {@link #FOCUS_UP},
4439     * the user may specify which view to go to next.
4440     */
4441    private int mNextFocusUpId = View.NO_ID;
4442
4443    /**
4444     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
4445     * the user may specify which view to go to next.
4446     */
4447    private int mNextFocusDownId = View.NO_ID;
4448
4449    /**
4450     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
4451     * the user may specify which view to go to next.
4452     */
4453    int mNextFocusForwardId = View.NO_ID;
4454
4455    /**
4456     * User-specified next keyboard navigation cluster in the {@link #FOCUS_FORWARD} direction.
4457     *
4458     * @see #findUserSetNextKeyboardNavigationCluster(View, int)
4459     */
4460    int mNextClusterForwardId = View.NO_ID;
4461
4462    /**
4463     * Whether this View should use a default focus highlight when it gets focused but doesn't
4464     * have {@link android.R.attr#state_focused} defined in its background.
4465     */
4466    boolean mDefaultFocusHighlightEnabled = true;
4467
4468    private CheckForLongPress mPendingCheckForLongPress;
4469    private CheckForTap mPendingCheckForTap = null;
4470    private PerformClick mPerformClick;
4471    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
4472
4473    private UnsetPressedState mUnsetPressedState;
4474
4475    /**
4476     * Whether the long press's action has been invoked.  The tap's action is invoked on the
4477     * up event while a long press is invoked as soon as the long press duration is reached, so
4478     * a long press could be performed before the tap is checked, in which case the tap's action
4479     * should not be invoked.
4480     */
4481    private boolean mHasPerformedLongPress;
4482
4483    /**
4484     * Whether a context click button is currently pressed down. This is true when the stylus is
4485     * touching the screen and the primary button has been pressed, or if a mouse's right button is
4486     * pressed. This is false once the button is released or if the stylus has been lifted.
4487     */
4488    private boolean mInContextButtonPress;
4489
4490    /**
4491     * Whether the next up event should be ignored for the purposes of gesture recognition. This is
4492     * true after a stylus button press has occured, when the next up event should not be recognized
4493     * as a tap.
4494     */
4495    private boolean mIgnoreNextUpEvent;
4496
4497    /**
4498     * The minimum height of the view. We'll try our best to have the height
4499     * of this view to at least this amount.
4500     */
4501    @ViewDebug.ExportedProperty(category = "measurement")
4502    private int mMinHeight;
4503
4504    /**
4505     * The minimum width of the view. We'll try our best to have the width
4506     * of this view to at least this amount.
4507     */
4508    @ViewDebug.ExportedProperty(category = "measurement")
4509    private int mMinWidth;
4510
4511    /**
4512     * The delegate to handle touch events that are physically in this view
4513     * but should be handled by another view.
4514     */
4515    private TouchDelegate mTouchDelegate = null;
4516
4517    /**
4518     * Solid color to use as a background when creating the drawing cache. Enables
4519     * the cache to use 16 bit bitmaps instead of 32 bit.
4520     */
4521    private int mDrawingCacheBackgroundColor = 0;
4522
4523    /**
4524     * Special tree observer used when mAttachInfo is null.
4525     */
4526    private ViewTreeObserver mFloatingTreeObserver;
4527
4528    /**
4529     * Cache the touch slop from the context that created the view.
4530     */
4531    private int mTouchSlop;
4532
4533    /**
4534     * Object that handles automatic animation of view properties.
4535     */
4536    private ViewPropertyAnimator mAnimator = null;
4537
4538    /**
4539     * List of registered FrameMetricsObservers.
4540     */
4541    private ArrayList<FrameMetricsObserver> mFrameMetricsObservers;
4542
4543    /**
4544     * Flag indicating that a drag can cross window boundaries.  When
4545     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called
4546     * with this flag set, all visible applications with targetSdkVersion >=
4547     * {@link android.os.Build.VERSION_CODES#N API 24} will be able to participate
4548     * in the drag operation and receive the dragged content.
4549     *
4550     * <p>If this is the only flag set, then the drag recipient will only have access to text data
4551     * and intents contained in the {@link ClipData} object. Access to URIs contained in the
4552     * {@link ClipData} is determined by other DRAG_FLAG_GLOBAL_* flags</p>
4553     */
4554    public static final int DRAG_FLAG_GLOBAL = 1 << 8;  // 256
4555
4556    /**
4557     * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to
4558     * request read access to the content URI(s) contained in the {@link ClipData} object.
4559     * @see android.content.Intent#FLAG_GRANT_READ_URI_PERMISSION
4560     */
4561    public static final int DRAG_FLAG_GLOBAL_URI_READ = Intent.FLAG_GRANT_READ_URI_PERMISSION;
4562
4563    /**
4564     * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to
4565     * request write access to the content URI(s) contained in the {@link ClipData} object.
4566     * @see android.content.Intent#FLAG_GRANT_WRITE_URI_PERMISSION
4567     */
4568    public static final int DRAG_FLAG_GLOBAL_URI_WRITE = Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
4569
4570    /**
4571     * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link
4572     * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant can be persisted across device
4573     * reboots until explicitly revoked with
4574     * {@link android.content.Context#revokeUriPermission(Uri, int)} Context.revokeUriPermission}.
4575     * @see android.content.Intent#FLAG_GRANT_PERSISTABLE_URI_PERMISSION
4576     */
4577    public static final int DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION =
4578            Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION;
4579
4580    /**
4581     * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link
4582     * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant applies to any URI that is a prefix
4583     * match against the original granted URI.
4584     * @see android.content.Intent#FLAG_GRANT_PREFIX_URI_PERMISSION
4585     */
4586    public static final int DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION =
4587            Intent.FLAG_GRANT_PREFIX_URI_PERMISSION;
4588
4589    /**
4590     * Flag indicating that the drag shadow will be opaque.  When
4591     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called
4592     * with this flag set, the drag shadow will be opaque, otherwise, it will be semitransparent.
4593     */
4594    public static final int DRAG_FLAG_OPAQUE = 1 << 9;
4595
4596    /**
4597     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
4598     */
4599    private float mVerticalScrollFactor;
4600
4601    /**
4602     * Position of the vertical scroll bar.
4603     */
4604    private int mVerticalScrollbarPosition;
4605
4606    /**
4607     * Position the scroll bar at the default position as determined by the system.
4608     */
4609    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
4610
4611    /**
4612     * Position the scroll bar along the left edge.
4613     */
4614    public static final int SCROLLBAR_POSITION_LEFT = 1;
4615
4616    /**
4617     * Position the scroll bar along the right edge.
4618     */
4619    public static final int SCROLLBAR_POSITION_RIGHT = 2;
4620
4621    /**
4622     * Indicates that the view does not have a layer.
4623     *
4624     * @see #getLayerType()
4625     * @see #setLayerType(int, android.graphics.Paint)
4626     * @see #LAYER_TYPE_SOFTWARE
4627     * @see #LAYER_TYPE_HARDWARE
4628     */
4629    public static final int LAYER_TYPE_NONE = 0;
4630
4631    /**
4632     * <p>Indicates that the view has a software layer. A software layer is backed
4633     * by a bitmap and causes the view to be rendered using Android's software
4634     * rendering pipeline, even if hardware acceleration is enabled.</p>
4635     *
4636     * <p>Software layers have various usages:</p>
4637     * <p>When the application is not using hardware acceleration, a software layer
4638     * is useful to apply a specific color filter and/or blending mode and/or
4639     * translucency to a view and all its children.</p>
4640     * <p>When the application is using hardware acceleration, a software layer
4641     * is useful to render drawing primitives not supported by the hardware
4642     * accelerated pipeline. It can also be used to cache a complex view tree
4643     * into a texture and reduce the complexity of drawing operations. For instance,
4644     * when animating a complex view tree with a translation, a software layer can
4645     * be used to render the view tree only once.</p>
4646     * <p>Software layers should be avoided when the affected view tree updates
4647     * often. Every update will require to re-render the software layer, which can
4648     * potentially be slow (particularly when hardware acceleration is turned on
4649     * since the layer will have to be uploaded into a hardware texture after every
4650     * update.)</p>
4651     *
4652     * @see #getLayerType()
4653     * @see #setLayerType(int, android.graphics.Paint)
4654     * @see #LAYER_TYPE_NONE
4655     * @see #LAYER_TYPE_HARDWARE
4656     */
4657    public static final int LAYER_TYPE_SOFTWARE = 1;
4658
4659    /**
4660     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
4661     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
4662     * OpenGL hardware) and causes the view to be rendered using Android's hardware
4663     * rendering pipeline, but only if hardware acceleration is turned on for the
4664     * view hierarchy. When hardware acceleration is turned off, hardware layers
4665     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
4666     *
4667     * <p>A hardware layer is useful to apply a specific color filter and/or
4668     * blending mode and/or translucency to a view and all its children.</p>
4669     * <p>A hardware layer can be used to cache a complex view tree into a
4670     * texture and reduce the complexity of drawing operations. For instance,
4671     * when animating a complex view tree with a translation, a hardware layer can
4672     * be used to render the view tree only once.</p>
4673     * <p>A hardware layer can also be used to increase the rendering quality when
4674     * rotation transformations are applied on a view. It can also be used to
4675     * prevent potential clipping issues when applying 3D transforms on a view.</p>
4676     *
4677     * @see #getLayerType()
4678     * @see #setLayerType(int, android.graphics.Paint)
4679     * @see #LAYER_TYPE_NONE
4680     * @see #LAYER_TYPE_SOFTWARE
4681     */
4682    public static final int LAYER_TYPE_HARDWARE = 2;
4683
4684    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
4685            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
4686            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
4687            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
4688    })
4689    int mLayerType = LAYER_TYPE_NONE;
4690    Paint mLayerPaint;
4691
4692    /**
4693     * Set to true when drawing cache is enabled and cannot be created.
4694     *
4695     * @hide
4696     */
4697    public boolean mCachingFailed;
4698    private Bitmap mDrawingCache;
4699    private Bitmap mUnscaledDrawingCache;
4700
4701    /**
4702     * RenderNode holding View properties, potentially holding a DisplayList of View content.
4703     * <p>
4704     * When non-null and valid, this is expected to contain an up-to-date copy
4705     * of the View content. Its DisplayList content is cleared on temporary detach and reset on
4706     * cleanup.
4707     */
4708    final RenderNode mRenderNode;
4709
4710    /**
4711     * Set to true when the view is sending hover accessibility events because it
4712     * is the innermost hovered view.
4713     */
4714    private boolean mSendingHoverAccessibilityEvents;
4715
4716    /**
4717     * Delegate for injecting accessibility functionality.
4718     */
4719    AccessibilityDelegate mAccessibilityDelegate;
4720
4721    /**
4722     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
4723     * and add/remove objects to/from the overlay directly through the Overlay methods.
4724     */
4725    ViewOverlay mOverlay;
4726
4727    /**
4728     * The currently active parent view for receiving delegated nested scrolling events.
4729     * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared
4730     * by {@link #stopNestedScroll()} at the same point where we clear
4731     * requestDisallowInterceptTouchEvent.
4732     */
4733    private ViewParent mNestedScrollingParent;
4734
4735    /**
4736     * Consistency verifier for debugging purposes.
4737     * @hide
4738     */
4739    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
4740            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
4741                    new InputEventConsistencyVerifier(this, 0) : null;
4742
4743    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
4744
4745    private int[] mTempNestedScrollConsumed;
4746
4747    /**
4748     * An overlay is going to draw this View instead of being drawn as part of this
4749     * View's parent. mGhostView is the View in the Overlay that must be invalidated
4750     * when this view is invalidated.
4751     */
4752    GhostView mGhostView;
4753
4754    /**
4755     * Holds pairs of adjacent attribute data: attribute name followed by its value.
4756     * @hide
4757     */
4758    @ViewDebug.ExportedProperty(category = "attributes", hasAdjacentMapping = true)
4759    public String[] mAttributes;
4760
4761    /**
4762     * Maps a Resource id to its name.
4763     */
4764    private static SparseArray<String> mAttributeMap;
4765
4766    /**
4767     * Queue of pending runnables. Used to postpone calls to post() until this
4768     * view is attached and has a handler.
4769     */
4770    private HandlerActionQueue mRunQueue;
4771
4772    /**
4773     * The pointer icon when the mouse hovers on this view. The default is null.
4774     */
4775    private PointerIcon mPointerIcon;
4776
4777    /**
4778     * @hide
4779     */
4780    String mStartActivityRequestWho;
4781
4782    @Nullable
4783    private RoundScrollbarRenderer mRoundScrollbarRenderer;
4784
4785    /** Used to delay visibility updates sent to the autofill manager */
4786    private Handler mVisibilityChangeForAutofillHandler;
4787
4788    /**
4789     * Simple constructor to use when creating a view from code.
4790     *
4791     * @param context The Context the view is running in, through which it can
4792     *        access the current theme, resources, etc.
4793     */
4794    public View(Context context) {
4795        mContext = context;
4796        mResources = context != null ? context.getResources() : null;
4797        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED | FOCUSABLE_AUTO;
4798        // Set some flags defaults
4799        mPrivateFlags2 =
4800                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
4801                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
4802                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
4803                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
4804                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
4805                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
4806        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
4807        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
4808        mUserPaddingStart = UNDEFINED_PADDING;
4809        mUserPaddingEnd = UNDEFINED_PADDING;
4810        mRenderNode = RenderNode.create(getClass().getName(), this);
4811
4812        if (!sCompatibilityDone && context != null) {
4813            final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
4814
4815            // Older apps may need this compatibility hack for measurement.
4816            sUseBrokenMakeMeasureSpec = targetSdkVersion <= Build.VERSION_CODES.JELLY_BEAN_MR1;
4817
4818            // Older apps expect onMeasure() to always be called on a layout pass, regardless
4819            // of whether a layout was requested on that View.
4820            sIgnoreMeasureCache = targetSdkVersion < Build.VERSION_CODES.KITKAT;
4821
4822            Canvas.sCompatibilityRestore = targetSdkVersion < Build.VERSION_CODES.M;
4823            Canvas.sCompatibilitySetBitmap = targetSdkVersion < Build.VERSION_CODES.O;
4824            Canvas.setCompatibilityVersion(targetSdkVersion);
4825
4826            // In M and newer, our widgets can pass a "hint" value in the size
4827            // for UNSPECIFIED MeasureSpecs. This lets child views of scrolling containers
4828            // know what the expected parent size is going to be, so e.g. list items can size
4829            // themselves at 1/3 the size of their container. It breaks older apps though,
4830            // specifically apps that use some popular open source libraries.
4831            sUseZeroUnspecifiedMeasureSpec = targetSdkVersion < Build.VERSION_CODES.M;
4832
4833            // Old versions of the platform would give different results from
4834            // LinearLayout measurement passes using EXACTLY and non-EXACTLY
4835            // modes, so we always need to run an additional EXACTLY pass.
4836            sAlwaysRemeasureExactly = targetSdkVersion <= Build.VERSION_CODES.M;
4837
4838            // Prior to N, layout params could change without requiring a
4839            // subsequent call to setLayoutParams() and they would usually
4840            // work. Partial layout breaks this assumption.
4841            sLayoutParamsAlwaysChanged = targetSdkVersion <= Build.VERSION_CODES.M;
4842
4843            // Prior to N, TextureView would silently ignore calls to setBackground/setForeground.
4844            // On N+, we throw, but that breaks compatibility with apps that use these methods.
4845            sTextureViewIgnoresDrawableSetters = targetSdkVersion <= Build.VERSION_CODES.M;
4846
4847            // Prior to N, we would drop margins in LayoutParam conversions. The fix triggers bugs
4848            // in apps so we target check it to avoid breaking existing apps.
4849            sPreserveMarginParamsInLayoutParamConversion =
4850                    targetSdkVersion >= Build.VERSION_CODES.N;
4851
4852            sCascadedDragDrop = targetSdkVersion < Build.VERSION_CODES.N;
4853
4854            sHasFocusableExcludeAutoFocusable = targetSdkVersion < Build.VERSION_CODES.O;
4855
4856            sAutoFocusableOffUIThreadWontNotifyParents = targetSdkVersion < Build.VERSION_CODES.O;
4857
4858            sUseDefaultFocusHighlight = context.getResources().getBoolean(
4859                    com.android.internal.R.bool.config_useDefaultFocusHighlight);
4860
4861            sThrowOnInvalidFloatProperties = targetSdkVersion >= Build.VERSION_CODES.P;
4862
4863            sCanFocusZeroSized = targetSdkVersion < Build.VERSION_CODES.P;
4864
4865            sAlwaysAssignFocus = targetSdkVersion < Build.VERSION_CODES.P;
4866
4867            sAcceptZeroSizeDragShadow = targetSdkVersion < Build.VERSION_CODES.P;
4868
4869            sCompatibilityDone = true;
4870        }
4871    }
4872
4873    /**
4874     * Constructor that is called when inflating a view from XML. This is called
4875     * when a view is being constructed from an XML file, supplying attributes
4876     * that were specified in the XML file. This version uses a default style of
4877     * 0, so the only attribute values applied are those in the Context's Theme
4878     * and the given AttributeSet.
4879     *
4880     * <p>
4881     * The method onFinishInflate() will be called after all children have been
4882     * added.
4883     *
4884     * @param context The Context the view is running in, through which it can
4885     *        access the current theme, resources, etc.
4886     * @param attrs The attributes of the XML tag that is inflating the view.
4887     * @see #View(Context, AttributeSet, int)
4888     */
4889    public View(Context context, @Nullable AttributeSet attrs) {
4890        this(context, attrs, 0);
4891    }
4892
4893    /**
4894     * Perform inflation from XML and apply a class-specific base style from a
4895     * theme attribute. This constructor of View allows subclasses to use their
4896     * own base style when they are inflating. For example, a Button class's
4897     * constructor would call this version of the super class constructor and
4898     * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this
4899     * allows the theme's button style to modify all of the base view attributes
4900     * (in particular its background) as well as the Button class's attributes.
4901     *
4902     * @param context The Context the view is running in, through which it can
4903     *        access the current theme, resources, etc.
4904     * @param attrs The attributes of the XML tag that is inflating the view.
4905     * @param defStyleAttr An attribute in the current theme that contains a
4906     *        reference to a style resource that supplies default values for
4907     *        the view. Can be 0 to not look for defaults.
4908     * @see #View(Context, AttributeSet)
4909     */
4910    public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
4911        this(context, attrs, defStyleAttr, 0);
4912    }
4913
4914    /**
4915     * Perform inflation from XML and apply a class-specific base style from a
4916     * theme attribute or style resource. This constructor of View allows
4917     * subclasses to use their own base style when they are inflating.
4918     * <p>
4919     * When determining the final value of a particular attribute, there are
4920     * four inputs that come into play:
4921     * <ol>
4922     * <li>Any attribute values in the given AttributeSet.
4923     * <li>The style resource specified in the AttributeSet (named "style").
4924     * <li>The default style specified by <var>defStyleAttr</var>.
4925     * <li>The default style specified by <var>defStyleRes</var>.
4926     * <li>The base values in this theme.
4927     * </ol>
4928     * <p>
4929     * Each of these inputs is considered in-order, with the first listed taking
4930     * precedence over the following ones. In other words, if in the
4931     * AttributeSet you have supplied <code>&lt;Button * textColor="#ff000000"&gt;</code>
4932     * , then the button's text will <em>always</em> be black, regardless of
4933     * what is specified in any of the styles.
4934     *
4935     * @param context The Context the view is running in, through which it can
4936     *        access the current theme, resources, etc.
4937     * @param attrs The attributes of the XML tag that is inflating the view.
4938     * @param defStyleAttr An attribute in the current theme that contains a
4939     *        reference to a style resource that supplies default values for
4940     *        the view. Can be 0 to not look for defaults.
4941     * @param defStyleRes A resource identifier of a style resource that
4942     *        supplies default values for the view, used only if
4943     *        defStyleAttr is 0 or can not be found in the theme. Can be 0
4944     *        to not look for defaults.
4945     * @see #View(Context, AttributeSet, int)
4946     */
4947    public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
4948        this(context);
4949
4950        final TypedArray a = context.obtainStyledAttributes(
4951                attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes);
4952
4953        if (mDebugViewAttributes) {
4954            saveAttributeData(attrs, a);
4955        }
4956
4957        Drawable background = null;
4958
4959        int leftPadding = -1;
4960        int topPadding = -1;
4961        int rightPadding = -1;
4962        int bottomPadding = -1;
4963        int startPadding = UNDEFINED_PADDING;
4964        int endPadding = UNDEFINED_PADDING;
4965
4966        int padding = -1;
4967        int paddingHorizontal = -1;
4968        int paddingVertical = -1;
4969
4970        int viewFlagValues = 0;
4971        int viewFlagMasks = 0;
4972
4973        boolean setScrollContainer = false;
4974
4975        int x = 0;
4976        int y = 0;
4977
4978        float tx = 0;
4979        float ty = 0;
4980        float tz = 0;
4981        float elevation = 0;
4982        float rotation = 0;
4983        float rotationX = 0;
4984        float rotationY = 0;
4985        float sx = 1f;
4986        float sy = 1f;
4987        boolean transformSet = false;
4988
4989        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
4990        int overScrollMode = mOverScrollMode;
4991        boolean initializeScrollbars = false;
4992        boolean initializeScrollIndicators = false;
4993
4994        boolean startPaddingDefined = false;
4995        boolean endPaddingDefined = false;
4996        boolean leftPaddingDefined = false;
4997        boolean rightPaddingDefined = false;
4998
4999        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
5000
5001        // Set default values.
5002        viewFlagValues |= FOCUSABLE_AUTO;
5003        viewFlagMasks |= FOCUSABLE_AUTO;
5004
5005        final int N = a.getIndexCount();
5006        for (int i = 0; i < N; i++) {
5007            int attr = a.getIndex(i);
5008            switch (attr) {
5009                case com.android.internal.R.styleable.View_background:
5010                    background = a.getDrawable(attr);
5011                    break;
5012                case com.android.internal.R.styleable.View_padding:
5013                    padding = a.getDimensionPixelSize(attr, -1);
5014                    mUserPaddingLeftInitial = padding;
5015                    mUserPaddingRightInitial = padding;
5016                    leftPaddingDefined = true;
5017                    rightPaddingDefined = true;
5018                    break;
5019                case com.android.internal.R.styleable.View_paddingHorizontal:
5020                    paddingHorizontal = a.getDimensionPixelSize(attr, -1);
5021                    mUserPaddingLeftInitial = paddingHorizontal;
5022                    mUserPaddingRightInitial = paddingHorizontal;
5023                    leftPaddingDefined = true;
5024                    rightPaddingDefined = true;
5025                    break;
5026                case com.android.internal.R.styleable.View_paddingVertical:
5027                    paddingVertical = a.getDimensionPixelSize(attr, -1);
5028                    break;
5029                 case com.android.internal.R.styleable.View_paddingLeft:
5030                    leftPadding = a.getDimensionPixelSize(attr, -1);
5031                    mUserPaddingLeftInitial = leftPadding;
5032                    leftPaddingDefined = true;
5033                    break;
5034                case com.android.internal.R.styleable.View_paddingTop:
5035                    topPadding = a.getDimensionPixelSize(attr, -1);
5036                    break;
5037                case com.android.internal.R.styleable.View_paddingRight:
5038                    rightPadding = a.getDimensionPixelSize(attr, -1);
5039                    mUserPaddingRightInitial = rightPadding;
5040                    rightPaddingDefined = true;
5041                    break;
5042                case com.android.internal.R.styleable.View_paddingBottom:
5043                    bottomPadding = a.getDimensionPixelSize(attr, -1);
5044                    break;
5045                case com.android.internal.R.styleable.View_paddingStart:
5046                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
5047                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
5048                    break;
5049                case com.android.internal.R.styleable.View_paddingEnd:
5050                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
5051                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
5052                    break;
5053                case com.android.internal.R.styleable.View_scrollX:
5054                    x = a.getDimensionPixelOffset(attr, 0);
5055                    break;
5056                case com.android.internal.R.styleable.View_scrollY:
5057                    y = a.getDimensionPixelOffset(attr, 0);
5058                    break;
5059                case com.android.internal.R.styleable.View_alpha:
5060                    setAlpha(a.getFloat(attr, 1f));
5061                    break;
5062                case com.android.internal.R.styleable.View_transformPivotX:
5063                    setPivotX(a.getDimension(attr, 0));
5064                    break;
5065                case com.android.internal.R.styleable.View_transformPivotY:
5066                    setPivotY(a.getDimension(attr, 0));
5067                    break;
5068                case com.android.internal.R.styleable.View_translationX:
5069                    tx = a.getDimension(attr, 0);
5070                    transformSet = true;
5071                    break;
5072                case com.android.internal.R.styleable.View_translationY:
5073                    ty = a.getDimension(attr, 0);
5074                    transformSet = true;
5075                    break;
5076                case com.android.internal.R.styleable.View_translationZ:
5077                    tz = a.getDimension(attr, 0);
5078                    transformSet = true;
5079                    break;
5080                case com.android.internal.R.styleable.View_elevation:
5081                    elevation = a.getDimension(attr, 0);
5082                    transformSet = true;
5083                    break;
5084                case com.android.internal.R.styleable.View_rotation:
5085                    rotation = a.getFloat(attr, 0);
5086                    transformSet = true;
5087                    break;
5088                case com.android.internal.R.styleable.View_rotationX:
5089                    rotationX = a.getFloat(attr, 0);
5090                    transformSet = true;
5091                    break;
5092                case com.android.internal.R.styleable.View_rotationY:
5093                    rotationY = a.getFloat(attr, 0);
5094                    transformSet = true;
5095                    break;
5096                case com.android.internal.R.styleable.View_scaleX:
5097                    sx = a.getFloat(attr, 1f);
5098                    transformSet = true;
5099                    break;
5100                case com.android.internal.R.styleable.View_scaleY:
5101                    sy = a.getFloat(attr, 1f);
5102                    transformSet = true;
5103                    break;
5104                case com.android.internal.R.styleable.View_id:
5105                    mID = a.getResourceId(attr, NO_ID);
5106                    break;
5107                case com.android.internal.R.styleable.View_tag:
5108                    mTag = a.getText(attr);
5109                    break;
5110                case com.android.internal.R.styleable.View_fitsSystemWindows:
5111                    if (a.getBoolean(attr, false)) {
5112                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
5113                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
5114                    }
5115                    break;
5116                case com.android.internal.R.styleable.View_focusable:
5117                    viewFlagValues = (viewFlagValues & ~FOCUSABLE_MASK) | getFocusableAttribute(a);
5118                    if ((viewFlagValues & FOCUSABLE_AUTO) == 0) {
5119                        viewFlagMasks |= FOCUSABLE_MASK;
5120                    }
5121                    break;
5122                case com.android.internal.R.styleable.View_focusableInTouchMode:
5123                    if (a.getBoolean(attr, false)) {
5124                        // unset auto focus since focusableInTouchMode implies explicit focusable
5125                        viewFlagValues &= ~FOCUSABLE_AUTO;
5126                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
5127                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
5128                    }
5129                    break;
5130                case com.android.internal.R.styleable.View_clickable:
5131                    if (a.getBoolean(attr, false)) {
5132                        viewFlagValues |= CLICKABLE;
5133                        viewFlagMasks |= CLICKABLE;
5134                    }
5135                    break;
5136                case com.android.internal.R.styleable.View_longClickable:
5137                    if (a.getBoolean(attr, false)) {
5138                        viewFlagValues |= LONG_CLICKABLE;
5139                        viewFlagMasks |= LONG_CLICKABLE;
5140                    }
5141                    break;
5142                case com.android.internal.R.styleable.View_contextClickable:
5143                    if (a.getBoolean(attr, false)) {
5144                        viewFlagValues |= CONTEXT_CLICKABLE;
5145                        viewFlagMasks |= CONTEXT_CLICKABLE;
5146                    }
5147                    break;
5148                case com.android.internal.R.styleable.View_saveEnabled:
5149                    if (!a.getBoolean(attr, true)) {
5150                        viewFlagValues |= SAVE_DISABLED;
5151                        viewFlagMasks |= SAVE_DISABLED_MASK;
5152                    }
5153                    break;
5154                case com.android.internal.R.styleable.View_duplicateParentState:
5155                    if (a.getBoolean(attr, false)) {
5156                        viewFlagValues |= DUPLICATE_PARENT_STATE;
5157                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
5158                    }
5159                    break;
5160                case com.android.internal.R.styleable.View_visibility:
5161                    final int visibility = a.getInt(attr, 0);
5162                    if (visibility != 0) {
5163                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
5164                        viewFlagMasks |= VISIBILITY_MASK;
5165                    }
5166                    break;
5167                case com.android.internal.R.styleable.View_layoutDirection:
5168                    // Clear any layout direction flags (included resolved bits) already set
5169                    mPrivateFlags2 &=
5170                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
5171                    // Set the layout direction flags depending on the value of the attribute
5172                    final int layoutDirection = a.getInt(attr, -1);
5173                    final int value = (layoutDirection != -1) ?
5174                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
5175                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
5176                    break;
5177                case com.android.internal.R.styleable.View_drawingCacheQuality:
5178                    final int cacheQuality = a.getInt(attr, 0);
5179                    if (cacheQuality != 0) {
5180                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
5181                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
5182                    }
5183                    break;
5184                case com.android.internal.R.styleable.View_contentDescription:
5185                    setContentDescription(a.getString(attr));
5186                    break;
5187                case com.android.internal.R.styleable.View_accessibilityTraversalBefore:
5188                    setAccessibilityTraversalBefore(a.getResourceId(attr, NO_ID));
5189                    break;
5190                case com.android.internal.R.styleable.View_accessibilityTraversalAfter:
5191                    setAccessibilityTraversalAfter(a.getResourceId(attr, NO_ID));
5192                    break;
5193                case com.android.internal.R.styleable.View_labelFor:
5194                    setLabelFor(a.getResourceId(attr, NO_ID));
5195                    break;
5196                case com.android.internal.R.styleable.View_soundEffectsEnabled:
5197                    if (!a.getBoolean(attr, true)) {
5198                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
5199                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
5200                    }
5201                    break;
5202                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
5203                    if (!a.getBoolean(attr, true)) {
5204                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
5205                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
5206                    }
5207                    break;
5208                case R.styleable.View_scrollbars:
5209                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
5210                    if (scrollbars != SCROLLBARS_NONE) {
5211                        viewFlagValues |= scrollbars;
5212                        viewFlagMasks |= SCROLLBARS_MASK;
5213                        initializeScrollbars = true;
5214                    }
5215                    break;
5216                //noinspection deprecation
5217                case R.styleable.View_fadingEdge:
5218                    if (targetSdkVersion >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
5219                        // Ignore the attribute starting with ICS
5220                        break;
5221                    }
5222                    // With builds < ICS, fall through and apply fading edges
5223                case R.styleable.View_requiresFadingEdge:
5224                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
5225                    if (fadingEdge != FADING_EDGE_NONE) {
5226                        viewFlagValues |= fadingEdge;
5227                        viewFlagMasks |= FADING_EDGE_MASK;
5228                        initializeFadingEdgeInternal(a);
5229                    }
5230                    break;
5231                case R.styleable.View_scrollbarStyle:
5232                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
5233                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
5234                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
5235                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
5236                    }
5237                    break;
5238                case R.styleable.View_isScrollContainer:
5239                    setScrollContainer = true;
5240                    if (a.getBoolean(attr, false)) {
5241                        setScrollContainer(true);
5242                    }
5243                    break;
5244                case com.android.internal.R.styleable.View_keepScreenOn:
5245                    if (a.getBoolean(attr, false)) {
5246                        viewFlagValues |= KEEP_SCREEN_ON;
5247                        viewFlagMasks |= KEEP_SCREEN_ON;
5248                    }
5249                    break;
5250                case R.styleable.View_filterTouchesWhenObscured:
5251                    if (a.getBoolean(attr, false)) {
5252                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
5253                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
5254                    }
5255                    break;
5256                case R.styleable.View_nextFocusLeft:
5257                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
5258                    break;
5259                case R.styleable.View_nextFocusRight:
5260                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
5261                    break;
5262                case R.styleable.View_nextFocusUp:
5263                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
5264                    break;
5265                case R.styleable.View_nextFocusDown:
5266                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
5267                    break;
5268                case R.styleable.View_nextFocusForward:
5269                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
5270                    break;
5271                case R.styleable.View_nextClusterForward:
5272                    mNextClusterForwardId = a.getResourceId(attr, View.NO_ID);
5273                    break;
5274                case R.styleable.View_minWidth:
5275                    mMinWidth = a.getDimensionPixelSize(attr, 0);
5276                    break;
5277                case R.styleable.View_minHeight:
5278                    mMinHeight = a.getDimensionPixelSize(attr, 0);
5279                    break;
5280                case R.styleable.View_onClick:
5281                    if (context.isRestricted()) {
5282                        throw new IllegalStateException("The android:onClick attribute cannot "
5283                                + "be used within a restricted context");
5284                    }
5285
5286                    final String handlerName = a.getString(attr);
5287                    if (handlerName != null) {
5288                        setOnClickListener(new DeclaredOnClickListener(this, handlerName));
5289                    }
5290                    break;
5291                case R.styleable.View_overScrollMode:
5292                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
5293                    break;
5294                case R.styleable.View_verticalScrollbarPosition:
5295                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
5296                    break;
5297                case R.styleable.View_layerType:
5298                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
5299                    break;
5300                case R.styleable.View_textDirection:
5301                    // Clear any text direction flag already set
5302                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
5303                    // Set the text direction flags depending on the value of the attribute
5304                    final int textDirection = a.getInt(attr, -1);
5305                    if (textDirection != -1) {
5306                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
5307                    }
5308                    break;
5309                case R.styleable.View_textAlignment:
5310                    // Clear any text alignment flag already set
5311                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
5312                    // Set the text alignment flag depending on the value of the attribute
5313                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
5314                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
5315                    break;
5316                case R.styleable.View_importantForAccessibility:
5317                    setImportantForAccessibility(a.getInt(attr,
5318                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
5319                    break;
5320                case R.styleable.View_accessibilityLiveRegion:
5321                    setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT));
5322                    break;
5323                case R.styleable.View_transitionName:
5324                    setTransitionName(a.getString(attr));
5325                    break;
5326                case R.styleable.View_nestedScrollingEnabled:
5327                    setNestedScrollingEnabled(a.getBoolean(attr, false));
5328                    break;
5329                case R.styleable.View_stateListAnimator:
5330                    setStateListAnimator(AnimatorInflater.loadStateListAnimator(context,
5331                            a.getResourceId(attr, 0)));
5332                    break;
5333                case R.styleable.View_backgroundTint:
5334                    // This will get applied later during setBackground().
5335                    if (mBackgroundTint == null) {
5336                        mBackgroundTint = new TintInfo();
5337                    }
5338                    mBackgroundTint.mTintList = a.getColorStateList(
5339                            R.styleable.View_backgroundTint);
5340                    mBackgroundTint.mHasTintList = true;
5341                    break;
5342                case R.styleable.View_backgroundTintMode:
5343                    // This will get applied later during setBackground().
5344                    if (mBackgroundTint == null) {
5345                        mBackgroundTint = new TintInfo();
5346                    }
5347                    mBackgroundTint.mTintMode = Drawable.parseTintMode(a.getInt(
5348                            R.styleable.View_backgroundTintMode, -1), null);
5349                    mBackgroundTint.mHasTintMode = true;
5350                    break;
5351                case R.styleable.View_outlineProvider:
5352                    setOutlineProviderFromAttribute(a.getInt(R.styleable.View_outlineProvider,
5353                            PROVIDER_BACKGROUND));
5354                    break;
5355                case R.styleable.View_foreground:
5356                    if (targetSdkVersion >= Build.VERSION_CODES.M || this instanceof FrameLayout) {
5357                        setForeground(a.getDrawable(attr));
5358                    }
5359                    break;
5360                case R.styleable.View_foregroundGravity:
5361                    if (targetSdkVersion >= Build.VERSION_CODES.M || this instanceof FrameLayout) {
5362                        setForegroundGravity(a.getInt(attr, Gravity.NO_GRAVITY));
5363                    }
5364                    break;
5365                case R.styleable.View_foregroundTintMode:
5366                    if (targetSdkVersion >= Build.VERSION_CODES.M || this instanceof FrameLayout) {
5367                        setForegroundTintMode(Drawable.parseTintMode(a.getInt(attr, -1), null));
5368                    }
5369                    break;
5370                case R.styleable.View_foregroundTint:
5371                    if (targetSdkVersion >= Build.VERSION_CODES.M || this instanceof FrameLayout) {
5372                        setForegroundTintList(a.getColorStateList(attr));
5373                    }
5374                    break;
5375                case R.styleable.View_foregroundInsidePadding:
5376                    if (targetSdkVersion >= Build.VERSION_CODES.M || this instanceof FrameLayout) {
5377                        if (mForegroundInfo == null) {
5378                            mForegroundInfo = new ForegroundInfo();
5379                        }
5380                        mForegroundInfo.mInsidePadding = a.getBoolean(attr,
5381                                mForegroundInfo.mInsidePadding);
5382                    }
5383                    break;
5384                case R.styleable.View_scrollIndicators:
5385                    final int scrollIndicators =
5386                            (a.getInt(attr, 0) << SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT)
5387                                    & SCROLL_INDICATORS_PFLAG3_MASK;
5388                    if (scrollIndicators != 0) {
5389                        mPrivateFlags3 |= scrollIndicators;
5390                        initializeScrollIndicators = true;
5391                    }
5392                    break;
5393                case R.styleable.View_pointerIcon:
5394                    final int resourceId = a.getResourceId(attr, 0);
5395                    if (resourceId != 0) {
5396                        setPointerIcon(PointerIcon.load(
5397                                context.getResources(), resourceId));
5398                    } else {
5399                        final int pointerType = a.getInt(attr, PointerIcon.TYPE_NOT_SPECIFIED);
5400                        if (pointerType != PointerIcon.TYPE_NOT_SPECIFIED) {
5401                            setPointerIcon(PointerIcon.getSystemIcon(context, pointerType));
5402                        }
5403                    }
5404                    break;
5405                case R.styleable.View_forceHasOverlappingRendering:
5406                    if (a.peekValue(attr) != null) {
5407                        forceHasOverlappingRendering(a.getBoolean(attr, true));
5408                    }
5409                    break;
5410                case R.styleable.View_tooltipText:
5411                    setTooltipText(a.getText(attr));
5412                    break;
5413                case R.styleable.View_keyboardNavigationCluster:
5414                    if (a.peekValue(attr) != null) {
5415                        setKeyboardNavigationCluster(a.getBoolean(attr, true));
5416                    }
5417                    break;
5418                case R.styleable.View_focusedByDefault:
5419                    if (a.peekValue(attr) != null) {
5420                        setFocusedByDefault(a.getBoolean(attr, true));
5421                    }
5422                    break;
5423                case R.styleable.View_autofillHints:
5424                    if (a.peekValue(attr) != null) {
5425                        CharSequence[] rawHints = null;
5426                        String rawString = null;
5427
5428                        if (a.getType(attr) == TypedValue.TYPE_REFERENCE) {
5429                            int resId = a.getResourceId(attr, 0);
5430
5431                            try {
5432                                rawHints = a.getTextArray(attr);
5433                            } catch (Resources.NotFoundException e) {
5434                                rawString = getResources().getString(resId);
5435                            }
5436                        } else {
5437                            rawString = a.getString(attr);
5438                        }
5439
5440                        if (rawHints == null) {
5441                            if (rawString == null) {
5442                                throw new IllegalArgumentException(
5443                                        "Could not resolve autofillHints");
5444                            } else {
5445                                rawHints = rawString.split(",");
5446                            }
5447                        }
5448
5449                        String[] hints = new String[rawHints.length];
5450
5451                        int numHints = rawHints.length;
5452                        for (int rawHintNum = 0; rawHintNum < numHints; rawHintNum++) {
5453                            hints[rawHintNum] = rawHints[rawHintNum].toString().trim();
5454                        }
5455                        setAutofillHints(hints);
5456                    }
5457                    break;
5458                case R.styleable.View_importantForAutofill:
5459                    if (a.peekValue(attr) != null) {
5460                        setImportantForAutofill(a.getInt(attr, IMPORTANT_FOR_AUTOFILL_AUTO));
5461                    }
5462                    break;
5463                case R.styleable.View_defaultFocusHighlightEnabled:
5464                    if (a.peekValue(attr) != null) {
5465                        setDefaultFocusHighlightEnabled(a.getBoolean(attr, true));
5466                    }
5467                    break;
5468                case R.styleable.View_screenReaderFocusable:
5469                    if (a.peekValue(attr) != null) {
5470                        setScreenReaderFocusable(a.getBoolean(attr, false));
5471                    }
5472                    break;
5473                case R.styleable.View_accessibilityPaneTitle:
5474                    if (a.peekValue(attr) != null) {
5475                        setAccessibilityPaneTitle(a.getString(attr));
5476                    }
5477                    break;
5478                case R.styleable.View_outlineSpotShadowColor:
5479                    setOutlineSpotShadowColor(a.getColor(attr, Color.BLACK));
5480                    break;
5481                case R.styleable.View_outlineAmbientShadowColor:
5482                    setOutlineAmbientShadowColor(a.getColor(attr, Color.BLACK));
5483                    break;
5484                case com.android.internal.R.styleable.View_accessibilityHeading:
5485                    setAccessibilityHeading(a.getBoolean(attr, false));
5486            }
5487        }
5488
5489        setOverScrollMode(overScrollMode);
5490
5491        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
5492        // the resolved layout direction). Those cached values will be used later during padding
5493        // resolution.
5494        mUserPaddingStart = startPadding;
5495        mUserPaddingEnd = endPadding;
5496
5497        if (background != null) {
5498            setBackground(background);
5499        }
5500
5501        // setBackground above will record that padding is currently provided by the background.
5502        // If we have padding specified via xml, record that here instead and use it.
5503        mLeftPaddingDefined = leftPaddingDefined;
5504        mRightPaddingDefined = rightPaddingDefined;
5505
5506        if (padding >= 0) {
5507            leftPadding = padding;
5508            topPadding = padding;
5509            rightPadding = padding;
5510            bottomPadding = padding;
5511            mUserPaddingLeftInitial = padding;
5512            mUserPaddingRightInitial = padding;
5513        } else {
5514            if (paddingHorizontal >= 0) {
5515                leftPadding = paddingHorizontal;
5516                rightPadding = paddingHorizontal;
5517                mUserPaddingLeftInitial = paddingHorizontal;
5518                mUserPaddingRightInitial = paddingHorizontal;
5519            }
5520            if (paddingVertical >= 0) {
5521                topPadding = paddingVertical;
5522                bottomPadding = paddingVertical;
5523            }
5524        }
5525
5526        if (isRtlCompatibilityMode()) {
5527            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
5528            // left / right padding are used if defined (meaning here nothing to do). If they are not
5529            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
5530            // start / end and resolve them as left / right (layout direction is not taken into account).
5531            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
5532            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
5533            // defined.
5534            if (!mLeftPaddingDefined && startPaddingDefined) {
5535                leftPadding = startPadding;
5536            }
5537            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
5538            if (!mRightPaddingDefined && endPaddingDefined) {
5539                rightPadding = endPadding;
5540            }
5541            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
5542        } else {
5543            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
5544            // values defined. Otherwise, left /right values are used.
5545            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
5546            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
5547            // defined.
5548            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
5549
5550            if (mLeftPaddingDefined && !hasRelativePadding) {
5551                mUserPaddingLeftInitial = leftPadding;
5552            }
5553            if (mRightPaddingDefined && !hasRelativePadding) {
5554                mUserPaddingRightInitial = rightPadding;
5555            }
5556        }
5557
5558        internalSetPadding(
5559                mUserPaddingLeftInitial,
5560                topPadding >= 0 ? topPadding : mPaddingTop,
5561                mUserPaddingRightInitial,
5562                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
5563
5564        if (viewFlagMasks != 0) {
5565            setFlags(viewFlagValues, viewFlagMasks);
5566        }
5567
5568        if (initializeScrollbars) {
5569            initializeScrollbarsInternal(a);
5570        }
5571
5572        if (initializeScrollIndicators) {
5573            initializeScrollIndicatorsInternal();
5574        }
5575
5576        a.recycle();
5577
5578        // Needs to be called after mViewFlags is set
5579        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
5580            recomputePadding();
5581        }
5582
5583        if (x != 0 || y != 0) {
5584            scrollTo(x, y);
5585        }
5586
5587        if (transformSet) {
5588            setTranslationX(tx);
5589            setTranslationY(ty);
5590            setTranslationZ(tz);
5591            setElevation(elevation);
5592            setRotation(rotation);
5593            setRotationX(rotationX);
5594            setRotationY(rotationY);
5595            setScaleX(sx);
5596            setScaleY(sy);
5597        }
5598
5599        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
5600            setScrollContainer(true);
5601        }
5602
5603        computeOpaqueFlags();
5604    }
5605
5606    /**
5607     * An implementation of OnClickListener that attempts to lazily load a
5608     * named click handling method from a parent or ancestor context.
5609     */
5610    private static class DeclaredOnClickListener implements OnClickListener {
5611        private final View mHostView;
5612        private final String mMethodName;
5613
5614        private Method mResolvedMethod;
5615        private Context mResolvedContext;
5616
5617        public DeclaredOnClickListener(@NonNull View hostView, @NonNull String methodName) {
5618            mHostView = hostView;
5619            mMethodName = methodName;
5620        }
5621
5622        @Override
5623        public void onClick(@NonNull View v) {
5624            if (mResolvedMethod == null) {
5625                resolveMethod(mHostView.getContext(), mMethodName);
5626            }
5627
5628            try {
5629                mResolvedMethod.invoke(mResolvedContext, v);
5630            } catch (IllegalAccessException e) {
5631                throw new IllegalStateException(
5632                        "Could not execute non-public method for android:onClick", e);
5633            } catch (InvocationTargetException e) {
5634                throw new IllegalStateException(
5635                        "Could not execute method for android:onClick", e);
5636            }
5637        }
5638
5639        @NonNull
5640        private void resolveMethod(@Nullable Context context, @NonNull String name) {
5641            while (context != null) {
5642                try {
5643                    if (!context.isRestricted()) {
5644                        final Method method = context.getClass().getMethod(mMethodName, View.class);
5645                        if (method != null) {
5646                            mResolvedMethod = method;
5647                            mResolvedContext = context;
5648                            return;
5649                        }
5650                    }
5651                } catch (NoSuchMethodException e) {
5652                    // Failed to find method, keep searching up the hierarchy.
5653                }
5654
5655                if (context instanceof ContextWrapper) {
5656                    context = ((ContextWrapper) context).getBaseContext();
5657                } else {
5658                    // Can't search up the hierarchy, null out and fail.
5659                    context = null;
5660                }
5661            }
5662
5663            final int id = mHostView.getId();
5664            final String idText = id == NO_ID ? "" : " with id '"
5665                    + mHostView.getContext().getResources().getResourceEntryName(id) + "'";
5666            throw new IllegalStateException("Could not find method " + mMethodName
5667                    + "(View) in a parent or ancestor Context for android:onClick "
5668                    + "attribute defined on view " + mHostView.getClass() + idText);
5669        }
5670    }
5671
5672    /**
5673     * Non-public constructor for use in testing
5674     */
5675    View() {
5676        mResources = null;
5677        mRenderNode = RenderNode.create(getClass().getName(), this);
5678    }
5679
5680    final boolean debugDraw() {
5681        return DEBUG_DRAW || mAttachInfo != null && mAttachInfo.mDebugLayout;
5682    }
5683
5684    private static SparseArray<String> getAttributeMap() {
5685        if (mAttributeMap == null) {
5686            mAttributeMap = new SparseArray<>();
5687        }
5688        return mAttributeMap;
5689    }
5690
5691    private void saveAttributeData(@Nullable AttributeSet attrs, @NonNull TypedArray t) {
5692        final int attrsCount = attrs == null ? 0 : attrs.getAttributeCount();
5693        final int indexCount = t.getIndexCount();
5694        final String[] attributes = new String[(attrsCount + indexCount) * 2];
5695
5696        int i = 0;
5697
5698        // Store raw XML attributes.
5699        for (int j = 0; j < attrsCount; ++j) {
5700            attributes[i] = attrs.getAttributeName(j);
5701            attributes[i + 1] = attrs.getAttributeValue(j);
5702            i += 2;
5703        }
5704
5705        // Store resolved styleable attributes.
5706        final Resources res = t.getResources();
5707        final SparseArray<String> attributeMap = getAttributeMap();
5708        for (int j = 0; j < indexCount; ++j) {
5709            final int index = t.getIndex(j);
5710            if (!t.hasValueOrEmpty(index)) {
5711                // Value is undefined. Skip it.
5712                continue;
5713            }
5714
5715            final int resourceId = t.getResourceId(index, 0);
5716            if (resourceId == 0) {
5717                // Value is not a reference. Skip it.
5718                continue;
5719            }
5720
5721            String resourceName = attributeMap.get(resourceId);
5722            if (resourceName == null) {
5723                try {
5724                    resourceName = res.getResourceName(resourceId);
5725                } catch (Resources.NotFoundException e) {
5726                    resourceName = "0x" + Integer.toHexString(resourceId);
5727                }
5728                attributeMap.put(resourceId, resourceName);
5729            }
5730
5731            attributes[i] = resourceName;
5732            attributes[i + 1] = t.getString(index);
5733            i += 2;
5734        }
5735
5736        // Trim to fit contents.
5737        final String[] trimmed = new String[i];
5738        System.arraycopy(attributes, 0, trimmed, 0, i);
5739        mAttributes = trimmed;
5740    }
5741
5742    public String toString() {
5743        StringBuilder out = new StringBuilder(128);
5744        out.append(getClass().getName());
5745        out.append('{');
5746        out.append(Integer.toHexString(System.identityHashCode(this)));
5747        out.append(' ');
5748        switch (mViewFlags&VISIBILITY_MASK) {
5749            case VISIBLE: out.append('V'); break;
5750            case INVISIBLE: out.append('I'); break;
5751            case GONE: out.append('G'); break;
5752            default: out.append('.'); break;
5753        }
5754        out.append((mViewFlags & FOCUSABLE) == FOCUSABLE ? 'F' : '.');
5755        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
5756        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
5757        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
5758        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
5759        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
5760        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
5761        out.append((mViewFlags&CONTEXT_CLICKABLE) != 0 ? 'X' : '.');
5762        out.append(' ');
5763        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
5764        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
5765        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
5766        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
5767            out.append('p');
5768        } else {
5769            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
5770        }
5771        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
5772        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
5773        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
5774        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
5775        out.append(' ');
5776        out.append(mLeft);
5777        out.append(',');
5778        out.append(mTop);
5779        out.append('-');
5780        out.append(mRight);
5781        out.append(',');
5782        out.append(mBottom);
5783        final int id = getId();
5784        if (id != NO_ID) {
5785            out.append(" #");
5786            out.append(Integer.toHexString(id));
5787            final Resources r = mResources;
5788            if (id > 0 && Resources.resourceHasPackage(id) && r != null) {
5789                try {
5790                    String pkgname;
5791                    switch (id&0xff000000) {
5792                        case 0x7f000000:
5793                            pkgname="app";
5794                            break;
5795                        case 0x01000000:
5796                            pkgname="android";
5797                            break;
5798                        default:
5799                            pkgname = r.getResourcePackageName(id);
5800                            break;
5801                    }
5802                    String typename = r.getResourceTypeName(id);
5803                    String entryname = r.getResourceEntryName(id);
5804                    out.append(" ");
5805                    out.append(pkgname);
5806                    out.append(":");
5807                    out.append(typename);
5808                    out.append("/");
5809                    out.append(entryname);
5810                } catch (Resources.NotFoundException e) {
5811                }
5812            }
5813        }
5814        out.append("}");
5815        return out.toString();
5816    }
5817
5818    /**
5819     * <p>
5820     * Initializes the fading edges from a given set of styled attributes. This
5821     * method should be called by subclasses that need fading edges and when an
5822     * instance of these subclasses is created programmatically rather than
5823     * being inflated from XML. This method is automatically called when the XML
5824     * is inflated.
5825     * </p>
5826     *
5827     * @param a the styled attributes set to initialize the fading edges from
5828     *
5829     * @removed
5830     */
5831    protected void initializeFadingEdge(TypedArray a) {
5832        // This method probably shouldn't have been included in the SDK to begin with.
5833        // It relies on 'a' having been initialized using an attribute filter array that is
5834        // not publicly available to the SDK. The old method has been renamed
5835        // to initializeFadingEdgeInternal and hidden for framework use only;
5836        // this one initializes using defaults to make it safe to call for apps.
5837
5838        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
5839
5840        initializeFadingEdgeInternal(arr);
5841
5842        arr.recycle();
5843    }
5844
5845    /**
5846     * <p>
5847     * Initializes the fading edges from a given set of styled attributes. This
5848     * method should be called by subclasses that need fading edges and when an
5849     * instance of these subclasses is created programmatically rather than
5850     * being inflated from XML. This method is automatically called when the XML
5851     * is inflated.
5852     * </p>
5853     *
5854     * @param a the styled attributes set to initialize the fading edges from
5855     * @hide This is the real method; the public one is shimmed to be safe to call from apps.
5856     */
5857    protected void initializeFadingEdgeInternal(TypedArray a) {
5858        initScrollCache();
5859
5860        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
5861                R.styleable.View_fadingEdgeLength,
5862                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
5863    }
5864
5865    /**
5866     * Returns the size of the vertical faded edges used to indicate that more
5867     * content in this view is visible.
5868     *
5869     * @return The size in pixels of the vertical faded edge or 0 if vertical
5870     *         faded edges are not enabled for this view.
5871     * @attr ref android.R.styleable#View_fadingEdgeLength
5872     */
5873    public int getVerticalFadingEdgeLength() {
5874        if (isVerticalFadingEdgeEnabled()) {
5875            ScrollabilityCache cache = mScrollCache;
5876            if (cache != null) {
5877                return cache.fadingEdgeLength;
5878            }
5879        }
5880        return 0;
5881    }
5882
5883    /**
5884     * Set the size of the faded edge used to indicate that more content in this
5885     * view is available.  Will not change whether the fading edge is enabled; use
5886     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
5887     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
5888     * for the vertical or horizontal fading edges.
5889     *
5890     * @param length The size in pixels of the faded edge used to indicate that more
5891     *        content in this view is visible.
5892     */
5893    public void setFadingEdgeLength(int length) {
5894        initScrollCache();
5895        mScrollCache.fadingEdgeLength = length;
5896    }
5897
5898    /**
5899     * Returns the size of the horizontal faded edges used to indicate that more
5900     * content in this view is visible.
5901     *
5902     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
5903     *         faded edges are not enabled for this view.
5904     * @attr ref android.R.styleable#View_fadingEdgeLength
5905     */
5906    public int getHorizontalFadingEdgeLength() {
5907        if (isHorizontalFadingEdgeEnabled()) {
5908            ScrollabilityCache cache = mScrollCache;
5909            if (cache != null) {
5910                return cache.fadingEdgeLength;
5911            }
5912        }
5913        return 0;
5914    }
5915
5916    /**
5917     * Returns the width of the vertical scrollbar.
5918     *
5919     * @return The width in pixels of the vertical scrollbar or 0 if there
5920     *         is no vertical scrollbar.
5921     */
5922    public int getVerticalScrollbarWidth() {
5923        ScrollabilityCache cache = mScrollCache;
5924        if (cache != null) {
5925            ScrollBarDrawable scrollBar = cache.scrollBar;
5926            if (scrollBar != null) {
5927                int size = scrollBar.getSize(true);
5928                if (size <= 0) {
5929                    size = cache.scrollBarSize;
5930                }
5931                return size;
5932            }
5933            return 0;
5934        }
5935        return 0;
5936    }
5937
5938    /**
5939     * Returns the height of the horizontal scrollbar.
5940     *
5941     * @return The height in pixels of the horizontal scrollbar or 0 if
5942     *         there is no horizontal scrollbar.
5943     */
5944    protected int getHorizontalScrollbarHeight() {
5945        ScrollabilityCache cache = mScrollCache;
5946        if (cache != null) {
5947            ScrollBarDrawable scrollBar = cache.scrollBar;
5948            if (scrollBar != null) {
5949                int size = scrollBar.getSize(false);
5950                if (size <= 0) {
5951                    size = cache.scrollBarSize;
5952                }
5953                return size;
5954            }
5955            return 0;
5956        }
5957        return 0;
5958    }
5959
5960    /**
5961     * <p>
5962     * Initializes the scrollbars from a given set of styled attributes. This
5963     * method should be called by subclasses that need scrollbars and when an
5964     * instance of these subclasses is created programmatically rather than
5965     * being inflated from XML. This method is automatically called when the XML
5966     * is inflated.
5967     * </p>
5968     *
5969     * @param a the styled attributes set to initialize the scrollbars from
5970     *
5971     * @removed
5972     */
5973    protected void initializeScrollbars(TypedArray a) {
5974        // It's not safe to use this method from apps. The parameter 'a' must have been obtained
5975        // using the View filter array which is not available to the SDK. As such, internal
5976        // framework usage now uses initializeScrollbarsInternal and we grab a default
5977        // TypedArray with the right filter instead here.
5978        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
5979
5980        initializeScrollbarsInternal(arr);
5981
5982        // We ignored the method parameter. Recycle the one we actually did use.
5983        arr.recycle();
5984    }
5985
5986    /**
5987     * <p>
5988     * Initializes the scrollbars from a given set of styled attributes. This
5989     * method should be called by subclasses that need scrollbars and when an
5990     * instance of these subclasses is created programmatically rather than
5991     * being inflated from XML. This method is automatically called when the XML
5992     * is inflated.
5993     * </p>
5994     *
5995     * @param a the styled attributes set to initialize the scrollbars from
5996     * @hide
5997     */
5998    protected void initializeScrollbarsInternal(TypedArray a) {
5999        initScrollCache();
6000
6001        final ScrollabilityCache scrollabilityCache = mScrollCache;
6002
6003        if (scrollabilityCache.scrollBar == null) {
6004            scrollabilityCache.scrollBar = new ScrollBarDrawable();
6005            scrollabilityCache.scrollBar.setState(getDrawableState());
6006            scrollabilityCache.scrollBar.setCallback(this);
6007        }
6008
6009        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
6010
6011        if (!fadeScrollbars) {
6012            scrollabilityCache.state = ScrollabilityCache.ON;
6013        }
6014        scrollabilityCache.fadeScrollBars = fadeScrollbars;
6015
6016
6017        scrollabilityCache.scrollBarFadeDuration = a.getInt(
6018                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
6019                        .getScrollBarFadeDuration());
6020        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
6021                R.styleable.View_scrollbarDefaultDelayBeforeFade,
6022                ViewConfiguration.getScrollDefaultDelay());
6023
6024
6025        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
6026                com.android.internal.R.styleable.View_scrollbarSize,
6027                ViewConfiguration.get(mContext).getScaledScrollBarSize());
6028
6029        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
6030        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
6031
6032        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
6033        if (thumb != null) {
6034            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
6035        }
6036
6037        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
6038                false);
6039        if (alwaysDraw) {
6040            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
6041        }
6042
6043        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
6044        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
6045
6046        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
6047        if (thumb != null) {
6048            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
6049        }
6050
6051        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
6052                false);
6053        if (alwaysDraw) {
6054            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
6055        }
6056
6057        // Apply layout direction to the new Drawables if needed
6058        final int layoutDirection = getLayoutDirection();
6059        if (track != null) {
6060            track.setLayoutDirection(layoutDirection);
6061        }
6062        if (thumb != null) {
6063            thumb.setLayoutDirection(layoutDirection);
6064        }
6065
6066        // Re-apply user/background padding so that scrollbar(s) get added
6067        resolvePadding();
6068    }
6069
6070    private void initializeScrollIndicatorsInternal() {
6071        // Some day maybe we'll break this into top/left/start/etc. and let the
6072        // client control it. Until then, you can have any scroll indicator you
6073        // want as long as it's a 1dp foreground-colored rectangle.
6074        if (mScrollIndicatorDrawable == null) {
6075            mScrollIndicatorDrawable = mContext.getDrawable(R.drawable.scroll_indicator_material);
6076        }
6077    }
6078
6079    /**
6080     * <p>
6081     * Initalizes the scrollability cache if necessary.
6082     * </p>
6083     */
6084    private void initScrollCache() {
6085        if (mScrollCache == null) {
6086            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
6087        }
6088    }
6089
6090    private ScrollabilityCache getScrollCache() {
6091        initScrollCache();
6092        return mScrollCache;
6093    }
6094
6095    /**
6096     * Set the position of the vertical scroll bar. Should be one of
6097     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
6098     * {@link #SCROLLBAR_POSITION_RIGHT}.
6099     *
6100     * @param position Where the vertical scroll bar should be positioned.
6101     */
6102    public void setVerticalScrollbarPosition(int position) {
6103        if (mVerticalScrollbarPosition != position) {
6104            mVerticalScrollbarPosition = position;
6105            computeOpaqueFlags();
6106            resolvePadding();
6107        }
6108    }
6109
6110    /**
6111     * @return The position where the vertical scroll bar will show, if applicable.
6112     * @see #setVerticalScrollbarPosition(int)
6113     */
6114    public int getVerticalScrollbarPosition() {
6115        return mVerticalScrollbarPosition;
6116    }
6117
6118    boolean isOnScrollbar(float x, float y) {
6119        if (mScrollCache == null) {
6120            return false;
6121        }
6122        x += getScrollX();
6123        y += getScrollY();
6124        if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) {
6125            final Rect touchBounds = mScrollCache.mScrollBarTouchBounds;
6126            getVerticalScrollBarBounds(null, touchBounds);
6127            if (touchBounds.contains((int) x, (int) y)) {
6128                return true;
6129            }
6130        }
6131        if (isHorizontalScrollBarEnabled()) {
6132            final Rect touchBounds = mScrollCache.mScrollBarTouchBounds;
6133            getHorizontalScrollBarBounds(null, touchBounds);
6134            if (touchBounds.contains((int) x, (int) y)) {
6135                return true;
6136            }
6137        }
6138        return false;
6139    }
6140
6141    boolean isOnScrollbarThumb(float x, float y) {
6142        return isOnVerticalScrollbarThumb(x, y) || isOnHorizontalScrollbarThumb(x, y);
6143    }
6144
6145    private boolean isOnVerticalScrollbarThumb(float x, float y) {
6146        if (mScrollCache == null) {
6147            return false;
6148        }
6149        if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) {
6150            x += getScrollX();
6151            y += getScrollY();
6152            final Rect bounds = mScrollCache.mScrollBarBounds;
6153            final Rect touchBounds = mScrollCache.mScrollBarTouchBounds;
6154            getVerticalScrollBarBounds(bounds, touchBounds);
6155            final int range = computeVerticalScrollRange();
6156            final int offset = computeVerticalScrollOffset();
6157            final int extent = computeVerticalScrollExtent();
6158            final int thumbLength = ScrollBarUtils.getThumbLength(bounds.height(), bounds.width(),
6159                    extent, range);
6160            final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.height(), thumbLength,
6161                    extent, range, offset);
6162            final int thumbTop = bounds.top + thumbOffset;
6163            final int adjust = Math.max(mScrollCache.scrollBarMinTouchTarget - thumbLength, 0) / 2;
6164            if (x >= touchBounds.left && x <= touchBounds.right
6165                    && y >= thumbTop - adjust && y <= thumbTop + thumbLength + adjust) {
6166                return true;
6167            }
6168        }
6169        return false;
6170    }
6171
6172    private boolean isOnHorizontalScrollbarThumb(float x, float y) {
6173        if (mScrollCache == null) {
6174            return false;
6175        }
6176        if (isHorizontalScrollBarEnabled()) {
6177            x += getScrollX();
6178            y += getScrollY();
6179            final Rect bounds = mScrollCache.mScrollBarBounds;
6180            final Rect touchBounds = mScrollCache.mScrollBarTouchBounds;
6181            getHorizontalScrollBarBounds(bounds, touchBounds);
6182            final int range = computeHorizontalScrollRange();
6183            final int offset = computeHorizontalScrollOffset();
6184            final int extent = computeHorizontalScrollExtent();
6185            final int thumbLength = ScrollBarUtils.getThumbLength(bounds.width(), bounds.height(),
6186                    extent, range);
6187            final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.width(), thumbLength,
6188                    extent, range, offset);
6189            final int thumbLeft = bounds.left + thumbOffset;
6190            final int adjust = Math.max(mScrollCache.scrollBarMinTouchTarget - thumbLength, 0) / 2;
6191            if (x >= thumbLeft - adjust && x <= thumbLeft + thumbLength + adjust
6192                    && y >= touchBounds.top && y <= touchBounds.bottom) {
6193                return true;
6194            }
6195        }
6196        return false;
6197    }
6198
6199    boolean isDraggingScrollBar() {
6200        return mScrollCache != null
6201                && mScrollCache.mScrollBarDraggingState != ScrollabilityCache.NOT_DRAGGING;
6202    }
6203
6204    /**
6205     * Sets the state of all scroll indicators.
6206     * <p>
6207     * See {@link #setScrollIndicators(int, int)} for usage information.
6208     *
6209     * @param indicators a bitmask of indicators that should be enabled, or
6210     *                   {@code 0} to disable all indicators
6211     * @see #setScrollIndicators(int, int)
6212     * @see #getScrollIndicators()
6213     * @attr ref android.R.styleable#View_scrollIndicators
6214     */
6215    public void setScrollIndicators(@ScrollIndicators int indicators) {
6216        setScrollIndicators(indicators,
6217                SCROLL_INDICATORS_PFLAG3_MASK >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT);
6218    }
6219
6220    /**
6221     * Sets the state of the scroll indicators specified by the mask. To change
6222     * all scroll indicators at once, see {@link #setScrollIndicators(int)}.
6223     * <p>
6224     * When a scroll indicator is enabled, it will be displayed if the view
6225     * can scroll in the direction of the indicator.
6226     * <p>
6227     * Multiple indicator types may be enabled or disabled by passing the
6228     * logical OR of the desired types. If multiple types are specified, they
6229     * will all be set to the same enabled state.
6230     * <p>
6231     * For example, to enable the top scroll indicatorExample: {@code setScrollIndicators
6232     *
6233     * @param indicators the indicator direction, or the logical OR of multiple
6234     *             indicator directions. One or more of:
6235     *             <ul>
6236     *               <li>{@link #SCROLL_INDICATOR_TOP}</li>
6237     *               <li>{@link #SCROLL_INDICATOR_BOTTOM}</li>
6238     *               <li>{@link #SCROLL_INDICATOR_LEFT}</li>
6239     *               <li>{@link #SCROLL_INDICATOR_RIGHT}</li>
6240     *               <li>{@link #SCROLL_INDICATOR_START}</li>
6241     *               <li>{@link #SCROLL_INDICATOR_END}</li>
6242     *             </ul>
6243     * @see #setScrollIndicators(int)
6244     * @see #getScrollIndicators()
6245     * @attr ref android.R.styleable#View_scrollIndicators
6246     */
6247    public void setScrollIndicators(@ScrollIndicators int indicators, @ScrollIndicators int mask) {
6248        // Shift and sanitize mask.
6249        mask <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
6250        mask &= SCROLL_INDICATORS_PFLAG3_MASK;
6251
6252        // Shift and mask indicators.
6253        indicators <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
6254        indicators &= mask;
6255
6256        // Merge with non-masked flags.
6257        final int updatedFlags = indicators | (mPrivateFlags3 & ~mask);
6258
6259        if (mPrivateFlags3 != updatedFlags) {
6260            mPrivateFlags3 = updatedFlags;
6261
6262            if (indicators != 0) {
6263                initializeScrollIndicatorsInternal();
6264            }
6265            invalidate();
6266        }
6267    }
6268
6269    /**
6270     * Returns a bitmask representing the enabled scroll indicators.
6271     * <p>
6272     * For example, if the top and left scroll indicators are enabled and all
6273     * other indicators are disabled, the return value will be
6274     * {@code View.SCROLL_INDICATOR_TOP | View.SCROLL_INDICATOR_LEFT}.
6275     * <p>
6276     * To check whether the bottom scroll indicator is enabled, use the value
6277     * of {@code (getScrollIndicators() & View.SCROLL_INDICATOR_BOTTOM) != 0}.
6278     *
6279     * @return a bitmask representing the enabled scroll indicators
6280     */
6281    @ScrollIndicators
6282    public int getScrollIndicators() {
6283        return (mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK)
6284                >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
6285    }
6286
6287    ListenerInfo getListenerInfo() {
6288        if (mListenerInfo != null) {
6289            return mListenerInfo;
6290        }
6291        mListenerInfo = new ListenerInfo();
6292        return mListenerInfo;
6293    }
6294
6295    /**
6296     * Register a callback to be invoked when the scroll X or Y positions of
6297     * this view change.
6298     * <p>
6299     * <b>Note:</b> Some views handle scrolling independently from View and may
6300     * have their own separate listeners for scroll-type events. For example,
6301     * {@link android.widget.ListView ListView} allows clients to register an
6302     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
6303     * to listen for changes in list scroll position.
6304     *
6305     * @param l The listener to notify when the scroll X or Y position changes.
6306     * @see android.view.View#getScrollX()
6307     * @see android.view.View#getScrollY()
6308     */
6309    public void setOnScrollChangeListener(OnScrollChangeListener l) {
6310        getListenerInfo().mOnScrollChangeListener = l;
6311    }
6312
6313    /**
6314     * Register a callback to be invoked when focus of this view changed.
6315     *
6316     * @param l The callback that will run.
6317     */
6318    public void setOnFocusChangeListener(OnFocusChangeListener l) {
6319        getListenerInfo().mOnFocusChangeListener = l;
6320    }
6321
6322    /**
6323     * Add a listener that will be called when the bounds of the view change due to
6324     * layout processing.
6325     *
6326     * @param listener The listener that will be called when layout bounds change.
6327     */
6328    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
6329        ListenerInfo li = getListenerInfo();
6330        if (li.mOnLayoutChangeListeners == null) {
6331            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
6332        }
6333        if (!li.mOnLayoutChangeListeners.contains(listener)) {
6334            li.mOnLayoutChangeListeners.add(listener);
6335        }
6336    }
6337
6338    /**
6339     * Remove a listener for layout changes.
6340     *
6341     * @param listener The listener for layout bounds change.
6342     */
6343    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
6344        ListenerInfo li = mListenerInfo;
6345        if (li == null || li.mOnLayoutChangeListeners == null) {
6346            return;
6347        }
6348        li.mOnLayoutChangeListeners.remove(listener);
6349    }
6350
6351    /**
6352     * Add a listener for attach state changes.
6353     *
6354     * This listener will be called whenever this view is attached or detached
6355     * from a window. Remove the listener using
6356     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
6357     *
6358     * @param listener Listener to attach
6359     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
6360     */
6361    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
6362        ListenerInfo li = getListenerInfo();
6363        if (li.mOnAttachStateChangeListeners == null) {
6364            li.mOnAttachStateChangeListeners
6365                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
6366        }
6367        li.mOnAttachStateChangeListeners.add(listener);
6368    }
6369
6370    /**
6371     * Remove a listener for attach state changes. The listener will receive no further
6372     * notification of window attach/detach events.
6373     *
6374     * @param listener Listener to remove
6375     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
6376     */
6377    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
6378        ListenerInfo li = mListenerInfo;
6379        if (li == null || li.mOnAttachStateChangeListeners == null) {
6380            return;
6381        }
6382        li.mOnAttachStateChangeListeners.remove(listener);
6383    }
6384
6385    /**
6386     * Returns the focus-change callback registered for this view.
6387     *
6388     * @return The callback, or null if one is not registered.
6389     */
6390    public OnFocusChangeListener getOnFocusChangeListener() {
6391        ListenerInfo li = mListenerInfo;
6392        return li != null ? li.mOnFocusChangeListener : null;
6393    }
6394
6395    /**
6396     * Register a callback to be invoked when this view is clicked. If this view is not
6397     * clickable, it becomes clickable.
6398     *
6399     * @param l The callback that will run
6400     *
6401     * @see #setClickable(boolean)
6402     */
6403    public void setOnClickListener(@Nullable OnClickListener l) {
6404        if (!isClickable()) {
6405            setClickable(true);
6406        }
6407        getListenerInfo().mOnClickListener = l;
6408    }
6409
6410    /**
6411     * Return whether this view has an attached OnClickListener.  Returns
6412     * true if there is a listener, false if there is none.
6413     */
6414    public boolean hasOnClickListeners() {
6415        ListenerInfo li = mListenerInfo;
6416        return (li != null && li.mOnClickListener != null);
6417    }
6418
6419    /**
6420     * Register a callback to be invoked when this view is clicked and held. If this view is not
6421     * long clickable, it becomes long clickable.
6422     *
6423     * @param l The callback that will run
6424     *
6425     * @see #setLongClickable(boolean)
6426     */
6427    public void setOnLongClickListener(@Nullable OnLongClickListener l) {
6428        if (!isLongClickable()) {
6429            setLongClickable(true);
6430        }
6431        getListenerInfo().mOnLongClickListener = l;
6432    }
6433
6434    /**
6435     * Register a callback to be invoked when this view is context clicked. If the view is not
6436     * context clickable, it becomes context clickable.
6437     *
6438     * @param l The callback that will run
6439     * @see #setContextClickable(boolean)
6440     */
6441    public void setOnContextClickListener(@Nullable OnContextClickListener l) {
6442        if (!isContextClickable()) {
6443            setContextClickable(true);
6444        }
6445        getListenerInfo().mOnContextClickListener = l;
6446    }
6447
6448    /**
6449     * Register a callback to be invoked when the context menu for this view is
6450     * being built. If this view is not long clickable, it becomes long clickable.
6451     *
6452     * @param l The callback that will run
6453     *
6454     */
6455    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
6456        if (!isLongClickable()) {
6457            setLongClickable(true);
6458        }
6459        getListenerInfo().mOnCreateContextMenuListener = l;
6460    }
6461
6462    /**
6463     * Set an observer to collect stats for each frame rendered for this view.
6464     *
6465     * @hide
6466     */
6467    public void addFrameMetricsListener(Window window,
6468            Window.OnFrameMetricsAvailableListener listener,
6469            Handler handler) {
6470        if (mAttachInfo != null) {
6471            if (mAttachInfo.mThreadedRenderer != null) {
6472                if (mFrameMetricsObservers == null) {
6473                    mFrameMetricsObservers = new ArrayList<>();
6474                }
6475
6476                FrameMetricsObserver fmo = new FrameMetricsObserver(window,
6477                        handler.getLooper(), listener);
6478                mFrameMetricsObservers.add(fmo);
6479                mAttachInfo.mThreadedRenderer.addFrameMetricsObserver(fmo);
6480            } else {
6481                Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats");
6482            }
6483        } else {
6484            if (mFrameMetricsObservers == null) {
6485                mFrameMetricsObservers = new ArrayList<>();
6486            }
6487
6488            FrameMetricsObserver fmo = new FrameMetricsObserver(window,
6489                    handler.getLooper(), listener);
6490            mFrameMetricsObservers.add(fmo);
6491        }
6492    }
6493
6494    /**
6495     * Remove observer configured to collect frame stats for this view.
6496     *
6497     * @hide
6498     */
6499    public void removeFrameMetricsListener(
6500            Window.OnFrameMetricsAvailableListener listener) {
6501        ThreadedRenderer renderer = getThreadedRenderer();
6502        FrameMetricsObserver fmo = findFrameMetricsObserver(listener);
6503        if (fmo == null) {
6504            throw new IllegalArgumentException(
6505                    "attempt to remove OnFrameMetricsAvailableListener that was never added");
6506        }
6507
6508        if (mFrameMetricsObservers != null) {
6509            mFrameMetricsObservers.remove(fmo);
6510            if (renderer != null) {
6511                renderer.removeFrameMetricsObserver(fmo);
6512            }
6513        }
6514    }
6515
6516    private void registerPendingFrameMetricsObservers() {
6517        if (mFrameMetricsObservers != null) {
6518            ThreadedRenderer renderer = getThreadedRenderer();
6519            if (renderer != null) {
6520                for (FrameMetricsObserver fmo : mFrameMetricsObservers) {
6521                    renderer.addFrameMetricsObserver(fmo);
6522                }
6523            } else {
6524                Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats");
6525            }
6526        }
6527    }
6528
6529    private FrameMetricsObserver findFrameMetricsObserver(
6530            Window.OnFrameMetricsAvailableListener listener) {
6531        for (int i = 0; i < mFrameMetricsObservers.size(); i++) {
6532            FrameMetricsObserver observer = mFrameMetricsObservers.get(i);
6533            if (observer.mListener == listener) {
6534                return observer;
6535            }
6536        }
6537
6538        return null;
6539    }
6540
6541    /** @hide */
6542    public void setNotifyAutofillManagerOnClick(boolean notify) {
6543        if (notify) {
6544            mPrivateFlags |= PFLAG_NOTIFY_AUTOFILL_MANAGER_ON_CLICK;
6545        } else {
6546            mPrivateFlags &= ~PFLAG_NOTIFY_AUTOFILL_MANAGER_ON_CLICK;
6547        }
6548    }
6549
6550    private void notifyAutofillManagerOnClick() {
6551        if ((mPrivateFlags & PFLAG_NOTIFY_AUTOFILL_MANAGER_ON_CLICK) != 0) {
6552            try {
6553                getAutofillManager().notifyViewClicked(this);
6554            } finally {
6555                // Set it to already called so it's not called twice when called by
6556                // performClickInternal()
6557                mPrivateFlags &= ~PFLAG_NOTIFY_AUTOFILL_MANAGER_ON_CLICK;
6558            }
6559        }
6560    }
6561
6562    /**
6563     * Entry point for {@link #performClick()} - other methods on View should call it instead of
6564     * {@code performClick()} directly to make sure the autofill manager is notified when
6565     * necessary (as subclasses could extend {@code performClick()} without calling the parent's
6566     * method).
6567     */
6568    private boolean performClickInternal() {
6569        // Must notify autofill manager before performing the click actions to avoid scenarios where
6570        // the app has a click listener that changes the state of views the autofill service might
6571        // be interested on.
6572        notifyAutofillManagerOnClick();
6573
6574        return performClick();
6575    }
6576
6577    /**
6578     * Call this view's OnClickListener, if it is defined.  Performs all normal
6579     * actions associated with clicking: reporting accessibility event, playing
6580     * a sound, etc.
6581     *
6582     * @return True there was an assigned OnClickListener that was called, false
6583     *         otherwise is returned.
6584     */
6585    // NOTE: other methods on View should not call this method directly, but performClickInternal()
6586    // instead, to guarantee that the autofill manager is notified when necessary (as subclasses
6587    // could extend this method without calling super.performClick()).
6588    public boolean performClick() {
6589        // We still need to call this method to handle the cases where performClick() was called
6590        // externally, instead of through performClickInternal()
6591        notifyAutofillManagerOnClick();
6592
6593        final boolean result;
6594        final ListenerInfo li = mListenerInfo;
6595        if (li != null && li.mOnClickListener != null) {
6596            playSoundEffect(SoundEffectConstants.CLICK);
6597            li.mOnClickListener.onClick(this);
6598            result = true;
6599        } else {
6600            result = false;
6601        }
6602
6603        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
6604
6605        notifyEnterOrExitForAutoFillIfNeeded(true);
6606
6607        return result;
6608    }
6609
6610    /**
6611     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
6612     * this only calls the listener, and does not do any associated clicking
6613     * actions like reporting an accessibility event.
6614     *
6615     * @return True there was an assigned OnClickListener that was called, false
6616     *         otherwise is returned.
6617     */
6618    public boolean callOnClick() {
6619        ListenerInfo li = mListenerInfo;
6620        if (li != null && li.mOnClickListener != null) {
6621            li.mOnClickListener.onClick(this);
6622            return true;
6623        }
6624        return false;
6625    }
6626
6627    /**
6628     * Calls this view's OnLongClickListener, if it is defined. Invokes the
6629     * context menu if the OnLongClickListener did not consume the event.
6630     *
6631     * @return {@code true} if one of the above receivers consumed the event,
6632     *         {@code false} otherwise
6633     */
6634    public boolean performLongClick() {
6635        return performLongClickInternal(mLongClickX, mLongClickY);
6636    }
6637
6638    /**
6639     * Calls this view's OnLongClickListener, if it is defined. Invokes the
6640     * context menu if the OnLongClickListener did not consume the event,
6641     * anchoring it to an (x,y) coordinate.
6642     *
6643     * @param x x coordinate of the anchoring touch event, or {@link Float#NaN}
6644     *          to disable anchoring
6645     * @param y y coordinate of the anchoring touch event, or {@link Float#NaN}
6646     *          to disable anchoring
6647     * @return {@code true} if one of the above receivers consumed the event,
6648     *         {@code false} otherwise
6649     */
6650    public boolean performLongClick(float x, float y) {
6651        mLongClickX = x;
6652        mLongClickY = y;
6653        final boolean handled = performLongClick();
6654        mLongClickX = Float.NaN;
6655        mLongClickY = Float.NaN;
6656        return handled;
6657    }
6658
6659    /**
6660     * Calls this view's OnLongClickListener, if it is defined. Invokes the
6661     * context menu if the OnLongClickListener did not consume the event,
6662     * optionally anchoring it to an (x,y) coordinate.
6663     *
6664     * @param x x coordinate of the anchoring touch event, or {@link Float#NaN}
6665     *          to disable anchoring
6666     * @param y y coordinate of the anchoring touch event, or {@link Float#NaN}
6667     *          to disable anchoring
6668     * @return {@code true} if one of the above receivers consumed the event,
6669     *         {@code false} otherwise
6670     */
6671    private boolean performLongClickInternal(float x, float y) {
6672        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
6673
6674        boolean handled = false;
6675        final ListenerInfo li = mListenerInfo;
6676        if (li != null && li.mOnLongClickListener != null) {
6677            handled = li.mOnLongClickListener.onLongClick(View.this);
6678        }
6679        if (!handled) {
6680            final boolean isAnchored = !Float.isNaN(x) && !Float.isNaN(y);
6681            handled = isAnchored ? showContextMenu(x, y) : showContextMenu();
6682        }
6683        if ((mViewFlags & TOOLTIP) == TOOLTIP) {
6684            if (!handled) {
6685                handled = showLongClickTooltip((int) x, (int) y);
6686            }
6687        }
6688        if (handled) {
6689            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
6690        }
6691        return handled;
6692    }
6693
6694    /**
6695     * Call this view's OnContextClickListener, if it is defined.
6696     *
6697     * @param x the x coordinate of the context click
6698     * @param y the y coordinate of the context click
6699     * @return True if there was an assigned OnContextClickListener that consumed the event, false
6700     *         otherwise.
6701     */
6702    public boolean performContextClick(float x, float y) {
6703        return performContextClick();
6704    }
6705
6706    /**
6707     * Call this view's OnContextClickListener, if it is defined.
6708     *
6709     * @return True if there was an assigned OnContextClickListener that consumed the event, false
6710     *         otherwise.
6711     */
6712    public boolean performContextClick() {
6713        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CONTEXT_CLICKED);
6714
6715        boolean handled = false;
6716        ListenerInfo li = mListenerInfo;
6717        if (li != null && li.mOnContextClickListener != null) {
6718            handled = li.mOnContextClickListener.onContextClick(View.this);
6719        }
6720        if (handled) {
6721            performHapticFeedback(HapticFeedbackConstants.CONTEXT_CLICK);
6722        }
6723        return handled;
6724    }
6725
6726    /**
6727     * Performs button-related actions during a touch down event.
6728     *
6729     * @param event The event.
6730     * @return True if the down was consumed.
6731     *
6732     * @hide
6733     */
6734    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
6735        if (event.isFromSource(InputDevice.SOURCE_MOUSE) &&
6736            (event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
6737            showContextMenu(event.getX(), event.getY());
6738            mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
6739            return true;
6740        }
6741        return false;
6742    }
6743
6744    /**
6745     * Shows the context menu for this view.
6746     *
6747     * @return {@code true} if the context menu was shown, {@code false}
6748     *         otherwise
6749     * @see #showContextMenu(float, float)
6750     */
6751    public boolean showContextMenu() {
6752        return getParent().showContextMenuForChild(this);
6753    }
6754
6755    /**
6756     * Shows the context menu for this view anchored to the specified
6757     * view-relative coordinate.
6758     *
6759     * @param x the X coordinate in pixels relative to the view to which the
6760     *          menu should be anchored, or {@link Float#NaN} to disable anchoring
6761     * @param y the Y coordinate in pixels relative to the view to which the
6762     *          menu should be anchored, or {@link Float#NaN} to disable anchoring
6763     * @return {@code true} if the context menu was shown, {@code false}
6764     *         otherwise
6765     */
6766    public boolean showContextMenu(float x, float y) {
6767        return getParent().showContextMenuForChild(this, x, y);
6768    }
6769
6770    /**
6771     * Start an action mode with the default type {@link ActionMode#TYPE_PRIMARY}.
6772     *
6773     * @param callback Callback that will control the lifecycle of the action mode
6774     * @return The new action mode if it is started, null otherwise
6775     *
6776     * @see ActionMode
6777     * @see #startActionMode(android.view.ActionMode.Callback, int)
6778     */
6779    public ActionMode startActionMode(ActionMode.Callback callback) {
6780        return startActionMode(callback, ActionMode.TYPE_PRIMARY);
6781    }
6782
6783    /**
6784     * Start an action mode with the given type.
6785     *
6786     * @param callback Callback that will control the lifecycle of the action mode
6787     * @param type One of {@link ActionMode#TYPE_PRIMARY} or {@link ActionMode#TYPE_FLOATING}.
6788     * @return The new action mode if it is started, null otherwise
6789     *
6790     * @see ActionMode
6791     */
6792    public ActionMode startActionMode(ActionMode.Callback callback, int type) {
6793        ViewParent parent = getParent();
6794        if (parent == null) return null;
6795        try {
6796            return parent.startActionModeForChild(this, callback, type);
6797        } catch (AbstractMethodError ame) {
6798            // Older implementations of custom views might not implement this.
6799            return parent.startActionModeForChild(this, callback);
6800        }
6801    }
6802
6803    /**
6804     * Call {@link Context#startActivityForResult(String, Intent, int, Bundle)} for the View's
6805     * Context, creating a unique View identifier to retrieve the result.
6806     *
6807     * @param intent The Intent to be started.
6808     * @param requestCode The request code to use.
6809     * @hide
6810     */
6811    public void startActivityForResult(Intent intent, int requestCode) {
6812        mStartActivityRequestWho = "@android:view:" + System.identityHashCode(this);
6813        getContext().startActivityForResult(mStartActivityRequestWho, intent, requestCode, null);
6814    }
6815
6816    /**
6817     * If this View corresponds to the calling who, dispatches the activity result.
6818     * @param who The identifier for the targeted View to receive the result.
6819     * @param requestCode The integer request code originally supplied to
6820     *                    startActivityForResult(), allowing you to identify who this
6821     *                    result came from.
6822     * @param resultCode The integer result code returned by the child activity
6823     *                   through its setResult().
6824     * @param data An Intent, which can return result data to the caller
6825     *               (various data can be attached to Intent "extras").
6826     * @return {@code true} if the activity result was dispatched.
6827     * @hide
6828     */
6829    public boolean dispatchActivityResult(
6830            String who, int requestCode, int resultCode, Intent data) {
6831        if (mStartActivityRequestWho != null && mStartActivityRequestWho.equals(who)) {
6832            onActivityResult(requestCode, resultCode, data);
6833            mStartActivityRequestWho = null;
6834            return true;
6835        }
6836        return false;
6837    }
6838
6839    /**
6840     * Receive the result from a previous call to {@link #startActivityForResult(Intent, int)}.
6841     *
6842     * @param requestCode The integer request code originally supplied to
6843     *                    startActivityForResult(), allowing you to identify who this
6844     *                    result came from.
6845     * @param resultCode The integer result code returned by the child activity
6846     *                   through its setResult().
6847     * @param data An Intent, which can return result data to the caller
6848     *               (various data can be attached to Intent "extras").
6849     * @hide
6850     */
6851    public void onActivityResult(int requestCode, int resultCode, Intent data) {
6852        // Do nothing.
6853    }
6854
6855    /**
6856     * Register a callback to be invoked when a hardware key is pressed in this view.
6857     * Key presses in software input methods will generally not trigger the methods of
6858     * this listener.
6859     * @param l the key listener to attach to this view
6860     */
6861    public void setOnKeyListener(OnKeyListener l) {
6862        getListenerInfo().mOnKeyListener = l;
6863    }
6864
6865    /**
6866     * Register a callback to be invoked when a touch event is sent to this view.
6867     * @param l the touch listener to attach to this view
6868     */
6869    public void setOnTouchListener(OnTouchListener l) {
6870        getListenerInfo().mOnTouchListener = l;
6871    }
6872
6873    /**
6874     * Register a callback to be invoked when a generic motion event is sent to this view.
6875     * @param l the generic motion listener to attach to this view
6876     */
6877    public void setOnGenericMotionListener(OnGenericMotionListener l) {
6878        getListenerInfo().mOnGenericMotionListener = l;
6879    }
6880
6881    /**
6882     * Register a callback to be invoked when a hover event is sent to this view.
6883     * @param l the hover listener to attach to this view
6884     */
6885    public void setOnHoverListener(OnHoverListener l) {
6886        getListenerInfo().mOnHoverListener = l;
6887    }
6888
6889    /**
6890     * Register a drag event listener callback object for this View. The parameter is
6891     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
6892     * View, the system calls the
6893     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
6894     * @param l An implementation of {@link android.view.View.OnDragListener}.
6895     */
6896    public void setOnDragListener(OnDragListener l) {
6897        getListenerInfo().mOnDragListener = l;
6898    }
6899
6900    /**
6901     * Give this view focus. This will cause
6902     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
6903     *
6904     * Note: this does not check whether this {@link View} should get focus, it just
6905     * gives it focus no matter what.  It should only be called internally by framework
6906     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
6907     *
6908     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
6909     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
6910     *        focus moved when requestFocus() is called. It may not always
6911     *        apply, in which case use the default View.FOCUS_DOWN.
6912     * @param previouslyFocusedRect The rectangle of the view that had focus
6913     *        prior in this View's coordinate system.
6914     */
6915    void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) {
6916        if (DBG) {
6917            System.out.println(this + " requestFocus()");
6918        }
6919
6920        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
6921            mPrivateFlags |= PFLAG_FOCUSED;
6922
6923            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
6924
6925            if (mParent != null) {
6926                mParent.requestChildFocus(this, this);
6927                updateFocusedInCluster(oldFocus, direction);
6928            }
6929
6930            if (mAttachInfo != null) {
6931                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
6932            }
6933
6934            onFocusChanged(true, direction, previouslyFocusedRect);
6935            refreshDrawableState();
6936        }
6937    }
6938
6939    /**
6940     * Sets this view's preference for reveal behavior when it gains focus.
6941     *
6942     * <p>When set to true, this is a signal to ancestor views in the hierarchy that
6943     * this view would prefer to be brought fully into view when it gains focus.
6944     * For example, a text field that a user is meant to type into. Other views such
6945     * as scrolling containers may prefer to opt-out of this behavior.</p>
6946     *
6947     * <p>The default value for views is true, though subclasses may change this
6948     * based on their preferred behavior.</p>
6949     *
6950     * @param revealOnFocus true to request reveal on focus in ancestors, false otherwise
6951     *
6952     * @see #getRevealOnFocusHint()
6953     */
6954    public final void setRevealOnFocusHint(boolean revealOnFocus) {
6955        if (revealOnFocus) {
6956            mPrivateFlags3 &= ~PFLAG3_NO_REVEAL_ON_FOCUS;
6957        } else {
6958            mPrivateFlags3 |= PFLAG3_NO_REVEAL_ON_FOCUS;
6959        }
6960    }
6961
6962    /**
6963     * Returns this view's preference for reveal behavior when it gains focus.
6964     *
6965     * <p>When this method returns true for a child view requesting focus, ancestor
6966     * views responding to a focus change in {@link ViewParent#requestChildFocus(View, View)}
6967     * should make a best effort to make the newly focused child fully visible to the user.
6968     * When it returns false, ancestor views should preferably not disrupt scroll positioning or
6969     * other properties affecting visibility to the user as part of the focus change.</p>
6970     *
6971     * @return true if this view would prefer to become fully visible when it gains focus,
6972     *         false if it would prefer not to disrupt scroll positioning
6973     *
6974     * @see #setRevealOnFocusHint(boolean)
6975     */
6976    public final boolean getRevealOnFocusHint() {
6977        return (mPrivateFlags3 & PFLAG3_NO_REVEAL_ON_FOCUS) == 0;
6978    }
6979
6980    /**
6981     * Populates <code>outRect</code> with the hotspot bounds. By default,
6982     * the hotspot bounds are identical to the screen bounds.
6983     *
6984     * @param outRect rect to populate with hotspot bounds
6985     * @hide Only for internal use by views and widgets.
6986     */
6987    public void getHotspotBounds(Rect outRect) {
6988        final Drawable background = getBackground();
6989        if (background != null) {
6990            background.getHotspotBounds(outRect);
6991        } else {
6992            getBoundsOnScreen(outRect);
6993        }
6994    }
6995
6996    /**
6997     * Request that a rectangle of this view be visible on the screen,
6998     * scrolling if necessary just enough.
6999     *
7000     * <p>A View should call this if it maintains some notion of which part
7001     * of its content is interesting.  For example, a text editing view
7002     * should call this when its cursor moves.
7003     * <p>The Rectangle passed into this method should be in the View's content coordinate space.
7004     * It should not be affected by which part of the View is currently visible or its scroll
7005     * position.
7006     *
7007     * @param rectangle The rectangle in the View's content coordinate space
7008     * @return Whether any parent scrolled.
7009     */
7010    public boolean requestRectangleOnScreen(Rect rectangle) {
7011        return requestRectangleOnScreen(rectangle, false);
7012    }
7013
7014    /**
7015     * Request that a rectangle of this view be visible on the screen,
7016     * scrolling if necessary just enough.
7017     *
7018     * <p>A View should call this if it maintains some notion of which part
7019     * of its content is interesting.  For example, a text editing view
7020     * should call this when its cursor moves.
7021     * <p>The Rectangle passed into this method should be in the View's content coordinate space.
7022     * It should not be affected by which part of the View is currently visible or its scroll
7023     * position.
7024     * <p>When <code>immediate</code> is set to true, scrolling will not be
7025     * animated.
7026     *
7027     * @param rectangle The rectangle in the View's content coordinate space
7028     * @param immediate True to forbid animated scrolling, false otherwise
7029     * @return Whether any parent scrolled.
7030     */
7031    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
7032        if (mParent == null) {
7033            return false;
7034        }
7035
7036        View child = this;
7037
7038        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
7039        position.set(rectangle);
7040
7041        ViewParent parent = mParent;
7042        boolean scrolled = false;
7043        while (parent != null) {
7044            rectangle.set((int) position.left, (int) position.top,
7045                    (int) position.right, (int) position.bottom);
7046
7047            scrolled |= parent.requestChildRectangleOnScreen(child, rectangle, immediate);
7048
7049            if (!(parent instanceof View)) {
7050                break;
7051            }
7052
7053            // move it from child's content coordinate space to parent's content coordinate space
7054            position.offset(child.mLeft - child.getScrollX(), child.mTop -child.getScrollY());
7055
7056            child = (View) parent;
7057            parent = child.getParent();
7058        }
7059
7060        return scrolled;
7061    }
7062
7063    /**
7064     * Called when this view wants to give up focus. If focus is cleared
7065     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
7066     * <p>
7067     * <strong>Note:</strong> When not in touch-mode, the framework will try to give focus
7068     * to the first focusable View from the top after focus is cleared. Hence, if this
7069     * View is the first from the top that can take focus, then all callbacks
7070     * related to clearing focus will be invoked after which the framework will
7071     * give focus to this view.
7072     * </p>
7073     */
7074    public void clearFocus() {
7075        if (DBG) {
7076            System.out.println(this + " clearFocus()");
7077        }
7078
7079        final boolean refocus = sAlwaysAssignFocus || !isInTouchMode();
7080        clearFocusInternal(null, true, refocus);
7081    }
7082
7083    /**
7084     * Clears focus from the view, optionally propagating the change up through
7085     * the parent hierarchy and requesting that the root view place new focus.
7086     *
7087     * @param propagate whether to propagate the change up through the parent
7088     *            hierarchy
7089     * @param refocus when propagate is true, specifies whether to request the
7090     *            root view place new focus
7091     */
7092    void clearFocusInternal(View focused, boolean propagate, boolean refocus) {
7093        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
7094            mPrivateFlags &= ~PFLAG_FOCUSED;
7095            clearParentsWantFocus();
7096
7097            if (propagate && mParent != null) {
7098                mParent.clearChildFocus(this);
7099            }
7100
7101            onFocusChanged(false, 0, null);
7102            refreshDrawableState();
7103
7104            if (propagate && (!refocus || !rootViewRequestFocus())) {
7105                notifyGlobalFocusCleared(this);
7106            }
7107        }
7108    }
7109
7110    void notifyGlobalFocusCleared(View oldFocus) {
7111        if (oldFocus != null && mAttachInfo != null) {
7112            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
7113        }
7114    }
7115
7116    boolean rootViewRequestFocus() {
7117        final View root = getRootView();
7118        return root != null && root.requestFocus();
7119    }
7120
7121    /**
7122     * Called internally by the view system when a new view is getting focus.
7123     * This is what clears the old focus.
7124     * <p>
7125     * <b>NOTE:</b> The parent view's focused child must be updated manually
7126     * after calling this method. Otherwise, the view hierarchy may be left in
7127     * an inconstent state.
7128     */
7129    void unFocus(View focused) {
7130        if (DBG) {
7131            System.out.println(this + " unFocus()");
7132        }
7133
7134        clearFocusInternal(focused, false, false);
7135    }
7136
7137    /**
7138     * Returns true if this view has focus itself, or is the ancestor of the
7139     * view that has focus.
7140     *
7141     * @return True if this view has or contains focus, false otherwise.
7142     */
7143    @ViewDebug.ExportedProperty(category = "focus")
7144    public boolean hasFocus() {
7145        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
7146    }
7147
7148    /**
7149     * Returns true if this view is focusable or if it contains a reachable View
7150     * for which {@link #hasFocusable()} returns {@code true}. A "reachable hasFocusable()"
7151     * is a view whose parents do not block descendants focus.
7152     * Only {@link #VISIBLE} views are considered focusable.
7153     *
7154     * <p>As of {@link Build.VERSION_CODES#O} views that are determined to be focusable
7155     * through {@link #FOCUSABLE_AUTO} will also cause this method to return {@code true}.
7156     * Apps that declare a {@link android.content.pm.ApplicationInfo#targetSdkVersion} of
7157     * earlier than {@link Build.VERSION_CODES#O} will continue to see this method return
7158     * {@code false} for views not explicitly marked as focusable.
7159     * Use {@link #hasExplicitFocusable()} if you require the pre-{@link Build.VERSION_CODES#O}
7160     * behavior.</p>
7161     *
7162     * @return {@code true} if the view is focusable or if the view contains a focusable
7163     *         view, {@code false} otherwise
7164     *
7165     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
7166     * @see ViewGroup#getTouchscreenBlocksFocus()
7167     * @see #hasExplicitFocusable()
7168     */
7169    public boolean hasFocusable() {
7170        return hasFocusable(!sHasFocusableExcludeAutoFocusable, false);
7171    }
7172
7173    /**
7174     * Returns true if this view is focusable or if it contains a reachable View
7175     * for which {@link #hasExplicitFocusable()} returns {@code true}.
7176     * A "reachable hasExplicitFocusable()" is a view whose parents do not block descendants focus.
7177     * Only {@link #VISIBLE} views for which {@link #getFocusable()} would return
7178     * {@link #FOCUSABLE} are considered focusable.
7179     *
7180     * <p>This method preserves the pre-{@link Build.VERSION_CODES#O} behavior of
7181     * {@link #hasFocusable()} in that only views explicitly set focusable will cause
7182     * this method to return true. A view set to {@link #FOCUSABLE_AUTO} that resolves
7183     * to focusable will not.</p>
7184     *
7185     * @return {@code true} if the view is focusable or if the view contains a focusable
7186     *         view, {@code false} otherwise
7187     *
7188     * @see #hasFocusable()
7189     */
7190    public boolean hasExplicitFocusable() {
7191        return hasFocusable(false, true);
7192    }
7193
7194    boolean hasFocusable(boolean allowAutoFocus, boolean dispatchExplicit) {
7195        if (!isFocusableInTouchMode()) {
7196            for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) {
7197                final ViewGroup g = (ViewGroup) p;
7198                if (g.shouldBlockFocusForTouchscreen()) {
7199                    return false;
7200                }
7201            }
7202        }
7203
7204        // Invisible, gone, or disabled views are never focusable.
7205        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE
7206                || (mViewFlags & ENABLED_MASK) != ENABLED) {
7207            return false;
7208        }
7209
7210        // Only use effective focusable value when allowed.
7211        if ((allowAutoFocus || getFocusable() != FOCUSABLE_AUTO) && isFocusable()) {
7212            return true;
7213        }
7214
7215        return false;
7216    }
7217
7218    /**
7219     * Called by the view system when the focus state of this view changes.
7220     * When the focus change event is caused by directional navigation, direction
7221     * and previouslyFocusedRect provide insight into where the focus is coming from.
7222     * When overriding, be sure to call up through to the super class so that
7223     * the standard focus handling will occur.
7224     *
7225     * @param gainFocus True if the View has focus; false otherwise.
7226     * @param direction The direction focus has moved when requestFocus()
7227     *                  is called to give this view focus. Values are
7228     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
7229     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
7230     *                  It may not always apply, in which case use the default.
7231     * @param previouslyFocusedRect The rectangle, in this view's coordinate
7232     *        system, of the previously focused view.  If applicable, this will be
7233     *        passed in as finer grained information about where the focus is coming
7234     *        from (in addition to direction).  Will be <code>null</code> otherwise.
7235     */
7236    @CallSuper
7237    protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction,
7238            @Nullable Rect previouslyFocusedRect) {
7239        if (gainFocus) {
7240            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
7241        } else {
7242            notifyViewAccessibilityStateChangedIfNeeded(
7243                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7244        }
7245
7246        // Here we check whether we still need the default focus highlight, and switch it on/off.
7247        switchDefaultFocusHighlight();
7248
7249        InputMethodManager imm = InputMethodManager.peekInstance();
7250        if (!gainFocus) {
7251            if (isPressed()) {
7252                setPressed(false);
7253            }
7254            if (imm != null && mAttachInfo != null && mAttachInfo.mHasWindowFocus) {
7255                imm.focusOut(this);
7256            }
7257            onFocusLost();
7258        } else if (imm != null && mAttachInfo != null && mAttachInfo.mHasWindowFocus) {
7259            imm.focusIn(this);
7260        }
7261
7262        invalidate(true);
7263        ListenerInfo li = mListenerInfo;
7264        if (li != null && li.mOnFocusChangeListener != null) {
7265            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
7266        }
7267
7268        if (mAttachInfo != null) {
7269            mAttachInfo.mKeyDispatchState.reset(this);
7270        }
7271
7272        notifyEnterOrExitForAutoFillIfNeeded(gainFocus);
7273    }
7274
7275    /** @hide */
7276    public void notifyEnterOrExitForAutoFillIfNeeded(boolean enter) {
7277        if (canNotifyAutofillEnterExitEvent()) {
7278            AutofillManager afm = getAutofillManager();
7279            if (afm != null) {
7280                if (enter && isFocused()) {
7281                    // We have not been laid out yet, hence cannot evaluate
7282                    // whether this view is visible to the user, we will do
7283                    // the evaluation once layout is complete.
7284                    if (!isLaidOut()) {
7285                        mPrivateFlags3 |= PFLAG3_NOTIFY_AUTOFILL_ENTER_ON_LAYOUT;
7286                    } else if (isVisibleToUser()) {
7287                        // TODO This is a potential problem that View gets focus before it's visible
7288                        // to User. Ideally View should handle the event when isVisibleToUser()
7289                        // becomes true where it should issue notifyViewEntered().
7290                        afm.notifyViewEntered(this);
7291                    }
7292                } else if (!enter && !isFocused()) {
7293                    afm.notifyViewExited(this);
7294                }
7295            }
7296        }
7297    }
7298
7299    /**
7300     * Visually distinct portion of a window with window-like semantics are considered panes for
7301     * accessibility purposes. One example is the content view of a fragment that is replaced.
7302     * In order for accessibility services to understand a pane's window-like behavior, panes
7303     * should have descriptive titles. Views with pane titles produce {@link AccessibilityEvent}s
7304     * when they appear, disappear, or change title.
7305     *
7306     * @param accessibilityPaneTitle The pane's title. Setting to {@code null} indicates that this
7307     *                               View is not a pane.
7308     *
7309     * {@see AccessibilityNodeInfo#setPaneTitle(CharSequence)}
7310     */
7311    public void setAccessibilityPaneTitle(@Nullable CharSequence accessibilityPaneTitle) {
7312        if (!TextUtils.equals(accessibilityPaneTitle, mAccessibilityPaneTitle)) {
7313            mAccessibilityPaneTitle = accessibilityPaneTitle;
7314            notifyViewAccessibilityStateChangedIfNeeded(
7315                    AccessibilityEvent.CONTENT_CHANGE_TYPE_PANE_TITLE);
7316        }
7317    }
7318
7319    /**
7320     * Get the title of the pane for purposes of accessibility.
7321     *
7322     * @return The current pane title.
7323     *
7324     * {@see #setAccessibilityPaneTitle}.
7325     */
7326    @Nullable public CharSequence getAccessibilityPaneTitle() {
7327        return mAccessibilityPaneTitle;
7328    }
7329
7330    private boolean isAccessibilityPane() {
7331        return mAccessibilityPaneTitle != null;
7332    }
7333
7334    /**
7335     * Sends an accessibility event of the given type. If accessibility is
7336     * not enabled this method has no effect. The default implementation calls
7337     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
7338     * to populate information about the event source (this View), then calls
7339     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
7340     * populate the text content of the event source including its descendants,
7341     * and last calls
7342     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
7343     * on its parent to request sending of the event to interested parties.
7344     * <p>
7345     * If an {@link AccessibilityDelegate} has been specified via calling
7346     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7347     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
7348     * responsible for handling this call.
7349     * </p>
7350     *
7351     * @param eventType The type of the event to send, as defined by several types from
7352     * {@link android.view.accessibility.AccessibilityEvent}, such as
7353     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
7354     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
7355     *
7356     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
7357     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
7358     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
7359     * @see AccessibilityDelegate
7360     */
7361    public void sendAccessibilityEvent(int eventType) {
7362        if (mAccessibilityDelegate != null) {
7363            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
7364        } else {
7365            sendAccessibilityEventInternal(eventType);
7366        }
7367    }
7368
7369    /**
7370     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
7371     * {@link AccessibilityEvent} to make an announcement which is related to some
7372     * sort of a context change for which none of the events representing UI transitions
7373     * is a good fit. For example, announcing a new page in a book. If accessibility
7374     * is not enabled this method does nothing.
7375     *
7376     * @param text The announcement text.
7377     */
7378    public void announceForAccessibility(CharSequence text) {
7379        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
7380            AccessibilityEvent event = AccessibilityEvent.obtain(
7381                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
7382            onInitializeAccessibilityEvent(event);
7383            event.getText().add(text);
7384            event.setContentDescription(null);
7385            mParent.requestSendAccessibilityEvent(this, event);
7386        }
7387    }
7388
7389    /**
7390     * @see #sendAccessibilityEvent(int)
7391     *
7392     * Note: Called from the default {@link AccessibilityDelegate}.
7393     *
7394     * @hide
7395     */
7396    public void sendAccessibilityEventInternal(int eventType) {
7397        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
7398            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
7399        }
7400    }
7401
7402    /**
7403     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
7404     * takes as an argument an empty {@link AccessibilityEvent} and does not
7405     * perform a check whether accessibility is enabled.
7406     * <p>
7407     * If an {@link AccessibilityDelegate} has been specified via calling
7408     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7409     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
7410     * is responsible for handling this call.
7411     * </p>
7412     *
7413     * @param event The event to send.
7414     *
7415     * @see #sendAccessibilityEvent(int)
7416     */
7417    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
7418        if (mAccessibilityDelegate != null) {
7419            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
7420        } else {
7421            sendAccessibilityEventUncheckedInternal(event);
7422        }
7423    }
7424
7425    /**
7426     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
7427     *
7428     * Note: Called from the default {@link AccessibilityDelegate}.
7429     *
7430     * @hide
7431     */
7432    public void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
7433        // Panes disappearing are relevant even if though the view is no longer visible.
7434        boolean isWindowStateChanged =
7435                (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
7436        boolean isWindowDisappearedEvent = isWindowStateChanged && ((event.getContentChangeTypes()
7437                & AccessibilityEvent.CONTENT_CHANGE_TYPE_PANE_DISAPPEARED) != 0);
7438        if (!isShown() && !isWindowDisappearedEvent) {
7439            return;
7440        }
7441        onInitializeAccessibilityEvent(event);
7442        // Only a subset of accessibility events populates text content.
7443        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
7444            dispatchPopulateAccessibilityEvent(event);
7445        }
7446        // In the beginning we called #isShown(), so we know that getParent() is not null.
7447        ViewParent parent = getParent();
7448        if (parent != null) {
7449            getParent().requestSendAccessibilityEvent(this, event);
7450        }
7451    }
7452
7453    /**
7454     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
7455     * to its children for adding their text content to the event. Note that the
7456     * event text is populated in a separate dispatch path since we add to the
7457     * event not only the text of the source but also the text of all its descendants.
7458     * A typical implementation will call
7459     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
7460     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
7461     * on each child. Override this method if custom population of the event text
7462     * content is required.
7463     * <p>
7464     * If an {@link AccessibilityDelegate} has been specified via calling
7465     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7466     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
7467     * is responsible for handling this call.
7468     * </p>
7469     * <p>
7470     * <em>Note:</em> Accessibility events of certain types are not dispatched for
7471     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
7472     * </p>
7473     *
7474     * @param event The event.
7475     *
7476     * @return True if the event population was completed.
7477     */
7478    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
7479        if (mAccessibilityDelegate != null) {
7480            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
7481        } else {
7482            return dispatchPopulateAccessibilityEventInternal(event);
7483        }
7484    }
7485
7486    /**
7487     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
7488     *
7489     * Note: Called from the default {@link AccessibilityDelegate}.
7490     *
7491     * @hide
7492     */
7493    public boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
7494        onPopulateAccessibilityEvent(event);
7495        return false;
7496    }
7497
7498    /**
7499     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
7500     * giving a chance to this View to populate the accessibility event with its
7501     * text content. While this method is free to modify event
7502     * attributes other than text content, doing so should normally be performed in
7503     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
7504     * <p>
7505     * Example: Adding formatted date string to an accessibility event in addition
7506     *          to the text added by the super implementation:
7507     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
7508     *     super.onPopulateAccessibilityEvent(event);
7509     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
7510     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
7511     *         mCurrentDate.getTimeInMillis(), flags);
7512     *     event.getText().add(selectedDateUtterance);
7513     * }</pre>
7514     * <p>
7515     * If an {@link AccessibilityDelegate} has been specified via calling
7516     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7517     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
7518     * is responsible for handling this call.
7519     * </p>
7520     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
7521     * information to the event, in case the default implementation has basic information to add.
7522     * </p>
7523     *
7524     * @param event The accessibility event which to populate.
7525     *
7526     * @see #sendAccessibilityEvent(int)
7527     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
7528     */
7529    @CallSuper
7530    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
7531        if (mAccessibilityDelegate != null) {
7532            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
7533        } else {
7534            onPopulateAccessibilityEventInternal(event);
7535        }
7536    }
7537
7538    /**
7539     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
7540     *
7541     * Note: Called from the default {@link AccessibilityDelegate}.
7542     *
7543     * @hide
7544     */
7545    public void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
7546        if ((event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED)
7547                && !TextUtils.isEmpty(getAccessibilityPaneTitle())) {
7548            event.getText().add(getAccessibilityPaneTitle());
7549        }
7550    }
7551
7552    /**
7553     * Initializes an {@link AccessibilityEvent} with information about
7554     * this View which is the event source. In other words, the source of
7555     * an accessibility event is the view whose state change triggered firing
7556     * the event.
7557     * <p>
7558     * Example: Setting the password property of an event in addition
7559     *          to properties set by the super implementation:
7560     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
7561     *     super.onInitializeAccessibilityEvent(event);
7562     *     event.setPassword(true);
7563     * }</pre>
7564     * <p>
7565     * If an {@link AccessibilityDelegate} has been specified via calling
7566     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7567     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
7568     * is responsible for handling this call.
7569     * </p>
7570     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
7571     * information to the event, in case the default implementation has basic information to add.
7572     * </p>
7573     * @param event The event to initialize.
7574     *
7575     * @see #sendAccessibilityEvent(int)
7576     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
7577     */
7578    @CallSuper
7579    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
7580        if (mAccessibilityDelegate != null) {
7581            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
7582        } else {
7583            onInitializeAccessibilityEventInternal(event);
7584        }
7585    }
7586
7587    /**
7588     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
7589     *
7590     * Note: Called from the default {@link AccessibilityDelegate}.
7591     *
7592     * @hide
7593     */
7594    public void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
7595        event.setSource(this);
7596        event.setClassName(getAccessibilityClassName());
7597        event.setPackageName(getContext().getPackageName());
7598        event.setEnabled(isEnabled());
7599        event.setContentDescription(mContentDescription);
7600
7601        switch (event.getEventType()) {
7602            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
7603                ArrayList<View> focusablesTempList = (mAttachInfo != null)
7604                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
7605                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
7606                event.setItemCount(focusablesTempList.size());
7607                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
7608                if (mAttachInfo != null) {
7609                    focusablesTempList.clear();
7610                }
7611            } break;
7612            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
7613                CharSequence text = getIterableTextForAccessibility();
7614                if (text != null && text.length() > 0) {
7615                    event.setFromIndex(getAccessibilitySelectionStart());
7616                    event.setToIndex(getAccessibilitySelectionEnd());
7617                    event.setItemCount(text.length());
7618                }
7619            } break;
7620        }
7621    }
7622
7623    /**
7624     * Returns an {@link AccessibilityNodeInfo} representing this view from the
7625     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
7626     * This method is responsible for obtaining an accessibility node info from a
7627     * pool of reusable instances and calling
7628     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
7629     * initialize the former.
7630     * <p>
7631     * Note: The client is responsible for recycling the obtained instance by calling
7632     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
7633     * </p>
7634     *
7635     * @return A populated {@link AccessibilityNodeInfo}.
7636     *
7637     * @see AccessibilityNodeInfo
7638     */
7639    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
7640        if (mAccessibilityDelegate != null) {
7641            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
7642        } else {
7643            return createAccessibilityNodeInfoInternal();
7644        }
7645    }
7646
7647    /**
7648     * @see #createAccessibilityNodeInfo()
7649     *
7650     * @hide
7651     */
7652    public AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
7653        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
7654        if (provider != null) {
7655            return provider.createAccessibilityNodeInfo(AccessibilityNodeProvider.HOST_VIEW_ID);
7656        } else {
7657            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
7658            onInitializeAccessibilityNodeInfo(info);
7659            return info;
7660        }
7661    }
7662
7663    /**
7664     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
7665     * The base implementation sets:
7666     * <ul>
7667     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
7668     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
7669     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
7670     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
7671     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
7672     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
7673     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
7674     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
7675     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
7676     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
7677     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
7678     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
7679     *   <li>{@link AccessibilityNodeInfo#setContextClickable(boolean)}</li>
7680     * </ul>
7681     * <p>
7682     * Subclasses should override this method, call the super implementation,
7683     * and set additional attributes.
7684     * </p>
7685     * <p>
7686     * If an {@link AccessibilityDelegate} has been specified via calling
7687     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7688     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
7689     * is responsible for handling this call.
7690     * </p>
7691     *
7692     * @param info The instance to initialize.
7693     */
7694    @CallSuper
7695    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
7696        if (mAccessibilityDelegate != null) {
7697            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
7698        } else {
7699            onInitializeAccessibilityNodeInfoInternal(info);
7700        }
7701    }
7702
7703    /**
7704     * Gets the location of this view in screen coordinates.
7705     *
7706     * @param outRect The output location
7707     * @hide
7708     */
7709    public void getBoundsOnScreen(Rect outRect) {
7710        getBoundsOnScreen(outRect, false);
7711    }
7712
7713    /**
7714     * Gets the location of this view in screen coordinates.
7715     *
7716     * @param outRect The output location
7717     * @param clipToParent Whether to clip child bounds to the parent ones.
7718     * @hide
7719     */
7720    public void getBoundsOnScreen(Rect outRect, boolean clipToParent) {
7721        if (mAttachInfo == null) {
7722            return;
7723        }
7724
7725        RectF position = mAttachInfo.mTmpTransformRect;
7726        position.set(0, 0, mRight - mLeft, mBottom - mTop);
7727        mapRectFromViewToScreenCoords(position, clipToParent);
7728        outRect.set(Math.round(position.left), Math.round(position.top),
7729                Math.round(position.right), Math.round(position.bottom));
7730    }
7731
7732    /**
7733     * Map a rectangle from view-relative coordinates to screen-relative coordinates
7734     *
7735     * @param rect The rectangle to be mapped
7736     * @param clipToParent Whether to clip child bounds to the parent ones.
7737     * @hide
7738     */
7739    public void mapRectFromViewToScreenCoords(RectF rect, boolean clipToParent) {
7740        if (!hasIdentityMatrix()) {
7741            getMatrix().mapRect(rect);
7742        }
7743
7744        rect.offset(mLeft, mTop);
7745
7746        ViewParent parent = mParent;
7747        while (parent instanceof View) {
7748            View parentView = (View) parent;
7749
7750            rect.offset(-parentView.mScrollX, -parentView.mScrollY);
7751
7752            if (clipToParent) {
7753                rect.left = Math.max(rect.left, 0);
7754                rect.top = Math.max(rect.top, 0);
7755                rect.right = Math.min(rect.right, parentView.getWidth());
7756                rect.bottom = Math.min(rect.bottom, parentView.getHeight());
7757            }
7758
7759            if (!parentView.hasIdentityMatrix()) {
7760                parentView.getMatrix().mapRect(rect);
7761            }
7762
7763            rect.offset(parentView.mLeft, parentView.mTop);
7764
7765            parent = parentView.mParent;
7766        }
7767
7768        if (parent instanceof ViewRootImpl) {
7769            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
7770            rect.offset(0, -viewRootImpl.mCurScrollY);
7771        }
7772
7773        rect.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
7774    }
7775
7776    /**
7777     * Return the class name of this object to be used for accessibility purposes.
7778     * Subclasses should only override this if they are implementing something that
7779     * should be seen as a completely new class of view when used by accessibility,
7780     * unrelated to the class it is deriving from.  This is used to fill in
7781     * {@link AccessibilityNodeInfo#setClassName AccessibilityNodeInfo.setClassName}.
7782     */
7783    public CharSequence getAccessibilityClassName() {
7784        return View.class.getName();
7785    }
7786
7787    /**
7788     * Called when assist structure is being retrieved from a view as part of
7789     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData}.
7790     * @param structure Fill in with structured view data.  The default implementation
7791     * fills in all data that can be inferred from the view itself.
7792     */
7793    public void onProvideStructure(ViewStructure structure) {
7794        onProvideStructureForAssistOrAutofill(structure, false, 0);
7795    }
7796
7797    /**
7798     * Populates a {@link ViewStructure} to fullfil an autofill request.
7799     *
7800     * <p>The structure should contain at least the following properties:
7801     * <ul>
7802     *   <li>Autofill id ({@link ViewStructure#setAutofillId(AutofillId, int)}).
7803     *   <li>Autofill type ({@link ViewStructure#setAutofillType(int)}).
7804     *   <li>Autofill value ({@link ViewStructure#setAutofillValue(AutofillValue)}).
7805     *   <li>Whether the data is sensitive ({@link ViewStructure#setDataIsSensitive(boolean)}).
7806     * </ul>
7807     *
7808     * <p>It's also recommended to set the following properties - the more properties the structure
7809     * has, the higher the changes of an {@link android.service.autofill.AutofillService} properly
7810     * using the structure:
7811     *
7812     * <ul>
7813     *   <li>Autofill hints ({@link ViewStructure#setAutofillHints(String[])}).
7814     *   <li>Autofill options ({@link ViewStructure#setAutofillOptions(CharSequence[])}) when the
7815     *       view can only be filled with predefined values (typically used when the autofill type
7816     *       is {@link #AUTOFILL_TYPE_LIST}).
7817     *   <li>Resource id ({@link ViewStructure#setId(int, String, String, String)}).
7818     *   <li>Class name ({@link ViewStructure#setClassName(String)}).
7819     *   <li>Content description ({@link ViewStructure#setContentDescription(CharSequence)}).
7820     *   <li>Visual properties such as visibility ({@link ViewStructure#setVisibility(int)}),
7821     *       dimensions ({@link ViewStructure#setDimens(int, int, int, int, int, int)}), and
7822     *       opacity ({@link ViewStructure#setOpaque(boolean)}).
7823     *   <li>For views representing text fields, text properties such as the text itself
7824     *       ({@link ViewStructure#setText(CharSequence)}), text hints
7825     *       ({@link ViewStructure#setHint(CharSequence)}, input type
7826     *       ({@link ViewStructure#setInputType(int)}),
7827     *   <li>For views representing HTML nodes, its web domain
7828     *       ({@link ViewStructure#setWebDomain(String)}) and HTML properties
7829     *       (({@link ViewStructure#setHtmlInfo(android.view.ViewStructure.HtmlInfo)}).
7830     * </ul>
7831     *
7832     * <p>The default implementation of this method already sets most of these properties based on
7833     * related {@link View} methods (for example, the autofill id is set using
7834     * {@link #getAutofillId()}, the autofill type set using {@link #getAutofillType()}, etc.),
7835     * and views in the standard Android widgets library also override it to set their
7836     * relevant properties (for example, {@link android.widget.TextView} already sets the text
7837     * properties), so it's recommended to only override this method
7838     * (and call {@code super.onProvideAutofillStructure()}) when:
7839     *
7840     * <ul>
7841     *   <li>The view contents does not include PII (Personally Identifiable Information), so it
7842     *       can call {@link ViewStructure#setDataIsSensitive(boolean)} passing {@code false}.
7843     *   <li>The view can only be autofilled with predefined options, so it can call
7844     *       {@link ViewStructure#setAutofillOptions(CharSequence[])}.
7845     * </ul>
7846     *
7847     * <p><b>Note:</b> The {@code left} and {@code top} values set in
7848     * {@link ViewStructure#setDimens(int, int, int, int, int, int)} must be relative to the next
7849     * {@link ViewGroup#isImportantForAutofill()} predecessor view included in the structure.
7850     *
7851     * <p>Views support the Autofill Framework mainly by:
7852     * <ul>
7853     *   <li>Providing the metadata defining what the view means and how it can be autofilled.
7854     *   <li>Notifying the Android System when the view value changed by calling
7855     *       {@link AutofillManager#notifyValueChanged(View)}.
7856     *   <li>Implementing the methods that autofill the view.
7857     * </ul>
7858     * <p>This method is responsible for the former; {@link #autofill(AutofillValue)} is responsible
7859     * for the latter.
7860     *
7861     * @param structure fill in with structured view data for autofill purposes.
7862     * @param flags optional flags.
7863     *
7864     * @see #AUTOFILL_FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
7865     */
7866    public void onProvideAutofillStructure(ViewStructure structure, @AutofillFlags int flags) {
7867        onProvideStructureForAssistOrAutofill(structure, true, flags);
7868    }
7869
7870    private void onProvideStructureForAssistOrAutofill(ViewStructure structure,
7871            boolean forAutofill, @AutofillFlags int flags) {
7872        final int id = mID;
7873        if (id != NO_ID && !isViewIdGenerated(id)) {
7874            String pkg, type, entry;
7875            try {
7876                final Resources res = getResources();
7877                entry = res.getResourceEntryName(id);
7878                type = res.getResourceTypeName(id);
7879                pkg = res.getResourcePackageName(id);
7880            } catch (Resources.NotFoundException e) {
7881                entry = type = pkg = null;
7882            }
7883            structure.setId(id, pkg, type, entry);
7884        } else {
7885            structure.setId(id, null, null, null);
7886        }
7887
7888        if (forAutofill) {
7889            final @AutofillType int autofillType = getAutofillType();
7890            // Don't need to fill autofill info if view does not support it.
7891            // For example, only TextViews that are editable support autofill
7892            if (autofillType != AUTOFILL_TYPE_NONE) {
7893                structure.setAutofillType(autofillType);
7894                structure.setAutofillHints(getAutofillHints());
7895                structure.setAutofillValue(getAutofillValue());
7896            }
7897            structure.setImportantForAutofill(getImportantForAutofill());
7898        }
7899
7900        int ignoredParentLeft = 0;
7901        int ignoredParentTop = 0;
7902        if (forAutofill && (flags & AUTOFILL_FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) == 0) {
7903            View parentGroup = null;
7904
7905            ViewParent viewParent = getParent();
7906            if (viewParent instanceof View) {
7907                parentGroup = (View) viewParent;
7908            }
7909
7910            while (parentGroup != null && !parentGroup.isImportantForAutofill()) {
7911                ignoredParentLeft += parentGroup.mLeft;
7912                ignoredParentTop += parentGroup.mTop;
7913
7914                viewParent = parentGroup.getParent();
7915                if (viewParent instanceof View) {
7916                    parentGroup = (View) viewParent;
7917                } else {
7918                    break;
7919                }
7920            }
7921        }
7922
7923        structure.setDimens(ignoredParentLeft + mLeft, ignoredParentTop + mTop, mScrollX, mScrollY,
7924                mRight - mLeft, mBottom - mTop);
7925        if (!forAutofill) {
7926            if (!hasIdentityMatrix()) {
7927                structure.setTransformation(getMatrix());
7928            }
7929            structure.setElevation(getZ());
7930        }
7931        structure.setVisibility(getVisibility());
7932        structure.setEnabled(isEnabled());
7933        if (isClickable()) {
7934            structure.setClickable(true);
7935        }
7936        if (isFocusable()) {
7937            structure.setFocusable(true);
7938        }
7939        if (isFocused()) {
7940            structure.setFocused(true);
7941        }
7942        if (isAccessibilityFocused()) {
7943            structure.setAccessibilityFocused(true);
7944        }
7945        if (isSelected()) {
7946            structure.setSelected(true);
7947        }
7948        if (isActivated()) {
7949            structure.setActivated(true);
7950        }
7951        if (isLongClickable()) {
7952            structure.setLongClickable(true);
7953        }
7954        if (this instanceof Checkable) {
7955            structure.setCheckable(true);
7956            if (((Checkable)this).isChecked()) {
7957                structure.setChecked(true);
7958            }
7959        }
7960        if (isOpaque()) {
7961            structure.setOpaque(true);
7962        }
7963        if (isContextClickable()) {
7964            structure.setContextClickable(true);
7965        }
7966        structure.setClassName(getAccessibilityClassName().toString());
7967        structure.setContentDescription(getContentDescription());
7968    }
7969
7970    /**
7971     * Called when assist structure is being retrieved from a view as part of
7972     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData} to
7973     * generate additional virtual structure under this view.  The defaullt implementation
7974     * uses {@link #getAccessibilityNodeProvider()} to try to generate this from the
7975     * view's virtual accessibility nodes, if any.  You can override this for a more
7976     * optimal implementation providing this data.
7977     */
7978    public void onProvideVirtualStructure(ViewStructure structure) {
7979        onProvideVirtualStructureCompat(structure, false);
7980    }
7981
7982    /**
7983     * Fallback implementation to populate a ViewStructure from accessibility state.
7984     *
7985     * @param structure The structure to populate.
7986     * @param forAutofill Whether the structure is needed for autofill.
7987     */
7988    private void onProvideVirtualStructureCompat(ViewStructure structure, boolean forAutofill) {
7989        final AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
7990        if (provider != null) {
7991            if (android.view.autofill.Helper.sVerbose && forAutofill) {
7992                Log.v(VIEW_LOG_TAG, "onProvideVirtualStructureCompat() for " + this);
7993            }
7994
7995            final AccessibilityNodeInfo info = createAccessibilityNodeInfo();
7996            structure.setChildCount(1);
7997            final ViewStructure root = structure.newChild(0);
7998            populateVirtualStructure(root, provider, info, forAutofill);
7999            info.recycle();
8000        }
8001    }
8002
8003    /**
8004     * Populates a {@link ViewStructure} containing virtual children to fullfil an autofill
8005     * request.
8006     *
8007     * <p>This method should be used when the view manages a virtual structure under this view. For
8008     * example, a view that draws input fields using {@link #draw(Canvas)}.
8009     *
8010     * <p>When implementing this method, subclasses must follow the rules below:
8011     *
8012     * <ul>
8013     *   <li>Add virtual children by calling the {@link ViewStructure#newChild(int)} or
8014     *       {@link ViewStructure#asyncNewChild(int)} methods, where the {@code id} is an unique id
8015     *       identifying the children in the virtual structure.
8016     *   <li>The children hierarchy can have multiple levels if necessary, but ideally it should
8017     *       exclude intermediate levels that are irrelevant for autofill; that would improve the
8018     *       autofill performance.
8019     *   <li>Also implement {@link #autofill(SparseArray)} to autofill the virtual
8020     *       children.
8021     *   <li>Set the autofill properties of the child structure as defined by
8022     *       {@link #onProvideAutofillStructure(ViewStructure, int)}, using
8023     *       {@link ViewStructure#setAutofillId(AutofillId, int)} to set its autofill id.
8024     *   <li>Call {@link android.view.autofill.AutofillManager#notifyViewEntered(View, int, Rect)}
8025     *       and/or {@link android.view.autofill.AutofillManager#notifyViewExited(View, int)}
8026     *       when the focused virtual child changed.
8027     *   <li>Override {@link #isVisibleToUserForAutofill(int)} to allow the platform to query
8028     *       whether a given virtual view is visible to the user in order to support triggering
8029     *       save when all views of interest go away.
8030     *   <li>Call
8031     *    {@link android.view.autofill.AutofillManager#notifyValueChanged(View, int, AutofillValue)}
8032     *       when the value of a virtual child changed.
8033     *   <li>Call {@link
8034     *    android.view.autofill.AutofillManager#notifyViewVisibilityChanged(View, int, boolean)}
8035     *       when the visibility of a virtual child changed.
8036     *   <li>Call
8037     *    {@link android.view.autofill.AutofillManager#notifyViewClicked(View, int)} when a virtual
8038     *       child is clicked.
8039     *   <li>Call {@link AutofillManager#commit()} when the autofill context of the view structure
8040     *       changed and the current context should be committed (for example, when the user tapped
8041     *       a {@code SUBMIT} button in an HTML page).
8042     *   <li>Call {@link AutofillManager#cancel()} when the autofill context of the view structure
8043     *       changed and the current context should be canceled (for example, when the user tapped
8044     *       a {@code CANCEL} button in an HTML page).
8045     *   <li>Provide ways for users to manually request autofill by calling
8046     *       {@link AutofillManager#requestAutofill(View, int, Rect)}.
8047     *   <li>The {@code left} and {@code top} values set in
8048     *       {@link ViewStructure#setDimens(int, int, int, int, int, int)} must be relative to the
8049     *       next {@link ViewGroup#isImportantForAutofill()} predecessor view included in the
8050     *       structure.
8051     * </ul>
8052     *
8053     * <p>Views with virtual children support the Autofill Framework mainly by:
8054     * <ul>
8055     *   <li>Providing the metadata defining what the virtual children mean and how they can be
8056     *       autofilled.
8057     *   <li>Implementing the methods that autofill the virtual children.
8058     * </ul>
8059     * <p>This method is responsible for the former; {@link #autofill(SparseArray)} is responsible
8060     * for the latter.
8061     *
8062     * @param structure fill in with virtual children data for autofill purposes.
8063     * @param flags optional flags.
8064     *
8065     * @see #AUTOFILL_FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
8066     */
8067    public void onProvideAutofillVirtualStructure(ViewStructure structure, int flags) {
8068        if (mContext.isAutofillCompatibilityEnabled()) {
8069            onProvideVirtualStructureCompat(structure, true);
8070        }
8071    }
8072
8073    /**
8074     * Automatically fills the content of this view with the {@code value}.
8075     *
8076     * <p>Views support the Autofill Framework mainly by:
8077     * <ul>
8078     *   <li>Providing the metadata defining what the view means and how it can be autofilled.
8079     *   <li>Implementing the methods that autofill the view.
8080     * </ul>
8081     * <p>{@link #onProvideAutofillStructure(ViewStructure, int)} is responsible for the former,
8082     * this method is responsible for latter.
8083     *
8084     * <p>This method does nothing by default, but when overridden it typically:
8085     * <ol>
8086     *   <li>Checks if the provided value matches the expected type (which is defined by
8087     *       {@link #getAutofillType()}).
8088     *   <li>Checks if the view is editable - if it isn't, it should return right away.
8089     *   <li>Call the proper getter method on {@link AutofillValue} to fetch the actual value.
8090     *   <li>Pass the actual value to the equivalent setter in the view.
8091     * </ol>
8092     *
8093     * <p>For example, a text-field view could implement the method this way:
8094     *
8095     * <pre class="prettyprint">
8096     * &#64;Override
8097     * public void autofill(AutofillValue value) {
8098     *   if (!value.isText() || !this.isEditable()) {
8099     *      return;
8100     *   }
8101     *   CharSequence text = value.getTextValue();
8102     *   if (text != null) {
8103     *     this.setText(text);
8104     *   }
8105     * }
8106     * </pre>
8107     *
8108     * <p>If the value is updated asynchronously, the next call to
8109     * {@link AutofillManager#notifyValueChanged(View)} must happen <b>after</b> the value was
8110     * changed to the autofilled value. If not, the view will not be considered autofilled.
8111     *
8112     * <p><b>Note:</b> After this method is called, the value returned by
8113     * {@link #getAutofillValue()} must be equal to the {@code value} passed to it, otherwise the
8114     * view will not be highlighted as autofilled.
8115     *
8116     * @param value value to be autofilled.
8117     */
8118    public void autofill(@SuppressWarnings("unused") AutofillValue value) {
8119    }
8120
8121    /**
8122     * Automatically fills the content of the virtual children within this view.
8123     *
8124     * <p>Views with virtual children support the Autofill Framework mainly by:
8125     * <ul>
8126     *   <li>Providing the metadata defining what the virtual children mean and how they can be
8127     *       autofilled.
8128     *   <li>Implementing the methods that autofill the virtual children.
8129     * </ul>
8130     * <p>{@link #onProvideAutofillVirtualStructure(ViewStructure, int)} is responsible for the
8131     * former, this method is responsible for the latter - see {@link #autofill(AutofillValue)} and
8132     * {@link #onProvideAutofillVirtualStructure(ViewStructure, int)} for more info about autofill.
8133     *
8134     * <p>If a child value is updated asynchronously, the next call to
8135     * {@link AutofillManager#notifyValueChanged(View, int, AutofillValue)} must happen
8136     * <b>after</b> the value was changed to the autofilled value. If not, the child will not be
8137     * considered autofilled.
8138     *
8139     * <p><b>Note:</b> To indicate that a virtual view was autofilled,
8140     * <code>?android:attr/autofilledHighlight</code> should be drawn over it until the data
8141     * changes.
8142     *
8143     * @param values map of values to be autofilled, keyed by virtual child id.
8144     *
8145     * @attr ref android.R.styleable#Theme_autofilledHighlight
8146     */
8147    public void autofill(@NonNull @SuppressWarnings("unused") SparseArray<AutofillValue> values) {
8148        if (!mContext.isAutofillCompatibilityEnabled()) {
8149            return;
8150        }
8151        final AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
8152        if (provider == null) {
8153            return;
8154        }
8155        final int valueCount = values.size();
8156        for (int i = 0; i < valueCount; i++) {
8157            final AutofillValue value = values.valueAt(i);
8158            if (value.isText()) {
8159                final int virtualId = values.keyAt(i);
8160                final CharSequence text = value.getTextValue();
8161                final Bundle arguments = new Bundle();
8162                arguments.putCharSequence(
8163                        AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, text);
8164                provider.performAction(virtualId, AccessibilityNodeInfo.ACTION_SET_TEXT, arguments);
8165            }
8166        }
8167    }
8168
8169    /**
8170     * Gets the unique, logical identifier of this view in the activity, for autofill purposes.
8171     *
8172     * <p>The autofill id is created on demand, unless it is explicitly set by
8173     * {@link #setAutofillId(AutofillId)}.
8174     *
8175     * <p>See {@link #setAutofillId(AutofillId)} for more info.
8176     *
8177     * @return The View's autofill id.
8178     */
8179    public final AutofillId getAutofillId() {
8180        if (mAutofillId == null) {
8181            // The autofill id needs to be unique, but its value doesn't matter,
8182            // so it's better to reuse the accessibility id to save space.
8183            mAutofillId = new AutofillId(getAutofillViewId());
8184        }
8185        return mAutofillId;
8186    }
8187
8188    /**
8189     * Sets the unique, logical identifier of this view in the activity, for autofill purposes.
8190     *
8191     * <p>The autofill id is created on demand, and this method should only be called when a view is
8192     * reused after {@link #dispatchProvideAutofillStructure(ViewStructure, int)} is called, as
8193     * that method creates a snapshot of the view that is passed along to the autofill service.
8194     *
8195     * <p>This method is typically used when view subtrees are recycled to represent different
8196     * content* &mdash;in this case, the autofill id can be saved before the view content is swapped
8197     * out, and restored later when it's swapped back in. For example:
8198     *
8199     * <pre>
8200     * EditText reusableView = ...;
8201     * ViewGroup parentView = ...;
8202     * AutofillManager afm = ...;
8203     *
8204     * // Swap out the view and change its contents
8205     * AutofillId oldId = reusableView.getAutofillId();
8206     * CharSequence oldText = reusableView.getText();
8207     * parentView.removeView(reusableView);
8208     * AutofillId newId = afm.getNextAutofillId();
8209     * reusableView.setText("New I am");
8210     * reusableView.setAutofillId(newId);
8211     * parentView.addView(reusableView);
8212     *
8213     * // Later, swap the old content back in
8214     * parentView.removeView(reusableView);
8215     * reusableView.setAutofillId(oldId);
8216     * reusableView.setText(oldText);
8217     * parentView.addView(reusableView);
8218     * </pre>
8219     *
8220     * @param id an autofill ID that is unique in the {@link android.app.Activity} hosting the view,
8221     * or {@code null} to reset it. Usually it's an id previously allocated to another view (and
8222     * obtained through {@link #getAutofillId()}), or a new value obtained through
8223     * {@link AutofillManager#getNextAutofillId()}.
8224     *
8225     * @throws IllegalStateException if the view is already {@link #isAttachedToWindow() attached to
8226     * a window}.
8227     *
8228     * @throws IllegalArgumentException if the id is an autofill id associated with a virtual view.
8229     */
8230    public void setAutofillId(@Nullable AutofillId id) {
8231        // TODO(b/37566627): add unit / CTS test for all possible combinations below
8232        if (android.view.autofill.Helper.sVerbose) {
8233            Log.v(VIEW_LOG_TAG, "setAutofill(): from " + mAutofillId + " to " + id);
8234        }
8235        if (isAttachedToWindow()) {
8236            throw new IllegalStateException("Cannot set autofill id when view is attached");
8237        }
8238        if (id != null && id.isVirtual()) {
8239            throw new IllegalStateException("Cannot set autofill id assigned to virtual views");
8240        }
8241        if (id == null && (mPrivateFlags3 & PFLAG3_AUTOFILLID_EXPLICITLY_SET) == 0) {
8242            // Ignore reset because it was never explicitly set before.
8243            return;
8244        }
8245        mAutofillId = id;
8246        if (id != null) {
8247            mAutofillViewId = id.getViewId();
8248            mPrivateFlags3 |= PFLAG3_AUTOFILLID_EXPLICITLY_SET;
8249        } else {
8250            mAutofillViewId = NO_ID;
8251            mPrivateFlags3 &= ~PFLAG3_AUTOFILLID_EXPLICITLY_SET;
8252        }
8253    }
8254
8255    /**
8256     * Describes the autofill type of this view, so an
8257     * {@link android.service.autofill.AutofillService} can create the proper {@link AutofillValue}
8258     * when autofilling the view.
8259     *
8260     * <p>By default returns {@link #AUTOFILL_TYPE_NONE}, but views should override it to properly
8261     * support the Autofill Framework.
8262     *
8263     * @return either {@link #AUTOFILL_TYPE_NONE}, {@link #AUTOFILL_TYPE_TEXT},
8264     * {@link #AUTOFILL_TYPE_LIST}, {@link #AUTOFILL_TYPE_DATE}, or {@link #AUTOFILL_TYPE_TOGGLE}.
8265     *
8266     * @see #onProvideAutofillStructure(ViewStructure, int)
8267     * @see #autofill(AutofillValue)
8268     */
8269    public @AutofillType int getAutofillType() {
8270        return AUTOFILL_TYPE_NONE;
8271    }
8272
8273    /**
8274     * Gets the hints that help an {@link android.service.autofill.AutofillService} determine how
8275     * to autofill the view with the user's data.
8276     *
8277     * <p>See {@link #setAutofillHints(String...)} for more info about these hints.
8278     *
8279     * @return The hints set via the attribute or {@link #setAutofillHints(String...)}, or
8280     * {@code null} if no hints were set.
8281     *
8282     * @attr ref android.R.styleable#View_autofillHints
8283     */
8284    @ViewDebug.ExportedProperty()
8285    @Nullable public String[] getAutofillHints() {
8286        return mAutofillHints;
8287    }
8288
8289    /**
8290     * @hide
8291     */
8292    public boolean isAutofilled() {
8293        return (mPrivateFlags3 & PFLAG3_IS_AUTOFILLED) != 0;
8294    }
8295
8296    /**
8297     * Gets the {@link View}'s current autofill value.
8298     *
8299     * <p>By default returns {@code null}, but subclasses should override it and return an
8300     * appropriate value to properly support the Autofill Framework.
8301     *
8302     * @see #onProvideAutofillStructure(ViewStructure, int)
8303     * @see #autofill(AutofillValue)
8304     */
8305    @Nullable
8306    public AutofillValue getAutofillValue() {
8307        return null;
8308    }
8309
8310    /**
8311     * Gets the mode for determining whether this view is important for autofill.
8312     *
8313     * <p>See {@link #setImportantForAutofill(int)} and {@link #isImportantForAutofill()} for more
8314     * info about this mode.
8315     *
8316     * @return {@link #IMPORTANT_FOR_AUTOFILL_AUTO} by default, or value passed to
8317     * {@link #setImportantForAutofill(int)}.
8318     *
8319     * @attr ref android.R.styleable#View_importantForAutofill
8320     */
8321    @ViewDebug.ExportedProperty(mapping = {
8322            @ViewDebug.IntToString(from = IMPORTANT_FOR_AUTOFILL_AUTO, to = "auto"),
8323            @ViewDebug.IntToString(from = IMPORTANT_FOR_AUTOFILL_YES, to = "yes"),
8324            @ViewDebug.IntToString(from = IMPORTANT_FOR_AUTOFILL_NO, to = "no"),
8325            @ViewDebug.IntToString(from = IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS,
8326                to = "yesExcludeDescendants"),
8327            @ViewDebug.IntToString(from = IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS,
8328                to = "noExcludeDescendants")})
8329    public @AutofillImportance int getImportantForAutofill() {
8330        return (mPrivateFlags3
8331                & PFLAG3_IMPORTANT_FOR_AUTOFILL_MASK) >> PFLAG3_IMPORTANT_FOR_AUTOFILL_SHIFT;
8332    }
8333
8334    /**
8335     * Sets the mode for determining whether this view is considered important for autofill.
8336     *
8337     * <p>The platform determines the importance for autofill automatically but you
8338     * can use this method to customize the behavior. For example:
8339     *
8340     * <ol>
8341     *   <li>When the view contents is irrelevant for autofill (for example, a text field used in a
8342     *       "Captcha" challenge), it should be {@link #IMPORTANT_FOR_AUTOFILL_NO}.
8343     *   <li>When both the view and its children are irrelevant for autofill (for example, the root
8344     *       view of an activity containing a spreadhseet editor), it should be
8345     *       {@link #IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS}.
8346     *   <li>When the view content is relevant for autofill but its children aren't (for example,
8347     *       a credit card expiration date represented by a custom view that overrides the proper
8348     *       autofill methods and has 2 children representing the month and year), it should
8349     *       be {@link #IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS}.
8350     * </ol>
8351     *
8352     * <p><b>Note:</b> Setting the mode as {@link #IMPORTANT_FOR_AUTOFILL_NO} or
8353     * {@link #IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS} does not guarantee the view (and its
8354     * children) will be always be considered not important; for example, when the user explicitly
8355     * makes an autofill request, all views are considered important. See
8356     * {@link #isImportantForAutofill()} for more details about how the View's importance for
8357     * autofill is used.
8358     *
8359     * @param mode {@link #IMPORTANT_FOR_AUTOFILL_AUTO}, {@link #IMPORTANT_FOR_AUTOFILL_YES},
8360     * {@link #IMPORTANT_FOR_AUTOFILL_NO}, {@link #IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS},
8361     * or {@link #IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS}.
8362     *
8363     * @attr ref android.R.styleable#View_importantForAutofill
8364     */
8365    public void setImportantForAutofill(@AutofillImportance int mode) {
8366        mPrivateFlags3 &= ~PFLAG3_IMPORTANT_FOR_AUTOFILL_MASK;
8367        mPrivateFlags3 |= (mode << PFLAG3_IMPORTANT_FOR_AUTOFILL_SHIFT)
8368                & PFLAG3_IMPORTANT_FOR_AUTOFILL_MASK;
8369    }
8370
8371    /**
8372     * Hints the Android System whether the {@link android.app.assist.AssistStructure.ViewNode}
8373     * associated with this view is considered important for autofill purposes.
8374     *
8375     * <p>Generally speaking, a view is important for autofill if:
8376     * <ol>
8377     * <li>The view can be autofilled by an {@link android.service.autofill.AutofillService}.
8378     * <li>The view contents can help an {@link android.service.autofill.AutofillService}
8379     *     determine how other views can be autofilled.
8380     * <ol>
8381     *
8382     * <p>For example, view containers should typically return {@code false} for performance reasons
8383     * (since the important info is provided by their children), but if its properties have relevant
8384     * information (for example, a resource id called {@code credentials}, it should return
8385     * {@code true}. On the other hand, views representing labels or editable fields should
8386     * typically return {@code true}, but in some cases they could return {@code false}
8387     * (for example, if they're part of a "Captcha" mechanism).
8388     *
8389     * <p>The value returned by this method depends on the value returned by
8390     * {@link #getImportantForAutofill()}:
8391     *
8392     * <ol>
8393     *   <li>if it returns {@link #IMPORTANT_FOR_AUTOFILL_YES} or
8394     *       {@link #IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS}, then it returns {@code true}
8395     *   <li>if it returns {@link #IMPORTANT_FOR_AUTOFILL_NO} or
8396     *       {@link #IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS}, then it returns {@code false}
8397     *   <li>if it returns {@link #IMPORTANT_FOR_AUTOFILL_AUTO}, then it uses some simple heuristics
8398     *       that can return {@code true} in some cases (like a container with a resource id),
8399     *       but {@code false} in most.
8400     *   <li>otherwise, it returns {@code false}.
8401     * </ol>
8402     *
8403     * <p>When a view is considered important for autofill:
8404     * <ul>
8405     *   <li>The view might automatically trigger an autofill request when focused on.
8406     *   <li>The contents of the view are included in the {@link ViewStructure} used in an autofill
8407     *       request.
8408     * </ul>
8409     *
8410     * <p>On the other hand, when a view is considered not important for autofill:
8411     * <ul>
8412     *   <li>The view never automatically triggers autofill requests, but it can trigger a manual
8413     *       request through {@link AutofillManager#requestAutofill(View)}.
8414     *   <li>The contents of the view are not included in the {@link ViewStructure} used in an
8415     *       autofill request, unless the request has the
8416     *       {@link #AUTOFILL_FLAG_INCLUDE_NOT_IMPORTANT_VIEWS} flag.
8417     * </ul>
8418     *
8419     * @return whether the view is considered important for autofill.
8420     *
8421     * @see #setImportantForAutofill(int)
8422     * @see #IMPORTANT_FOR_AUTOFILL_AUTO
8423     * @see #IMPORTANT_FOR_AUTOFILL_YES
8424     * @see #IMPORTANT_FOR_AUTOFILL_NO
8425     * @see #IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS
8426     * @see #IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS
8427     * @see AutofillManager#requestAutofill(View)
8428     */
8429    public final boolean isImportantForAutofill() {
8430        // Check parent mode to ensure we're not hidden.
8431        ViewParent parent = mParent;
8432        while (parent instanceof View) {
8433            final int parentImportance = ((View) parent).getImportantForAutofill();
8434            if (parentImportance == IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS
8435                    || parentImportance == IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS) {
8436                return false;
8437            }
8438            parent = parent.getParent();
8439        }
8440
8441        final int importance = getImportantForAutofill();
8442
8443        // First, check the explicit states.
8444        if (importance == IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS
8445                || importance == IMPORTANT_FOR_AUTOFILL_YES) {
8446            return true;
8447        }
8448        if (importance == IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS
8449                || importance == IMPORTANT_FOR_AUTOFILL_NO) {
8450            return false;
8451        }
8452
8453        // Then use some heuristics to handle AUTO.
8454
8455        // Always include views that have an explicit resource id.
8456        final int id = mID;
8457        if (id != NO_ID && !isViewIdGenerated(id)) {
8458            final Resources res = getResources();
8459            String entry = null;
8460            String pkg = null;
8461            try {
8462                entry = res.getResourceEntryName(id);
8463                pkg = res.getResourcePackageName(id);
8464            } catch (Resources.NotFoundException e) {
8465                // ignore
8466            }
8467            if (entry != null && pkg != null && pkg.equals(mContext.getPackageName())) {
8468                return true;
8469            }
8470        }
8471
8472        // If the app developer explicitly set hints for it, it's important.
8473        if (getAutofillHints() != null) {
8474            return true;
8475        }
8476
8477        // Otherwise, assume it's not important...
8478        return false;
8479    }
8480
8481    @Nullable
8482    private AutofillManager getAutofillManager() {
8483        return mContext.getSystemService(AutofillManager.class);
8484    }
8485
8486    private boolean isAutofillable() {
8487        return getAutofillType() != AUTOFILL_TYPE_NONE && isImportantForAutofill()
8488                && getAutofillViewId() > LAST_APP_AUTOFILL_ID;
8489    }
8490
8491    /** @hide */
8492    public boolean canNotifyAutofillEnterExitEvent() {
8493        return isAutofillable() && isAttachedToWindow();
8494    }
8495
8496    private void populateVirtualStructure(ViewStructure structure,
8497            AccessibilityNodeProvider provider, AccessibilityNodeInfo info,
8498            boolean forAutofill) {
8499        structure.setId(AccessibilityNodeInfo.getVirtualDescendantId(info.getSourceNodeId()),
8500                null, null, info.getViewIdResourceName());
8501        Rect rect = structure.getTempRect();
8502        info.getBoundsInParent(rect);
8503        structure.setDimens(rect.left, rect.top, 0, 0, rect.width(), rect.height());
8504        structure.setVisibility(VISIBLE);
8505        structure.setEnabled(info.isEnabled());
8506        if (info.isClickable()) {
8507            structure.setClickable(true);
8508        }
8509        if (info.isFocusable()) {
8510            structure.setFocusable(true);
8511        }
8512        if (info.isFocused()) {
8513            structure.setFocused(true);
8514        }
8515        if (info.isAccessibilityFocused()) {
8516            structure.setAccessibilityFocused(true);
8517        }
8518        if (info.isSelected()) {
8519            structure.setSelected(true);
8520        }
8521        if (info.isLongClickable()) {
8522            structure.setLongClickable(true);
8523        }
8524        if (info.isCheckable()) {
8525            structure.setCheckable(true);
8526            if (info.isChecked()) {
8527                structure.setChecked(true);
8528            }
8529        }
8530        if (info.isContextClickable()) {
8531            structure.setContextClickable(true);
8532        }
8533        if (forAutofill) {
8534            structure.setAutofillId(new AutofillId(getAutofillId(),
8535                    AccessibilityNodeInfo.getVirtualDescendantId(info.getSourceNodeId())));
8536        }
8537        CharSequence cname = info.getClassName();
8538        structure.setClassName(cname != null ? cname.toString() : null);
8539        structure.setContentDescription(info.getContentDescription());
8540        if (forAutofill) {
8541            final int maxTextLength = info.getMaxTextLength();
8542            if (maxTextLength != -1) {
8543                structure.setMaxTextLength(maxTextLength);
8544            }
8545            structure.setHint(info.getHintText());
8546        }
8547        CharSequence text = info.getText();
8548        boolean hasText = text != null || info.getError() != null;
8549        if (hasText) {
8550            structure.setText(text, info.getTextSelectionStart(), info.getTextSelectionEnd());
8551        }
8552        if (forAutofill) {
8553            if (info.isEditable()) {
8554                structure.setDataIsSensitive(true);
8555                if (hasText) {
8556                    structure.setAutofillType(AUTOFILL_TYPE_TEXT);
8557                    structure.setAutofillValue(AutofillValue.forText(text));
8558                }
8559                int inputType = info.getInputType();
8560                if (inputType == 0 && info.isPassword()) {
8561                    inputType = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD;
8562                }
8563                structure.setInputType(inputType);
8564            } else {
8565                structure.setDataIsSensitive(false);
8566            }
8567        }
8568        final int NCHILDREN = info.getChildCount();
8569        if (NCHILDREN > 0) {
8570            structure.setChildCount(NCHILDREN);
8571            for (int i=0; i<NCHILDREN; i++) {
8572                if (AccessibilityNodeInfo.getVirtualDescendantId(info.getChildNodeIds().get(i))
8573                        == AccessibilityNodeProvider.HOST_VIEW_ID) {
8574                    Log.e(VIEW_LOG_TAG, "Virtual view pointing to its host. Ignoring");
8575                    continue;
8576                }
8577                AccessibilityNodeInfo cinfo = provider.createAccessibilityNodeInfo(
8578                        AccessibilityNodeInfo.getVirtualDescendantId(info.getChildId(i)));
8579                ViewStructure child = structure.newChild(i);
8580                populateVirtualStructure(child, provider, cinfo, forAutofill);
8581                cinfo.recycle();
8582            }
8583        }
8584    }
8585
8586    /**
8587     * Dispatch creation of {@link ViewStructure} down the hierarchy.  The default
8588     * implementation calls {@link #onProvideStructure} and
8589     * {@link #onProvideVirtualStructure}.
8590     */
8591    public void dispatchProvideStructure(ViewStructure structure) {
8592        dispatchProvideStructureForAssistOrAutofill(structure, false, 0);
8593    }
8594
8595    /**
8596     * Dispatches creation of a {@link ViewStructure}s for autofill purposes down the hierarchy,
8597     * when an Assist structure is being created as part of an autofill request.
8598     *
8599     * <p>The default implementation does the following:
8600     * <ul>
8601     *   <li>Sets the {@link AutofillId} in the structure.
8602     *   <li>Calls {@link #onProvideAutofillStructure(ViewStructure, int)}.
8603     *   <li>Calls {@link #onProvideAutofillVirtualStructure(ViewStructure, int)}.
8604     * </ul>
8605     *
8606     * <p>Typically, this method should only be overridden by subclasses that provide a view
8607     * hierarchy (such as {@link ViewGroup}) - other classes should override
8608     * {@link #onProvideAutofillStructure(ViewStructure, int)} or
8609     * {@link #onProvideAutofillVirtualStructure(ViewStructure, int)} instead.
8610     *
8611     * <p>When overridden, it must:
8612     *
8613     * <ul>
8614     *   <li>Either call
8615     *       {@code super.dispatchProvideAutofillStructure(structure, flags)} or explicitly
8616     *       set the {@link AutofillId} in the structure (for example, by calling
8617     *       {@code structure.setAutofillId(getAutofillId())}).
8618     *   <li>Decide how to handle the {@link #AUTOFILL_FLAG_INCLUDE_NOT_IMPORTANT_VIEWS} flag - when
8619     *       set, all views in the structure should be considered important for autofill,
8620     *       regardless of what {@link #isImportantForAutofill()} returns. We encourage you to
8621     *       respect this flag to provide a better user experience - this flag is typically used
8622     *       when an user explicitly requested autofill. If the flag is not set,
8623     *       then only views marked as important for autofill should be included in the
8624     *       structure - skipping non-important views optimizes the overall autofill performance.
8625     * </ul>
8626     *
8627     * @param structure fill in with structured view data for autofill purposes.
8628     * @param flags optional flags.
8629     *
8630     * @see #AUTOFILL_FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
8631     */
8632    public void dispatchProvideAutofillStructure(@NonNull ViewStructure structure,
8633            @AutofillFlags int flags) {
8634        dispatchProvideStructureForAssistOrAutofill(structure, true, flags);
8635    }
8636
8637    private void dispatchProvideStructureForAssistOrAutofill(ViewStructure structure,
8638            boolean forAutofill, @AutofillFlags int flags) {
8639        if (forAutofill) {
8640            structure.setAutofillId(getAutofillId());
8641            onProvideAutofillStructure(structure, flags);
8642            onProvideAutofillVirtualStructure(structure, flags);
8643        } else if (!isAssistBlocked()) {
8644            onProvideStructure(structure);
8645            onProvideVirtualStructure(structure);
8646        } else {
8647            structure.setClassName(getAccessibilityClassName().toString());
8648            structure.setAssistBlocked(true);
8649        }
8650    }
8651
8652    /**
8653     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
8654     *
8655     * Note: Called from the default {@link AccessibilityDelegate}.
8656     *
8657     * @hide
8658     */
8659    public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
8660        if (mAttachInfo == null) {
8661            return;
8662        }
8663
8664        Rect bounds = mAttachInfo.mTmpInvalRect;
8665
8666        getDrawingRect(bounds);
8667        info.setBoundsInParent(bounds);
8668
8669        getBoundsOnScreen(bounds, true);
8670        info.setBoundsInScreen(bounds);
8671
8672        ViewParent parent = getParentForAccessibility();
8673        if (parent instanceof View) {
8674            info.setParent((View) parent);
8675        }
8676
8677        if (mID != View.NO_ID) {
8678            View rootView = getRootView();
8679            if (rootView == null) {
8680                rootView = this;
8681            }
8682
8683            View label = rootView.findLabelForView(this, mID);
8684            if (label != null) {
8685                info.setLabeledBy(label);
8686            }
8687
8688            if ((mAttachInfo.mAccessibilityFetchFlags
8689                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
8690                    && Resources.resourceHasPackage(mID)) {
8691                try {
8692                    String viewId = getResources().getResourceName(mID);
8693                    info.setViewIdResourceName(viewId);
8694                } catch (Resources.NotFoundException nfe) {
8695                    /* ignore */
8696                }
8697            }
8698        }
8699
8700        if (mLabelForId != View.NO_ID) {
8701            View rootView = getRootView();
8702            if (rootView == null) {
8703                rootView = this;
8704            }
8705            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
8706            if (labeled != null) {
8707                info.setLabelFor(labeled);
8708            }
8709        }
8710
8711        if (mAccessibilityTraversalBeforeId != View.NO_ID) {
8712            View rootView = getRootView();
8713            if (rootView == null) {
8714                rootView = this;
8715            }
8716            View next = rootView.findViewInsideOutShouldExist(this,
8717                    mAccessibilityTraversalBeforeId);
8718            if (next != null && next.includeForAccessibility()) {
8719                info.setTraversalBefore(next);
8720            }
8721        }
8722
8723        if (mAccessibilityTraversalAfterId != View.NO_ID) {
8724            View rootView = getRootView();
8725            if (rootView == null) {
8726                rootView = this;
8727            }
8728            View next = rootView.findViewInsideOutShouldExist(this,
8729                    mAccessibilityTraversalAfterId);
8730            if (next != null && next.includeForAccessibility()) {
8731                info.setTraversalAfter(next);
8732            }
8733        }
8734
8735        info.setVisibleToUser(isVisibleToUser());
8736
8737        info.setImportantForAccessibility(isImportantForAccessibility());
8738        info.setPackageName(mContext.getPackageName());
8739        info.setClassName(getAccessibilityClassName());
8740        info.setContentDescription(getContentDescription());
8741
8742        info.setEnabled(isEnabled());
8743        info.setClickable(isClickable());
8744        info.setFocusable(isFocusable());
8745        info.setScreenReaderFocusable(isScreenReaderFocusable());
8746        info.setFocused(isFocused());
8747        info.setAccessibilityFocused(isAccessibilityFocused());
8748        info.setSelected(isSelected());
8749        info.setLongClickable(isLongClickable());
8750        info.setContextClickable(isContextClickable());
8751        info.setLiveRegion(getAccessibilityLiveRegion());
8752        if ((mTooltipInfo != null) && (mTooltipInfo.mTooltipText != null)) {
8753            info.setTooltipText(mTooltipInfo.mTooltipText);
8754            info.addAction((mTooltipInfo.mTooltipPopup == null)
8755                    ? AccessibilityNodeInfo.AccessibilityAction.ACTION_SHOW_TOOLTIP
8756                    : AccessibilityNodeInfo.AccessibilityAction.ACTION_HIDE_TOOLTIP);
8757        }
8758
8759        // TODO: These make sense only if we are in an AdapterView but all
8760        // views can be selected. Maybe from accessibility perspective
8761        // we should report as selectable view in an AdapterView.
8762        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
8763        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
8764
8765        if (isFocusable()) {
8766            if (isFocused()) {
8767                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
8768            } else {
8769                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
8770            }
8771        }
8772
8773        if (!isAccessibilityFocused()) {
8774            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
8775        } else {
8776            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
8777        }
8778
8779        if (isClickable() && isEnabled()) {
8780            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
8781        }
8782
8783        if (isLongClickable() && isEnabled()) {
8784            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
8785        }
8786
8787        if (isContextClickable() && isEnabled()) {
8788            info.addAction(AccessibilityAction.ACTION_CONTEXT_CLICK);
8789        }
8790
8791        CharSequence text = getIterableTextForAccessibility();
8792        if (text != null && text.length() > 0) {
8793            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
8794
8795            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
8796            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
8797            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
8798            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
8799                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
8800                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
8801        }
8802
8803        info.addAction(AccessibilityAction.ACTION_SHOW_ON_SCREEN);
8804        populateAccessibilityNodeInfoDrawingOrderInParent(info);
8805        info.setPaneTitle(mAccessibilityPaneTitle);
8806        info.setHeading(isAccessibilityHeading());
8807    }
8808
8809    /**
8810     * Adds extra data to an {@link AccessibilityNodeInfo} based on an explicit request for the
8811     * additional data.
8812     * <p>
8813     * This method only needs overloading if the node is marked as having extra data available.
8814     * </p>
8815     *
8816     * @param info The info to which to add the extra data. Never {@code null}.
8817     * @param extraDataKey A key specifying the type of extra data to add to the info. The
8818     *                     extra data should be added to the {@link Bundle} returned by
8819     *                     the info's {@link AccessibilityNodeInfo#getExtras} method. Never
8820     *                     {@code null}.
8821     * @param arguments A {@link Bundle} holding any arguments relevant for this request. May be
8822     *                  {@code null} if the service provided no arguments.
8823     *
8824     * @see AccessibilityNodeInfo#setAvailableExtraData(List)
8825     */
8826    public void addExtraDataToAccessibilityNodeInfo(
8827            @NonNull AccessibilityNodeInfo info, @NonNull String extraDataKey,
8828            @Nullable Bundle arguments) {
8829    }
8830
8831    /**
8832     * Determine the order in which this view will be drawn relative to its siblings for a11y
8833     *
8834     * @param info The info whose drawing order should be populated
8835     */
8836    private void populateAccessibilityNodeInfoDrawingOrderInParent(AccessibilityNodeInfo info) {
8837        /*
8838         * If the view's bounds haven't been set yet, layout has not completed. In that situation,
8839         * drawing order may not be well-defined, and some Views with custom drawing order may
8840         * not be initialized sufficiently to respond properly getChildDrawingOrder.
8841         */
8842        if ((mPrivateFlags & PFLAG_HAS_BOUNDS) == 0) {
8843            info.setDrawingOrder(0);
8844            return;
8845        }
8846        int drawingOrderInParent = 1;
8847        // Iterate up the hierarchy if parents are not important for a11y
8848        View viewAtDrawingLevel = this;
8849        final ViewParent parent = getParentForAccessibility();
8850        while (viewAtDrawingLevel != parent) {
8851            final ViewParent currentParent = viewAtDrawingLevel.getParent();
8852            if (!(currentParent instanceof ViewGroup)) {
8853                // Should only happen for the Decor
8854                drawingOrderInParent = 0;
8855                break;
8856            } else {
8857                final ViewGroup parentGroup = (ViewGroup) currentParent;
8858                final int childCount = parentGroup.getChildCount();
8859                if (childCount > 1) {
8860                    List<View> preorderedList = parentGroup.buildOrderedChildList();
8861                    if (preorderedList != null) {
8862                        final int childDrawIndex = preorderedList.indexOf(viewAtDrawingLevel);
8863                        for (int i = 0; i < childDrawIndex; i++) {
8864                            drawingOrderInParent += numViewsForAccessibility(preorderedList.get(i));
8865                        }
8866                    } else {
8867                        final int childIndex = parentGroup.indexOfChild(viewAtDrawingLevel);
8868                        final boolean customOrder = parentGroup.isChildrenDrawingOrderEnabled();
8869                        final int childDrawIndex = ((childIndex >= 0) && customOrder) ? parentGroup
8870                                .getChildDrawingOrder(childCount, childIndex) : childIndex;
8871                        final int numChildrenToIterate = customOrder ? childCount : childDrawIndex;
8872                        if (childDrawIndex != 0) {
8873                            for (int i = 0; i < numChildrenToIterate; i++) {
8874                                final int otherDrawIndex = (customOrder ?
8875                                        parentGroup.getChildDrawingOrder(childCount, i) : i);
8876                                if (otherDrawIndex < childDrawIndex) {
8877                                    drawingOrderInParent +=
8878                                            numViewsForAccessibility(parentGroup.getChildAt(i));
8879                                }
8880                            }
8881                        }
8882                    }
8883                }
8884            }
8885            viewAtDrawingLevel = (View) currentParent;
8886        }
8887        info.setDrawingOrder(drawingOrderInParent);
8888    }
8889
8890    private static int numViewsForAccessibility(View view) {
8891        if (view != null) {
8892            if (view.includeForAccessibility()) {
8893                return 1;
8894            } else if (view instanceof ViewGroup) {
8895                return ((ViewGroup) view).getNumChildrenForAccessibility();
8896            }
8897        }
8898        return 0;
8899    }
8900
8901    private View findLabelForView(View view, int labeledId) {
8902        if (mMatchLabelForPredicate == null) {
8903            mMatchLabelForPredicate = new MatchLabelForPredicate();
8904        }
8905        mMatchLabelForPredicate.mLabeledId = labeledId;
8906        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
8907    }
8908
8909    /**
8910     * Computes whether this virtual autofill view is visible to the user.
8911     *
8912     * <p><b>Note: </b>By default it returns {@code true}, but views providing a virtual hierarchy
8913     * view must override it.
8914     *
8915     * @return Whether the view is visible on the screen.
8916     */
8917    public boolean isVisibleToUserForAutofill(int virtualId) {
8918        if (mContext.isAutofillCompatibilityEnabled()) {
8919            final AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
8920            if (provider != null) {
8921                final AccessibilityNodeInfo node = provider.createAccessibilityNodeInfo(virtualId);
8922                if (node != null) {
8923                    return node.isVisibleToUser();
8924                }
8925                // if node is null, assume it's not visible anymore
8926            } else {
8927                Log.w(VIEW_LOG_TAG, "isVisibleToUserForAutofill(" + virtualId + "): no provider");
8928            }
8929            return false;
8930        }
8931        return true;
8932    }
8933
8934    /**
8935     * Computes whether this view is visible to the user. Such a view is
8936     * attached, visible, all its predecessors are visible, it is not clipped
8937     * entirely by its predecessors, and has an alpha greater than zero.
8938     *
8939     * @return Whether the view is visible on the screen.
8940     *
8941     * @hide
8942     */
8943    public boolean isVisibleToUser() {
8944        return isVisibleToUser(null);
8945    }
8946
8947    /**
8948     * Computes whether the given portion of this view is visible to the user.
8949     * Such a view is attached, visible, all its predecessors are visible,
8950     * has an alpha greater than zero, and the specified portion is not
8951     * clipped entirely by its predecessors.
8952     *
8953     * @param boundInView the portion of the view to test; coordinates should be relative; may be
8954     *                    <code>null</code>, and the entire view will be tested in this case.
8955     *                    When <code>true</code> is returned by the function, the actual visible
8956     *                    region will be stored in this parameter; that is, if boundInView is fully
8957     *                    contained within the view, no modification will be made, otherwise regions
8958     *                    outside of the visible area of the view will be clipped.
8959     *
8960     * @return Whether the specified portion of the view is visible on the screen.
8961     *
8962     * @hide
8963     */
8964    protected boolean isVisibleToUser(Rect boundInView) {
8965        if (mAttachInfo != null) {
8966            // Attached to invisible window means this view is not visible.
8967            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
8968                return false;
8969            }
8970            // An invisible predecessor or one with alpha zero means
8971            // that this view is not visible to the user.
8972            Object current = this;
8973            while (current instanceof View) {
8974                View view = (View) current;
8975                // We have attach info so this view is attached and there is no
8976                // need to check whether we reach to ViewRootImpl on the way up.
8977                if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
8978                        view.getVisibility() != VISIBLE) {
8979                    return false;
8980                }
8981                current = view.mParent;
8982            }
8983            // Check if the view is entirely covered by its predecessors.
8984            Rect visibleRect = mAttachInfo.mTmpInvalRect;
8985            Point offset = mAttachInfo.mPoint;
8986            if (!getGlobalVisibleRect(visibleRect, offset)) {
8987                return false;
8988            }
8989            // Check if the visible portion intersects the rectangle of interest.
8990            if (boundInView != null) {
8991                visibleRect.offset(-offset.x, -offset.y);
8992                return boundInView.intersect(visibleRect);
8993            }
8994            return true;
8995        }
8996        return false;
8997    }
8998
8999    /**
9000     * Returns the delegate for implementing accessibility support via
9001     * composition. For more details see {@link AccessibilityDelegate}.
9002     *
9003     * @return The delegate, or null if none set.
9004     *
9005     * @hide
9006     */
9007    public AccessibilityDelegate getAccessibilityDelegate() {
9008        return mAccessibilityDelegate;
9009    }
9010
9011    /**
9012     * Sets a delegate for implementing accessibility support via composition
9013     * (as opposed to inheritance). For more details, see
9014     * {@link AccessibilityDelegate}.
9015     * <p>
9016     * <strong>Note:</strong> On platform versions prior to
9017     * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on
9018     * views in the {@code android.widget.*} package are called <i>before</i>
9019     * host methods. This prevents certain properties such as class name from
9020     * being modified by overriding
9021     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)},
9022     * as any changes will be overwritten by the host class.
9023     * <p>
9024     * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate
9025     * methods are called <i>after</i> host methods, which all properties to be
9026     * modified without being overwritten by the host class.
9027     *
9028     * @param delegate the object to which accessibility method calls should be
9029     *                 delegated
9030     * @see AccessibilityDelegate
9031     */
9032    public void setAccessibilityDelegate(@Nullable AccessibilityDelegate delegate) {
9033        mAccessibilityDelegate = delegate;
9034    }
9035
9036    /**
9037     * Gets the provider for managing a virtual view hierarchy rooted at this View
9038     * and reported to {@link android.accessibilityservice.AccessibilityService}s
9039     * that explore the window content.
9040     * <p>
9041     * If this method returns an instance, this instance is responsible for managing
9042     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
9043     * View including the one representing the View itself. Similarly the returned
9044     * instance is responsible for performing accessibility actions on any virtual
9045     * view or the root view itself.
9046     * </p>
9047     * <p>
9048     * If an {@link AccessibilityDelegate} has been specified via calling
9049     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
9050     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
9051     * is responsible for handling this call.
9052     * </p>
9053     *
9054     * @return The provider.
9055     *
9056     * @see AccessibilityNodeProvider
9057     */
9058    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
9059        if (mAccessibilityDelegate != null) {
9060            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
9061        } else {
9062            return null;
9063        }
9064    }
9065
9066    /**
9067     * Gets the unique identifier of this view on the screen for accessibility purposes.
9068     *
9069     * @return The view accessibility id.
9070     *
9071     * @hide
9072     */
9073    public int getAccessibilityViewId() {
9074        if (mAccessibilityViewId == NO_ID) {
9075            mAccessibilityViewId = sNextAccessibilityViewId++;
9076        }
9077        return mAccessibilityViewId;
9078    }
9079
9080    /**
9081     * Gets the unique identifier of this view on the screen for autofill purposes.
9082     *
9083     * @return The view autofill id.
9084     *
9085     * @hide
9086     */
9087    public int getAutofillViewId() {
9088        if (mAutofillViewId == NO_ID) {
9089            mAutofillViewId = mContext.getNextAutofillId();
9090        }
9091        return mAutofillViewId;
9092    }
9093
9094    /**
9095     * Gets the unique identifier of the window in which this View reseides.
9096     *
9097     * @return The window accessibility id.
9098     *
9099     * @hide
9100     */
9101    public int getAccessibilityWindowId() {
9102        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId
9103                : AccessibilityWindowInfo.UNDEFINED_WINDOW_ID;
9104    }
9105
9106    /**
9107     * Returns the {@link View}'s content description.
9108     * <p>
9109     * <strong>Note:</strong> Do not override this method, as it will have no
9110     * effect on the content description presented to accessibility services.
9111     * You must call {@link #setContentDescription(CharSequence)} to modify the
9112     * content description.
9113     *
9114     * @return the content description
9115     * @see #setContentDescription(CharSequence)
9116     * @attr ref android.R.styleable#View_contentDescription
9117     */
9118    @ViewDebug.ExportedProperty(category = "accessibility")
9119    public CharSequence getContentDescription() {
9120        return mContentDescription;
9121    }
9122
9123    /**
9124     * Sets the {@link View}'s content description.
9125     * <p>
9126     * A content description briefly describes the view and is primarily used
9127     * for accessibility support to determine how a view should be presented to
9128     * the user. In the case of a view with no textual representation, such as
9129     * {@link android.widget.ImageButton}, a useful content description
9130     * explains what the view does. For example, an image button with a phone
9131     * icon that is used to place a call may use "Call" as its content
9132     * description. An image of a floppy disk that is used to save a file may
9133     * use "Save".
9134     *
9135     * @param contentDescription The content description.
9136     * @see #getContentDescription()
9137     * @attr ref android.R.styleable#View_contentDescription
9138     */
9139    @RemotableViewMethod
9140    public void setContentDescription(CharSequence contentDescription) {
9141        if (mContentDescription == null) {
9142            if (contentDescription == null) {
9143                return;
9144            }
9145        } else if (mContentDescription.equals(contentDescription)) {
9146            return;
9147        }
9148        mContentDescription = contentDescription;
9149        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
9150        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
9151            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
9152            notifySubtreeAccessibilityStateChangedIfNeeded();
9153        } else {
9154            notifyViewAccessibilityStateChangedIfNeeded(
9155                    AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
9156        }
9157    }
9158
9159    /**
9160     * Sets the id of a view before which this one is visited in accessibility traversal.
9161     * A screen-reader must visit the content of this view before the content of the one
9162     * it precedes. For example, if view B is set to be before view A, then a screen-reader
9163     * will traverse the entire content of B before traversing the entire content of A,
9164     * regardles of what traversal strategy it is using.
9165     * <p>
9166     * Views that do not have specified before/after relationships are traversed in order
9167     * determined by the screen-reader.
9168     * </p>
9169     * <p>
9170     * Setting that this view is before a view that is not important for accessibility
9171     * or if this view is not important for accessibility will have no effect as the
9172     * screen-reader is not aware of unimportant views.
9173     * </p>
9174     *
9175     * @param beforeId The id of a view this one precedes in accessibility traversal.
9176     *
9177     * @attr ref android.R.styleable#View_accessibilityTraversalBefore
9178     *
9179     * @see #setImportantForAccessibility(int)
9180     */
9181    @RemotableViewMethod
9182    public void setAccessibilityTraversalBefore(int beforeId) {
9183        if (mAccessibilityTraversalBeforeId == beforeId) {
9184            return;
9185        }
9186        mAccessibilityTraversalBeforeId = beforeId;
9187        notifyViewAccessibilityStateChangedIfNeeded(
9188                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9189    }
9190
9191    /**
9192     * Gets the id of a view before which this one is visited in accessibility traversal.
9193     *
9194     * @return The id of a view this one precedes in accessibility traversal if
9195     *         specified, otherwise {@link #NO_ID}.
9196     *
9197     * @see #setAccessibilityTraversalBefore(int)
9198     */
9199    public int getAccessibilityTraversalBefore() {
9200        return mAccessibilityTraversalBeforeId;
9201    }
9202
9203    /**
9204     * Sets the id of a view after which this one is visited in accessibility traversal.
9205     * A screen-reader must visit the content of the other view before the content of this
9206     * one. For example, if view B is set to be after view A, then a screen-reader
9207     * will traverse the entire content of A before traversing the entire content of B,
9208     * regardles of what traversal strategy it is using.
9209     * <p>
9210     * Views that do not have specified before/after relationships are traversed in order
9211     * determined by the screen-reader.
9212     * </p>
9213     * <p>
9214     * Setting that this view is after a view that is not important for accessibility
9215     * or if this view is not important for accessibility will have no effect as the
9216     * screen-reader is not aware of unimportant views.
9217     * </p>
9218     *
9219     * @param afterId The id of a view this one succedees in accessibility traversal.
9220     *
9221     * @attr ref android.R.styleable#View_accessibilityTraversalAfter
9222     *
9223     * @see #setImportantForAccessibility(int)
9224     */
9225    @RemotableViewMethod
9226    public void setAccessibilityTraversalAfter(int afterId) {
9227        if (mAccessibilityTraversalAfterId == afterId) {
9228            return;
9229        }
9230        mAccessibilityTraversalAfterId = afterId;
9231        notifyViewAccessibilityStateChangedIfNeeded(
9232                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9233    }
9234
9235    /**
9236     * Gets the id of a view after which this one is visited in accessibility traversal.
9237     *
9238     * @return The id of a view this one succeedes in accessibility traversal if
9239     *         specified, otherwise {@link #NO_ID}.
9240     *
9241     * @see #setAccessibilityTraversalAfter(int)
9242     */
9243    public int getAccessibilityTraversalAfter() {
9244        return mAccessibilityTraversalAfterId;
9245    }
9246
9247    /**
9248     * Gets the id of a view for which this view serves as a label for
9249     * accessibility purposes.
9250     *
9251     * @return The labeled view id.
9252     */
9253    @ViewDebug.ExportedProperty(category = "accessibility")
9254    public int getLabelFor() {
9255        return mLabelForId;
9256    }
9257
9258    /**
9259     * Sets the id of a view for which this view serves as a label for
9260     * accessibility purposes.
9261     *
9262     * @param id The labeled view id.
9263     */
9264    @RemotableViewMethod
9265    public void setLabelFor(@IdRes int id) {
9266        if (mLabelForId == id) {
9267            return;
9268        }
9269        mLabelForId = id;
9270        if (mLabelForId != View.NO_ID
9271                && mID == View.NO_ID) {
9272            mID = generateViewId();
9273        }
9274        notifyViewAccessibilityStateChangedIfNeeded(
9275                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9276    }
9277
9278    /**
9279     * Invoked whenever this view loses focus, either by losing window focus or by losing
9280     * focus within its window. This method can be used to clear any state tied to the
9281     * focus. For instance, if a button is held pressed with the trackball and the window
9282     * loses focus, this method can be used to cancel the press.
9283     *
9284     * Subclasses of View overriding this method should always call super.onFocusLost().
9285     *
9286     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
9287     * @see #onWindowFocusChanged(boolean)
9288     *
9289     * @hide pending API council approval
9290     */
9291    @CallSuper
9292    protected void onFocusLost() {
9293        resetPressedState();
9294    }
9295
9296    private void resetPressedState() {
9297        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
9298            return;
9299        }
9300
9301        if (isPressed()) {
9302            setPressed(false);
9303
9304            if (!mHasPerformedLongPress) {
9305                removeLongPressCallback();
9306            }
9307        }
9308    }
9309
9310    /**
9311     * Returns true if this view has focus
9312     *
9313     * @return True if this view has focus, false otherwise.
9314     */
9315    @ViewDebug.ExportedProperty(category = "focus")
9316    public boolean isFocused() {
9317        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
9318    }
9319
9320    /**
9321     * Find the view in the hierarchy rooted at this view that currently has
9322     * focus.
9323     *
9324     * @return The view that currently has focus, or null if no focused view can
9325     *         be found.
9326     */
9327    public View findFocus() {
9328        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
9329    }
9330
9331    /**
9332     * Indicates whether this view is one of the set of scrollable containers in
9333     * its window.
9334     *
9335     * @return whether this view is one of the set of scrollable containers in
9336     * its window
9337     *
9338     * @attr ref android.R.styleable#View_isScrollContainer
9339     */
9340    public boolean isScrollContainer() {
9341        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
9342    }
9343
9344    /**
9345     * Change whether this view is one of the set of scrollable containers in
9346     * its window.  This will be used to determine whether the window can
9347     * resize or must pan when a soft input area is open -- scrollable
9348     * containers allow the window to use resize mode since the container
9349     * will appropriately shrink.
9350     *
9351     * @attr ref android.R.styleable#View_isScrollContainer
9352     */
9353    public void setScrollContainer(boolean isScrollContainer) {
9354        if (isScrollContainer) {
9355            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
9356                mAttachInfo.mScrollContainers.add(this);
9357                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
9358            }
9359            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
9360        } else {
9361            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
9362                mAttachInfo.mScrollContainers.remove(this);
9363            }
9364            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
9365        }
9366    }
9367
9368    /**
9369     * Returns the quality of the drawing cache.
9370     *
9371     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
9372     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
9373     *
9374     * @see #setDrawingCacheQuality(int)
9375     * @see #setDrawingCacheEnabled(boolean)
9376     * @see #isDrawingCacheEnabled()
9377     *
9378     * @attr ref android.R.styleable#View_drawingCacheQuality
9379     *
9380     * @deprecated The view drawing cache was largely made obsolete with the introduction of
9381     * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
9382     * layers are largely unnecessary and can easily result in a net loss in performance due to the
9383     * cost of creating and updating the layer. In the rare cases where caching layers are useful,
9384     * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
9385     * rendering. For software-rendered snapshots of a small part of the View hierarchy or
9386     * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
9387     * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
9388     * software-rendered usages are discouraged and have compatibility issues with hardware-only
9389     * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
9390     * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
9391     * reports or unit testing the {@link PixelCopy} API is recommended.
9392     */
9393    @Deprecated
9394    @DrawingCacheQuality
9395    public int getDrawingCacheQuality() {
9396        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
9397    }
9398
9399    /**
9400     * Set the drawing cache quality of this view. This value is used only when the
9401     * drawing cache is enabled
9402     *
9403     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
9404     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
9405     *
9406     * @see #getDrawingCacheQuality()
9407     * @see #setDrawingCacheEnabled(boolean)
9408     * @see #isDrawingCacheEnabled()
9409     *
9410     * @attr ref android.R.styleable#View_drawingCacheQuality
9411     *
9412     * @deprecated The view drawing cache was largely made obsolete with the introduction of
9413     * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
9414     * layers are largely unnecessary and can easily result in a net loss in performance due to the
9415     * cost of creating and updating the layer. In the rare cases where caching layers are useful,
9416     * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
9417     * rendering. For software-rendered snapshots of a small part of the View hierarchy or
9418     * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
9419     * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
9420     * software-rendered usages are discouraged and have compatibility issues with hardware-only
9421     * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
9422     * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
9423     * reports or unit testing the {@link PixelCopy} API is recommended.
9424     */
9425    @Deprecated
9426    public void setDrawingCacheQuality(@DrawingCacheQuality int quality) {
9427        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
9428    }
9429
9430    /**
9431     * Returns whether the screen should remain on, corresponding to the current
9432     * value of {@link #KEEP_SCREEN_ON}.
9433     *
9434     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
9435     *
9436     * @see #setKeepScreenOn(boolean)
9437     *
9438     * @attr ref android.R.styleable#View_keepScreenOn
9439     */
9440    public boolean getKeepScreenOn() {
9441        return (mViewFlags & KEEP_SCREEN_ON) != 0;
9442    }
9443
9444    /**
9445     * Controls whether the screen should remain on, modifying the
9446     * value of {@link #KEEP_SCREEN_ON}.
9447     *
9448     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
9449     *
9450     * @see #getKeepScreenOn()
9451     *
9452     * @attr ref android.R.styleable#View_keepScreenOn
9453     */
9454    public void setKeepScreenOn(boolean keepScreenOn) {
9455        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
9456    }
9457
9458    /**
9459     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
9460     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
9461     *
9462     * @attr ref android.R.styleable#View_nextFocusLeft
9463     */
9464    public int getNextFocusLeftId() {
9465        return mNextFocusLeftId;
9466    }
9467
9468    /**
9469     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
9470     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
9471     * decide automatically.
9472     *
9473     * @attr ref android.R.styleable#View_nextFocusLeft
9474     */
9475    public void setNextFocusLeftId(int nextFocusLeftId) {
9476        mNextFocusLeftId = nextFocusLeftId;
9477    }
9478
9479    /**
9480     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
9481     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
9482     *
9483     * @attr ref android.R.styleable#View_nextFocusRight
9484     */
9485    public int getNextFocusRightId() {
9486        return mNextFocusRightId;
9487    }
9488
9489    /**
9490     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
9491     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
9492     * decide automatically.
9493     *
9494     * @attr ref android.R.styleable#View_nextFocusRight
9495     */
9496    public void setNextFocusRightId(int nextFocusRightId) {
9497        mNextFocusRightId = nextFocusRightId;
9498    }
9499
9500    /**
9501     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
9502     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
9503     *
9504     * @attr ref android.R.styleable#View_nextFocusUp
9505     */
9506    public int getNextFocusUpId() {
9507        return mNextFocusUpId;
9508    }
9509
9510    /**
9511     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
9512     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
9513     * decide automatically.
9514     *
9515     * @attr ref android.R.styleable#View_nextFocusUp
9516     */
9517    public void setNextFocusUpId(int nextFocusUpId) {
9518        mNextFocusUpId = nextFocusUpId;
9519    }
9520
9521    /**
9522     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
9523     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
9524     *
9525     * @attr ref android.R.styleable#View_nextFocusDown
9526     */
9527    public int getNextFocusDownId() {
9528        return mNextFocusDownId;
9529    }
9530
9531    /**
9532     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
9533     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
9534     * decide automatically.
9535     *
9536     * @attr ref android.R.styleable#View_nextFocusDown
9537     */
9538    public void setNextFocusDownId(int nextFocusDownId) {
9539        mNextFocusDownId = nextFocusDownId;
9540    }
9541
9542    /**
9543     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
9544     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
9545     *
9546     * @attr ref android.R.styleable#View_nextFocusForward
9547     */
9548    public int getNextFocusForwardId() {
9549        return mNextFocusForwardId;
9550    }
9551
9552    /**
9553     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
9554     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
9555     * decide automatically.
9556     *
9557     * @attr ref android.R.styleable#View_nextFocusForward
9558     */
9559    public void setNextFocusForwardId(int nextFocusForwardId) {
9560        mNextFocusForwardId = nextFocusForwardId;
9561    }
9562
9563    /**
9564     * Gets the id of the root of the next keyboard navigation cluster.
9565     * @return The next keyboard navigation cluster ID, or {@link #NO_ID} if the framework should
9566     * decide automatically.
9567     *
9568     * @attr ref android.R.styleable#View_nextClusterForward
9569     */
9570    public int getNextClusterForwardId() {
9571        return mNextClusterForwardId;
9572    }
9573
9574    /**
9575     * Sets the id of the view to use as the root of the next keyboard navigation cluster.
9576     * @param nextClusterForwardId The next cluster ID, or {@link #NO_ID} if the framework should
9577     * decide automatically.
9578     *
9579     * @attr ref android.R.styleable#View_nextClusterForward
9580     */
9581    public void setNextClusterForwardId(int nextClusterForwardId) {
9582        mNextClusterForwardId = nextClusterForwardId;
9583    }
9584
9585    /**
9586     * Returns the visibility of this view and all of its ancestors
9587     *
9588     * @return True if this view and all of its ancestors are {@link #VISIBLE}
9589     */
9590    public boolean isShown() {
9591        View current = this;
9592        //noinspection ConstantConditions
9593        do {
9594            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
9595                return false;
9596            }
9597            ViewParent parent = current.mParent;
9598            if (parent == null) {
9599                return false; // We are not attached to the view root
9600            }
9601            if (!(parent instanceof View)) {
9602                return true;
9603            }
9604            current = (View) parent;
9605        } while (current != null);
9606
9607        return false;
9608    }
9609
9610    /**
9611     * Called by the view hierarchy when the content insets for a window have
9612     * changed, to allow it to adjust its content to fit within those windows.
9613     * The content insets tell you the space that the status bar, input method,
9614     * and other system windows infringe on the application's window.
9615     *
9616     * <p>You do not normally need to deal with this function, since the default
9617     * window decoration given to applications takes care of applying it to the
9618     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
9619     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
9620     * and your content can be placed under those system elements.  You can then
9621     * use this method within your view hierarchy if you have parts of your UI
9622     * which you would like to ensure are not being covered.
9623     *
9624     * <p>The default implementation of this method simply applies the content
9625     * insets to the view's padding, consuming that content (modifying the
9626     * insets to be 0), and returning true.  This behavior is off by default, but can
9627     * be enabled through {@link #setFitsSystemWindows(boolean)}.
9628     *
9629     * <p>This function's traversal down the hierarchy is depth-first.  The same content
9630     * insets object is propagated down the hierarchy, so any changes made to it will
9631     * be seen by all following views (including potentially ones above in
9632     * the hierarchy since this is a depth-first traversal).  The first view
9633     * that returns true will abort the entire traversal.
9634     *
9635     * <p>The default implementation works well for a situation where it is
9636     * used with a container that covers the entire window, allowing it to
9637     * apply the appropriate insets to its content on all edges.  If you need
9638     * a more complicated layout (such as two different views fitting system
9639     * windows, one on the top of the window, and one on the bottom),
9640     * you can override the method and handle the insets however you would like.
9641     * Note that the insets provided by the framework are always relative to the
9642     * far edges of the window, not accounting for the location of the called view
9643     * within that window.  (In fact when this method is called you do not yet know
9644     * where the layout will place the view, as it is done before layout happens.)
9645     *
9646     * <p>Note: unlike many View methods, there is no dispatch phase to this
9647     * call.  If you are overriding it in a ViewGroup and want to allow the
9648     * call to continue to your children, you must be sure to call the super
9649     * implementation.
9650     *
9651     * <p>Here is a sample layout that makes use of fitting system windows
9652     * to have controls for a video view placed inside of the window decorations
9653     * that it hides and shows.  This can be used with code like the second
9654     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
9655     *
9656     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
9657     *
9658     * @param insets Current content insets of the window.  Prior to
9659     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
9660     * the insets or else you and Android will be unhappy.
9661     *
9662     * @return {@code true} if this view applied the insets and it should not
9663     * continue propagating further down the hierarchy, {@code false} otherwise.
9664     * @see #getFitsSystemWindows()
9665     * @see #setFitsSystemWindows(boolean)
9666     * @see #setSystemUiVisibility(int)
9667     *
9668     * @deprecated As of API 20 use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply
9669     * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use
9670     * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)}
9671     * to implement handling their own insets.
9672     */
9673    @Deprecated
9674    protected boolean fitSystemWindows(Rect insets) {
9675        if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) {
9676            if (insets == null) {
9677                // Null insets by definition have already been consumed.
9678                // This call cannot apply insets since there are none to apply,
9679                // so return false.
9680                return false;
9681            }
9682            // If we're not in the process of dispatching the newer apply insets call,
9683            // that means we're not in the compatibility path. Dispatch into the newer
9684            // apply insets path and take things from there.
9685            try {
9686                mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS;
9687                return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed();
9688            } finally {
9689                mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS;
9690            }
9691        } else {
9692            // We're being called from the newer apply insets path.
9693            // Perform the standard fallback behavior.
9694            return fitSystemWindowsInt(insets);
9695        }
9696    }
9697
9698    private boolean fitSystemWindowsInt(Rect insets) {
9699        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
9700            mUserPaddingStart = UNDEFINED_PADDING;
9701            mUserPaddingEnd = UNDEFINED_PADDING;
9702            Rect localInsets = sThreadLocal.get();
9703            if (localInsets == null) {
9704                localInsets = new Rect();
9705                sThreadLocal.set(localInsets);
9706            }
9707            boolean res = computeFitSystemWindows(insets, localInsets);
9708            mUserPaddingLeftInitial = localInsets.left;
9709            mUserPaddingRightInitial = localInsets.right;
9710            internalSetPadding(localInsets.left, localInsets.top,
9711                    localInsets.right, localInsets.bottom);
9712            return res;
9713        }
9714        return false;
9715    }
9716
9717    /**
9718     * Called when the view should apply {@link WindowInsets} according to its internal policy.
9719     *
9720     * <p>This method should be overridden by views that wish to apply a policy different from or
9721     * in addition to the default behavior. Clients that wish to force a view subtree
9722     * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p>
9723     *
9724     * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set
9725     * it will be called during dispatch instead of this method. The listener may optionally
9726     * call this method from its own implementation if it wishes to apply the view's default
9727     * insets policy in addition to its own.</p>
9728     *
9729     * <p>Implementations of this method should either return the insets parameter unchanged
9730     * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed
9731     * that this view applied itself. This allows new inset types added in future platform
9732     * versions to pass through existing implementations unchanged without being erroneously
9733     * consumed.</p>
9734     *
9735     * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows}
9736     * property is set then the view will consume the system window insets and apply them
9737     * as padding for the view.</p>
9738     *
9739     * @param insets Insets to apply
9740     * @return The supplied insets with any applied insets consumed
9741     */
9742    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
9743        if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) {
9744            // We weren't called from within a direct call to fitSystemWindows,
9745            // call into it as a fallback in case we're in a class that overrides it
9746            // and has logic to perform.
9747            if (fitSystemWindows(insets.getSystemWindowInsets())) {
9748                return insets.consumeSystemWindowInsets();
9749            }
9750        } else {
9751            // We were called from within a direct call to fitSystemWindows.
9752            if (fitSystemWindowsInt(insets.getSystemWindowInsets())) {
9753                return insets.consumeSystemWindowInsets();
9754            }
9755        }
9756        return insets;
9757    }
9758
9759    /**
9760     * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying
9761     * window insets to this view. The listener's
9762     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
9763     * method will be called instead of the view's
9764     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
9765     *
9766     * @param listener Listener to set
9767     *
9768     * @see #onApplyWindowInsets(WindowInsets)
9769     */
9770    public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {
9771        getListenerInfo().mOnApplyWindowInsetsListener = listener;
9772    }
9773
9774    /**
9775     * Request to apply the given window insets to this view or another view in its subtree.
9776     *
9777     * <p>This method should be called by clients wishing to apply insets corresponding to areas
9778     * obscured by window decorations or overlays. This can include the status and navigation bars,
9779     * action bars, input methods and more. New inset categories may be added in the future.
9780     * The method returns the insets provided minus any that were applied by this view or its
9781     * children.</p>
9782     *
9783     * <p>Clients wishing to provide custom behavior should override the
9784     * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a
9785     * {@link OnApplyWindowInsetsListener} via the
9786     * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener}
9787     * method.</p>
9788     *
9789     * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method.
9790     * </p>
9791     *
9792     * @param insets Insets to apply
9793     * @return The provided insets minus the insets that were consumed
9794     */
9795    public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
9796        try {
9797            mPrivateFlags3 |= PFLAG3_APPLYING_INSETS;
9798            if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
9799                return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);
9800            } else {
9801                return onApplyWindowInsets(insets);
9802            }
9803        } finally {
9804            mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS;
9805        }
9806    }
9807
9808    /**
9809     * Compute the view's coordinate within the surface.
9810     *
9811     * <p>Computes the coordinates of this view in its surface. The argument
9812     * must be an array of two integers. After the method returns, the array
9813     * contains the x and y location in that order.</p>
9814     * @hide
9815     * @param location an array of two integers in which to hold the coordinates
9816     */
9817    public void getLocationInSurface(@Size(2) int[] location) {
9818        getLocationInWindow(location);
9819        if (mAttachInfo != null && mAttachInfo.mViewRootImpl != null) {
9820            location[0] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.left;
9821            location[1] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.top;
9822        }
9823    }
9824
9825    /**
9826     * Provide original WindowInsets that are dispatched to the view hierarchy. The insets are
9827     * only available if the view is attached.
9828     *
9829     * @return WindowInsets from the top of the view hierarchy or null if View is detached
9830     */
9831    public WindowInsets getRootWindowInsets() {
9832        if (mAttachInfo != null) {
9833            return mAttachInfo.mViewRootImpl.getWindowInsets(false /* forceConstruct */);
9834        }
9835        return null;
9836    }
9837
9838    /**
9839     * @hide Compute the insets that should be consumed by this view and the ones
9840     * that should propagate to those under it.
9841     */
9842    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
9843        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
9844                || mAttachInfo == null
9845                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
9846                        && !mAttachInfo.mOverscanRequested)) {
9847            outLocalInsets.set(inoutInsets);
9848            inoutInsets.set(0, 0, 0, 0);
9849            return true;
9850        } else {
9851            // The application wants to take care of fitting system window for
9852            // the content...  however we still need to take care of any overscan here.
9853            final Rect overscan = mAttachInfo.mOverscanInsets;
9854            outLocalInsets.set(overscan);
9855            inoutInsets.left -= overscan.left;
9856            inoutInsets.top -= overscan.top;
9857            inoutInsets.right -= overscan.right;
9858            inoutInsets.bottom -= overscan.bottom;
9859            return false;
9860        }
9861    }
9862
9863    /**
9864     * Compute insets that should be consumed by this view and the ones that should propagate
9865     * to those under it.
9866     *
9867     * @param in Insets currently being processed by this View, likely received as a parameter
9868     *           to {@link #onApplyWindowInsets(WindowInsets)}.
9869     * @param outLocalInsets A Rect that will receive the insets that should be consumed
9870     *                       by this view
9871     * @return Insets that should be passed along to views under this one
9872     */
9873    public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) {
9874        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
9875                || mAttachInfo == null
9876                || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
9877            outLocalInsets.set(in.getSystemWindowInsets());
9878            return in.consumeSystemWindowInsets();
9879        } else {
9880            outLocalInsets.set(0, 0, 0, 0);
9881            return in;
9882        }
9883    }
9884
9885    /**
9886     * Sets whether or not this view should account for system screen decorations
9887     * such as the status bar and inset its content; that is, controlling whether
9888     * the default implementation of {@link #fitSystemWindows(Rect)} will be
9889     * executed.  See that method for more details.
9890     *
9891     * <p>Note that if you are providing your own implementation of
9892     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
9893     * flag to true -- your implementation will be overriding the default
9894     * implementation that checks this flag.
9895     *
9896     * @param fitSystemWindows If true, then the default implementation of
9897     * {@link #fitSystemWindows(Rect)} will be executed.
9898     *
9899     * @attr ref android.R.styleable#View_fitsSystemWindows
9900     * @see #getFitsSystemWindows()
9901     * @see #fitSystemWindows(Rect)
9902     * @see #setSystemUiVisibility(int)
9903     */
9904    public void setFitsSystemWindows(boolean fitSystemWindows) {
9905        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
9906    }
9907
9908    /**
9909     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
9910     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
9911     * will be executed.
9912     *
9913     * @return {@code true} if the default implementation of
9914     * {@link #fitSystemWindows(Rect)} will be executed.
9915     *
9916     * @attr ref android.R.styleable#View_fitsSystemWindows
9917     * @see #setFitsSystemWindows(boolean)
9918     * @see #fitSystemWindows(Rect)
9919     * @see #setSystemUiVisibility(int)
9920     */
9921    @ViewDebug.ExportedProperty
9922    public boolean getFitsSystemWindows() {
9923        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
9924    }
9925
9926    /** @hide */
9927    public boolean fitsSystemWindows() {
9928        return getFitsSystemWindows();
9929    }
9930
9931    /**
9932     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
9933     * @deprecated Use {@link #requestApplyInsets()} for newer platform versions.
9934     */
9935    @Deprecated
9936    public void requestFitSystemWindows() {
9937        if (mParent != null) {
9938            mParent.requestFitSystemWindows();
9939        }
9940    }
9941
9942    /**
9943     * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed.
9944     */
9945    public void requestApplyInsets() {
9946        requestFitSystemWindows();
9947    }
9948
9949    /**
9950     * For use by PhoneWindow to make its own system window fitting optional.
9951     * @hide
9952     */
9953    public void makeOptionalFitsSystemWindows() {
9954        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
9955    }
9956
9957    /**
9958     * Returns the outsets, which areas of the device that aren't a surface, but we would like to
9959     * treat them as such.
9960     * @hide
9961     */
9962    public void getOutsets(Rect outOutsetRect) {
9963        if (mAttachInfo != null) {
9964            outOutsetRect.set(mAttachInfo.mOutsets);
9965        } else {
9966            outOutsetRect.setEmpty();
9967        }
9968    }
9969
9970    /**
9971     * Returns the visibility status for this view.
9972     *
9973     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
9974     * @attr ref android.R.styleable#View_visibility
9975     */
9976    @ViewDebug.ExportedProperty(mapping = {
9977        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
9978        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
9979        @ViewDebug.IntToString(from = GONE,      to = "GONE")
9980    })
9981    @Visibility
9982    public int getVisibility() {
9983        return mViewFlags & VISIBILITY_MASK;
9984    }
9985
9986    /**
9987     * Set the visibility state of this view.
9988     *
9989     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
9990     * @attr ref android.R.styleable#View_visibility
9991     */
9992    @RemotableViewMethod
9993    public void setVisibility(@Visibility int visibility) {
9994        setFlags(visibility, VISIBILITY_MASK);
9995    }
9996
9997    /**
9998     * Returns the enabled status for this view. The interpretation of the
9999     * enabled state varies by subclass.
10000     *
10001     * @return True if this view is enabled, false otherwise.
10002     */
10003    @ViewDebug.ExportedProperty
10004    public boolean isEnabled() {
10005        return (mViewFlags & ENABLED_MASK) == ENABLED;
10006    }
10007
10008    /**
10009     * Set the enabled state of this view. The interpretation of the enabled
10010     * state varies by subclass.
10011     *
10012     * @param enabled True if this view is enabled, false otherwise.
10013     */
10014    @RemotableViewMethod
10015    public void setEnabled(boolean enabled) {
10016        if (enabled == isEnabled()) return;
10017
10018        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
10019
10020        /*
10021         * The View most likely has to change its appearance, so refresh
10022         * the drawable state.
10023         */
10024        refreshDrawableState();
10025
10026        // Invalidate too, since the default behavior for views is to be
10027        // be drawn at 50% alpha rather than to change the drawable.
10028        invalidate(true);
10029
10030        if (!enabled) {
10031            cancelPendingInputEvents();
10032        }
10033    }
10034
10035    /**
10036     * Set whether this view can receive the focus.
10037     * <p>
10038     * Setting this to false will also ensure that this view is not focusable
10039     * in touch mode.
10040     *
10041     * @param focusable If true, this view can receive the focus.
10042     *
10043     * @see #setFocusableInTouchMode(boolean)
10044     * @see #setFocusable(int)
10045     * @attr ref android.R.styleable#View_focusable
10046     */
10047    public void setFocusable(boolean focusable) {
10048        setFocusable(focusable ? FOCUSABLE : NOT_FOCUSABLE);
10049    }
10050
10051    /**
10052     * Sets whether this view can receive focus.
10053     * <p>
10054     * Setting this to {@link #FOCUSABLE_AUTO} tells the framework to determine focusability
10055     * automatically based on the view's interactivity. This is the default.
10056     * <p>
10057     * Setting this to NOT_FOCUSABLE will ensure that this view is also not focusable
10058     * in touch mode.
10059     *
10060     * @param focusable One of {@link #NOT_FOCUSABLE}, {@link #FOCUSABLE},
10061     *                  or {@link #FOCUSABLE_AUTO}.
10062     * @see #setFocusableInTouchMode(boolean)
10063     * @attr ref android.R.styleable#View_focusable
10064     */
10065    public void setFocusable(@Focusable int focusable) {
10066        if ((focusable & (FOCUSABLE_AUTO | FOCUSABLE)) == 0) {
10067            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
10068        }
10069        setFlags(focusable, FOCUSABLE_MASK);
10070    }
10071
10072    /**
10073     * Set whether this view can receive focus while in touch mode.
10074     *
10075     * Setting this to true will also ensure that this view is focusable.
10076     *
10077     * @param focusableInTouchMode If true, this view can receive the focus while
10078     *   in touch mode.
10079     *
10080     * @see #setFocusable(boolean)
10081     * @attr ref android.R.styleable#View_focusableInTouchMode
10082     */
10083    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
10084        // Focusable in touch mode should always be set before the focusable flag
10085        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
10086        // which, in touch mode, will not successfully request focus on this view
10087        // because the focusable in touch mode flag is not set
10088        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
10089
10090        // Clear FOCUSABLE_AUTO if set.
10091        if (focusableInTouchMode) {
10092            // Clears FOCUSABLE_AUTO if set.
10093            setFlags(FOCUSABLE, FOCUSABLE_MASK);
10094        }
10095    }
10096
10097    /**
10098     * Sets the hints that help an {@link android.service.autofill.AutofillService} determine how
10099     * to autofill the view with the user's data.
10100     *
10101     * <p>Typically, there is only one way to autofill a view, but there could be more than one.
10102     * For example, if the application accepts either an username or email address to identify
10103     * an user.
10104     *
10105     * <p>These hints are not validated by the Android System, but passed "as is" to the service.
10106     * Hence, they can have any value, but it's recommended to use the {@code AUTOFILL_HINT_}
10107     * constants such as:
10108     * {@link #AUTOFILL_HINT_USERNAME}, {@link #AUTOFILL_HINT_PASSWORD},
10109     * {@link #AUTOFILL_HINT_EMAIL_ADDRESS},
10110     * {@link #AUTOFILL_HINT_NAME},
10111     * {@link #AUTOFILL_HINT_PHONE},
10112     * {@link #AUTOFILL_HINT_POSTAL_ADDRESS}, {@link #AUTOFILL_HINT_POSTAL_CODE},
10113     * {@link #AUTOFILL_HINT_CREDIT_CARD_NUMBER}, {@link #AUTOFILL_HINT_CREDIT_CARD_SECURITY_CODE},
10114     * {@link #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DATE},
10115     * {@link #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DAY},
10116     * {@link #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_MONTH} or
10117     * {@link #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_YEAR}.
10118     *
10119     * @param autofillHints The autofill hints to set. If the array is emtpy, {@code null} is set.
10120     * @attr ref android.R.styleable#View_autofillHints
10121     */
10122    public void setAutofillHints(@Nullable String... autofillHints) {
10123        if (autofillHints == null || autofillHints.length == 0) {
10124            mAutofillHints = null;
10125        } else {
10126            mAutofillHints = autofillHints;
10127        }
10128    }
10129
10130    /**
10131     * @hide
10132     */
10133    @TestApi
10134    public void setAutofilled(boolean isAutofilled) {
10135        boolean wasChanged = isAutofilled != isAutofilled();
10136
10137        if (wasChanged) {
10138            if (isAutofilled) {
10139                mPrivateFlags3 |= PFLAG3_IS_AUTOFILLED;
10140            } else {
10141                mPrivateFlags3 &= ~PFLAG3_IS_AUTOFILLED;
10142            }
10143
10144            invalidate();
10145        }
10146    }
10147
10148    /**
10149     * Set whether this view should have sound effects enabled for events such as
10150     * clicking and touching.
10151     *
10152     * <p>You may wish to disable sound effects for a view if you already play sounds,
10153     * for instance, a dial key that plays dtmf tones.
10154     *
10155     * @param soundEffectsEnabled whether sound effects are enabled for this view.
10156     * @see #isSoundEffectsEnabled()
10157     * @see #playSoundEffect(int)
10158     * @attr ref android.R.styleable#View_soundEffectsEnabled
10159     */
10160    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
10161        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
10162    }
10163
10164    /**
10165     * @return whether this view should have sound effects enabled for events such as
10166     *     clicking and touching.
10167     *
10168     * @see #setSoundEffectsEnabled(boolean)
10169     * @see #playSoundEffect(int)
10170     * @attr ref android.R.styleable#View_soundEffectsEnabled
10171     */
10172    @ViewDebug.ExportedProperty
10173    public boolean isSoundEffectsEnabled() {
10174        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
10175    }
10176
10177    /**
10178     * Set whether this view should have haptic feedback for events such as
10179     * long presses.
10180     *
10181     * <p>You may wish to disable haptic feedback if your view already controls
10182     * its own haptic feedback.
10183     *
10184     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
10185     * @see #isHapticFeedbackEnabled()
10186     * @see #performHapticFeedback(int)
10187     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
10188     */
10189    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
10190        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
10191    }
10192
10193    /**
10194     * @return whether this view should have haptic feedback enabled for events
10195     * long presses.
10196     *
10197     * @see #setHapticFeedbackEnabled(boolean)
10198     * @see #performHapticFeedback(int)
10199     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
10200     */
10201    @ViewDebug.ExportedProperty
10202    public boolean isHapticFeedbackEnabled() {
10203        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
10204    }
10205
10206    /**
10207     * Returns the layout direction for this view.
10208     *
10209     * @return One of {@link #LAYOUT_DIRECTION_LTR},
10210     *   {@link #LAYOUT_DIRECTION_RTL},
10211     *   {@link #LAYOUT_DIRECTION_INHERIT} or
10212     *   {@link #LAYOUT_DIRECTION_LOCALE}.
10213     *
10214     * @attr ref android.R.styleable#View_layoutDirection
10215     *
10216     * @hide
10217     */
10218    @ViewDebug.ExportedProperty(category = "layout", mapping = {
10219        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
10220        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
10221        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
10222        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
10223    })
10224    @LayoutDir
10225    public int getRawLayoutDirection() {
10226        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
10227    }
10228
10229    /**
10230     * Set the layout direction for this view. This will propagate a reset of layout direction
10231     * resolution to the view's children and resolve layout direction for this view.
10232     *
10233     * @param layoutDirection the layout direction to set. Should be one of:
10234     *
10235     * {@link #LAYOUT_DIRECTION_LTR},
10236     * {@link #LAYOUT_DIRECTION_RTL},
10237     * {@link #LAYOUT_DIRECTION_INHERIT},
10238     * {@link #LAYOUT_DIRECTION_LOCALE}.
10239     *
10240     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
10241     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
10242     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
10243     *
10244     * @attr ref android.R.styleable#View_layoutDirection
10245     */
10246    @RemotableViewMethod
10247    public void setLayoutDirection(@LayoutDir int layoutDirection) {
10248        if (getRawLayoutDirection() != layoutDirection) {
10249            // Reset the current layout direction and the resolved one
10250            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
10251            resetRtlProperties();
10252            // Set the new layout direction (filtered)
10253            mPrivateFlags2 |=
10254                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
10255            // We need to resolve all RTL properties as they all depend on layout direction
10256            resolveRtlPropertiesIfNeeded();
10257            requestLayout();
10258            invalidate(true);
10259        }
10260    }
10261
10262    /**
10263     * Returns the resolved layout direction for this view.
10264     *
10265     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
10266     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
10267     *
10268     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
10269     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
10270     *
10271     * @attr ref android.R.styleable#View_layoutDirection
10272     */
10273    @ViewDebug.ExportedProperty(category = "layout", mapping = {
10274        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
10275        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
10276    })
10277    @ResolvedLayoutDir
10278    public int getLayoutDirection() {
10279        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
10280        if (targetSdkVersion < Build.VERSION_CODES.JELLY_BEAN_MR1) {
10281            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
10282            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
10283        }
10284        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
10285                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
10286    }
10287
10288    /**
10289     * Indicates whether or not this view's layout is right-to-left. This is resolved from
10290     * layout attribute and/or the inherited value from the parent
10291     *
10292     * @return true if the layout is right-to-left.
10293     *
10294     * @hide
10295     */
10296    @ViewDebug.ExportedProperty(category = "layout")
10297    public boolean isLayoutRtl() {
10298        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
10299    }
10300
10301    /**
10302     * Indicates whether the view is currently tracking transient state that the
10303     * app should not need to concern itself with saving and restoring, but that
10304     * the framework should take special note to preserve when possible.
10305     *
10306     * <p>A view with transient state cannot be trivially rebound from an external
10307     * data source, such as an adapter binding item views in a list. This may be
10308     * because the view is performing an animation, tracking user selection
10309     * of content, or similar.</p>
10310     *
10311     * @return true if the view has transient state
10312     */
10313    @ViewDebug.ExportedProperty(category = "layout")
10314    public boolean hasTransientState() {
10315        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
10316    }
10317
10318    /**
10319     * Set whether this view is currently tracking transient state that the
10320     * framework should attempt to preserve when possible. This flag is reference counted,
10321     * so every call to setHasTransientState(true) should be paired with a later call
10322     * to setHasTransientState(false).
10323     *
10324     * <p>A view with transient state cannot be trivially rebound from an external
10325     * data source, such as an adapter binding item views in a list. This may be
10326     * because the view is performing an animation, tracking user selection
10327     * of content, or similar.</p>
10328     *
10329     * @param hasTransientState true if this view has transient state
10330     */
10331    public void setHasTransientState(boolean hasTransientState) {
10332        final boolean oldHasTransientState = hasTransientState();
10333        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
10334                mTransientStateCount - 1;
10335        if (mTransientStateCount < 0) {
10336            mTransientStateCount = 0;
10337            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
10338                    "unmatched pair of setHasTransientState calls");
10339        } else if ((hasTransientState && mTransientStateCount == 1) ||
10340                (!hasTransientState && mTransientStateCount == 0)) {
10341            // update flag if we've just incremented up from 0 or decremented down to 0
10342            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
10343                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
10344            final boolean newHasTransientState = hasTransientState();
10345            if (mParent != null && newHasTransientState != oldHasTransientState) {
10346                try {
10347                    mParent.childHasTransientStateChanged(this, newHasTransientState);
10348                } catch (AbstractMethodError e) {
10349                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
10350                            " does not fully implement ViewParent", e);
10351                }
10352            }
10353        }
10354    }
10355
10356    /**
10357     * Returns true if this view is currently attached to a window.
10358     */
10359    public boolean isAttachedToWindow() {
10360        return mAttachInfo != null;
10361    }
10362
10363    /**
10364     * Returns true if this view has been through at least one layout since it
10365     * was last attached to or detached from a window.
10366     */
10367    public boolean isLaidOut() {
10368        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
10369    }
10370
10371    /**
10372     * @return {@code true} if laid-out and not about to do another layout.
10373     */
10374    boolean isLayoutValid() {
10375        return isLaidOut() && ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == 0);
10376    }
10377
10378    /**
10379     * If this view doesn't do any drawing on its own, set this flag to
10380     * allow further optimizations. By default, this flag is not set on
10381     * View, but could be set on some View subclasses such as ViewGroup.
10382     *
10383     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
10384     * you should clear this flag.
10385     *
10386     * @param willNotDraw whether or not this View draw on its own
10387     */
10388    public void setWillNotDraw(boolean willNotDraw) {
10389        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
10390    }
10391
10392    /**
10393     * Returns whether or not this View draws on its own.
10394     *
10395     * @return true if this view has nothing to draw, false otherwise
10396     */
10397    @ViewDebug.ExportedProperty(category = "drawing")
10398    public boolean willNotDraw() {
10399        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
10400    }
10401
10402    /**
10403     * When a View's drawing cache is enabled, drawing is redirected to an
10404     * offscreen bitmap. Some views, like an ImageView, must be able to
10405     * bypass this mechanism if they already draw a single bitmap, to avoid
10406     * unnecessary usage of the memory.
10407     *
10408     * @param willNotCacheDrawing true if this view does not cache its
10409     *        drawing, false otherwise
10410     *
10411     * @deprecated The view drawing cache was largely made obsolete with the introduction of
10412     * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
10413     * layers are largely unnecessary and can easily result in a net loss in performance due to the
10414     * cost of creating and updating the layer. In the rare cases where caching layers are useful,
10415     * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
10416     * rendering. For software-rendered snapshots of a small part of the View hierarchy or
10417     * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
10418     * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
10419     * software-rendered usages are discouraged and have compatibility issues with hardware-only
10420     * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
10421     * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
10422     * reports or unit testing the {@link PixelCopy} API is recommended.
10423     */
10424    @Deprecated
10425    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
10426        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
10427    }
10428
10429    /**
10430     * Returns whether or not this View can cache its drawing or not.
10431     *
10432     * @return true if this view does not cache its drawing, false otherwise
10433     *
10434     * @deprecated The view drawing cache was largely made obsolete with the introduction of
10435     * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
10436     * layers are largely unnecessary and can easily result in a net loss in performance due to the
10437     * cost of creating and updating the layer. In the rare cases where caching layers are useful,
10438     * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
10439     * rendering. For software-rendered snapshots of a small part of the View hierarchy or
10440     * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
10441     * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
10442     * software-rendered usages are discouraged and have compatibility issues with hardware-only
10443     * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
10444     * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
10445     * reports or unit testing the {@link PixelCopy} API is recommended.
10446     */
10447    @ViewDebug.ExportedProperty(category = "drawing")
10448    @Deprecated
10449    public boolean willNotCacheDrawing() {
10450        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
10451    }
10452
10453    /**
10454     * Indicates whether this view reacts to click events or not.
10455     *
10456     * @return true if the view is clickable, false otherwise
10457     *
10458     * @see #setClickable(boolean)
10459     * @attr ref android.R.styleable#View_clickable
10460     */
10461    @ViewDebug.ExportedProperty
10462    public boolean isClickable() {
10463        return (mViewFlags & CLICKABLE) == CLICKABLE;
10464    }
10465
10466    /**
10467     * Enables or disables click events for this view. When a view
10468     * is clickable it will change its state to "pressed" on every click.
10469     * Subclasses should set the view clickable to visually react to
10470     * user's clicks.
10471     *
10472     * @param clickable true to make the view clickable, false otherwise
10473     *
10474     * @see #isClickable()
10475     * @attr ref android.R.styleable#View_clickable
10476     */
10477    public void setClickable(boolean clickable) {
10478        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
10479    }
10480
10481    /**
10482     * Indicates whether this view reacts to long click events or not.
10483     *
10484     * @return true if the view is long clickable, false otherwise
10485     *
10486     * @see #setLongClickable(boolean)
10487     * @attr ref android.R.styleable#View_longClickable
10488     */
10489    public boolean isLongClickable() {
10490        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
10491    }
10492
10493    /**
10494     * Enables or disables long click events for this view. When a view is long
10495     * clickable it reacts to the user holding down the button for a longer
10496     * duration than a tap. This event can either launch the listener or a
10497     * context menu.
10498     *
10499     * @param longClickable true to make the view long clickable, false otherwise
10500     * @see #isLongClickable()
10501     * @attr ref android.R.styleable#View_longClickable
10502     */
10503    public void setLongClickable(boolean longClickable) {
10504        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
10505    }
10506
10507    /**
10508     * Indicates whether this view reacts to context clicks or not.
10509     *
10510     * @return true if the view is context clickable, false otherwise
10511     * @see #setContextClickable(boolean)
10512     * @attr ref android.R.styleable#View_contextClickable
10513     */
10514    public boolean isContextClickable() {
10515        return (mViewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
10516    }
10517
10518    /**
10519     * Enables or disables context clicking for this view. This event can launch the listener.
10520     *
10521     * @param contextClickable true to make the view react to a context click, false otherwise
10522     * @see #isContextClickable()
10523     * @attr ref android.R.styleable#View_contextClickable
10524     */
10525    public void setContextClickable(boolean contextClickable) {
10526        setFlags(contextClickable ? CONTEXT_CLICKABLE : 0, CONTEXT_CLICKABLE);
10527    }
10528
10529    /**
10530     * Sets the pressed state for this view and provides a touch coordinate for
10531     * animation hinting.
10532     *
10533     * @param pressed Pass true to set the View's internal state to "pressed",
10534     *            or false to reverts the View's internal state from a
10535     *            previously set "pressed" state.
10536     * @param x The x coordinate of the touch that caused the press
10537     * @param y The y coordinate of the touch that caused the press
10538     */
10539    private void setPressed(boolean pressed, float x, float y) {
10540        if (pressed) {
10541            drawableHotspotChanged(x, y);
10542        }
10543
10544        setPressed(pressed);
10545    }
10546
10547    /**
10548     * Sets the pressed state for this view.
10549     *
10550     * @see #isClickable()
10551     * @see #setClickable(boolean)
10552     *
10553     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
10554     *        the View's internal state from a previously set "pressed" state.
10555     */
10556    public void setPressed(boolean pressed) {
10557        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
10558
10559        if (pressed) {
10560            mPrivateFlags |= PFLAG_PRESSED;
10561        } else {
10562            mPrivateFlags &= ~PFLAG_PRESSED;
10563        }
10564
10565        if (needsRefresh) {
10566            refreshDrawableState();
10567        }
10568        dispatchSetPressed(pressed);
10569    }
10570
10571    /**
10572     * Dispatch setPressed to all of this View's children.
10573     *
10574     * @see #setPressed(boolean)
10575     *
10576     * @param pressed The new pressed state
10577     */
10578    protected void dispatchSetPressed(boolean pressed) {
10579    }
10580
10581    /**
10582     * Indicates whether the view is currently in pressed state. Unless
10583     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
10584     * the pressed state.
10585     *
10586     * @see #setPressed(boolean)
10587     * @see #isClickable()
10588     * @see #setClickable(boolean)
10589     *
10590     * @return true if the view is currently pressed, false otherwise
10591     */
10592    @ViewDebug.ExportedProperty
10593    public boolean isPressed() {
10594        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
10595    }
10596
10597    /**
10598     * @hide
10599     * Indicates whether this view will participate in data collection through
10600     * {@link ViewStructure}.  If true, it will not provide any data
10601     * for itself or its children.  If false, the normal data collection will be allowed.
10602     *
10603     * @return Returns false if assist data collection is not blocked, else true.
10604     *
10605     * @see #setAssistBlocked(boolean)
10606     * @attr ref android.R.styleable#View_assistBlocked
10607     */
10608    public boolean isAssistBlocked() {
10609        return (mPrivateFlags3 & PFLAG3_ASSIST_BLOCKED) != 0;
10610    }
10611
10612    /**
10613     * @hide
10614     * Controls whether assist data collection from this view and its children is enabled
10615     * (that is, whether {@link #onProvideStructure} and
10616     * {@link #onProvideVirtualStructure} will be called).  The default value is false,
10617     * allowing normal assist collection.  Setting this to false will disable assist collection.
10618     *
10619     * @param enabled Set to true to <em>disable</em> assist data collection, or false
10620     * (the default) to allow it.
10621     *
10622     * @see #isAssistBlocked()
10623     * @see #onProvideStructure
10624     * @see #onProvideVirtualStructure
10625     * @attr ref android.R.styleable#View_assistBlocked
10626     */
10627    public void setAssistBlocked(boolean enabled) {
10628        if (enabled) {
10629            mPrivateFlags3 |= PFLAG3_ASSIST_BLOCKED;
10630        } else {
10631            mPrivateFlags3 &= ~PFLAG3_ASSIST_BLOCKED;
10632        }
10633    }
10634
10635    /**
10636     * Indicates whether this view will save its state (that is,
10637     * whether its {@link #onSaveInstanceState} method will be called).
10638     *
10639     * @return Returns true if the view state saving is enabled, else false.
10640     *
10641     * @see #setSaveEnabled(boolean)
10642     * @attr ref android.R.styleable#View_saveEnabled
10643     */
10644    public boolean isSaveEnabled() {
10645        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
10646    }
10647
10648    /**
10649     * Controls whether the saving of this view's state is
10650     * enabled (that is, whether its {@link #onSaveInstanceState} method
10651     * will be called).  Note that even if freezing is enabled, the
10652     * view still must have an id assigned to it (via {@link #setId(int)})
10653     * for its state to be saved.  This flag can only disable the
10654     * saving of this view; any child views may still have their state saved.
10655     *
10656     * @param enabled Set to false to <em>disable</em> state saving, or true
10657     * (the default) to allow it.
10658     *
10659     * @see #isSaveEnabled()
10660     * @see #setId(int)
10661     * @see #onSaveInstanceState()
10662     * @attr ref android.R.styleable#View_saveEnabled
10663     */
10664    public void setSaveEnabled(boolean enabled) {
10665        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
10666    }
10667
10668    /**
10669     * Gets whether the framework should discard touches when the view's
10670     * window is obscured by another visible window.
10671     * Refer to the {@link View} security documentation for more details.
10672     *
10673     * @return True if touch filtering is enabled.
10674     *
10675     * @see #setFilterTouchesWhenObscured(boolean)
10676     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
10677     */
10678    @ViewDebug.ExportedProperty
10679    public boolean getFilterTouchesWhenObscured() {
10680        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
10681    }
10682
10683    /**
10684     * Sets whether the framework should discard touches when the view's
10685     * window is obscured by another visible window.
10686     * Refer to the {@link View} security documentation for more details.
10687     *
10688     * @param enabled True if touch filtering should be enabled.
10689     *
10690     * @see #getFilterTouchesWhenObscured
10691     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
10692     */
10693    public void setFilterTouchesWhenObscured(boolean enabled) {
10694        setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0,
10695                FILTER_TOUCHES_WHEN_OBSCURED);
10696    }
10697
10698    /**
10699     * Indicates whether the entire hierarchy under this view will save its
10700     * state when a state saving traversal occurs from its parent.  The default
10701     * is true; if false, these views will not be saved unless
10702     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
10703     *
10704     * @return Returns true if the view state saving from parent is enabled, else false.
10705     *
10706     * @see #setSaveFromParentEnabled(boolean)
10707     */
10708    public boolean isSaveFromParentEnabled() {
10709        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
10710    }
10711
10712    /**
10713     * Controls whether the entire hierarchy under this view will save its
10714     * state when a state saving traversal occurs from its parent.  The default
10715     * is true; if false, these views will not be saved unless
10716     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
10717     *
10718     * @param enabled Set to false to <em>disable</em> state saving, or true
10719     * (the default) to allow it.
10720     *
10721     * @see #isSaveFromParentEnabled()
10722     * @see #setId(int)
10723     * @see #onSaveInstanceState()
10724     */
10725    public void setSaveFromParentEnabled(boolean enabled) {
10726        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
10727    }
10728
10729
10730    /**
10731     * Returns whether this View is currently able to take focus.
10732     *
10733     * @return True if this view can take focus, or false otherwise.
10734     */
10735    @ViewDebug.ExportedProperty(category = "focus")
10736    public final boolean isFocusable() {
10737        return FOCUSABLE == (mViewFlags & FOCUSABLE);
10738    }
10739
10740    /**
10741     * Returns the focusable setting for this view.
10742     *
10743     * @return One of {@link #NOT_FOCUSABLE}, {@link #FOCUSABLE}, or {@link #FOCUSABLE_AUTO}.
10744     * @attr ref android.R.styleable#View_focusable
10745     */
10746    @ViewDebug.ExportedProperty(mapping = {
10747            @ViewDebug.IntToString(from = NOT_FOCUSABLE, to = "NOT_FOCUSABLE"),
10748            @ViewDebug.IntToString(from = FOCUSABLE, to = "FOCUSABLE"),
10749            @ViewDebug.IntToString(from = FOCUSABLE_AUTO, to = "FOCUSABLE_AUTO")
10750            }, category = "focus")
10751    @Focusable
10752    public int getFocusable() {
10753        return (mViewFlags & FOCUSABLE_AUTO) > 0 ? FOCUSABLE_AUTO : mViewFlags & FOCUSABLE;
10754    }
10755
10756    /**
10757     * When a view is focusable, it may not want to take focus when in touch mode.
10758     * For example, a button would like focus when the user is navigating via a D-pad
10759     * so that the user can click on it, but once the user starts touching the screen,
10760     * the button shouldn't take focus
10761     * @return Whether the view is focusable in touch mode.
10762     * @attr ref android.R.styleable#View_focusableInTouchMode
10763     */
10764    @ViewDebug.ExportedProperty(category = "focus")
10765    public final boolean isFocusableInTouchMode() {
10766        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
10767    }
10768
10769    /**
10770     * Returns whether the view should be treated as a focusable unit by screen reader
10771     * accessibility tools.
10772     * @see #setScreenReaderFocusable(boolean)
10773     *
10774     * @return Whether the view should be treated as a focusable unit by screen reader.
10775     */
10776    public boolean isScreenReaderFocusable() {
10777        return (mPrivateFlags3 & PFLAG3_SCREEN_READER_FOCUSABLE) != 0;
10778    }
10779
10780    /**
10781     * When screen readers (one type of accessibility tool) decide what should be read to the
10782     * user, they typically look for input focusable ({@link #isFocusable()}) parents of
10783     * non-focusable text items, and read those focusable parents and their non-focusable children
10784     * as a unit. In some situations, this behavior is desirable for views that should not take
10785     * input focus. Setting an item to be screen reader focusable requests that the view be
10786     * treated as a unit by screen readers without any effect on input focusability. The default
10787     * value of {@code false} lets screen readers use other signals, like focusable, to determine
10788     * how to group items.
10789     *
10790     * @param screenReaderFocusable Whether the view should be treated as a unit by screen reader
10791     *                              accessibility tools.
10792     */
10793    public void setScreenReaderFocusable(boolean screenReaderFocusable) {
10794        updatePflags3AndNotifyA11yIfChanged(PFLAG3_SCREEN_READER_FOCUSABLE, screenReaderFocusable);
10795    }
10796
10797    /**
10798     * Gets whether this view is a heading for accessibility purposes.
10799     *
10800     * @return {@code true} if the view is a heading, {@code false} otherwise.
10801     *
10802     * @attr ref android.R.styleable#View_accessibilityHeading
10803     */
10804    public boolean isAccessibilityHeading() {
10805        return (mPrivateFlags3 & PFLAG3_ACCESSIBILITY_HEADING) != 0;
10806    }
10807
10808    /**
10809     * Set if view is a heading for a section of content for accessibility purposes.
10810     *
10811     * @param isHeading {@code true} if the view is a heading, {@code false} otherwise.
10812     *
10813     * @attr ref android.R.styleable#View_accessibilityHeading
10814     */
10815    public void setAccessibilityHeading(boolean isHeading) {
10816        updatePflags3AndNotifyA11yIfChanged(PFLAG3_ACCESSIBILITY_HEADING, isHeading);
10817    }
10818
10819    private void updatePflags3AndNotifyA11yIfChanged(int mask, boolean newValue) {
10820        int pflags3 = mPrivateFlags3;
10821        if (newValue) {
10822            pflags3 |= mask;
10823        } else {
10824            pflags3 &= ~mask;
10825        }
10826
10827        if (pflags3 != mPrivateFlags3) {
10828            mPrivateFlags3 = pflags3;
10829            notifyViewAccessibilityStateChangedIfNeeded(
10830                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10831        }
10832    }
10833
10834    /**
10835     * Find the nearest view in the specified direction that can take focus.
10836     * This does not actually give focus to that view.
10837     *
10838     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
10839     *
10840     * @return The nearest focusable in the specified direction, or null if none
10841     *         can be found.
10842     */
10843    public View focusSearch(@FocusRealDirection int direction) {
10844        if (mParent != null) {
10845            return mParent.focusSearch(this, direction);
10846        } else {
10847            return null;
10848        }
10849    }
10850
10851    /**
10852     * Returns whether this View is a root of a keyboard navigation cluster.
10853     *
10854     * @return True if this view is a root of a cluster, or false otherwise.
10855     * @attr ref android.R.styleable#View_keyboardNavigationCluster
10856     */
10857    @ViewDebug.ExportedProperty(category = "focus")
10858    public final boolean isKeyboardNavigationCluster() {
10859        return (mPrivateFlags3 & PFLAG3_CLUSTER) != 0;
10860    }
10861
10862    /**
10863     * Searches up the view hierarchy to find the top-most cluster. All deeper/nested clusters
10864     * will be ignored.
10865     *
10866     * @return the keyboard navigation cluster that this view is in (can be this view)
10867     *         or {@code null} if not in one
10868     */
10869    View findKeyboardNavigationCluster() {
10870        if (mParent instanceof View) {
10871            View cluster = ((View) mParent).findKeyboardNavigationCluster();
10872            if (cluster != null) {
10873                return cluster;
10874            } else if (isKeyboardNavigationCluster()) {
10875                return this;
10876            }
10877        }
10878        return null;
10879    }
10880
10881    /**
10882     * Set whether this view is a root of a keyboard navigation cluster.
10883     *
10884     * @param isCluster If true, this view is a root of a cluster.
10885     *
10886     * @attr ref android.R.styleable#View_keyboardNavigationCluster
10887     */
10888    public void setKeyboardNavigationCluster(boolean isCluster) {
10889        if (isCluster) {
10890            mPrivateFlags3 |= PFLAG3_CLUSTER;
10891        } else {
10892            mPrivateFlags3 &= ~PFLAG3_CLUSTER;
10893        }
10894    }
10895
10896    /**
10897     * Sets this View as the one which receives focus the next time cluster navigation jumps
10898     * to the cluster containing this View. This does NOT change focus even if the cluster
10899     * containing this view is current.
10900     *
10901     * @hide
10902     */
10903    @TestApi
10904    public final void setFocusedInCluster() {
10905        setFocusedInCluster(findKeyboardNavigationCluster());
10906    }
10907
10908    private void setFocusedInCluster(View cluster) {
10909        if (this instanceof ViewGroup) {
10910            ((ViewGroup) this).mFocusedInCluster = null;
10911        }
10912        if (cluster == this) {
10913            return;
10914        }
10915        ViewParent parent = mParent;
10916        View child = this;
10917        while (parent instanceof ViewGroup) {
10918            ((ViewGroup) parent).mFocusedInCluster = child;
10919            if (parent == cluster) {
10920                break;
10921            }
10922            child = (View) parent;
10923            parent = parent.getParent();
10924        }
10925    }
10926
10927    private void updateFocusedInCluster(View oldFocus, @FocusDirection int direction) {
10928        if (oldFocus != null) {
10929            View oldCluster = oldFocus.findKeyboardNavigationCluster();
10930            View cluster = findKeyboardNavigationCluster();
10931            if (oldCluster != cluster) {
10932                // Going from one cluster to another, so save last-focused.
10933                // This covers cluster jumps because they are always FOCUS_DOWN
10934                oldFocus.setFocusedInCluster(oldCluster);
10935                if (!(oldFocus.mParent instanceof ViewGroup)) {
10936                    return;
10937                }
10938                if (direction == FOCUS_FORWARD || direction == FOCUS_BACKWARD) {
10939                    // This is a result of ordered navigation so consider navigation through
10940                    // the previous cluster "complete" and clear its last-focused memory.
10941                    ((ViewGroup) oldFocus.mParent).clearFocusedInCluster(oldFocus);
10942                } else if (oldFocus instanceof ViewGroup
10943                        && ((ViewGroup) oldFocus).getDescendantFocusability()
10944                                == ViewGroup.FOCUS_AFTER_DESCENDANTS
10945                        && ViewRootImpl.isViewDescendantOf(this, oldFocus)) {
10946                    // This means oldFocus is not focusable since it obviously has a focusable
10947                    // child (this). Don't restore focus to it in the future.
10948                    ((ViewGroup) oldFocus.mParent).clearFocusedInCluster(oldFocus);
10949                }
10950            }
10951        }
10952    }
10953
10954    /**
10955     * Returns whether this View should receive focus when the focus is restored for the view
10956     * hierarchy containing this view.
10957     * <p>
10958     * Focus gets restored for a view hierarchy when the root of the hierarchy gets added to a
10959     * window or serves as a target of cluster navigation.
10960     *
10961     * @see #restoreDefaultFocus()
10962     *
10963     * @return {@code true} if this view is the default-focus view, {@code false} otherwise
10964     * @attr ref android.R.styleable#View_focusedByDefault
10965     */
10966    @ViewDebug.ExportedProperty(category = "focus")
10967    public final boolean isFocusedByDefault() {
10968        return (mPrivateFlags3 & PFLAG3_FOCUSED_BY_DEFAULT) != 0;
10969    }
10970
10971    /**
10972     * Sets whether this View should receive focus when the focus is restored for the view
10973     * hierarchy containing this view.
10974     * <p>
10975     * Focus gets restored for a view hierarchy when the root of the hierarchy gets added to a
10976     * window or serves as a target of cluster navigation.
10977     *
10978     * @param isFocusedByDefault {@code true} to set this view as the default-focus view,
10979     *                           {@code false} otherwise.
10980     *
10981     * @see #restoreDefaultFocus()
10982     *
10983     * @attr ref android.R.styleable#View_focusedByDefault
10984     */
10985    public void setFocusedByDefault(boolean isFocusedByDefault) {
10986        if (isFocusedByDefault == ((mPrivateFlags3 & PFLAG3_FOCUSED_BY_DEFAULT) != 0)) {
10987            return;
10988        }
10989
10990        if (isFocusedByDefault) {
10991            mPrivateFlags3 |= PFLAG3_FOCUSED_BY_DEFAULT;
10992        } else {
10993            mPrivateFlags3 &= ~PFLAG3_FOCUSED_BY_DEFAULT;
10994        }
10995
10996        if (mParent instanceof ViewGroup) {
10997            if (isFocusedByDefault) {
10998                ((ViewGroup) mParent).setDefaultFocus(this);
10999            } else {
11000                ((ViewGroup) mParent).clearDefaultFocus(this);
11001            }
11002        }
11003    }
11004
11005    /**
11006     * Returns whether the view hierarchy with this view as a root contain a default-focus view.
11007     *
11008     * @return {@code true} if this view has default focus, {@code false} otherwise
11009     */
11010    boolean hasDefaultFocus() {
11011        return isFocusedByDefault();
11012    }
11013
11014    /**
11015     * Find the nearest keyboard navigation cluster in the specified direction.
11016     * This does not actually give focus to that cluster.
11017     *
11018     * @param currentCluster The starting point of the search. Null means the current cluster is not
11019     *                       found yet
11020     * @param direction Direction to look
11021     *
11022     * @return The nearest keyboard navigation cluster in the specified direction, or null if none
11023     *         can be found
11024     */
11025    public View keyboardNavigationClusterSearch(View currentCluster,
11026            @FocusDirection int direction) {
11027        if (isKeyboardNavigationCluster()) {
11028            currentCluster = this;
11029        }
11030        if (isRootNamespace()) {
11031            // Root namespace means we should consider ourselves the top of the
11032            // tree for group searching; otherwise we could be group searching
11033            // into other tabs.  see LocalActivityManager and TabHost for more info.
11034            return FocusFinder.getInstance().findNextKeyboardNavigationCluster(
11035                    this, currentCluster, direction);
11036        } else if (mParent != null) {
11037            return mParent.keyboardNavigationClusterSearch(currentCluster, direction);
11038        }
11039        return null;
11040    }
11041
11042    /**
11043     * This method is the last chance for the focused view and its ancestors to
11044     * respond to an arrow key. This is called when the focused view did not
11045     * consume the key internally, nor could the view system find a new view in
11046     * the requested direction to give focus to.
11047     *
11048     * @param focused The currently focused view.
11049     * @param direction The direction focus wants to move. One of FOCUS_UP,
11050     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
11051     * @return True if the this view consumed this unhandled move.
11052     */
11053    public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) {
11054        return false;
11055    }
11056
11057    /**
11058     * Sets whether this View should use a default focus highlight when it gets focused but doesn't
11059     * have {@link android.R.attr#state_focused} defined in its background.
11060     *
11061     * @param defaultFocusHighlightEnabled {@code true} to set this view to use a default focus
11062     *                                      highlight, {@code false} otherwise.
11063     *
11064     * @attr ref android.R.styleable#View_defaultFocusHighlightEnabled
11065     */
11066    public void setDefaultFocusHighlightEnabled(boolean defaultFocusHighlightEnabled) {
11067        mDefaultFocusHighlightEnabled = defaultFocusHighlightEnabled;
11068    }
11069
11070    /**
11071
11072    /**
11073     * Returns whether this View should use a default focus highlight when it gets focused but
11074     * doesn't have {@link android.R.attr#state_focused} defined in its background.
11075     *
11076     * @return True if this View should use a default focus highlight.
11077     * @attr ref android.R.styleable#View_defaultFocusHighlightEnabled
11078     */
11079    @ViewDebug.ExportedProperty(category = "focus")
11080    public final boolean getDefaultFocusHighlightEnabled() {
11081        return mDefaultFocusHighlightEnabled;
11082    }
11083
11084    /**
11085     * If a user manually specified the next view id for a particular direction,
11086     * use the root to look up the view.
11087     * @param root The root view of the hierarchy containing this view.
11088     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
11089     * or FOCUS_BACKWARD.
11090     * @return The user specified next view, or null if there is none.
11091     */
11092    View findUserSetNextFocus(View root, @FocusDirection int direction) {
11093        switch (direction) {
11094            case FOCUS_LEFT:
11095                if (mNextFocusLeftId == View.NO_ID) return null;
11096                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
11097            case FOCUS_RIGHT:
11098                if (mNextFocusRightId == View.NO_ID) return null;
11099                return findViewInsideOutShouldExist(root, mNextFocusRightId);
11100            case FOCUS_UP:
11101                if (mNextFocusUpId == View.NO_ID) return null;
11102                return findViewInsideOutShouldExist(root, mNextFocusUpId);
11103            case FOCUS_DOWN:
11104                if (mNextFocusDownId == View.NO_ID) return null;
11105                return findViewInsideOutShouldExist(root, mNextFocusDownId);
11106            case FOCUS_FORWARD:
11107                if (mNextFocusForwardId == View.NO_ID) return null;
11108                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
11109            case FOCUS_BACKWARD: {
11110                if (mID == View.NO_ID) return null;
11111                final int id = mID;
11112                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
11113                    @Override
11114                    public boolean test(View t) {
11115                        return t.mNextFocusForwardId == id;
11116                    }
11117                });
11118            }
11119        }
11120        return null;
11121    }
11122
11123    /**
11124     * If a user manually specified the next keyboard-navigation cluster for a particular direction,
11125     * use the root to look up the view.
11126     *
11127     * @param root the root view of the hierarchy containing this view
11128     * @param direction {@link #FOCUS_FORWARD} or {@link #FOCUS_BACKWARD}
11129     * @return the user-specified next cluster, or {@code null} if there is none
11130     */
11131    View findUserSetNextKeyboardNavigationCluster(View root, @FocusDirection int direction) {
11132        switch (direction) {
11133            case FOCUS_FORWARD:
11134                if (mNextClusterForwardId == View.NO_ID) return null;
11135                return findViewInsideOutShouldExist(root, mNextClusterForwardId);
11136            case FOCUS_BACKWARD: {
11137                if (mID == View.NO_ID) return null;
11138                final int id = mID;
11139                return root.findViewByPredicateInsideOut(this,
11140                        (Predicate<View>) t -> t.mNextClusterForwardId == id);
11141            }
11142        }
11143        return null;
11144    }
11145
11146    private View findViewInsideOutShouldExist(View root, int id) {
11147        if (mMatchIdPredicate == null) {
11148            mMatchIdPredicate = new MatchIdPredicate();
11149        }
11150        mMatchIdPredicate.mId = id;
11151        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
11152        if (result == null) {
11153            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
11154        }
11155        return result;
11156    }
11157
11158    /**
11159     * Find and return all focusable views that are descendants of this view,
11160     * possibly including this view if it is focusable itself.
11161     *
11162     * @param direction The direction of the focus
11163     * @return A list of focusable views
11164     */
11165    public ArrayList<View> getFocusables(@FocusDirection int direction) {
11166        ArrayList<View> result = new ArrayList<View>(24);
11167        addFocusables(result, direction);
11168        return result;
11169    }
11170
11171    /**
11172     * Add any focusable views that are descendants of this view (possibly
11173     * including this view if it is focusable itself) to views.  If we are in touch mode,
11174     * only add views that are also focusable in touch mode.
11175     *
11176     * @param views Focusable views found so far
11177     * @param direction The direction of the focus
11178     */
11179    public void addFocusables(ArrayList<View> views, @FocusDirection int direction) {
11180        addFocusables(views, direction, isInTouchMode() ? FOCUSABLES_TOUCH_MODE : FOCUSABLES_ALL);
11181    }
11182
11183    /**
11184     * Adds any focusable views that are descendants of this view (possibly
11185     * including this view if it is focusable itself) to views. This method
11186     * adds all focusable views regardless if we are in touch mode or
11187     * only views focusable in touch mode if we are in touch mode or
11188     * only views that can take accessibility focus if accessibility is enabled
11189     * depending on the focusable mode parameter.
11190     *
11191     * @param views Focusable views found so far or null if all we are interested is
11192     *        the number of focusables.
11193     * @param direction The direction of the focus.
11194     * @param focusableMode The type of focusables to be added.
11195     *
11196     * @see #FOCUSABLES_ALL
11197     * @see #FOCUSABLES_TOUCH_MODE
11198     */
11199    public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
11200            @FocusableMode int focusableMode) {
11201        if (views == null) {
11202            return;
11203        }
11204        if (!canTakeFocus()) {
11205            return;
11206        }
11207        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
11208                && !isFocusableInTouchMode()) {
11209            return;
11210        }
11211        views.add(this);
11212    }
11213
11214    /**
11215     * Adds any keyboard navigation cluster roots that are descendants of this view (possibly
11216     * including this view if it is a cluster root itself) to views.
11217     *
11218     * @param views Keyboard navigation cluster roots found so far
11219     * @param direction Direction to look
11220     */
11221    public void addKeyboardNavigationClusters(
11222            @NonNull Collection<View> views,
11223            int direction) {
11224        if (!isKeyboardNavigationCluster()) {
11225            return;
11226        }
11227        if (!hasFocusable()) {
11228            return;
11229        }
11230        views.add(this);
11231    }
11232
11233    /**
11234     * Finds the Views that contain given text. The containment is case insensitive.
11235     * The search is performed by either the text that the View renders or the content
11236     * description that describes the view for accessibility purposes and the view does
11237     * not render or both. Clients can specify how the search is to be performed via
11238     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
11239     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
11240     *
11241     * @param outViews The output list of matching Views.
11242     * @param searched The text to match against.
11243     *
11244     * @see #FIND_VIEWS_WITH_TEXT
11245     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
11246     * @see #setContentDescription(CharSequence)
11247     */
11248    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched,
11249            @FindViewFlags int flags) {
11250        if (getAccessibilityNodeProvider() != null) {
11251            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
11252                outViews.add(this);
11253            }
11254        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
11255                && (searched != null && searched.length() > 0)
11256                && (mContentDescription != null && mContentDescription.length() > 0)) {
11257            String searchedLowerCase = searched.toString().toLowerCase();
11258            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
11259            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
11260                outViews.add(this);
11261            }
11262        }
11263    }
11264
11265    /**
11266     * Find and return all touchable views that are descendants of this view,
11267     * possibly including this view if it is touchable itself.
11268     *
11269     * @return A list of touchable views
11270     */
11271    public ArrayList<View> getTouchables() {
11272        ArrayList<View> result = new ArrayList<View>();
11273        addTouchables(result);
11274        return result;
11275    }
11276
11277    /**
11278     * Add any touchable views that are descendants of this view (possibly
11279     * including this view if it is touchable itself) to views.
11280     *
11281     * @param views Touchable views found so far
11282     */
11283    public void addTouchables(ArrayList<View> views) {
11284        final int viewFlags = mViewFlags;
11285
11286        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE
11287                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE)
11288                && (viewFlags & ENABLED_MASK) == ENABLED) {
11289            views.add(this);
11290        }
11291    }
11292
11293    /**
11294     * Returns whether this View is accessibility focused.
11295     *
11296     * @return True if this View is accessibility focused.
11297     */
11298    public boolean isAccessibilityFocused() {
11299        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
11300    }
11301
11302    /**
11303     * Call this to try to give accessibility focus to this view.
11304     *
11305     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
11306     * returns false or the view is no visible or the view already has accessibility
11307     * focus.
11308     *
11309     * See also {@link #focusSearch(int)}, which is what you call to say that you
11310     * have focus, and you want your parent to look for the next one.
11311     *
11312     * @return Whether this view actually took accessibility focus.
11313     *
11314     * @hide
11315     */
11316    public boolean requestAccessibilityFocus() {
11317        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
11318        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
11319            return false;
11320        }
11321        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
11322            return false;
11323        }
11324        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
11325            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
11326            ViewRootImpl viewRootImpl = getViewRootImpl();
11327            if (viewRootImpl != null) {
11328                viewRootImpl.setAccessibilityFocus(this, null);
11329            }
11330            invalidate();
11331            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
11332            return true;
11333        }
11334        return false;
11335    }
11336
11337    /**
11338     * Call this to try to clear accessibility focus of this view.
11339     *
11340     * See also {@link #focusSearch(int)}, which is what you call to say that you
11341     * have focus, and you want your parent to look for the next one.
11342     *
11343     * @hide
11344     */
11345    public void clearAccessibilityFocus() {
11346        clearAccessibilityFocusNoCallbacks(0);
11347
11348        // Clear the global reference of accessibility focus if this view or
11349        // any of its descendants had accessibility focus. This will NOT send
11350        // an event or update internal state if focus is cleared from a
11351        // descendant view, which may leave views in inconsistent states.
11352        final ViewRootImpl viewRootImpl = getViewRootImpl();
11353        if (viewRootImpl != null) {
11354            final View focusHost = viewRootImpl.getAccessibilityFocusedHost();
11355            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
11356                viewRootImpl.setAccessibilityFocus(null, null);
11357            }
11358        }
11359    }
11360
11361    private void sendAccessibilityHoverEvent(int eventType) {
11362        // Since we are not delivering to a client accessibility events from not
11363        // important views (unless the clinet request that) we need to fire the
11364        // event from the deepest view exposed to the client. As a consequence if
11365        // the user crosses a not exposed view the client will see enter and exit
11366        // of the exposed predecessor followed by and enter and exit of that same
11367        // predecessor when entering and exiting the not exposed descendant. This
11368        // is fine since the client has a clear idea which view is hovered at the
11369        // price of a couple more events being sent. This is a simple and
11370        // working solution.
11371        View source = this;
11372        while (true) {
11373            if (source.includeForAccessibility()) {
11374                source.sendAccessibilityEvent(eventType);
11375                return;
11376            }
11377            ViewParent parent = source.getParent();
11378            if (parent instanceof View) {
11379                source = (View) parent;
11380            } else {
11381                return;
11382            }
11383        }
11384    }
11385
11386    /**
11387     * Clears accessibility focus without calling any callback methods
11388     * normally invoked in {@link #clearAccessibilityFocus()}. This method
11389     * is used separately from that one for clearing accessibility focus when
11390     * giving this focus to another view.
11391     *
11392     * @param action The action, if any, that led to focus being cleared. Set to
11393     * AccessibilityNodeInfo#ACTION_ACCESSIBILITY_FOCUS to specify that focus is moving within
11394     * the window.
11395     */
11396    void clearAccessibilityFocusNoCallbacks(int action) {
11397        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
11398            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
11399            invalidate();
11400            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
11401                AccessibilityEvent event = AccessibilityEvent.obtain(
11402                        AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
11403                event.setAction(action);
11404                if (mAccessibilityDelegate != null) {
11405                    mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
11406                } else {
11407                    sendAccessibilityEventUnchecked(event);
11408                }
11409            }
11410        }
11411    }
11412
11413    /**
11414     * Call this to try to give focus to a specific view or to one of its
11415     * descendants.
11416     *
11417     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
11418     * false), or if it can't be focused due to other conditions (not focusable in touch mode
11419     * ({@link #isFocusableInTouchMode}) while the device is in touch mode, not visible, not
11420     * enabled, or has no size).
11421     *
11422     * See also {@link #focusSearch(int)}, which is what you call to say that you
11423     * have focus, and you want your parent to look for the next one.
11424     *
11425     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
11426     * {@link #FOCUS_DOWN} and <code>null</code>.
11427     *
11428     * @return Whether this view or one of its descendants actually took focus.
11429     */
11430    public final boolean requestFocus() {
11431        return requestFocus(View.FOCUS_DOWN);
11432    }
11433
11434    /**
11435     * This will request focus for whichever View was last focused within this
11436     * cluster before a focus-jump out of it.
11437     *
11438     * @hide
11439     */
11440    @TestApi
11441    public boolean restoreFocusInCluster(@FocusRealDirection int direction) {
11442        // Prioritize focusableByDefault over algorithmic focus selection.
11443        if (restoreDefaultFocus()) {
11444            return true;
11445        }
11446        return requestFocus(direction);
11447    }
11448
11449    /**
11450     * This will request focus for whichever View not in a cluster was last focused before a
11451     * focus-jump to a cluster. If no non-cluster View has previously had focus, this will focus
11452     * the "first" focusable view it finds.
11453     *
11454     * @hide
11455     */
11456    @TestApi
11457    public boolean restoreFocusNotInCluster() {
11458        return requestFocus(View.FOCUS_DOWN);
11459    }
11460
11461    /**
11462     * Gives focus to the default-focus view in the view hierarchy that has this view as a root.
11463     * If the default-focus view cannot be found, falls back to calling {@link #requestFocus(int)}.
11464     *
11465     * @return Whether this view or one of its descendants actually took focus
11466     */
11467    public boolean restoreDefaultFocus() {
11468        return requestFocus(View.FOCUS_DOWN);
11469    }
11470
11471    /**
11472     * Call this to try to give focus to a specific view or to one of its
11473     * descendants and give it a hint about what direction focus is heading.
11474     *
11475     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
11476     * false), or if it is focusable and it is not focusable in touch mode
11477     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
11478     *
11479     * See also {@link #focusSearch(int)}, which is what you call to say that you
11480     * have focus, and you want your parent to look for the next one.
11481     *
11482     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
11483     * <code>null</code> set for the previously focused rectangle.
11484     *
11485     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
11486     * @return Whether this view or one of its descendants actually took focus.
11487     */
11488    public final boolean requestFocus(int direction) {
11489        return requestFocus(direction, null);
11490    }
11491
11492    /**
11493     * Call this to try to give focus to a specific view or to one of its descendants
11494     * and give it hints about the direction and a specific rectangle that the focus
11495     * is coming from.  The rectangle can help give larger views a finer grained hint
11496     * about where focus is coming from, and therefore, where to show selection, or
11497     * forward focus change internally.
11498     *
11499     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
11500     * false), or if it is focusable and it is not focusable in touch mode
11501     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
11502     *
11503     * A View will not take focus if it is not visible.
11504     *
11505     * A View will not take focus if one of its parents has
11506     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
11507     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
11508     *
11509     * See also {@link #focusSearch(int)}, which is what you call to say that you
11510     * have focus, and you want your parent to look for the next one.
11511     *
11512     * You may wish to override this method if your custom {@link View} has an internal
11513     * {@link View} that it wishes to forward the request to.
11514     *
11515     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
11516     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
11517     *        to give a finer grained hint about where focus is coming from.  May be null
11518     *        if there is no hint.
11519     * @return Whether this view or one of its descendants actually took focus.
11520     */
11521    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
11522        return requestFocusNoSearch(direction, previouslyFocusedRect);
11523    }
11524
11525    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
11526        // need to be focusable
11527        if (!canTakeFocus()) {
11528            return false;
11529        }
11530
11531        // need to be focusable in touch mode if in touch mode
11532        if (isInTouchMode() &&
11533            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
11534               return false;
11535        }
11536
11537        // need to not have any parents blocking us
11538        if (hasAncestorThatBlocksDescendantFocus()) {
11539            return false;
11540        }
11541
11542        if (!isLayoutValid()) {
11543            mPrivateFlags |= PFLAG_WANTS_FOCUS;
11544        } else {
11545            clearParentsWantFocus();
11546        }
11547
11548        handleFocusGainInternal(direction, previouslyFocusedRect);
11549        return true;
11550    }
11551
11552    void clearParentsWantFocus() {
11553        if (mParent instanceof View) {
11554            ((View) mParent).mPrivateFlags &= ~PFLAG_WANTS_FOCUS;
11555            ((View) mParent).clearParentsWantFocus();
11556        }
11557    }
11558
11559    /**
11560     * Call this to try to give focus to a specific view or to one of its descendants. This is a
11561     * special variant of {@link #requestFocus() } that will allow views that are not focusable in
11562     * touch mode to request focus when they are touched.
11563     *
11564     * @return Whether this view or one of its descendants actually took focus.
11565     *
11566     * @see #isInTouchMode()
11567     *
11568     */
11569    public final boolean requestFocusFromTouch() {
11570        // Leave touch mode if we need to
11571        if (isInTouchMode()) {
11572            ViewRootImpl viewRoot = getViewRootImpl();
11573            if (viewRoot != null) {
11574                viewRoot.ensureTouchMode(false);
11575            }
11576        }
11577        return requestFocus(View.FOCUS_DOWN);
11578    }
11579
11580    /**
11581     * @return Whether any ancestor of this view blocks descendant focus.
11582     */
11583    private boolean hasAncestorThatBlocksDescendantFocus() {
11584        final boolean focusableInTouchMode = isFocusableInTouchMode();
11585        ViewParent ancestor = mParent;
11586        while (ancestor instanceof ViewGroup) {
11587            final ViewGroup vgAncestor = (ViewGroup) ancestor;
11588            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS
11589                    || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) {
11590                return true;
11591            } else {
11592                ancestor = vgAncestor.getParent();
11593            }
11594        }
11595        return false;
11596    }
11597
11598    /**
11599     * Gets the mode for determining whether this View is important for accessibility.
11600     * A view is important for accessibility if it fires accessibility events and if it
11601     * is reported to accessibility services that query the screen.
11602     *
11603     * @return The mode for determining whether a view is important for accessibility, one
11604     * of {@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, {@link #IMPORTANT_FOR_ACCESSIBILITY_YES},
11605     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO}, or
11606     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}.
11607     *
11608     * @attr ref android.R.styleable#View_importantForAccessibility
11609     *
11610     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
11611     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
11612     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
11613     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
11614     */
11615    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
11616            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
11617            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
11618            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"),
11619            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
11620                    to = "noHideDescendants")
11621        })
11622    public int getImportantForAccessibility() {
11623        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
11624                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
11625    }
11626
11627    /**
11628     * Sets the live region mode for this view. This indicates to accessibility
11629     * services whether they should automatically notify the user about changes
11630     * to the view's content description or text, or to the content descriptions
11631     * or text of the view's children (where applicable).
11632     * <p>
11633     * For example, in a login screen with a TextView that displays an "incorrect
11634     * password" notification, that view should be marked as a live region with
11635     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
11636     * <p>
11637     * To disable change notifications for this view, use
11638     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
11639     * mode for most views.
11640     * <p>
11641     * To indicate that the user should be notified of changes, use
11642     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
11643     * <p>
11644     * If the view's changes should interrupt ongoing speech and notify the user
11645     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
11646     *
11647     * @param mode The live region mode for this view, one of:
11648     *        <ul>
11649     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
11650     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
11651     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
11652     *        </ul>
11653     * @attr ref android.R.styleable#View_accessibilityLiveRegion
11654     */
11655    public void setAccessibilityLiveRegion(int mode) {
11656        if (mode != getAccessibilityLiveRegion()) {
11657            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
11658            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
11659                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
11660            notifyViewAccessibilityStateChangedIfNeeded(
11661                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
11662        }
11663    }
11664
11665    /**
11666     * Gets the live region mode for this View.
11667     *
11668     * @return The live region mode for the view.
11669     *
11670     * @attr ref android.R.styleable#View_accessibilityLiveRegion
11671     *
11672     * @see #setAccessibilityLiveRegion(int)
11673     */
11674    public int getAccessibilityLiveRegion() {
11675        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
11676                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
11677    }
11678
11679    /**
11680     * Sets how to determine whether this view is important for accessibility
11681     * which is if it fires accessibility events and if it is reported to
11682     * accessibility services that query the screen.
11683     *
11684     * @param mode How to determine whether this view is important for accessibility.
11685     *
11686     * @attr ref android.R.styleable#View_importantForAccessibility
11687     *
11688     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
11689     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
11690     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
11691     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
11692     */
11693    public void setImportantForAccessibility(int mode) {
11694        final int oldMode = getImportantForAccessibility();
11695        if (mode != oldMode) {
11696            final boolean hideDescendants =
11697                    mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS;
11698
11699            // If this node or its descendants are no longer important, try to
11700            // clear accessibility focus.
11701            if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO || hideDescendants) {
11702                final View focusHost = findAccessibilityFocusHost(hideDescendants);
11703                if (focusHost != null) {
11704                    focusHost.clearAccessibilityFocus();
11705                }
11706            }
11707
11708            // If we're moving between AUTO and another state, we might not need
11709            // to send a subtree changed notification. We'll store the computed
11710            // importance, since we'll need to check it later to make sure.
11711            final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO
11712                    || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO;
11713            final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility();
11714            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
11715            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
11716                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
11717            if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) {
11718                notifySubtreeAccessibilityStateChangedIfNeeded();
11719            } else {
11720                notifyViewAccessibilityStateChangedIfNeeded(
11721                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
11722            }
11723        }
11724    }
11725
11726    /**
11727     * Returns the view within this view's hierarchy that is hosting
11728     * accessibility focus.
11729     *
11730     * @param searchDescendants whether to search for focus in descendant views
11731     * @return the view hosting accessibility focus, or {@code null}
11732     */
11733    private View findAccessibilityFocusHost(boolean searchDescendants) {
11734        if (isAccessibilityFocusedViewOrHost()) {
11735            return this;
11736        }
11737
11738        if (searchDescendants) {
11739            final ViewRootImpl viewRoot = getViewRootImpl();
11740            if (viewRoot != null) {
11741                final View focusHost = viewRoot.getAccessibilityFocusedHost();
11742                if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
11743                    return focusHost;
11744                }
11745            }
11746        }
11747
11748        return null;
11749    }
11750
11751    /**
11752     * Computes whether this view should be exposed for accessibility. In
11753     * general, views that are interactive or provide information are exposed
11754     * while views that serve only as containers are hidden.
11755     * <p>
11756     * If an ancestor of this view has importance
11757     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method
11758     * returns <code>false</code>.
11759     * <p>
11760     * Otherwise, the value is computed according to the view's
11761     * {@link #getImportantForAccessibility()} value:
11762     * <ol>
11763     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or
11764     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false
11765     * </code>
11766     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code>
11767     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if
11768     * view satisfies any of the following:
11769     * <ul>
11770     * <li>Is actionable, e.g. {@link #isClickable()},
11771     * {@link #isLongClickable()}, or {@link #isFocusable()}
11772     * <li>Has an {@link AccessibilityDelegate}
11773     * <li>Has an interaction listener, e.g. {@link OnTouchListener},
11774     * {@link OnKeyListener}, etc.
11775     * <li>Is an accessibility live region, e.g.
11776     * {@link #getAccessibilityLiveRegion()} is not
11777     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}.
11778     * </ul>
11779     * <li>Has an accessibility pane title, see {@link #setAccessibilityPaneTitle}</li>
11780     * </ol>
11781     *
11782     * @return Whether the view is exposed for accessibility.
11783     * @see #setImportantForAccessibility(int)
11784     * @see #getImportantForAccessibility()
11785     */
11786    public boolean isImportantForAccessibility() {
11787        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
11788                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
11789        if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO
11790                || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
11791            return false;
11792        }
11793
11794        // Check parent mode to ensure we're not hidden.
11795        ViewParent parent = mParent;
11796        while (parent instanceof View) {
11797            if (((View) parent).getImportantForAccessibility()
11798                    == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
11799                return false;
11800            }
11801            parent = parent.getParent();
11802        }
11803
11804        return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
11805                || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
11806                || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE
11807                || isAccessibilityPane();
11808    }
11809
11810    /**
11811     * Gets the parent for accessibility purposes. Note that the parent for
11812     * accessibility is not necessary the immediate parent. It is the first
11813     * predecessor that is important for accessibility.
11814     *
11815     * @return The parent for accessibility purposes.
11816     */
11817    public ViewParent getParentForAccessibility() {
11818        if (mParent instanceof View) {
11819            View parentView = (View) mParent;
11820            if (parentView.includeForAccessibility()) {
11821                return mParent;
11822            } else {
11823                return mParent.getParentForAccessibility();
11824            }
11825        }
11826        return null;
11827    }
11828
11829    /**
11830     * Adds the children of this View relevant for accessibility to the given list
11831     * as output. Since some Views are not important for accessibility the added
11832     * child views are not necessarily direct children of this view, rather they are
11833     * the first level of descendants important for accessibility.
11834     *
11835     * @param outChildren The output list that will receive children for accessibility.
11836     */
11837    public void addChildrenForAccessibility(ArrayList<View> outChildren) {
11838
11839    }
11840
11841    /**
11842     * Whether to regard this view for accessibility. A view is regarded for
11843     * accessibility if it is important for accessibility or the querying
11844     * accessibility service has explicitly requested that view not
11845     * important for accessibility are regarded.
11846     *
11847     * @return Whether to regard the view for accessibility.
11848     *
11849     * @hide
11850     */
11851    public boolean includeForAccessibility() {
11852        if (mAttachInfo != null) {
11853            return (mAttachInfo.mAccessibilityFetchFlags
11854                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
11855                    || isImportantForAccessibility();
11856        }
11857        return false;
11858    }
11859
11860    /**
11861     * Returns whether the View is considered actionable from
11862     * accessibility perspective. Such view are important for
11863     * accessibility.
11864     *
11865     * @return True if the view is actionable for accessibility.
11866     *
11867     * @hide
11868     */
11869    public boolean isActionableForAccessibility() {
11870        return (isClickable() || isLongClickable() || isFocusable());
11871    }
11872
11873    /**
11874     * Returns whether the View has registered callbacks which makes it
11875     * important for accessibility.
11876     *
11877     * @return True if the view is actionable for accessibility.
11878     */
11879    private boolean hasListenersForAccessibility() {
11880        ListenerInfo info = getListenerInfo();
11881        return mTouchDelegate != null || info.mOnKeyListener != null
11882                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
11883                || info.mOnHoverListener != null || info.mOnDragListener != null;
11884    }
11885
11886    /**
11887     * Notifies that the accessibility state of this view changed. The change
11888     * is local to this view and does not represent structural changes such
11889     * as children and parent. For example, the view became focusable. The
11890     * notification is at at most once every
11891     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
11892     * to avoid unnecessary load to the system. Also once a view has a pending
11893     * notification this method is a NOP until the notification has been sent.
11894     *
11895     * @hide
11896     */
11897    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
11898        if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) {
11899            return;
11900        }
11901
11902        // Changes to views with a pane title count as window state changes, as the pane title
11903        // marks them as significant parts of the UI.
11904        if ((changeType != AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE)
11905                && isAccessibilityPane()) {
11906            // If the pane isn't visible, content changed events are sufficient unless we're
11907            // reporting that the view just disappeared
11908            if ((getVisibility() == VISIBLE)
11909                    || (changeType == AccessibilityEvent.CONTENT_CHANGE_TYPE_PANE_DISAPPEARED)) {
11910                final AccessibilityEvent event = AccessibilityEvent.obtain();
11911                event.setEventType(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
11912                event.setContentChangeTypes(changeType);
11913                event.setSource(this);
11914                onPopulateAccessibilityEvent(event);
11915                if (mParent != null) {
11916                    try {
11917                        mParent.requestSendAccessibilityEvent(this, event);
11918                    } catch (AbstractMethodError e) {
11919                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName()
11920                                + " does not fully implement ViewParent", e);
11921                    }
11922                }
11923                return;
11924            }
11925        }
11926
11927        // If this is a live region, we should send a subtree change event
11928        // from this view immediately. Otherwise, we can let it propagate up.
11929        if (getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE) {
11930            final AccessibilityEvent event = AccessibilityEvent.obtain();
11931            event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
11932            event.setContentChangeTypes(changeType);
11933            sendAccessibilityEventUnchecked(event);
11934        } else if (mParent != null) {
11935            try {
11936                mParent.notifySubtreeAccessibilityStateChanged(this, this, changeType);
11937            } catch (AbstractMethodError e) {
11938                Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
11939                        " does not fully implement ViewParent", e);
11940            }
11941        }
11942    }
11943
11944    /**
11945     * Notifies that the accessibility state of this view changed. The change
11946     * is *not* local to this view and does represent structural changes such
11947     * as children and parent. For example, the view size changed. The
11948     * notification is at at most once every
11949     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
11950     * to avoid unnecessary load to the system. Also once a view has a pending
11951     * notification this method is a NOP until the notification has been sent.
11952     *
11953     * @hide
11954     */
11955    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
11956        if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) {
11957            return;
11958        }
11959
11960        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
11961            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
11962            if (mParent != null) {
11963                try {
11964                    mParent.notifySubtreeAccessibilityStateChanged(
11965                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
11966                } catch (AbstractMethodError e) {
11967                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
11968                            " does not fully implement ViewParent", e);
11969                }
11970            }
11971        }
11972    }
11973
11974    /**
11975     * Change the visibility of the View without triggering any other changes. This is
11976     * important for transitions, where visibility changes should not adjust focus or
11977     * trigger a new layout. This is only used when the visibility has already been changed
11978     * and we need a transient value during an animation. When the animation completes,
11979     * the original visibility value is always restored.
11980     *
11981     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
11982     * @hide
11983     */
11984    public void setTransitionVisibility(@Visibility int visibility) {
11985        mViewFlags = (mViewFlags & ~View.VISIBILITY_MASK) | visibility;
11986    }
11987
11988    /**
11989     * Reset the flag indicating the accessibility state of the subtree rooted
11990     * at this view changed.
11991     */
11992    void resetSubtreeAccessibilityStateChanged() {
11993        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
11994    }
11995
11996    /**
11997     * Report an accessibility action to this view's parents for delegated processing.
11998     *
11999     * <p>Implementations of {@link #performAccessibilityAction(int, Bundle)} may internally
12000     * call this method to delegate an accessibility action to a supporting parent. If the parent
12001     * returns true from its
12002     * {@link ViewParent#onNestedPrePerformAccessibilityAction(View, int, android.os.Bundle)}
12003     * method this method will return true to signify that the action was consumed.</p>
12004     *
12005     * <p>This method is useful for implementing nested scrolling child views. If
12006     * {@link #isNestedScrollingEnabled()} returns true and the action is a scrolling action
12007     * a custom view implementation may invoke this method to allow a parent to consume the
12008     * scroll first. If this method returns true the custom view should skip its own scrolling
12009     * behavior.</p>
12010     *
12011     * @param action Accessibility action to delegate
12012     * @param arguments Optional action arguments
12013     * @return true if the action was consumed by a parent
12014     */
12015    public boolean dispatchNestedPrePerformAccessibilityAction(int action, Bundle arguments) {
12016        for (ViewParent p = getParent(); p != null; p = p.getParent()) {
12017            if (p.onNestedPrePerformAccessibilityAction(this, action, arguments)) {
12018                return true;
12019            }
12020        }
12021        return false;
12022    }
12023
12024    /**
12025     * Performs the specified accessibility action on the view. For
12026     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
12027     * <p>
12028     * If an {@link AccessibilityDelegate} has been specified via calling
12029     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
12030     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
12031     * is responsible for handling this call.
12032     * </p>
12033     *
12034     * <p>The default implementation will delegate
12035     * {@link AccessibilityNodeInfo#ACTION_SCROLL_BACKWARD} and
12036     * {@link AccessibilityNodeInfo#ACTION_SCROLL_FORWARD} to nested scrolling parents if
12037     * {@link #isNestedScrollingEnabled() nested scrolling is enabled} on this view.</p>
12038     *
12039     * @param action The action to perform.
12040     * @param arguments Optional action arguments.
12041     * @return Whether the action was performed.
12042     */
12043    public boolean performAccessibilityAction(int action, Bundle arguments) {
12044      if (mAccessibilityDelegate != null) {
12045          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
12046      } else {
12047          return performAccessibilityActionInternal(action, arguments);
12048      }
12049    }
12050
12051   /**
12052    * @see #performAccessibilityAction(int, Bundle)
12053    *
12054    * Note: Called from the default {@link AccessibilityDelegate}.
12055    *
12056    * @hide
12057    */
12058    public boolean performAccessibilityActionInternal(int action, Bundle arguments) {
12059        if (isNestedScrollingEnabled()
12060                && (action == AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD
12061                || action == AccessibilityNodeInfo.ACTION_SCROLL_FORWARD
12062                || action == R.id.accessibilityActionScrollUp
12063                || action == R.id.accessibilityActionScrollLeft
12064                || action == R.id.accessibilityActionScrollDown
12065                || action == R.id.accessibilityActionScrollRight)) {
12066            if (dispatchNestedPrePerformAccessibilityAction(action, arguments)) {
12067                return true;
12068            }
12069        }
12070
12071        switch (action) {
12072            case AccessibilityNodeInfo.ACTION_CLICK: {
12073                if (isClickable()) {
12074                    performClickInternal();
12075                    return true;
12076                }
12077            } break;
12078            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
12079                if (isLongClickable()) {
12080                    performLongClick();
12081                    return true;
12082                }
12083            } break;
12084            case AccessibilityNodeInfo.ACTION_FOCUS: {
12085                if (!hasFocus()) {
12086                    // Get out of touch mode since accessibility
12087                    // wants to move focus around.
12088                    getViewRootImpl().ensureTouchMode(false);
12089                    return requestFocus();
12090                }
12091            } break;
12092            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
12093                if (hasFocus()) {
12094                    clearFocus();
12095                    return !isFocused();
12096                }
12097            } break;
12098            case AccessibilityNodeInfo.ACTION_SELECT: {
12099                if (!isSelected()) {
12100                    setSelected(true);
12101                    return isSelected();
12102                }
12103            } break;
12104            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
12105                if (isSelected()) {
12106                    setSelected(false);
12107                    return !isSelected();
12108                }
12109            } break;
12110            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
12111                if (!isAccessibilityFocused()) {
12112                    return requestAccessibilityFocus();
12113                }
12114            } break;
12115            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
12116                if (isAccessibilityFocused()) {
12117                    clearAccessibilityFocus();
12118                    return true;
12119                }
12120            } break;
12121            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
12122                if (arguments != null) {
12123                    final int granularity = arguments.getInt(
12124                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
12125                    final boolean extendSelection = arguments.getBoolean(
12126                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
12127                    return traverseAtGranularity(granularity, true, extendSelection);
12128                }
12129            } break;
12130            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
12131                if (arguments != null) {
12132                    final int granularity = arguments.getInt(
12133                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
12134                    final boolean extendSelection = arguments.getBoolean(
12135                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
12136                    return traverseAtGranularity(granularity, false, extendSelection);
12137                }
12138            } break;
12139            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
12140                CharSequence text = getIterableTextForAccessibility();
12141                if (text == null) {
12142                    return false;
12143                }
12144                final int start = (arguments != null) ? arguments.getInt(
12145                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
12146                final int end = (arguments != null) ? arguments.getInt(
12147                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
12148                // Only cursor position can be specified (selection length == 0)
12149                if ((getAccessibilitySelectionStart() != start
12150                        || getAccessibilitySelectionEnd() != end)
12151                        && (start == end)) {
12152                    setAccessibilitySelection(start, end);
12153                    notifyViewAccessibilityStateChangedIfNeeded(
12154                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
12155                    return true;
12156                }
12157            } break;
12158            case R.id.accessibilityActionShowOnScreen: {
12159                if (mAttachInfo != null) {
12160                    final Rect r = mAttachInfo.mTmpInvalRect;
12161                    getDrawingRect(r);
12162                    return requestRectangleOnScreen(r, true);
12163                }
12164            } break;
12165            case R.id.accessibilityActionContextClick: {
12166                if (isContextClickable()) {
12167                    performContextClick();
12168                    return true;
12169                }
12170            } break;
12171            case R.id.accessibilityActionShowTooltip: {
12172                if ((mTooltipInfo != null) && (mTooltipInfo.mTooltipPopup != null)) {
12173                    // Tooltip already showing
12174                    return false;
12175                }
12176                return showLongClickTooltip(0, 0);
12177            }
12178            case R.id.accessibilityActionHideTooltip: {
12179                if ((mTooltipInfo == null) || (mTooltipInfo.mTooltipPopup == null)) {
12180                    // No tooltip showing
12181                    return false;
12182                }
12183                hideTooltip();
12184                return true;
12185            }
12186        }
12187        return false;
12188    }
12189
12190    private boolean traverseAtGranularity(int granularity, boolean forward,
12191            boolean extendSelection) {
12192        CharSequence text = getIterableTextForAccessibility();
12193        if (text == null || text.length() == 0) {
12194            return false;
12195        }
12196        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
12197        if (iterator == null) {
12198            return false;
12199        }
12200        int current = getAccessibilitySelectionEnd();
12201        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
12202            current = forward ? 0 : text.length();
12203        }
12204        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
12205        if (range == null) {
12206            return false;
12207        }
12208        final int segmentStart = range[0];
12209        final int segmentEnd = range[1];
12210        int selectionStart;
12211        int selectionEnd;
12212        if (extendSelection && isAccessibilitySelectionExtendable()) {
12213            selectionStart = getAccessibilitySelectionStart();
12214            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
12215                selectionStart = forward ? segmentStart : segmentEnd;
12216            }
12217            selectionEnd = forward ? segmentEnd : segmentStart;
12218        } else {
12219            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
12220        }
12221        setAccessibilitySelection(selectionStart, selectionEnd);
12222        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
12223                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
12224        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
12225        return true;
12226    }
12227
12228    /**
12229     * Gets the text reported for accessibility purposes.
12230     *
12231     * @return The accessibility text.
12232     *
12233     * @hide
12234     */
12235    public CharSequence getIterableTextForAccessibility() {
12236        return getContentDescription();
12237    }
12238
12239    /**
12240     * Gets whether accessibility selection can be extended.
12241     *
12242     * @return If selection is extensible.
12243     *
12244     * @hide
12245     */
12246    public boolean isAccessibilitySelectionExtendable() {
12247        return false;
12248    }
12249
12250    /**
12251     * @hide
12252     */
12253    public int getAccessibilitySelectionStart() {
12254        return mAccessibilityCursorPosition;
12255    }
12256
12257    /**
12258     * @hide
12259     */
12260    public int getAccessibilitySelectionEnd() {
12261        return getAccessibilitySelectionStart();
12262    }
12263
12264    /**
12265     * @hide
12266     */
12267    public void setAccessibilitySelection(int start, int end) {
12268        if (start ==  end && end == mAccessibilityCursorPosition) {
12269            return;
12270        }
12271        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
12272            mAccessibilityCursorPosition = start;
12273        } else {
12274            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
12275        }
12276        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
12277    }
12278
12279    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
12280            int fromIndex, int toIndex) {
12281        if (mParent == null) {
12282            return;
12283        }
12284        AccessibilityEvent event = AccessibilityEvent.obtain(
12285                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
12286        onInitializeAccessibilityEvent(event);
12287        onPopulateAccessibilityEvent(event);
12288        event.setFromIndex(fromIndex);
12289        event.setToIndex(toIndex);
12290        event.setAction(action);
12291        event.setMovementGranularity(granularity);
12292        mParent.requestSendAccessibilityEvent(this, event);
12293    }
12294
12295    /**
12296     * @hide
12297     */
12298    public TextSegmentIterator getIteratorForGranularity(int granularity) {
12299        switch (granularity) {
12300            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
12301                CharSequence text = getIterableTextForAccessibility();
12302                if (text != null && text.length() > 0) {
12303                    CharacterTextSegmentIterator iterator =
12304                        CharacterTextSegmentIterator.getInstance(
12305                                mContext.getResources().getConfiguration().locale);
12306                    iterator.initialize(text.toString());
12307                    return iterator;
12308                }
12309            } break;
12310            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
12311                CharSequence text = getIterableTextForAccessibility();
12312                if (text != null && text.length() > 0) {
12313                    WordTextSegmentIterator iterator =
12314                        WordTextSegmentIterator.getInstance(
12315                                mContext.getResources().getConfiguration().locale);
12316                    iterator.initialize(text.toString());
12317                    return iterator;
12318                }
12319            } break;
12320            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
12321                CharSequence text = getIterableTextForAccessibility();
12322                if (text != null && text.length() > 0) {
12323                    ParagraphTextSegmentIterator iterator =
12324                        ParagraphTextSegmentIterator.getInstance();
12325                    iterator.initialize(text.toString());
12326                    return iterator;
12327                }
12328            } break;
12329        }
12330        return null;
12331    }
12332
12333    /**
12334     * Tells whether the {@link View} is in the state between {@link #onStartTemporaryDetach()}
12335     * and {@link #onFinishTemporaryDetach()}.
12336     *
12337     * <p>This method always returns {@code true} when called directly or indirectly from
12338     * {@link #onStartTemporaryDetach()}. The return value when called directly or indirectly from
12339     * {@link #onFinishTemporaryDetach()}, however, depends on the OS version.
12340     * <ul>
12341     *     <li>{@code true} on {@link android.os.Build.VERSION_CODES#N API 24}</li>
12342     *     <li>{@code false} on {@link android.os.Build.VERSION_CODES#N_MR1 API 25}} and later</li>
12343     * </ul>
12344     * </p>
12345     *
12346     * @return {@code true} when the View is in the state between {@link #onStartTemporaryDetach()}
12347     * and {@link #onFinishTemporaryDetach()}.
12348     */
12349    public final boolean isTemporarilyDetached() {
12350        return (mPrivateFlags3 & PFLAG3_TEMPORARY_DETACH) != 0;
12351    }
12352
12353    /**
12354     * Dispatch {@link #onStartTemporaryDetach()} to this View and its direct children if this is
12355     * a container View.
12356     */
12357    @CallSuper
12358    public void dispatchStartTemporaryDetach() {
12359        mPrivateFlags3 |= PFLAG3_TEMPORARY_DETACH;
12360        notifyEnterOrExitForAutoFillIfNeeded(false);
12361        onStartTemporaryDetach();
12362    }
12363
12364    /**
12365     * This is called when a container is going to temporarily detach a child, with
12366     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
12367     * It will either be followed by {@link #onFinishTemporaryDetach()} or
12368     * {@link #onDetachedFromWindow()} when the container is done.
12369     */
12370    public void onStartTemporaryDetach() {
12371        removeUnsetPressCallback();
12372        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
12373    }
12374
12375    /**
12376     * Dispatch {@link #onFinishTemporaryDetach()} to this View and its direct children if this is
12377     * a container View.
12378     */
12379    @CallSuper
12380    public void dispatchFinishTemporaryDetach() {
12381        mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH;
12382        onFinishTemporaryDetach();
12383        if (hasWindowFocus() && hasFocus()) {
12384            InputMethodManager.getInstance().focusIn(this);
12385        }
12386        notifyEnterOrExitForAutoFillIfNeeded(true);
12387    }
12388
12389    /**
12390     * Called after {@link #onStartTemporaryDetach} when the container is done
12391     * changing the view.
12392     */
12393    public void onFinishTemporaryDetach() {
12394    }
12395
12396    /**
12397     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
12398     * for this view's window.  Returns null if the view is not currently attached
12399     * to the window.  Normally you will not need to use this directly, but
12400     * just use the standard high-level event callbacks like
12401     * {@link #onKeyDown(int, KeyEvent)}.
12402     */
12403    public KeyEvent.DispatcherState getKeyDispatcherState() {
12404        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
12405    }
12406
12407    /**
12408     * Dispatch a key event before it is processed by any input method
12409     * associated with the view hierarchy.  This can be used to intercept
12410     * key events in special situations before the IME consumes them; a
12411     * typical example would be handling the BACK key to update the application's
12412     * UI instead of allowing the IME to see it and close itself.
12413     *
12414     * @param event The key event to be dispatched.
12415     * @return True if the event was handled, false otherwise.
12416     */
12417    public boolean dispatchKeyEventPreIme(KeyEvent event) {
12418        return onKeyPreIme(event.getKeyCode(), event);
12419    }
12420
12421    /**
12422     * Dispatch a key event to the next view on the focus path. This path runs
12423     * from the top of the view tree down to the currently focused view. If this
12424     * view has focus, it will dispatch to itself. Otherwise it will dispatch
12425     * the next node down the focus path. This method also fires any key
12426     * listeners.
12427     *
12428     * @param event The key event to be dispatched.
12429     * @return True if the event was handled, false otherwise.
12430     */
12431    public boolean dispatchKeyEvent(KeyEvent event) {
12432        if (mInputEventConsistencyVerifier != null) {
12433            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
12434        }
12435
12436        // Give any attached key listener a first crack at the event.
12437        //noinspection SimplifiableIfStatement
12438        ListenerInfo li = mListenerInfo;
12439        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
12440                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
12441            return true;
12442        }
12443
12444        if (event.dispatch(this, mAttachInfo != null
12445                ? mAttachInfo.mKeyDispatchState : null, this)) {
12446            return true;
12447        }
12448
12449        if (mInputEventConsistencyVerifier != null) {
12450            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
12451        }
12452        return false;
12453    }
12454
12455    /**
12456     * Dispatches a key shortcut event.
12457     *
12458     * @param event The key event to be dispatched.
12459     * @return True if the event was handled by the view, false otherwise.
12460     */
12461    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
12462        return onKeyShortcut(event.getKeyCode(), event);
12463    }
12464
12465    /**
12466     * Pass the touch screen motion event down to the target view, or this
12467     * view if it is the target.
12468     *
12469     * @param event The motion event to be dispatched.
12470     * @return True if the event was handled by the view, false otherwise.
12471     */
12472    public boolean dispatchTouchEvent(MotionEvent event) {
12473        // If the event should be handled by accessibility focus first.
12474        if (event.isTargetAccessibilityFocus()) {
12475            // We don't have focus or no virtual descendant has it, do not handle the event.
12476            if (!isAccessibilityFocusedViewOrHost()) {
12477                return false;
12478            }
12479            // We have focus and got the event, then use normal event dispatch.
12480            event.setTargetAccessibilityFocus(false);
12481        }
12482
12483        boolean result = false;
12484
12485        if (mInputEventConsistencyVerifier != null) {
12486            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
12487        }
12488
12489        final int actionMasked = event.getActionMasked();
12490        if (actionMasked == MotionEvent.ACTION_DOWN) {
12491            // Defensive cleanup for new gesture
12492            stopNestedScroll();
12493        }
12494
12495        if (onFilterTouchEventForSecurity(event)) {
12496            if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
12497                result = true;
12498            }
12499            //noinspection SimplifiableIfStatement
12500            ListenerInfo li = mListenerInfo;
12501            if (li != null && li.mOnTouchListener != null
12502                    && (mViewFlags & ENABLED_MASK) == ENABLED
12503                    && li.mOnTouchListener.onTouch(this, event)) {
12504                result = true;
12505            }
12506
12507            if (!result && onTouchEvent(event)) {
12508                result = true;
12509            }
12510        }
12511
12512        if (!result && mInputEventConsistencyVerifier != null) {
12513            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
12514        }
12515
12516        // Clean up after nested scrolls if this is the end of a gesture;
12517        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
12518        // of the gesture.
12519        if (actionMasked == MotionEvent.ACTION_UP ||
12520                actionMasked == MotionEvent.ACTION_CANCEL ||
12521                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
12522            stopNestedScroll();
12523        }
12524
12525        return result;
12526    }
12527
12528    boolean isAccessibilityFocusedViewOrHost() {
12529        return isAccessibilityFocused() || (getViewRootImpl() != null && getViewRootImpl()
12530                .getAccessibilityFocusedHost() == this);
12531    }
12532
12533    /**
12534     * Filter the touch event to apply security policies.
12535     *
12536     * @param event The motion event to be filtered.
12537     * @return True if the event should be dispatched, false if the event should be dropped.
12538     *
12539     * @see #getFilterTouchesWhenObscured
12540     */
12541    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
12542        //noinspection RedundantIfStatement
12543        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
12544                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
12545            // Window is obscured, drop this touch.
12546            return false;
12547        }
12548        return true;
12549    }
12550
12551    /**
12552     * Pass a trackball motion event down to the focused view.
12553     *
12554     * @param event The motion event to be dispatched.
12555     * @return True if the event was handled by the view, false otherwise.
12556     */
12557    public boolean dispatchTrackballEvent(MotionEvent event) {
12558        if (mInputEventConsistencyVerifier != null) {
12559            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
12560        }
12561
12562        return onTrackballEvent(event);
12563    }
12564
12565    /**
12566     * Pass a captured pointer event down to the focused view.
12567     *
12568     * @param event The motion event to be dispatched.
12569     * @return True if the event was handled by the view, false otherwise.
12570     */
12571    public boolean dispatchCapturedPointerEvent(MotionEvent event) {
12572        if (!hasPointerCapture()) {
12573            return false;
12574        }
12575        //noinspection SimplifiableIfStatement
12576        ListenerInfo li = mListenerInfo;
12577        if (li != null && li.mOnCapturedPointerListener != null
12578                && li.mOnCapturedPointerListener.onCapturedPointer(this, event)) {
12579            return true;
12580        }
12581        return onCapturedPointerEvent(event);
12582    }
12583
12584    /**
12585     * Dispatch a generic motion event.
12586     * <p>
12587     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
12588     * are delivered to the view under the pointer.  All other generic motion events are
12589     * delivered to the focused view.  Hover events are handled specially and are delivered
12590     * to {@link #onHoverEvent(MotionEvent)}.
12591     * </p>
12592     *
12593     * @param event The motion event to be dispatched.
12594     * @return True if the event was handled by the view, false otherwise.
12595     */
12596    public boolean dispatchGenericMotionEvent(MotionEvent event) {
12597        if (mInputEventConsistencyVerifier != null) {
12598            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
12599        }
12600
12601        final int source = event.getSource();
12602        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
12603            final int action = event.getAction();
12604            if (action == MotionEvent.ACTION_HOVER_ENTER
12605                    || action == MotionEvent.ACTION_HOVER_MOVE
12606                    || action == MotionEvent.ACTION_HOVER_EXIT) {
12607                if (dispatchHoverEvent(event)) {
12608                    return true;
12609                }
12610            } else if (dispatchGenericPointerEvent(event)) {
12611                return true;
12612            }
12613        } else if (dispatchGenericFocusedEvent(event)) {
12614            return true;
12615        }
12616
12617        if (dispatchGenericMotionEventInternal(event)) {
12618            return true;
12619        }
12620
12621        if (mInputEventConsistencyVerifier != null) {
12622            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
12623        }
12624        return false;
12625    }
12626
12627    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
12628        //noinspection SimplifiableIfStatement
12629        ListenerInfo li = mListenerInfo;
12630        if (li != null && li.mOnGenericMotionListener != null
12631                && (mViewFlags & ENABLED_MASK) == ENABLED
12632                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
12633            return true;
12634        }
12635
12636        if (onGenericMotionEvent(event)) {
12637            return true;
12638        }
12639
12640        final int actionButton = event.getActionButton();
12641        switch (event.getActionMasked()) {
12642            case MotionEvent.ACTION_BUTTON_PRESS:
12643                if (isContextClickable() && !mInContextButtonPress && !mHasPerformedLongPress
12644                        && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY
12645                        || actionButton == MotionEvent.BUTTON_SECONDARY)) {
12646                    if (performContextClick(event.getX(), event.getY())) {
12647                        mInContextButtonPress = true;
12648                        setPressed(true, event.getX(), event.getY());
12649                        removeTapCallback();
12650                        removeLongPressCallback();
12651                        return true;
12652                    }
12653                }
12654                break;
12655
12656            case MotionEvent.ACTION_BUTTON_RELEASE:
12657                if (mInContextButtonPress && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY
12658                        || actionButton == MotionEvent.BUTTON_SECONDARY)) {
12659                    mInContextButtonPress = false;
12660                    mIgnoreNextUpEvent = true;
12661                }
12662                break;
12663        }
12664
12665        if (mInputEventConsistencyVerifier != null) {
12666            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
12667        }
12668        return false;
12669    }
12670
12671    /**
12672     * Dispatch a hover event.
12673     * <p>
12674     * Do not call this method directly.
12675     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
12676     * </p>
12677     *
12678     * @param event The motion event to be dispatched.
12679     * @return True if the event was handled by the view, false otherwise.
12680     */
12681    protected boolean dispatchHoverEvent(MotionEvent event) {
12682        ListenerInfo li = mListenerInfo;
12683        //noinspection SimplifiableIfStatement
12684        if (li != null && li.mOnHoverListener != null
12685                && (mViewFlags & ENABLED_MASK) == ENABLED
12686                && li.mOnHoverListener.onHover(this, event)) {
12687            return true;
12688        }
12689
12690        return onHoverEvent(event);
12691    }
12692
12693    /**
12694     * Returns true if the view has a child to which it has recently sent
12695     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
12696     * it does not have a hovered child, then it must be the innermost hovered view.
12697     * @hide
12698     */
12699    protected boolean hasHoveredChild() {
12700        return false;
12701    }
12702
12703    /**
12704     * Dispatch a generic motion event to the view under the first pointer.
12705     * <p>
12706     * Do not call this method directly.
12707     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
12708     * </p>
12709     *
12710     * @param event The motion event to be dispatched.
12711     * @return True if the event was handled by the view, false otherwise.
12712     */
12713    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
12714        return false;
12715    }
12716
12717    /**
12718     * Dispatch a generic motion event to the currently focused view.
12719     * <p>
12720     * Do not call this method directly.
12721     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
12722     * </p>
12723     *
12724     * @param event The motion event to be dispatched.
12725     * @return True if the event was handled by the view, false otherwise.
12726     */
12727    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
12728        return false;
12729    }
12730
12731    /**
12732     * Dispatch a pointer event.
12733     * <p>
12734     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
12735     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
12736     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
12737     * and should not be expected to handle other pointing device features.
12738     * </p>
12739     *
12740     * @param event The motion event to be dispatched.
12741     * @return True if the event was handled by the view, false otherwise.
12742     * @hide
12743     */
12744    public final boolean dispatchPointerEvent(MotionEvent event) {
12745        if (event.isTouchEvent()) {
12746            return dispatchTouchEvent(event);
12747        } else {
12748            return dispatchGenericMotionEvent(event);
12749        }
12750    }
12751
12752    /**
12753     * Called when the window containing this view gains or loses window focus.
12754     * ViewGroups should override to route to their children.
12755     *
12756     * @param hasFocus True if the window containing this view now has focus,
12757     *        false otherwise.
12758     */
12759    public void dispatchWindowFocusChanged(boolean hasFocus) {
12760        onWindowFocusChanged(hasFocus);
12761    }
12762
12763    /**
12764     * Called when the window containing this view gains or loses focus.  Note
12765     * that this is separate from view focus: to receive key events, both
12766     * your view and its window must have focus.  If a window is displayed
12767     * on top of yours that takes input focus, then your own window will lose
12768     * focus but the view focus will remain unchanged.
12769     *
12770     * @param hasWindowFocus True if the window containing this view now has
12771     *        focus, false otherwise.
12772     */
12773    public void onWindowFocusChanged(boolean hasWindowFocus) {
12774        InputMethodManager imm = InputMethodManager.peekInstance();
12775        if (!hasWindowFocus) {
12776            if (isPressed()) {
12777                setPressed(false);
12778            }
12779            mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
12780            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
12781                imm.focusOut(this);
12782            }
12783            removeLongPressCallback();
12784            removeTapCallback();
12785            onFocusLost();
12786        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
12787            imm.focusIn(this);
12788        }
12789
12790        refreshDrawableState();
12791    }
12792
12793    /**
12794     * Returns true if this view is in a window that currently has window focus.
12795     * Note that this is not the same as the view itself having focus.
12796     *
12797     * @return True if this view is in a window that currently has window focus.
12798     */
12799    public boolean hasWindowFocus() {
12800        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
12801    }
12802
12803    /**
12804     * Dispatch a view visibility change down the view hierarchy.
12805     * ViewGroups should override to route to their children.
12806     * @param changedView The view whose visibility changed. Could be 'this' or
12807     * an ancestor view.
12808     * @param visibility The new visibility of changedView: {@link #VISIBLE},
12809     * {@link #INVISIBLE} or {@link #GONE}.
12810     */
12811    protected void dispatchVisibilityChanged(@NonNull View changedView,
12812            @Visibility int visibility) {
12813        onVisibilityChanged(changedView, visibility);
12814    }
12815
12816    /**
12817     * Called when the visibility of the view or an ancestor of the view has
12818     * changed.
12819     *
12820     * @param changedView The view whose visibility changed. May be
12821     *                    {@code this} or an ancestor view.
12822     * @param visibility The new visibility, one of {@link #VISIBLE},
12823     *                   {@link #INVISIBLE} or {@link #GONE}.
12824     */
12825    protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) {
12826    }
12827
12828    /**
12829     * Dispatch a hint about whether this view is displayed. For instance, when
12830     * a View moves out of the screen, it might receives a display hint indicating
12831     * the view is not displayed. Applications should not <em>rely</em> on this hint
12832     * as there is no guarantee that they will receive one.
12833     *
12834     * @param hint A hint about whether or not this view is displayed:
12835     * {@link #VISIBLE} or {@link #INVISIBLE}.
12836     */
12837    public void dispatchDisplayHint(@Visibility int hint) {
12838        onDisplayHint(hint);
12839    }
12840
12841    /**
12842     * Gives this view a hint about whether is displayed or not. For instance, when
12843     * a View moves out of the screen, it might receives a display hint indicating
12844     * the view is not displayed. Applications should not <em>rely</em> on this hint
12845     * as there is no guarantee that they will receive one.
12846     *
12847     * @param hint A hint about whether or not this view is displayed:
12848     * {@link #VISIBLE} or {@link #INVISIBLE}.
12849     */
12850    protected void onDisplayHint(@Visibility int hint) {
12851    }
12852
12853    /**
12854     * Dispatch a window visibility change down the view hierarchy.
12855     * ViewGroups should override to route to their children.
12856     *
12857     * @param visibility The new visibility of the window.
12858     *
12859     * @see #onWindowVisibilityChanged(int)
12860     */
12861    public void dispatchWindowVisibilityChanged(@Visibility int visibility) {
12862        onWindowVisibilityChanged(visibility);
12863    }
12864
12865    /**
12866     * Called when the window containing has change its visibility
12867     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
12868     * that this tells you whether or not your window is being made visible
12869     * to the window manager; this does <em>not</em> tell you whether or not
12870     * your window is obscured by other windows on the screen, even if it
12871     * is itself visible.
12872     *
12873     * @param visibility The new visibility of the window.
12874     */
12875    protected void onWindowVisibilityChanged(@Visibility int visibility) {
12876        if (visibility == VISIBLE) {
12877            initialAwakenScrollBars();
12878        }
12879    }
12880
12881    /**
12882     * Internal dispatching method for {@link #onVisibilityAggregated}. Overridden by
12883     * ViewGroup. Intended to only be called when {@link #isAttachedToWindow()},
12884     * {@link #getWindowVisibility()} is {@link #VISIBLE} and this view's parent {@link #isShown()}.
12885     *
12886     * @param isVisible true if this view's visibility to the user is uninterrupted by its
12887     *                  ancestors or by window visibility
12888     * @return true if this view is visible to the user, not counting clipping or overlapping
12889     */
12890    boolean dispatchVisibilityAggregated(boolean isVisible) {
12891        final boolean thisVisible = getVisibility() == VISIBLE;
12892        // If we're not visible but something is telling us we are, ignore it.
12893        if (thisVisible || !isVisible) {
12894            onVisibilityAggregated(isVisible);
12895        }
12896        return thisVisible && isVisible;
12897    }
12898
12899    /**
12900     * Called when the user-visibility of this View is potentially affected by a change
12901     * to this view itself, an ancestor view or the window this view is attached to.
12902     *
12903     * @param isVisible true if this view and all of its ancestors are {@link #VISIBLE}
12904     *                  and this view's window is also visible
12905     */
12906    @CallSuper
12907    public void onVisibilityAggregated(boolean isVisible) {
12908        // Update our internal visibility tracking so we can detect changes
12909        boolean oldVisible = (mPrivateFlags3 & PFLAG3_AGGREGATED_VISIBLE) != 0;
12910        mPrivateFlags3 = isVisible ? (mPrivateFlags3 | PFLAG3_AGGREGATED_VISIBLE)
12911                : (mPrivateFlags3 & ~PFLAG3_AGGREGATED_VISIBLE);
12912        if (isVisible && mAttachInfo != null) {
12913            initialAwakenScrollBars();
12914        }
12915
12916        final Drawable dr = mBackground;
12917        if (dr != null && isVisible != dr.isVisible()) {
12918            dr.setVisible(isVisible, false);
12919        }
12920        final Drawable hl = mDefaultFocusHighlight;
12921        if (hl != null && isVisible != hl.isVisible()) {
12922            hl.setVisible(isVisible, false);
12923        }
12924        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
12925        if (fg != null && isVisible != fg.isVisible()) {
12926            fg.setVisible(isVisible, false);
12927        }
12928
12929        if (isAutofillable()) {
12930            AutofillManager afm = getAutofillManager();
12931
12932            if (afm != null && getAutofillViewId() > LAST_APP_AUTOFILL_ID) {
12933                if (mVisibilityChangeForAutofillHandler != null) {
12934                    mVisibilityChangeForAutofillHandler.removeMessages(0);
12935                }
12936
12937                // If the view is in the background but still part of the hierarchy this is called
12938                // with isVisible=false. Hence visibility==false requires further checks
12939                if (isVisible) {
12940                    afm.notifyViewVisibilityChanged(this, true);
12941                } else {
12942                    if (mVisibilityChangeForAutofillHandler == null) {
12943                        mVisibilityChangeForAutofillHandler =
12944                                new VisibilityChangeForAutofillHandler(afm, this);
12945                    }
12946                    // Let current operation (e.g. removal of the view from the hierarchy)
12947                    // finish before checking state
12948                    mVisibilityChangeForAutofillHandler.obtainMessage(0, this).sendToTarget();
12949                }
12950            }
12951        }
12952        if (!TextUtils.isEmpty(getAccessibilityPaneTitle())) {
12953            if (isVisible != oldVisible) {
12954                notifyViewAccessibilityStateChangedIfNeeded(isVisible
12955                        ? AccessibilityEvent.CONTENT_CHANGE_TYPE_PANE_APPEARED
12956                        : AccessibilityEvent.CONTENT_CHANGE_TYPE_PANE_DISAPPEARED);
12957            }
12958        }
12959    }
12960
12961    /**
12962     * Returns the current visibility of the window this view is attached to
12963     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
12964     *
12965     * @return Returns the current visibility of the view's window.
12966     */
12967    @Visibility
12968    public int getWindowVisibility() {
12969        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
12970    }
12971
12972    /**
12973     * Retrieve the overall visible display size in which the window this view is
12974     * attached to has been positioned in.  This takes into account screen
12975     * decorations above the window, for both cases where the window itself
12976     * is being position inside of them or the window is being placed under
12977     * then and covered insets are used for the window to position its content
12978     * inside.  In effect, this tells you the available area where content can
12979     * be placed and remain visible to users.
12980     *
12981     * <p>This function requires an IPC back to the window manager to retrieve
12982     * the requested information, so should not be used in performance critical
12983     * code like drawing.
12984     *
12985     * @param outRect Filled in with the visible display frame.  If the view
12986     * is not attached to a window, this is simply the raw display size.
12987     */
12988    public void getWindowVisibleDisplayFrame(Rect outRect) {
12989        if (mAttachInfo != null) {
12990            try {
12991                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
12992            } catch (RemoteException e) {
12993                return;
12994            }
12995            // XXX This is really broken, and probably all needs to be done
12996            // in the window manager, and we need to know more about whether
12997            // we want the area behind or in front of the IME.
12998            final Rect insets = mAttachInfo.mVisibleInsets;
12999            outRect.left += insets.left;
13000            outRect.top += insets.top;
13001            outRect.right -= insets.right;
13002            outRect.bottom -= insets.bottom;
13003            return;
13004        }
13005        // The view is not attached to a display so we don't have a context.
13006        // Make a best guess about the display size.
13007        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
13008        d.getRectSize(outRect);
13009    }
13010
13011    /**
13012     * Like {@link #getWindowVisibleDisplayFrame}, but returns the "full" display frame this window
13013     * is currently in without any insets.
13014     *
13015     * @hide
13016     */
13017    public void getWindowDisplayFrame(Rect outRect) {
13018        if (mAttachInfo != null) {
13019            try {
13020                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
13021            } catch (RemoteException e) {
13022                return;
13023            }
13024            return;
13025        }
13026        // The view is not attached to a display so we don't have a context.
13027        // Make a best guess about the display size.
13028        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
13029        d.getRectSize(outRect);
13030    }
13031
13032    /**
13033     * Dispatch a notification about a resource configuration change down
13034     * the view hierarchy.
13035     * ViewGroups should override to route to their children.
13036     *
13037     * @param newConfig The new resource configuration.
13038     *
13039     * @see #onConfigurationChanged(android.content.res.Configuration)
13040     */
13041    public void dispatchConfigurationChanged(Configuration newConfig) {
13042        onConfigurationChanged(newConfig);
13043    }
13044
13045    /**
13046     * Called when the current configuration of the resources being used
13047     * by the application have changed.  You can use this to decide when
13048     * to reload resources that can changed based on orientation and other
13049     * configuration characteristics.  You only need to use this if you are
13050     * not relying on the normal {@link android.app.Activity} mechanism of
13051     * recreating the activity instance upon a configuration change.
13052     *
13053     * @param newConfig The new resource configuration.
13054     */
13055    protected void onConfigurationChanged(Configuration newConfig) {
13056    }
13057
13058    /**
13059     * Private function to aggregate all per-view attributes in to the view
13060     * root.
13061     */
13062    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
13063        performCollectViewAttributes(attachInfo, visibility);
13064    }
13065
13066    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
13067        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
13068            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
13069                attachInfo.mKeepScreenOn = true;
13070            }
13071            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
13072            ListenerInfo li = mListenerInfo;
13073            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
13074                attachInfo.mHasSystemUiListeners = true;
13075            }
13076        }
13077    }
13078
13079    void needGlobalAttributesUpdate(boolean force) {
13080        final AttachInfo ai = mAttachInfo;
13081        if (ai != null && !ai.mRecomputeGlobalAttributes) {
13082            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
13083                    || ai.mHasSystemUiListeners) {
13084                ai.mRecomputeGlobalAttributes = true;
13085            }
13086        }
13087    }
13088
13089    /**
13090     * Returns whether the device is currently in touch mode.  Touch mode is entered
13091     * once the user begins interacting with the device by touch, and affects various
13092     * things like whether focus is always visible to the user.
13093     *
13094     * @return Whether the device is in touch mode.
13095     */
13096    @ViewDebug.ExportedProperty
13097    public boolean isInTouchMode() {
13098        if (mAttachInfo != null) {
13099            return mAttachInfo.mInTouchMode;
13100        } else {
13101            return ViewRootImpl.isInTouchMode();
13102        }
13103    }
13104
13105    /**
13106     * Returns the context the view is running in, through which it can
13107     * access the current theme, resources, etc.
13108     *
13109     * @return The view's Context.
13110     */
13111    @ViewDebug.CapturedViewProperty
13112    public final Context getContext() {
13113        return mContext;
13114    }
13115
13116    /**
13117     * Handle a key event before it is processed by any input method
13118     * associated with the view hierarchy.  This can be used to intercept
13119     * key events in special situations before the IME consumes them; a
13120     * typical example would be handling the BACK key to update the application's
13121     * UI instead of allowing the IME to see it and close itself.
13122     *
13123     * @param keyCode The value in event.getKeyCode().
13124     * @param event Description of the key event.
13125     * @return If you handled the event, return true. If you want to allow the
13126     *         event to be handled by the next receiver, return false.
13127     */
13128    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
13129        return false;
13130    }
13131
13132    /**
13133     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
13134     * KeyEvent.Callback.onKeyDown()}: perform press of the view
13135     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
13136     * is released, if the view is enabled and clickable.
13137     * <p>
13138     * Key presses in software keyboards will generally NOT trigger this
13139     * listener, although some may elect to do so in some situations. Do not
13140     * rely on this to catch software key presses.
13141     *
13142     * @param keyCode a key code that represents the button pressed, from
13143     *                {@link android.view.KeyEvent}
13144     * @param event the KeyEvent object that defines the button action
13145     */
13146    public boolean onKeyDown(int keyCode, KeyEvent event) {
13147        if (KeyEvent.isConfirmKey(keyCode)) {
13148            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
13149                return true;
13150            }
13151
13152            if (event.getRepeatCount() == 0) {
13153                // Long clickable items don't necessarily have to be clickable.
13154                final boolean clickable = (mViewFlags & CLICKABLE) == CLICKABLE
13155                        || (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
13156                if (clickable || (mViewFlags & TOOLTIP) == TOOLTIP) {
13157                    // For the purposes of menu anchoring and drawable hotspots,
13158                    // key events are considered to be at the center of the view.
13159                    final float x = getWidth() / 2f;
13160                    final float y = getHeight() / 2f;
13161                    if (clickable) {
13162                        setPressed(true, x, y);
13163                    }
13164                    checkForLongClick(0, x, y);
13165                    return true;
13166                }
13167            }
13168        }
13169
13170        return false;
13171    }
13172
13173    /**
13174     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
13175     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
13176     * the event).
13177     * <p>Key presses in software keyboards will generally NOT trigger this listener,
13178     * although some may elect to do so in some situations. Do not rely on this to
13179     * catch software key presses.
13180     */
13181    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
13182        return false;
13183    }
13184
13185    /**
13186     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
13187     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
13188     * when {@link KeyEvent#KEYCODE_DPAD_CENTER}, {@link KeyEvent#KEYCODE_ENTER}
13189     * or {@link KeyEvent#KEYCODE_SPACE} is released.
13190     * <p>Key presses in software keyboards will generally NOT trigger this listener,
13191     * although some may elect to do so in some situations. Do not rely on this to
13192     * catch software key presses.
13193     *
13194     * @param keyCode A key code that represents the button pressed, from
13195     *                {@link android.view.KeyEvent}.
13196     * @param event   The KeyEvent object that defines the button action.
13197     */
13198    public boolean onKeyUp(int keyCode, KeyEvent event) {
13199        if (KeyEvent.isConfirmKey(keyCode)) {
13200            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
13201                return true;
13202            }
13203            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
13204                setPressed(false);
13205
13206                if (!mHasPerformedLongPress) {
13207                    // This is a tap, so remove the longpress check
13208                    removeLongPressCallback();
13209                    if (!event.isCanceled()) {
13210                        return performClickInternal();
13211                    }
13212                }
13213            }
13214        }
13215        return false;
13216    }
13217
13218    /**
13219     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
13220     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
13221     * the event).
13222     * <p>Key presses in software keyboards will generally NOT trigger this listener,
13223     * although some may elect to do so in some situations. Do not rely on this to
13224     * catch software key presses.
13225     *
13226     * @param keyCode     A key code that represents the button pressed, from
13227     *                    {@link android.view.KeyEvent}.
13228     * @param repeatCount The number of times the action was made.
13229     * @param event       The KeyEvent object that defines the button action.
13230     */
13231    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
13232        return false;
13233    }
13234
13235    /**
13236     * Called on the focused view when a key shortcut event is not handled.
13237     * Override this method to implement local key shortcuts for the View.
13238     * Key shortcuts can also be implemented by setting the
13239     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
13240     *
13241     * @param keyCode The value in event.getKeyCode().
13242     * @param event Description of the key event.
13243     * @return If you handled the event, return true. If you want to allow the
13244     *         event to be handled by the next receiver, return false.
13245     */
13246    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
13247        return false;
13248    }
13249
13250    /**
13251     * Check whether the called view is a text editor, in which case it
13252     * would make sense to automatically display a soft input window for
13253     * it.  Subclasses should override this if they implement
13254     * {@link #onCreateInputConnection(EditorInfo)} to return true if
13255     * a call on that method would return a non-null InputConnection, and
13256     * they are really a first-class editor that the user would normally
13257     * start typing on when the go into a window containing your view.
13258     *
13259     * <p>The default implementation always returns false.  This does
13260     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
13261     * will not be called or the user can not otherwise perform edits on your
13262     * view; it is just a hint to the system that this is not the primary
13263     * purpose of this view.
13264     *
13265     * @return Returns true if this view is a text editor, else false.
13266     */
13267    public boolean onCheckIsTextEditor() {
13268        return false;
13269    }
13270
13271    /**
13272     * Create a new InputConnection for an InputMethod to interact
13273     * with the view.  The default implementation returns null, since it doesn't
13274     * support input methods.  You can override this to implement such support.
13275     * This is only needed for views that take focus and text input.
13276     *
13277     * <p>When implementing this, you probably also want to implement
13278     * {@link #onCheckIsTextEditor()} to indicate you will return a
13279     * non-null InputConnection.</p>
13280     *
13281     * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo}
13282     * object correctly and in its entirety, so that the connected IME can rely
13283     * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart}
13284     * and  {@link android.view.inputmethod.EditorInfo#initialSelEnd} members
13285     * must be filled in with the correct cursor position for IMEs to work correctly
13286     * with your application.</p>
13287     *
13288     * @param outAttrs Fill in with attribute information about the connection.
13289     */
13290    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
13291        return null;
13292    }
13293
13294    /**
13295     * Called by the {@link android.view.inputmethod.InputMethodManager}
13296     * when a view who is not the current
13297     * input connection target is trying to make a call on the manager.  The
13298     * default implementation returns false; you can override this to return
13299     * true for certain views if you are performing InputConnection proxying
13300     * to them.
13301     * @param view The View that is making the InputMethodManager call.
13302     * @return Return true to allow the call, false to reject.
13303     */
13304    public boolean checkInputConnectionProxy(View view) {
13305        return false;
13306    }
13307
13308    /**
13309     * Show the context menu for this view. It is not safe to hold on to the
13310     * menu after returning from this method.
13311     *
13312     * You should normally not overload this method. Overload
13313     * {@link #onCreateContextMenu(ContextMenu)} or define an
13314     * {@link OnCreateContextMenuListener} to add items to the context menu.
13315     *
13316     * @param menu The context menu to populate
13317     */
13318    public void createContextMenu(ContextMenu menu) {
13319        ContextMenuInfo menuInfo = getContextMenuInfo();
13320
13321        // Sets the current menu info so all items added to menu will have
13322        // my extra info set.
13323        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
13324
13325        onCreateContextMenu(menu);
13326        ListenerInfo li = mListenerInfo;
13327        if (li != null && li.mOnCreateContextMenuListener != null) {
13328            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
13329        }
13330
13331        // Clear the extra information so subsequent items that aren't mine don't
13332        // have my extra info.
13333        ((MenuBuilder)menu).setCurrentMenuInfo(null);
13334
13335        if (mParent != null) {
13336            mParent.createContextMenu(menu);
13337        }
13338    }
13339
13340    /**
13341     * Views should implement this if they have extra information to associate
13342     * with the context menu. The return result is supplied as a parameter to
13343     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
13344     * callback.
13345     *
13346     * @return Extra information about the item for which the context menu
13347     *         should be shown. This information will vary across different
13348     *         subclasses of View.
13349     */
13350    protected ContextMenuInfo getContextMenuInfo() {
13351        return null;
13352    }
13353
13354    /**
13355     * Views should implement this if the view itself is going to add items to
13356     * the context menu.
13357     *
13358     * @param menu the context menu to populate
13359     */
13360    protected void onCreateContextMenu(ContextMenu menu) {
13361    }
13362
13363    /**
13364     * Implement this method to handle trackball motion events.  The
13365     * <em>relative</em> movement of the trackball since the last event
13366     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
13367     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
13368     * that a movement of 1 corresponds to the user pressing one DPAD key (so
13369     * they will often be fractional values, representing the more fine-grained
13370     * movement information available from a trackball).
13371     *
13372     * @param event The motion event.
13373     * @return True if the event was handled, false otherwise.
13374     */
13375    public boolean onTrackballEvent(MotionEvent event) {
13376        return false;
13377    }
13378
13379    /**
13380     * Implement this method to handle generic motion events.
13381     * <p>
13382     * Generic motion events describe joystick movements, mouse hovers, track pad
13383     * touches, scroll wheel movements and other input events.  The
13384     * {@link MotionEvent#getSource() source} of the motion event specifies
13385     * the class of input that was received.  Implementations of this method
13386     * must examine the bits in the source before processing the event.
13387     * The following code example shows how this is done.
13388     * </p><p>
13389     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
13390     * are delivered to the view under the pointer.  All other generic motion events are
13391     * delivered to the focused view.
13392     * </p>
13393     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
13394     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
13395     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
13396     *             // process the joystick movement...
13397     *             return true;
13398     *         }
13399     *     }
13400     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
13401     *         switch (event.getAction()) {
13402     *             case MotionEvent.ACTION_HOVER_MOVE:
13403     *                 // process the mouse hover movement...
13404     *                 return true;
13405     *             case MotionEvent.ACTION_SCROLL:
13406     *                 // process the scroll wheel movement...
13407     *                 return true;
13408     *         }
13409     *     }
13410     *     return super.onGenericMotionEvent(event);
13411     * }</pre>
13412     *
13413     * @param event The generic motion event being processed.
13414     * @return True if the event was handled, false otherwise.
13415     */
13416    public boolean onGenericMotionEvent(MotionEvent event) {
13417        return false;
13418    }
13419
13420    /**
13421     * Implement this method to handle hover events.
13422     * <p>
13423     * This method is called whenever a pointer is hovering into, over, or out of the
13424     * bounds of a view and the view is not currently being touched.
13425     * Hover events are represented as pointer events with action
13426     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
13427     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
13428     * </p>
13429     * <ul>
13430     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
13431     * when the pointer enters the bounds of the view.</li>
13432     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
13433     * when the pointer has already entered the bounds of the view and has moved.</li>
13434     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
13435     * when the pointer has exited the bounds of the view or when the pointer is
13436     * about to go down due to a button click, tap, or similar user action that
13437     * causes the view to be touched.</li>
13438     * </ul>
13439     * <p>
13440     * The view should implement this method to return true to indicate that it is
13441     * handling the hover event, such as by changing its drawable state.
13442     * </p><p>
13443     * The default implementation calls {@link #setHovered} to update the hovered state
13444     * of the view when a hover enter or hover exit event is received, if the view
13445     * is enabled and is clickable.  The default implementation also sends hover
13446     * accessibility events.
13447     * </p>
13448     *
13449     * @param event The motion event that describes the hover.
13450     * @return True if the view handled the hover event.
13451     *
13452     * @see #isHovered
13453     * @see #setHovered
13454     * @see #onHoverChanged
13455     */
13456    public boolean onHoverEvent(MotionEvent event) {
13457        // The root view may receive hover (or touch) events that are outside the bounds of
13458        // the window.  This code ensures that we only send accessibility events for
13459        // hovers that are actually within the bounds of the root view.
13460        final int action = event.getActionMasked();
13461        if (!mSendingHoverAccessibilityEvents) {
13462            if ((action == MotionEvent.ACTION_HOVER_ENTER
13463                    || action == MotionEvent.ACTION_HOVER_MOVE)
13464                    && !hasHoveredChild()
13465                    && pointInView(event.getX(), event.getY())) {
13466                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
13467                mSendingHoverAccessibilityEvents = true;
13468            }
13469        } else {
13470            if (action == MotionEvent.ACTION_HOVER_EXIT
13471                    || (action == MotionEvent.ACTION_MOVE
13472                            && !pointInView(event.getX(), event.getY()))) {
13473                mSendingHoverAccessibilityEvents = false;
13474                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
13475            }
13476        }
13477
13478        if ((action == MotionEvent.ACTION_HOVER_ENTER || action == MotionEvent.ACTION_HOVER_MOVE)
13479                && event.isFromSource(InputDevice.SOURCE_MOUSE)
13480                && isOnScrollbar(event.getX(), event.getY())) {
13481            awakenScrollBars();
13482        }
13483
13484        // If we consider ourself hoverable, or if we we're already hovered,
13485        // handle changing state in response to ENTER and EXIT events.
13486        if (isHoverable() || isHovered()) {
13487            switch (action) {
13488                case MotionEvent.ACTION_HOVER_ENTER:
13489                    setHovered(true);
13490                    break;
13491                case MotionEvent.ACTION_HOVER_EXIT:
13492                    setHovered(false);
13493                    break;
13494            }
13495
13496            // Dispatch the event to onGenericMotionEvent before returning true.
13497            // This is to provide compatibility with existing applications that
13498            // handled HOVER_MOVE events in onGenericMotionEvent and that would
13499            // break because of the new default handling for hoverable views
13500            // in onHoverEvent.
13501            // Note that onGenericMotionEvent will be called by default when
13502            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
13503            dispatchGenericMotionEventInternal(event);
13504            // The event was already handled by calling setHovered(), so always
13505            // return true.
13506            return true;
13507        }
13508
13509        return false;
13510    }
13511
13512    /**
13513     * Returns true if the view should handle {@link #onHoverEvent}
13514     * by calling {@link #setHovered} to change its hovered state.
13515     *
13516     * @return True if the view is hoverable.
13517     */
13518    private boolean isHoverable() {
13519        final int viewFlags = mViewFlags;
13520        if ((viewFlags & ENABLED_MASK) == DISABLED) {
13521            return false;
13522        }
13523
13524        return (viewFlags & CLICKABLE) == CLICKABLE
13525                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE
13526                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
13527    }
13528
13529    /**
13530     * Returns true if the view is currently hovered.
13531     *
13532     * @return True if the view is currently hovered.
13533     *
13534     * @see #setHovered
13535     * @see #onHoverChanged
13536     */
13537    @ViewDebug.ExportedProperty
13538    public boolean isHovered() {
13539        return (mPrivateFlags & PFLAG_HOVERED) != 0;
13540    }
13541
13542    /**
13543     * Sets whether the view is currently hovered.
13544     * <p>
13545     * Calling this method also changes the drawable state of the view.  This
13546     * enables the view to react to hover by using different drawable resources
13547     * to change its appearance.
13548     * </p><p>
13549     * The {@link #onHoverChanged} method is called when the hovered state changes.
13550     * </p>
13551     *
13552     * @param hovered True if the view is hovered.
13553     *
13554     * @see #isHovered
13555     * @see #onHoverChanged
13556     */
13557    public void setHovered(boolean hovered) {
13558        if (hovered) {
13559            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
13560                mPrivateFlags |= PFLAG_HOVERED;
13561                refreshDrawableState();
13562                onHoverChanged(true);
13563            }
13564        } else {
13565            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
13566                mPrivateFlags &= ~PFLAG_HOVERED;
13567                refreshDrawableState();
13568                onHoverChanged(false);
13569            }
13570        }
13571    }
13572
13573    /**
13574     * Implement this method to handle hover state changes.
13575     * <p>
13576     * This method is called whenever the hover state changes as a result of a
13577     * call to {@link #setHovered}.
13578     * </p>
13579     *
13580     * @param hovered The current hover state, as returned by {@link #isHovered}.
13581     *
13582     * @see #isHovered
13583     * @see #setHovered
13584     */
13585    public void onHoverChanged(boolean hovered) {
13586    }
13587
13588    /**
13589     * Handles scroll bar dragging by mouse input.
13590     *
13591     * @hide
13592     * @param event The motion event.
13593     *
13594     * @return true if the event was handled as a scroll bar dragging, false otherwise.
13595     */
13596    protected boolean handleScrollBarDragging(MotionEvent event) {
13597        if (mScrollCache == null) {
13598            return false;
13599        }
13600        final float x = event.getX();
13601        final float y = event.getY();
13602        final int action = event.getAction();
13603        if ((mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING
13604                && action != MotionEvent.ACTION_DOWN)
13605                    || !event.isFromSource(InputDevice.SOURCE_MOUSE)
13606                    || !event.isButtonPressed(MotionEvent.BUTTON_PRIMARY)) {
13607            mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING;
13608            return false;
13609        }
13610
13611        switch (action) {
13612            case MotionEvent.ACTION_MOVE:
13613                if (mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING) {
13614                    return false;
13615                }
13616                if (mScrollCache.mScrollBarDraggingState
13617                        == ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR) {
13618                    final Rect bounds = mScrollCache.mScrollBarBounds;
13619                    getVerticalScrollBarBounds(bounds, null);
13620                    final int range = computeVerticalScrollRange();
13621                    final int offset = computeVerticalScrollOffset();
13622                    final int extent = computeVerticalScrollExtent();
13623
13624                    final int thumbLength = ScrollBarUtils.getThumbLength(
13625                            bounds.height(), bounds.width(), extent, range);
13626                    final int thumbOffset = ScrollBarUtils.getThumbOffset(
13627                            bounds.height(), thumbLength, extent, range, offset);
13628
13629                    final float diff = y - mScrollCache.mScrollBarDraggingPos;
13630                    final float maxThumbOffset = bounds.height() - thumbLength;
13631                    final float newThumbOffset =
13632                            Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset);
13633                    final int height = getHeight();
13634                    if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0
13635                            && height > 0 && extent > 0) {
13636                        final int newY = Math.round((range - extent)
13637                                / ((float)extent / height) * (newThumbOffset / maxThumbOffset));
13638                        if (newY != getScrollY()) {
13639                            mScrollCache.mScrollBarDraggingPos = y;
13640                            setScrollY(newY);
13641                        }
13642                    }
13643                    return true;
13644                }
13645                if (mScrollCache.mScrollBarDraggingState
13646                        == ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR) {
13647                    final Rect bounds = mScrollCache.mScrollBarBounds;
13648                    getHorizontalScrollBarBounds(bounds, null);
13649                    final int range = computeHorizontalScrollRange();
13650                    final int offset = computeHorizontalScrollOffset();
13651                    final int extent = computeHorizontalScrollExtent();
13652
13653                    final int thumbLength = ScrollBarUtils.getThumbLength(
13654                            bounds.width(), bounds.height(), extent, range);
13655                    final int thumbOffset = ScrollBarUtils.getThumbOffset(
13656                            bounds.width(), thumbLength, extent, range, offset);
13657
13658                    final float diff = x - mScrollCache.mScrollBarDraggingPos;
13659                    final float maxThumbOffset = bounds.width() - thumbLength;
13660                    final float newThumbOffset =
13661                            Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset);
13662                    final int width = getWidth();
13663                    if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0
13664                            && width > 0 && extent > 0) {
13665                        final int newX = Math.round((range - extent)
13666                                / ((float)extent / width) * (newThumbOffset / maxThumbOffset));
13667                        if (newX != getScrollX()) {
13668                            mScrollCache.mScrollBarDraggingPos = x;
13669                            setScrollX(newX);
13670                        }
13671                    }
13672                    return true;
13673                }
13674            case MotionEvent.ACTION_DOWN:
13675                if (mScrollCache.state == ScrollabilityCache.OFF) {
13676                    return false;
13677                }
13678                if (isOnVerticalScrollbarThumb(x, y)) {
13679                    mScrollCache.mScrollBarDraggingState =
13680                            ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR;
13681                    mScrollCache.mScrollBarDraggingPos = y;
13682                    return true;
13683                }
13684                if (isOnHorizontalScrollbarThumb(x, y)) {
13685                    mScrollCache.mScrollBarDraggingState =
13686                            ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR;
13687                    mScrollCache.mScrollBarDraggingPos = x;
13688                    return true;
13689                }
13690        }
13691        mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING;
13692        return false;
13693    }
13694
13695    /**
13696     * Implement this method to handle touch screen motion events.
13697     * <p>
13698     * If this method is used to detect click actions, it is recommended that
13699     * the actions be performed by implementing and calling
13700     * {@link #performClick()}. This will ensure consistent system behavior,
13701     * including:
13702     * <ul>
13703     * <li>obeying click sound preferences
13704     * <li>dispatching OnClickListener calls
13705     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
13706     * accessibility features are enabled
13707     * </ul>
13708     *
13709     * @param event The motion event.
13710     * @return True if the event was handled, false otherwise.
13711     */
13712    public boolean onTouchEvent(MotionEvent event) {
13713        final float x = event.getX();
13714        final float y = event.getY();
13715        final int viewFlags = mViewFlags;
13716        final int action = event.getAction();
13717
13718        final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE
13719                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
13720                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
13721
13722        if ((viewFlags & ENABLED_MASK) == DISABLED) {
13723            if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
13724                setPressed(false);
13725            }
13726            mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
13727            // A disabled view that is clickable still consumes the touch
13728            // events, it just doesn't respond to them.
13729            return clickable;
13730        }
13731        if (mTouchDelegate != null) {
13732            if (mTouchDelegate.onTouchEvent(event)) {
13733                return true;
13734            }
13735        }
13736
13737        if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
13738            switch (action) {
13739                case MotionEvent.ACTION_UP:
13740                    mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
13741                    if ((viewFlags & TOOLTIP) == TOOLTIP) {
13742                        handleTooltipUp();
13743                    }
13744                    if (!clickable) {
13745                        removeTapCallback();
13746                        removeLongPressCallback();
13747                        mInContextButtonPress = false;
13748                        mHasPerformedLongPress = false;
13749                        mIgnoreNextUpEvent = false;
13750                        break;
13751                    }
13752                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
13753                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
13754                        // take focus if we don't have it already and we should in
13755                        // touch mode.
13756                        boolean focusTaken = false;
13757                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
13758                            focusTaken = requestFocus();
13759                        }
13760
13761                        if (prepressed) {
13762                            // The button is being released before we actually
13763                            // showed it as pressed.  Make it show the pressed
13764                            // state now (before scheduling the click) to ensure
13765                            // the user sees it.
13766                            setPressed(true, x, y);
13767                        }
13768
13769                        if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
13770                            // This is a tap, so remove the longpress check
13771                            removeLongPressCallback();
13772
13773                            // Only perform take click actions if we were in the pressed state
13774                            if (!focusTaken) {
13775                                // Use a Runnable and post this rather than calling
13776                                // performClick directly. This lets other visual state
13777                                // of the view update before click actions start.
13778                                if (mPerformClick == null) {
13779                                    mPerformClick = new PerformClick();
13780                                }
13781                                if (!post(mPerformClick)) {
13782                                    performClickInternal();
13783                                }
13784                            }
13785                        }
13786
13787                        if (mUnsetPressedState == null) {
13788                            mUnsetPressedState = new UnsetPressedState();
13789                        }
13790
13791                        if (prepressed) {
13792                            postDelayed(mUnsetPressedState,
13793                                    ViewConfiguration.getPressedStateDuration());
13794                        } else if (!post(mUnsetPressedState)) {
13795                            // If the post failed, unpress right now
13796                            mUnsetPressedState.run();
13797                        }
13798
13799                        removeTapCallback();
13800                    }
13801                    mIgnoreNextUpEvent = false;
13802                    break;
13803
13804                case MotionEvent.ACTION_DOWN:
13805                    if (event.getSource() == InputDevice.SOURCE_TOUCHSCREEN) {
13806                        mPrivateFlags3 |= PFLAG3_FINGER_DOWN;
13807                    }
13808                    mHasPerformedLongPress = false;
13809
13810                    if (!clickable) {
13811                        checkForLongClick(0, x, y);
13812                        break;
13813                    }
13814
13815                    if (performButtonActionOnTouchDown(event)) {
13816                        break;
13817                    }
13818
13819                    // Walk up the hierarchy to determine if we're inside a scrolling container.
13820                    boolean isInScrollingContainer = isInScrollingContainer();
13821
13822                    // For views inside a scrolling container, delay the pressed feedback for
13823                    // a short period in case this is a scroll.
13824                    if (isInScrollingContainer) {
13825                        mPrivateFlags |= PFLAG_PREPRESSED;
13826                        if (mPendingCheckForTap == null) {
13827                            mPendingCheckForTap = new CheckForTap();
13828                        }
13829                        mPendingCheckForTap.x = event.getX();
13830                        mPendingCheckForTap.y = event.getY();
13831                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
13832                    } else {
13833                        // Not inside a scrolling container, so show the feedback right away
13834                        setPressed(true, x, y);
13835                        checkForLongClick(0, x, y);
13836                    }
13837                    break;
13838
13839                case MotionEvent.ACTION_CANCEL:
13840                    if (clickable) {
13841                        setPressed(false);
13842                    }
13843                    removeTapCallback();
13844                    removeLongPressCallback();
13845                    mInContextButtonPress = false;
13846                    mHasPerformedLongPress = false;
13847                    mIgnoreNextUpEvent = false;
13848                    mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
13849                    break;
13850
13851                case MotionEvent.ACTION_MOVE:
13852                    if (clickable) {
13853                        drawableHotspotChanged(x, y);
13854                    }
13855
13856                    // Be lenient about moving outside of buttons
13857                    if (!pointInView(x, y, mTouchSlop)) {
13858                        // Outside button
13859                        // Remove any future long press/tap checks
13860                        removeTapCallback();
13861                        removeLongPressCallback();
13862                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
13863                            setPressed(false);
13864                        }
13865                        mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
13866                    }
13867                    break;
13868            }
13869
13870            return true;
13871        }
13872
13873        return false;
13874    }
13875
13876    /**
13877     * @hide
13878     */
13879    public boolean isInScrollingContainer() {
13880        ViewParent p = getParent();
13881        while (p != null && p instanceof ViewGroup) {
13882            if (((ViewGroup) p).shouldDelayChildPressedState()) {
13883                return true;
13884            }
13885            p = p.getParent();
13886        }
13887        return false;
13888    }
13889
13890    /**
13891     * Remove the longpress detection timer.
13892     */
13893    private void removeLongPressCallback() {
13894        if (mPendingCheckForLongPress != null) {
13895            removeCallbacks(mPendingCheckForLongPress);
13896        }
13897    }
13898
13899    /**
13900     * Remove the pending click action
13901     */
13902    private void removePerformClickCallback() {
13903        if (mPerformClick != null) {
13904            removeCallbacks(mPerformClick);
13905        }
13906    }
13907
13908    /**
13909     * Remove the prepress detection timer.
13910     */
13911    private void removeUnsetPressCallback() {
13912        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
13913            setPressed(false);
13914            removeCallbacks(mUnsetPressedState);
13915        }
13916    }
13917
13918    /**
13919     * Remove the tap detection timer.
13920     */
13921    private void removeTapCallback() {
13922        if (mPendingCheckForTap != null) {
13923            mPrivateFlags &= ~PFLAG_PREPRESSED;
13924            removeCallbacks(mPendingCheckForTap);
13925        }
13926    }
13927
13928    /**
13929     * Cancels a pending long press.  Your subclass can use this if you
13930     * want the context menu to come up if the user presses and holds
13931     * at the same place, but you don't want it to come up if they press
13932     * and then move around enough to cause scrolling.
13933     */
13934    public void cancelLongPress() {
13935        removeLongPressCallback();
13936
13937        /*
13938         * The prepressed state handled by the tap callback is a display
13939         * construct, but the tap callback will post a long press callback
13940         * less its own timeout. Remove it here.
13941         */
13942        removeTapCallback();
13943    }
13944
13945    /**
13946     * Sets the TouchDelegate for this View.
13947     */
13948    public void setTouchDelegate(TouchDelegate delegate) {
13949        mTouchDelegate = delegate;
13950    }
13951
13952    /**
13953     * Gets the TouchDelegate for this View.
13954     */
13955    public TouchDelegate getTouchDelegate() {
13956        return mTouchDelegate;
13957    }
13958
13959    /**
13960     * Request unbuffered dispatch of the given stream of MotionEvents to this View.
13961     *
13962     * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input
13963     * system not batch {@link MotionEvent}s but instead deliver them as soon as they're
13964     * available. This method should only be called for touch events.
13965     *
13966     * <p class="note">This api is not intended for most applications. Buffered dispatch
13967     * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent
13968     * streams will not improve your input latency. Side effects include: increased latency,
13969     * jittery scrolls and inability to take advantage of system resampling. Talk to your input
13970     * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for
13971     * you.</p>
13972     */
13973    public final void requestUnbufferedDispatch(MotionEvent event) {
13974        final int action = event.getAction();
13975        if (mAttachInfo == null
13976                || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE
13977                || !event.isTouchEvent()) {
13978            return;
13979        }
13980        mAttachInfo.mUnbufferedDispatchRequested = true;
13981    }
13982
13983    private boolean hasSize() {
13984        return (mBottom > mTop) && (mRight > mLeft);
13985    }
13986
13987    private boolean canTakeFocus() {
13988        return ((mViewFlags & VISIBILITY_MASK) == VISIBLE)
13989                && ((mViewFlags & FOCUSABLE) == FOCUSABLE)
13990                && ((mViewFlags & ENABLED_MASK) == ENABLED)
13991                && (sCanFocusZeroSized || !isLayoutValid() || hasSize());
13992    }
13993
13994    /**
13995     * Set flags controlling behavior of this view.
13996     *
13997     * @param flags Constant indicating the value which should be set
13998     * @param mask Constant indicating the bit range that should be changed
13999     */
14000    void setFlags(int flags, int mask) {
14001        final boolean accessibilityEnabled =
14002                AccessibilityManager.getInstance(mContext).isEnabled();
14003        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
14004
14005        int old = mViewFlags;
14006        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
14007
14008        int changed = mViewFlags ^ old;
14009        if (changed == 0) {
14010            return;
14011        }
14012        int privateFlags = mPrivateFlags;
14013        boolean shouldNotifyFocusableAvailable = false;
14014
14015        // If focusable is auto, update the FOCUSABLE bit.
14016        int focusableChangedByAuto = 0;
14017        if (((mViewFlags & FOCUSABLE_AUTO) != 0)
14018                && (changed & (FOCUSABLE_MASK | CLICKABLE)) != 0) {
14019            // Heuristic only takes into account whether view is clickable.
14020            final int newFocus;
14021            if ((mViewFlags & CLICKABLE) != 0) {
14022                newFocus = FOCUSABLE;
14023            } else {
14024                newFocus = NOT_FOCUSABLE;
14025            }
14026            mViewFlags = (mViewFlags & ~FOCUSABLE) | newFocus;
14027            focusableChangedByAuto = (old & FOCUSABLE) ^ (newFocus & FOCUSABLE);
14028            changed = (changed & ~FOCUSABLE) | focusableChangedByAuto;
14029        }
14030
14031        /* Check if the FOCUSABLE bit has changed */
14032        if (((changed & FOCUSABLE) != 0) && ((privateFlags & PFLAG_HAS_BOUNDS) != 0)) {
14033            if (((old & FOCUSABLE) == FOCUSABLE)
14034                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
14035                /* Give up focus if we are no longer focusable */
14036                clearFocus();
14037                if (mParent instanceof ViewGroup) {
14038                    ((ViewGroup) mParent).clearFocusedInCluster();
14039                }
14040            } else if (((old & FOCUSABLE) == NOT_FOCUSABLE)
14041                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
14042                /*
14043                 * Tell the view system that we are now available to take focus
14044                 * if no one else already has it.
14045                 */
14046                if (mParent != null) {
14047                    ViewRootImpl viewRootImpl = getViewRootImpl();
14048                    if (!sAutoFocusableOffUIThreadWontNotifyParents
14049                            || focusableChangedByAuto == 0
14050                            || viewRootImpl == null
14051                            || viewRootImpl.mThread == Thread.currentThread()) {
14052                        shouldNotifyFocusableAvailable = canTakeFocus();
14053                    }
14054                }
14055            }
14056        }
14057
14058        final int newVisibility = flags & VISIBILITY_MASK;
14059        if (newVisibility == VISIBLE) {
14060            if ((changed & VISIBILITY_MASK) != 0) {
14061                /*
14062                 * If this view is becoming visible, invalidate it in case it changed while
14063                 * it was not visible. Marking it drawn ensures that the invalidation will
14064                 * go through.
14065                 */
14066                mPrivateFlags |= PFLAG_DRAWN;
14067                invalidate(true);
14068
14069                needGlobalAttributesUpdate(true);
14070
14071                // a view becoming visible is worth notifying the parent about in case nothing has
14072                // focus. Even if this specific view isn't focusable, it may contain something that
14073                // is, so let the root view try to give this focus if nothing else does.
14074                shouldNotifyFocusableAvailable = hasSize();
14075            }
14076        }
14077
14078        if ((changed & ENABLED_MASK) != 0) {
14079            if ((mViewFlags & ENABLED_MASK) == ENABLED) {
14080                // a view becoming enabled should notify the parent as long as the view is also
14081                // visible and the parent wasn't already notified by becoming visible during this
14082                // setFlags invocation.
14083                shouldNotifyFocusableAvailable = canTakeFocus();
14084            } else {
14085                if (isFocused()) clearFocus();
14086            }
14087        }
14088
14089        if (shouldNotifyFocusableAvailable && mParent != null) {
14090            mParent.focusableViewAvailable(this);
14091        }
14092
14093        /* Check if the GONE bit has changed */
14094        if ((changed & GONE) != 0) {
14095            needGlobalAttributesUpdate(false);
14096            requestLayout();
14097
14098            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
14099                if (hasFocus()) {
14100                    clearFocus();
14101                    if (mParent instanceof ViewGroup) {
14102                        ((ViewGroup) mParent).clearFocusedInCluster();
14103                    }
14104                }
14105                clearAccessibilityFocus();
14106                destroyDrawingCache();
14107                if (mParent instanceof View) {
14108                    // GONE views noop invalidation, so invalidate the parent
14109                    ((View) mParent).invalidate(true);
14110                }
14111                // Mark the view drawn to ensure that it gets invalidated properly the next
14112                // time it is visible and gets invalidated
14113                mPrivateFlags |= PFLAG_DRAWN;
14114            }
14115            if (mAttachInfo != null) {
14116                mAttachInfo.mViewVisibilityChanged = true;
14117            }
14118        }
14119
14120        /* Check if the VISIBLE bit has changed */
14121        if ((changed & INVISIBLE) != 0) {
14122            needGlobalAttributesUpdate(false);
14123            /*
14124             * If this view is becoming invisible, set the DRAWN flag so that
14125             * the next invalidate() will not be skipped.
14126             */
14127            mPrivateFlags |= PFLAG_DRAWN;
14128
14129            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
14130                // root view becoming invisible shouldn't clear focus and accessibility focus
14131                if (getRootView() != this) {
14132                    if (hasFocus()) {
14133                        clearFocus();
14134                        if (mParent instanceof ViewGroup) {
14135                            ((ViewGroup) mParent).clearFocusedInCluster();
14136                        }
14137                    }
14138                    clearAccessibilityFocus();
14139                }
14140            }
14141            if (mAttachInfo != null) {
14142                mAttachInfo.mViewVisibilityChanged = true;
14143            }
14144        }
14145
14146        if ((changed & VISIBILITY_MASK) != 0) {
14147            // If the view is invisible, cleanup its display list to free up resources
14148            if (newVisibility != VISIBLE && mAttachInfo != null) {
14149                cleanupDraw();
14150            }
14151
14152            if (mParent instanceof ViewGroup) {
14153                ((ViewGroup) mParent).onChildVisibilityChanged(this,
14154                        (changed & VISIBILITY_MASK), newVisibility);
14155                ((View) mParent).invalidate(true);
14156            } else if (mParent != null) {
14157                mParent.invalidateChild(this, null);
14158            }
14159
14160            if (mAttachInfo != null) {
14161                dispatchVisibilityChanged(this, newVisibility);
14162
14163                // Aggregated visibility changes are dispatched to attached views
14164                // in visible windows where the parent is currently shown/drawn
14165                // or the parent is not a ViewGroup (and therefore assumed to be a ViewRoot),
14166                // discounting clipping or overlapping. This makes it a good place
14167                // to change animation states.
14168                if (mParent != null && getWindowVisibility() == VISIBLE &&
14169                        ((!(mParent instanceof ViewGroup)) || ((ViewGroup) mParent).isShown())) {
14170                    dispatchVisibilityAggregated(newVisibility == VISIBLE);
14171                }
14172                notifySubtreeAccessibilityStateChangedIfNeeded();
14173            }
14174        }
14175
14176        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
14177            destroyDrawingCache();
14178        }
14179
14180        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
14181            destroyDrawingCache();
14182            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
14183            invalidateParentCaches();
14184        }
14185
14186        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
14187            destroyDrawingCache();
14188            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
14189        }
14190
14191        if ((changed & DRAW_MASK) != 0) {
14192            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
14193                if (mBackground != null
14194                        || mDefaultFocusHighlight != null
14195                        || (mForegroundInfo != null && mForegroundInfo.mDrawable != null)) {
14196                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
14197                } else {
14198                    mPrivateFlags |= PFLAG_SKIP_DRAW;
14199                }
14200            } else {
14201                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
14202            }
14203            requestLayout();
14204            invalidate(true);
14205        }
14206
14207        if ((changed & KEEP_SCREEN_ON) != 0) {
14208            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
14209                mParent.recomputeViewAttributes(this);
14210            }
14211        }
14212
14213        if (accessibilityEnabled) {
14214            // If we're an accessibility pane and the visibility changed, we already have sent
14215            // a state change, so we really don't need to report other changes.
14216            if (isAccessibilityPane()) {
14217                changed &= ~VISIBILITY_MASK;
14218            }
14219            if ((changed & FOCUSABLE) != 0 || (changed & VISIBILITY_MASK) != 0
14220                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0
14221                    || (changed & CONTEXT_CLICKABLE) != 0) {
14222                if (oldIncludeForAccessibility != includeForAccessibility()) {
14223                    notifySubtreeAccessibilityStateChangedIfNeeded();
14224                } else {
14225                    notifyViewAccessibilityStateChangedIfNeeded(
14226                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
14227                }
14228            } else if ((changed & ENABLED_MASK) != 0) {
14229                notifyViewAccessibilityStateChangedIfNeeded(
14230                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
14231            }
14232        }
14233    }
14234
14235    /**
14236     * Change the view's z order in the tree, so it's on top of other sibling
14237     * views. This ordering change may affect layout, if the parent container
14238     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
14239     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
14240     * method should be followed by calls to {@link #requestLayout()} and
14241     * {@link View#invalidate()} on the view's parent to force the parent to redraw
14242     * with the new child ordering.
14243     *
14244     * @see ViewGroup#bringChildToFront(View)
14245     */
14246    public void bringToFront() {
14247        if (mParent != null) {
14248            mParent.bringChildToFront(this);
14249        }
14250    }
14251
14252    /**
14253     * This is called in response to an internal scroll in this view (i.e., the
14254     * view scrolled its own contents). This is typically as a result of
14255     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
14256     * called.
14257     *
14258     * @param l Current horizontal scroll origin.
14259     * @param t Current vertical scroll origin.
14260     * @param oldl Previous horizontal scroll origin.
14261     * @param oldt Previous vertical scroll origin.
14262     */
14263    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
14264        notifySubtreeAccessibilityStateChangedIfNeeded();
14265
14266        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
14267            postSendViewScrolledAccessibilityEventCallback(l - oldl, t - oldt);
14268        }
14269
14270        mBackgroundSizeChanged = true;
14271        mDefaultFocusHighlightSizeChanged = true;
14272        if (mForegroundInfo != null) {
14273            mForegroundInfo.mBoundsChanged = true;
14274        }
14275
14276        final AttachInfo ai = mAttachInfo;
14277        if (ai != null) {
14278            ai.mViewScrollChanged = true;
14279        }
14280
14281        if (mListenerInfo != null && mListenerInfo.mOnScrollChangeListener != null) {
14282            mListenerInfo.mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt);
14283        }
14284    }
14285
14286    /**
14287     * Interface definition for a callback to be invoked when the scroll
14288     * X or Y positions of a view change.
14289     * <p>
14290     * <b>Note:</b> Some views handle scrolling independently from View and may
14291     * have their own separate listeners for scroll-type events. For example,
14292     * {@link android.widget.ListView ListView} allows clients to register an
14293     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
14294     * to listen for changes in list scroll position.
14295     *
14296     * @see #setOnScrollChangeListener(View.OnScrollChangeListener)
14297     */
14298    public interface OnScrollChangeListener {
14299        /**
14300         * Called when the scroll position of a view changes.
14301         *
14302         * @param v The view whose scroll position has changed.
14303         * @param scrollX Current horizontal scroll origin.
14304         * @param scrollY Current vertical scroll origin.
14305         * @param oldScrollX Previous horizontal scroll origin.
14306         * @param oldScrollY Previous vertical scroll origin.
14307         */
14308        void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY);
14309    }
14310
14311    /**
14312     * Interface definition for a callback to be invoked when the layout bounds of a view
14313     * changes due to layout processing.
14314     */
14315    public interface OnLayoutChangeListener {
14316        /**
14317         * Called when the layout bounds of a view changes due to layout processing.
14318         *
14319         * @param v The view whose bounds have changed.
14320         * @param left The new value of the view's left property.
14321         * @param top The new value of the view's top property.
14322         * @param right The new value of the view's right property.
14323         * @param bottom The new value of the view's bottom property.
14324         * @param oldLeft The previous value of the view's left property.
14325         * @param oldTop The previous value of the view's top property.
14326         * @param oldRight The previous value of the view's right property.
14327         * @param oldBottom The previous value of the view's bottom property.
14328         */
14329        void onLayoutChange(View v, int left, int top, int right, int bottom,
14330            int oldLeft, int oldTop, int oldRight, int oldBottom);
14331    }
14332
14333    /**
14334     * This is called during layout when the size of this view has changed. If
14335     * you were just added to the view hierarchy, you're called with the old
14336     * values of 0.
14337     *
14338     * @param w Current width of this view.
14339     * @param h Current height of this view.
14340     * @param oldw Old width of this view.
14341     * @param oldh Old height of this view.
14342     */
14343    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
14344    }
14345
14346    /**
14347     * Called by draw to draw the child views. This may be overridden
14348     * by derived classes to gain control just before its children are drawn
14349     * (but after its own view has been drawn).
14350     * @param canvas the canvas on which to draw the view
14351     */
14352    protected void dispatchDraw(Canvas canvas) {
14353
14354    }
14355
14356    /**
14357     * Gets the parent of this view. Note that the parent is a
14358     * ViewParent and not necessarily a View.
14359     *
14360     * @return Parent of this view.
14361     */
14362    public final ViewParent getParent() {
14363        return mParent;
14364    }
14365
14366    /**
14367     * Set the horizontal scrolled position of your view. This will cause a call to
14368     * {@link #onScrollChanged(int, int, int, int)} and the view will be
14369     * invalidated.
14370     * @param value the x position to scroll to
14371     */
14372    public void setScrollX(int value) {
14373        scrollTo(value, mScrollY);
14374    }
14375
14376    /**
14377     * Set the vertical scrolled position of your view. This will cause a call to
14378     * {@link #onScrollChanged(int, int, int, int)} and the view will be
14379     * invalidated.
14380     * @param value the y position to scroll to
14381     */
14382    public void setScrollY(int value) {
14383        scrollTo(mScrollX, value);
14384    }
14385
14386    /**
14387     * Return the scrolled left position of this view. This is the left edge of
14388     * the displayed part of your view. You do not need to draw any pixels
14389     * farther left, since those are outside of the frame of your view on
14390     * screen.
14391     *
14392     * @return The left edge of the displayed part of your view, in pixels.
14393     */
14394    public final int getScrollX() {
14395        return mScrollX;
14396    }
14397
14398    /**
14399     * Return the scrolled top position of this view. This is the top edge of
14400     * the displayed part of your view. You do not need to draw any pixels above
14401     * it, since those are outside of the frame of your view on screen.
14402     *
14403     * @return The top edge of the displayed part of your view, in pixels.
14404     */
14405    public final int getScrollY() {
14406        return mScrollY;
14407    }
14408
14409    /**
14410     * Return the width of your view.
14411     *
14412     * @return The width of your view, in pixels.
14413     */
14414    @ViewDebug.ExportedProperty(category = "layout")
14415    public final int getWidth() {
14416        return mRight - mLeft;
14417    }
14418
14419    /**
14420     * Return the height of your view.
14421     *
14422     * @return The height of your view, in pixels.
14423     */
14424    @ViewDebug.ExportedProperty(category = "layout")
14425    public final int getHeight() {
14426        return mBottom - mTop;
14427    }
14428
14429    /**
14430     * Return the visible drawing bounds of your view. Fills in the output
14431     * rectangle with the values from getScrollX(), getScrollY(),
14432     * getWidth(), and getHeight(). These bounds do not account for any
14433     * transformation properties currently set on the view, such as
14434     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
14435     *
14436     * @param outRect The (scrolled) drawing bounds of the view.
14437     */
14438    public void getDrawingRect(Rect outRect) {
14439        outRect.left = mScrollX;
14440        outRect.top = mScrollY;
14441        outRect.right = mScrollX + (mRight - mLeft);
14442        outRect.bottom = mScrollY + (mBottom - mTop);
14443    }
14444
14445    /**
14446     * Like {@link #getMeasuredWidthAndState()}, but only returns the
14447     * raw width component (that is the result is masked by
14448     * {@link #MEASURED_SIZE_MASK}).
14449     *
14450     * @return The raw measured width of this view.
14451     */
14452    public final int getMeasuredWidth() {
14453        return mMeasuredWidth & MEASURED_SIZE_MASK;
14454    }
14455
14456    /**
14457     * Return the full width measurement information for this view as computed
14458     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
14459     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
14460     * This should be used during measurement and layout calculations only. Use
14461     * {@link #getWidth()} to see how wide a view is after layout.
14462     *
14463     * @return The measured width of this view as a bit mask.
14464     */
14465    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
14466            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
14467                    name = "MEASURED_STATE_TOO_SMALL"),
14468    })
14469    public final int getMeasuredWidthAndState() {
14470        return mMeasuredWidth;
14471    }
14472
14473    /**
14474     * Like {@link #getMeasuredHeightAndState()}, but only returns the
14475     * raw height component (that is the result is masked by
14476     * {@link #MEASURED_SIZE_MASK}).
14477     *
14478     * @return The raw measured height of this view.
14479     */
14480    public final int getMeasuredHeight() {
14481        return mMeasuredHeight & MEASURED_SIZE_MASK;
14482    }
14483
14484    /**
14485     * Return the full height measurement information for this view as computed
14486     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
14487     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
14488     * This should be used during measurement and layout calculations only. Use
14489     * {@link #getHeight()} to see how wide a view is after layout.
14490     *
14491     * @return The measured height of this view as a bit mask.
14492     */
14493    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
14494            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
14495                    name = "MEASURED_STATE_TOO_SMALL"),
14496    })
14497    public final int getMeasuredHeightAndState() {
14498        return mMeasuredHeight;
14499    }
14500
14501    /**
14502     * Return only the state bits of {@link #getMeasuredWidthAndState()}
14503     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
14504     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
14505     * and the height component is at the shifted bits
14506     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
14507     */
14508    public final int getMeasuredState() {
14509        return (mMeasuredWidth&MEASURED_STATE_MASK)
14510                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
14511                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
14512    }
14513
14514    /**
14515     * The transform matrix of this view, which is calculated based on the current
14516     * rotation, scale, and pivot properties.
14517     *
14518     * @see #getRotation()
14519     * @see #getScaleX()
14520     * @see #getScaleY()
14521     * @see #getPivotX()
14522     * @see #getPivotY()
14523     * @return The current transform matrix for the view
14524     */
14525    public Matrix getMatrix() {
14526        ensureTransformationInfo();
14527        final Matrix matrix = mTransformationInfo.mMatrix;
14528        mRenderNode.getMatrix(matrix);
14529        return matrix;
14530    }
14531
14532    /**
14533     * Returns true if the transform matrix is the identity matrix.
14534     * Recomputes the matrix if necessary.
14535     *
14536     * @return True if the transform matrix is the identity matrix, false otherwise.
14537     */
14538    final boolean hasIdentityMatrix() {
14539        return mRenderNode.hasIdentityMatrix();
14540    }
14541
14542    void ensureTransformationInfo() {
14543        if (mTransformationInfo == null) {
14544            mTransformationInfo = new TransformationInfo();
14545        }
14546    }
14547
14548    /**
14549     * Utility method to retrieve the inverse of the current mMatrix property.
14550     * We cache the matrix to avoid recalculating it when transform properties
14551     * have not changed.
14552     *
14553     * @return The inverse of the current matrix of this view.
14554     * @hide
14555     */
14556    public final Matrix getInverseMatrix() {
14557        ensureTransformationInfo();
14558        if (mTransformationInfo.mInverseMatrix == null) {
14559            mTransformationInfo.mInverseMatrix = new Matrix();
14560        }
14561        final Matrix matrix = mTransformationInfo.mInverseMatrix;
14562        mRenderNode.getInverseMatrix(matrix);
14563        return matrix;
14564    }
14565
14566    /**
14567     * Gets the distance along the Z axis from the camera to this view.
14568     *
14569     * @see #setCameraDistance(float)
14570     *
14571     * @return The distance along the Z axis.
14572     */
14573    public float getCameraDistance() {
14574        final float dpi = mResources.getDisplayMetrics().densityDpi;
14575        return -(mRenderNode.getCameraDistance() * dpi);
14576    }
14577
14578    /**
14579     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
14580     * views are drawn) from the camera to this view. The camera's distance
14581     * affects 3D transformations, for instance rotations around the X and Y
14582     * axis. If the rotationX or rotationY properties are changed and this view is
14583     * large (more than half the size of the screen), it is recommended to always
14584     * use a camera distance that's greater than the height (X axis rotation) or
14585     * the width (Y axis rotation) of this view.</p>
14586     *
14587     * <p>The distance of the camera from the view plane can have an affect on the
14588     * perspective distortion of the view when it is rotated around the x or y axis.
14589     * For example, a large distance will result in a large viewing angle, and there
14590     * will not be much perspective distortion of the view as it rotates. A short
14591     * distance may cause much more perspective distortion upon rotation, and can
14592     * also result in some drawing artifacts if the rotated view ends up partially
14593     * behind the camera (which is why the recommendation is to use a distance at
14594     * least as far as the size of the view, if the view is to be rotated.)</p>
14595     *
14596     * <p>The distance is expressed in "depth pixels." The default distance depends
14597     * on the screen density. For instance, on a medium density display, the
14598     * default distance is 1280. On a high density display, the default distance
14599     * is 1920.</p>
14600     *
14601     * <p>If you want to specify a distance that leads to visually consistent
14602     * results across various densities, use the following formula:</p>
14603     * <pre>
14604     * float scale = context.getResources().getDisplayMetrics().density;
14605     * view.setCameraDistance(distance * scale);
14606     * </pre>
14607     *
14608     * <p>The density scale factor of a high density display is 1.5,
14609     * and 1920 = 1280 * 1.5.</p>
14610     *
14611     * @param distance The distance in "depth pixels", if negative the opposite
14612     *        value is used
14613     *
14614     * @see #setRotationX(float)
14615     * @see #setRotationY(float)
14616     */
14617    public void setCameraDistance(float distance) {
14618        final float dpi = mResources.getDisplayMetrics().densityDpi;
14619
14620        invalidateViewProperty(true, false);
14621        mRenderNode.setCameraDistance(-Math.abs(distance) / dpi);
14622        invalidateViewProperty(false, false);
14623
14624        invalidateParentIfNeededAndWasQuickRejected();
14625    }
14626
14627    /**
14628     * The degrees that the view is rotated around the pivot point.
14629     *
14630     * @see #setRotation(float)
14631     * @see #getPivotX()
14632     * @see #getPivotY()
14633     *
14634     * @return The degrees of rotation.
14635     */
14636    @ViewDebug.ExportedProperty(category = "drawing")
14637    public float getRotation() {
14638        return mRenderNode.getRotation();
14639    }
14640
14641    /**
14642     * Sets the degrees that the view is rotated around the pivot point. Increasing values
14643     * result in clockwise rotation.
14644     *
14645     * @param rotation The degrees of rotation.
14646     *
14647     * @see #getRotation()
14648     * @see #getPivotX()
14649     * @see #getPivotY()
14650     * @see #setRotationX(float)
14651     * @see #setRotationY(float)
14652     *
14653     * @attr ref android.R.styleable#View_rotation
14654     */
14655    public void setRotation(float rotation) {
14656        if (rotation != getRotation()) {
14657            // Double-invalidation is necessary to capture view's old and new areas
14658            invalidateViewProperty(true, false);
14659            mRenderNode.setRotation(rotation);
14660            invalidateViewProperty(false, true);
14661
14662            invalidateParentIfNeededAndWasQuickRejected();
14663            notifySubtreeAccessibilityStateChangedIfNeeded();
14664        }
14665    }
14666
14667    /**
14668     * The degrees that the view is rotated around the vertical axis through the pivot point.
14669     *
14670     * @see #getPivotX()
14671     * @see #getPivotY()
14672     * @see #setRotationY(float)
14673     *
14674     * @return The degrees of Y rotation.
14675     */
14676    @ViewDebug.ExportedProperty(category = "drawing")
14677    public float getRotationY() {
14678        return mRenderNode.getRotationY();
14679    }
14680
14681    /**
14682     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
14683     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
14684     * down the y axis.
14685     *
14686     * When rotating large views, it is recommended to adjust the camera distance
14687     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
14688     *
14689     * @param rotationY The degrees of Y rotation.
14690     *
14691     * @see #getRotationY()
14692     * @see #getPivotX()
14693     * @see #getPivotY()
14694     * @see #setRotation(float)
14695     * @see #setRotationX(float)
14696     * @see #setCameraDistance(float)
14697     *
14698     * @attr ref android.R.styleable#View_rotationY
14699     */
14700    public void setRotationY(float rotationY) {
14701        if (rotationY != getRotationY()) {
14702            invalidateViewProperty(true, false);
14703            mRenderNode.setRotationY(rotationY);
14704            invalidateViewProperty(false, true);
14705
14706            invalidateParentIfNeededAndWasQuickRejected();
14707            notifySubtreeAccessibilityStateChangedIfNeeded();
14708        }
14709    }
14710
14711    /**
14712     * The degrees that the view is rotated around the horizontal axis through the pivot point.
14713     *
14714     * @see #getPivotX()
14715     * @see #getPivotY()
14716     * @see #setRotationX(float)
14717     *
14718     * @return The degrees of X rotation.
14719     */
14720    @ViewDebug.ExportedProperty(category = "drawing")
14721    public float getRotationX() {
14722        return mRenderNode.getRotationX();
14723    }
14724
14725    /**
14726     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
14727     * Increasing values result in clockwise rotation from the viewpoint of looking down the
14728     * x axis.
14729     *
14730     * When rotating large views, it is recommended to adjust the camera distance
14731     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
14732     *
14733     * @param rotationX The degrees of X rotation.
14734     *
14735     * @see #getRotationX()
14736     * @see #getPivotX()
14737     * @see #getPivotY()
14738     * @see #setRotation(float)
14739     * @see #setRotationY(float)
14740     * @see #setCameraDistance(float)
14741     *
14742     * @attr ref android.R.styleable#View_rotationX
14743     */
14744    public void setRotationX(float rotationX) {
14745        if (rotationX != getRotationX()) {
14746            invalidateViewProperty(true, false);
14747            mRenderNode.setRotationX(rotationX);
14748            invalidateViewProperty(false, true);
14749
14750            invalidateParentIfNeededAndWasQuickRejected();
14751            notifySubtreeAccessibilityStateChangedIfNeeded();
14752        }
14753    }
14754
14755    /**
14756     * The amount that the view is scaled in x around the pivot point, as a proportion of
14757     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
14758     *
14759     * <p>By default, this is 1.0f.
14760     *
14761     * @see #getPivotX()
14762     * @see #getPivotY()
14763     * @return The scaling factor.
14764     */
14765    @ViewDebug.ExportedProperty(category = "drawing")
14766    public float getScaleX() {
14767        return mRenderNode.getScaleX();
14768    }
14769
14770    /**
14771     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
14772     * the view's unscaled width. A value of 1 means that no scaling is applied.
14773     *
14774     * @param scaleX The scaling factor.
14775     * @see #getPivotX()
14776     * @see #getPivotY()
14777     *
14778     * @attr ref android.R.styleable#View_scaleX
14779     */
14780    public void setScaleX(float scaleX) {
14781        if (scaleX != getScaleX()) {
14782            scaleX = sanitizeFloatPropertyValue(scaleX, "scaleX");
14783            invalidateViewProperty(true, false);
14784            mRenderNode.setScaleX(scaleX);
14785            invalidateViewProperty(false, true);
14786
14787            invalidateParentIfNeededAndWasQuickRejected();
14788            notifySubtreeAccessibilityStateChangedIfNeeded();
14789        }
14790    }
14791
14792    /**
14793     * The amount that the view is scaled in y around the pivot point, as a proportion of
14794     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
14795     *
14796     * <p>By default, this is 1.0f.
14797     *
14798     * @see #getPivotX()
14799     * @see #getPivotY()
14800     * @return The scaling factor.
14801     */
14802    @ViewDebug.ExportedProperty(category = "drawing")
14803    public float getScaleY() {
14804        return mRenderNode.getScaleY();
14805    }
14806
14807    /**
14808     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
14809     * the view's unscaled width. A value of 1 means that no scaling is applied.
14810     *
14811     * @param scaleY The scaling factor.
14812     * @see #getPivotX()
14813     * @see #getPivotY()
14814     *
14815     * @attr ref android.R.styleable#View_scaleY
14816     */
14817    public void setScaleY(float scaleY) {
14818        if (scaleY != getScaleY()) {
14819            scaleY = sanitizeFloatPropertyValue(scaleY, "scaleY");
14820            invalidateViewProperty(true, false);
14821            mRenderNode.setScaleY(scaleY);
14822            invalidateViewProperty(false, true);
14823
14824            invalidateParentIfNeededAndWasQuickRejected();
14825            notifySubtreeAccessibilityStateChangedIfNeeded();
14826        }
14827    }
14828
14829    /**
14830     * The x location of the point around which the view is {@link #setRotation(float) rotated}
14831     * and {@link #setScaleX(float) scaled}.
14832     *
14833     * @see #getRotation()
14834     * @see #getScaleX()
14835     * @see #getScaleY()
14836     * @see #getPivotY()
14837     * @return The x location of the pivot point.
14838     *
14839     * @attr ref android.R.styleable#View_transformPivotX
14840     */
14841    @ViewDebug.ExportedProperty(category = "drawing")
14842    public float getPivotX() {
14843        return mRenderNode.getPivotX();
14844    }
14845
14846    /**
14847     * Sets the x location of the point around which the view is
14848     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
14849     * By default, the pivot point is centered on the object.
14850     * Setting this property disables this behavior and causes the view to use only the
14851     * explicitly set pivotX and pivotY values.
14852     *
14853     * @param pivotX The x location of the pivot point.
14854     * @see #getRotation()
14855     * @see #getScaleX()
14856     * @see #getScaleY()
14857     * @see #getPivotY()
14858     *
14859     * @attr ref android.R.styleable#View_transformPivotX
14860     */
14861    public void setPivotX(float pivotX) {
14862        if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) {
14863            invalidateViewProperty(true, false);
14864            mRenderNode.setPivotX(pivotX);
14865            invalidateViewProperty(false, true);
14866
14867            invalidateParentIfNeededAndWasQuickRejected();
14868        }
14869    }
14870
14871    /**
14872     * The y location of the point around which the view is {@link #setRotation(float) rotated}
14873     * and {@link #setScaleY(float) scaled}.
14874     *
14875     * @see #getRotation()
14876     * @see #getScaleX()
14877     * @see #getScaleY()
14878     * @see #getPivotY()
14879     * @return The y location of the pivot point.
14880     *
14881     * @attr ref android.R.styleable#View_transformPivotY
14882     */
14883    @ViewDebug.ExportedProperty(category = "drawing")
14884    public float getPivotY() {
14885        return mRenderNode.getPivotY();
14886    }
14887
14888    /**
14889     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
14890     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
14891     * Setting this property disables this behavior and causes the view to use only the
14892     * explicitly set pivotX and pivotY values.
14893     *
14894     * @param pivotY The y location of the pivot point.
14895     * @see #getRotation()
14896     * @see #getScaleX()
14897     * @see #getScaleY()
14898     * @see #getPivotY()
14899     *
14900     * @attr ref android.R.styleable#View_transformPivotY
14901     */
14902    public void setPivotY(float pivotY) {
14903        if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) {
14904            invalidateViewProperty(true, false);
14905            mRenderNode.setPivotY(pivotY);
14906            invalidateViewProperty(false, true);
14907
14908            invalidateParentIfNeededAndWasQuickRejected();
14909        }
14910    }
14911
14912    /**
14913     * Returns whether or not a pivot has been set by a call to {@link #setPivotX(float)} or
14914     * {@link #setPivotY(float)}. If no pivot has been set then the pivot will be the center
14915     * of the view.
14916     *
14917     * @return True if a pivot has been set, false if the default pivot is being used
14918     */
14919    public boolean isPivotSet() {
14920        return mRenderNode.isPivotExplicitlySet();
14921    }
14922
14923    /**
14924     * Clears any pivot previously set by a call to  {@link #setPivotX(float)} or
14925     * {@link #setPivotY(float)}. After calling this {@link #isPivotSet()} will be false
14926     * and the pivot used for rotation will return to default of being centered on the view.
14927     */
14928    public void resetPivot() {
14929        if (mRenderNode.resetPivot()) {
14930            invalidateViewProperty(false, false);
14931        }
14932    }
14933
14934    /**
14935     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
14936     * completely transparent and 1 means the view is completely opaque.
14937     *
14938     * <p>By default this is 1.0f.
14939     * @return The opacity of the view.
14940     */
14941    @ViewDebug.ExportedProperty(category = "drawing")
14942    public float getAlpha() {
14943        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
14944    }
14945
14946    /**
14947     * Sets the behavior for overlapping rendering for this view (see {@link
14948     * #hasOverlappingRendering()} for more details on this behavior). Calling this method
14949     * is an alternative to overriding {@link #hasOverlappingRendering()} in a subclass,
14950     * providing the value which is then used internally. That is, when {@link
14951     * #forceHasOverlappingRendering(boolean)} is called, the value of {@link
14952     * #hasOverlappingRendering()} is ignored and the value passed into this method is used
14953     * instead.
14954     *
14955     * @param hasOverlappingRendering The value for overlapping rendering to be used internally
14956     * instead of that returned by {@link #hasOverlappingRendering()}.
14957     *
14958     * @attr ref android.R.styleable#View_forceHasOverlappingRendering
14959     */
14960    public void forceHasOverlappingRendering(boolean hasOverlappingRendering) {
14961        mPrivateFlags3 |= PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED;
14962        if (hasOverlappingRendering) {
14963            mPrivateFlags3 |= PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE;
14964        } else {
14965            mPrivateFlags3 &= ~PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE;
14966        }
14967    }
14968
14969    /**
14970     * Returns the value for overlapping rendering that is used internally. This is either
14971     * the value passed into {@link #forceHasOverlappingRendering(boolean)}, if called, or
14972     * the return value of {@link #hasOverlappingRendering()}, otherwise.
14973     *
14974     * @return The value for overlapping rendering being used internally.
14975     */
14976    public final boolean getHasOverlappingRendering() {
14977        return (mPrivateFlags3 & PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED) != 0 ?
14978                (mPrivateFlags3 & PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE) != 0 :
14979                hasOverlappingRendering();
14980    }
14981
14982    /**
14983     * Returns whether this View has content which overlaps.
14984     *
14985     * <p>This function, intended to be overridden by specific View types, is an optimization when
14986     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
14987     * an offscreen buffer and then composited into place, which can be expensive. If the view has
14988     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
14989     * directly. An example of overlapping rendering is a TextView with a background image, such as
14990     * a Button. An example of non-overlapping rendering is a TextView with no background, or an
14991     * ImageView with only the foreground image. The default implementation returns true; subclasses
14992     * should override if they have cases which can be optimized.</p>
14993     *
14994     * <p><strong>Note:</strong> The return value of this method is ignored if {@link
14995     * #forceHasOverlappingRendering(boolean)} has been called on this view.</p>
14996     *
14997     * @return true if the content in this view might overlap, false otherwise.
14998     */
14999    @ViewDebug.ExportedProperty(category = "drawing")
15000    public boolean hasOverlappingRendering() {
15001        return true;
15002    }
15003
15004    /**
15005     * Sets the opacity of the view to a value from 0 to 1, where 0 means the view is
15006     * completely transparent and 1 means the view is completely opaque.
15007     *
15008     * <p class="note"><strong>Note:</strong> setting alpha to a translucent value (0 < alpha < 1)
15009     * can have significant performance implications, especially for large views. It is best to use
15010     * the alpha property sparingly and transiently, as in the case of fading animations.</p>
15011     *
15012     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
15013     * strongly recommended for performance reasons to either override
15014     * {@link #hasOverlappingRendering()} to return <code>false</code> if appropriate, or setting a
15015     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view for the duration
15016     * of the animation. On versions {@link android.os.Build.VERSION_CODES#M} and below,
15017     * the default path for rendering an unlayered View with alpha could add multiple milliseconds
15018     * of rendering cost, even for simple or small views. Starting with
15019     * {@link android.os.Build.VERSION_CODES#M}, {@link #LAYER_TYPE_HARDWARE} is automatically
15020     * applied to the view at the rendering level.</p>
15021     *
15022     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
15023     * responsible for applying the opacity itself.</p>
15024     *
15025     * <p>On versions {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} and below, note that if
15026     * the view is backed by a {@link #setLayerType(int, android.graphics.Paint) layer} and is
15027     * associated with a {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an
15028     * alpha value less than 1.0 will supersede the alpha of the layer paint.</p>
15029     *
15030     * <p>Starting with {@link android.os.Build.VERSION_CODES#M}, setting a translucent alpha
15031     * value will clip a View to its bounds, unless the View returns <code>false</code> from
15032     * {@link #hasOverlappingRendering}.</p>
15033     *
15034     * @param alpha The opacity of the view.
15035     *
15036     * @see #hasOverlappingRendering()
15037     * @see #setLayerType(int, android.graphics.Paint)
15038     *
15039     * @attr ref android.R.styleable#View_alpha
15040     */
15041    public void setAlpha(@FloatRange(from=0.0, to=1.0) float alpha) {
15042        ensureTransformationInfo();
15043        if (mTransformationInfo.mAlpha != alpha) {
15044            // Report visibility changes, which can affect children, to accessibility
15045            if ((alpha == 0) ^ (mTransformationInfo.mAlpha == 0)) {
15046                notifySubtreeAccessibilityStateChangedIfNeeded();
15047            }
15048            mTransformationInfo.mAlpha = alpha;
15049            if (onSetAlpha((int) (alpha * 255))) {
15050                mPrivateFlags |= PFLAG_ALPHA_SET;
15051                // subclass is handling alpha - don't optimize rendering cache invalidation
15052                invalidateParentCaches();
15053                invalidate(true);
15054            } else {
15055                mPrivateFlags &= ~PFLAG_ALPHA_SET;
15056                invalidateViewProperty(true, false);
15057                mRenderNode.setAlpha(getFinalAlpha());
15058            }
15059        }
15060    }
15061
15062    /**
15063     * Faster version of setAlpha() which performs the same steps except there are
15064     * no calls to invalidate(). The caller of this function should perform proper invalidation
15065     * on the parent and this object. The return value indicates whether the subclass handles
15066     * alpha (the return value for onSetAlpha()).
15067     *
15068     * @param alpha The new value for the alpha property
15069     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
15070     *         the new value for the alpha property is different from the old value
15071     */
15072    boolean setAlphaNoInvalidation(float alpha) {
15073        ensureTransformationInfo();
15074        if (mTransformationInfo.mAlpha != alpha) {
15075            mTransformationInfo.mAlpha = alpha;
15076            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
15077            if (subclassHandlesAlpha) {
15078                mPrivateFlags |= PFLAG_ALPHA_SET;
15079                return true;
15080            } else {
15081                mPrivateFlags &= ~PFLAG_ALPHA_SET;
15082                mRenderNode.setAlpha(getFinalAlpha());
15083            }
15084        }
15085        return false;
15086    }
15087
15088    /**
15089     * This property is hidden and intended only for use by the Fade transition, which
15090     * animates it to produce a visual translucency that does not side-effect (or get
15091     * affected by) the real alpha property. This value is composited with the other
15092     * alpha value (and the AlphaAnimation value, when that is present) to produce
15093     * a final visual translucency result, which is what is passed into the DisplayList.
15094     *
15095     * @hide
15096     */
15097    public void setTransitionAlpha(float alpha) {
15098        ensureTransformationInfo();
15099        if (mTransformationInfo.mTransitionAlpha != alpha) {
15100            mTransformationInfo.mTransitionAlpha = alpha;
15101            mPrivateFlags &= ~PFLAG_ALPHA_SET;
15102            invalidateViewProperty(true, false);
15103            mRenderNode.setAlpha(getFinalAlpha());
15104        }
15105    }
15106
15107    /**
15108     * Calculates the visual alpha of this view, which is a combination of the actual
15109     * alpha value and the transitionAlpha value (if set).
15110     */
15111    private float getFinalAlpha() {
15112        if (mTransformationInfo != null) {
15113            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
15114        }
15115        return 1;
15116    }
15117
15118    /**
15119     * This property is hidden and intended only for use by the Fade transition, which
15120     * animates it to produce a visual translucency that does not side-effect (or get
15121     * affected by) the real alpha property. This value is composited with the other
15122     * alpha value (and the AlphaAnimation value, when that is present) to produce
15123     * a final visual translucency result, which is what is passed into the DisplayList.
15124     *
15125     * @hide
15126     */
15127    @ViewDebug.ExportedProperty(category = "drawing")
15128    public float getTransitionAlpha() {
15129        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
15130    }
15131
15132    /**
15133     * Top position of this view relative to its parent.
15134     *
15135     * @return The top of this view, in pixels.
15136     */
15137    @ViewDebug.CapturedViewProperty
15138    public final int getTop() {
15139        return mTop;
15140    }
15141
15142    /**
15143     * Sets the top position of this view relative to its parent. This method is meant to be called
15144     * by the layout system and should not generally be called otherwise, because the property
15145     * may be changed at any time by the layout.
15146     *
15147     * @param top The top of this view, in pixels.
15148     */
15149    public final void setTop(int top) {
15150        if (top != mTop) {
15151            final boolean matrixIsIdentity = hasIdentityMatrix();
15152            if (matrixIsIdentity) {
15153                if (mAttachInfo != null) {
15154                    int minTop;
15155                    int yLoc;
15156                    if (top < mTop) {
15157                        minTop = top;
15158                        yLoc = top - mTop;
15159                    } else {
15160                        minTop = mTop;
15161                        yLoc = 0;
15162                    }
15163                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
15164                }
15165            } else {
15166                // Double-invalidation is necessary to capture view's old and new areas
15167                invalidate(true);
15168            }
15169
15170            int width = mRight - mLeft;
15171            int oldHeight = mBottom - mTop;
15172
15173            mTop = top;
15174            mRenderNode.setTop(mTop);
15175
15176            sizeChange(width, mBottom - mTop, width, oldHeight);
15177
15178            if (!matrixIsIdentity) {
15179                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
15180                invalidate(true);
15181            }
15182            mBackgroundSizeChanged = true;
15183            mDefaultFocusHighlightSizeChanged = true;
15184            if (mForegroundInfo != null) {
15185                mForegroundInfo.mBoundsChanged = true;
15186            }
15187            invalidateParentIfNeeded();
15188            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
15189                // View was rejected last time it was drawn by its parent; this may have changed
15190                invalidateParentIfNeeded();
15191            }
15192        }
15193    }
15194
15195    /**
15196     * Bottom position of this view relative to its parent.
15197     *
15198     * @return The bottom of this view, in pixels.
15199     */
15200    @ViewDebug.CapturedViewProperty
15201    public final int getBottom() {
15202        return mBottom;
15203    }
15204
15205    /**
15206     * True if this view has changed since the last time being drawn.
15207     *
15208     * @return The dirty state of this view.
15209     */
15210    public boolean isDirty() {
15211        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
15212    }
15213
15214    /**
15215     * Sets the bottom position of this view relative to its parent. This method is meant to be
15216     * called by the layout system and should not generally be called otherwise, because the
15217     * property may be changed at any time by the layout.
15218     *
15219     * @param bottom The bottom of this view, in pixels.
15220     */
15221    public final void setBottom(int bottom) {
15222        if (bottom != mBottom) {
15223            final boolean matrixIsIdentity = hasIdentityMatrix();
15224            if (matrixIsIdentity) {
15225                if (mAttachInfo != null) {
15226                    int maxBottom;
15227                    if (bottom < mBottom) {
15228                        maxBottom = mBottom;
15229                    } else {
15230                        maxBottom = bottom;
15231                    }
15232                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
15233                }
15234            } else {
15235                // Double-invalidation is necessary to capture view's old and new areas
15236                invalidate(true);
15237            }
15238
15239            int width = mRight - mLeft;
15240            int oldHeight = mBottom - mTop;
15241
15242            mBottom = bottom;
15243            mRenderNode.setBottom(mBottom);
15244
15245            sizeChange(width, mBottom - mTop, width, oldHeight);
15246
15247            if (!matrixIsIdentity) {
15248                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
15249                invalidate(true);
15250            }
15251            mBackgroundSizeChanged = true;
15252            mDefaultFocusHighlightSizeChanged = true;
15253            if (mForegroundInfo != null) {
15254                mForegroundInfo.mBoundsChanged = true;
15255            }
15256            invalidateParentIfNeeded();
15257            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
15258                // View was rejected last time it was drawn by its parent; this may have changed
15259                invalidateParentIfNeeded();
15260            }
15261        }
15262    }
15263
15264    /**
15265     * Left position of this view relative to its parent.
15266     *
15267     * @return The left edge of this view, in pixels.
15268     */
15269    @ViewDebug.CapturedViewProperty
15270    public final int getLeft() {
15271        return mLeft;
15272    }
15273
15274    /**
15275     * Sets the left position of this view relative to its parent. This method is meant to be called
15276     * by the layout system and should not generally be called otherwise, because the property
15277     * may be changed at any time by the layout.
15278     *
15279     * @param left The left of this view, in pixels.
15280     */
15281    public final void setLeft(int left) {
15282        if (left != mLeft) {
15283            final boolean matrixIsIdentity = hasIdentityMatrix();
15284            if (matrixIsIdentity) {
15285                if (mAttachInfo != null) {
15286                    int minLeft;
15287                    int xLoc;
15288                    if (left < mLeft) {
15289                        minLeft = left;
15290                        xLoc = left - mLeft;
15291                    } else {
15292                        minLeft = mLeft;
15293                        xLoc = 0;
15294                    }
15295                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
15296                }
15297            } else {
15298                // Double-invalidation is necessary to capture view's old and new areas
15299                invalidate(true);
15300            }
15301
15302            int oldWidth = mRight - mLeft;
15303            int height = mBottom - mTop;
15304
15305            mLeft = left;
15306            mRenderNode.setLeft(left);
15307
15308            sizeChange(mRight - mLeft, height, oldWidth, height);
15309
15310            if (!matrixIsIdentity) {
15311                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
15312                invalidate(true);
15313            }
15314            mBackgroundSizeChanged = true;
15315            mDefaultFocusHighlightSizeChanged = true;
15316            if (mForegroundInfo != null) {
15317                mForegroundInfo.mBoundsChanged = true;
15318            }
15319            invalidateParentIfNeeded();
15320            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
15321                // View was rejected last time it was drawn by its parent; this may have changed
15322                invalidateParentIfNeeded();
15323            }
15324        }
15325    }
15326
15327    /**
15328     * Right position of this view relative to its parent.
15329     *
15330     * @return The right edge of this view, in pixels.
15331     */
15332    @ViewDebug.CapturedViewProperty
15333    public final int getRight() {
15334        return mRight;
15335    }
15336
15337    /**
15338     * Sets the right position of this view relative to its parent. This method is meant to be called
15339     * by the layout system and should not generally be called otherwise, because the property
15340     * may be changed at any time by the layout.
15341     *
15342     * @param right The right of this view, in pixels.
15343     */
15344    public final void setRight(int right) {
15345        if (right != mRight) {
15346            final boolean matrixIsIdentity = hasIdentityMatrix();
15347            if (matrixIsIdentity) {
15348                if (mAttachInfo != null) {
15349                    int maxRight;
15350                    if (right < mRight) {
15351                        maxRight = mRight;
15352                    } else {
15353                        maxRight = right;
15354                    }
15355                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
15356                }
15357            } else {
15358                // Double-invalidation is necessary to capture view's old and new areas
15359                invalidate(true);
15360            }
15361
15362            int oldWidth = mRight - mLeft;
15363            int height = mBottom - mTop;
15364
15365            mRight = right;
15366            mRenderNode.setRight(mRight);
15367
15368            sizeChange(mRight - mLeft, height, oldWidth, height);
15369
15370            if (!matrixIsIdentity) {
15371                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
15372                invalidate(true);
15373            }
15374            mBackgroundSizeChanged = true;
15375            mDefaultFocusHighlightSizeChanged = true;
15376            if (mForegroundInfo != null) {
15377                mForegroundInfo.mBoundsChanged = true;
15378            }
15379            invalidateParentIfNeeded();
15380            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
15381                // View was rejected last time it was drawn by its parent; this may have changed
15382                invalidateParentIfNeeded();
15383            }
15384        }
15385    }
15386
15387    private static float sanitizeFloatPropertyValue(float value, String propertyName) {
15388        return sanitizeFloatPropertyValue(value, propertyName, -Float.MAX_VALUE, Float.MAX_VALUE);
15389    }
15390
15391    private static float sanitizeFloatPropertyValue(float value, String propertyName,
15392            float min, float max) {
15393        // The expected "nothing bad happened" path
15394        if (value >= min && value <= max) return value;
15395
15396        if (value < min || value == Float.NEGATIVE_INFINITY) {
15397            if (sThrowOnInvalidFloatProperties) {
15398                throw new IllegalArgumentException("Cannot set '" + propertyName + "' to "
15399                        + value + ", the value must be >= " + min);
15400            }
15401            return min;
15402        }
15403
15404        if (value > max || value == Float.POSITIVE_INFINITY) {
15405            if (sThrowOnInvalidFloatProperties) {
15406                throw new IllegalArgumentException("Cannot set '" + propertyName + "' to "
15407                        + value + ", the value must be <= " + max);
15408            }
15409            return max;
15410        }
15411
15412        if (Float.isNaN(value)) {
15413            if (sThrowOnInvalidFloatProperties) {
15414                throw new IllegalArgumentException(
15415                        "Cannot set '" + propertyName + "' to Float.NaN");
15416            }
15417            return 0; // Unclear which direction this NaN went so... 0?
15418        }
15419
15420        // Shouldn't be possible to reach this.
15421        throw new IllegalStateException("How do you get here?? " + value);
15422    }
15423
15424    /**
15425     * The visual x position of this view, in pixels. This is equivalent to the
15426     * {@link #setTranslationX(float) translationX} property plus the current
15427     * {@link #getLeft() left} property.
15428     *
15429     * @return The visual x position of this view, in pixels.
15430     */
15431    @ViewDebug.ExportedProperty(category = "drawing")
15432    public float getX() {
15433        return mLeft + getTranslationX();
15434    }
15435
15436    /**
15437     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
15438     * {@link #setTranslationX(float) translationX} property to be the difference between
15439     * the x value passed in and the current {@link #getLeft() left} property.
15440     *
15441     * @param x The visual x position of this view, in pixels.
15442     */
15443    public void setX(float x) {
15444        setTranslationX(x - mLeft);
15445    }
15446
15447    /**
15448     * The visual y position of this view, in pixels. This is equivalent to the
15449     * {@link #setTranslationY(float) translationY} property plus the current
15450     * {@link #getTop() top} property.
15451     *
15452     * @return The visual y position of this view, in pixels.
15453     */
15454    @ViewDebug.ExportedProperty(category = "drawing")
15455    public float getY() {
15456        return mTop + getTranslationY();
15457    }
15458
15459    /**
15460     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
15461     * {@link #setTranslationY(float) translationY} property to be the difference between
15462     * the y value passed in and the current {@link #getTop() top} property.
15463     *
15464     * @param y The visual y position of this view, in pixels.
15465     */
15466    public void setY(float y) {
15467        setTranslationY(y - mTop);
15468    }
15469
15470    /**
15471     * The visual z position of this view, in pixels. This is equivalent to the
15472     * {@link #setTranslationZ(float) translationZ} property plus the current
15473     * {@link #getElevation() elevation} property.
15474     *
15475     * @return The visual z position of this view, in pixels.
15476     */
15477    @ViewDebug.ExportedProperty(category = "drawing")
15478    public float getZ() {
15479        return getElevation() + getTranslationZ();
15480    }
15481
15482    /**
15483     * Sets the visual z position of this view, in pixels. This is equivalent to setting the
15484     * {@link #setTranslationZ(float) translationZ} property to be the difference between
15485     * the x value passed in and the current {@link #getElevation() elevation} property.
15486     *
15487     * @param z The visual z position of this view, in pixels.
15488     */
15489    public void setZ(float z) {
15490        setTranslationZ(z - getElevation());
15491    }
15492
15493    /**
15494     * The base elevation of this view relative to its parent, in pixels.
15495     *
15496     * @return The base depth position of the view, in pixels.
15497     */
15498    @ViewDebug.ExportedProperty(category = "drawing")
15499    public float getElevation() {
15500        return mRenderNode.getElevation();
15501    }
15502
15503    /**
15504     * Sets the base elevation of this view, in pixels.
15505     *
15506     * @attr ref android.R.styleable#View_elevation
15507     */
15508    public void setElevation(float elevation) {
15509        if (elevation != getElevation()) {
15510            elevation = sanitizeFloatPropertyValue(elevation, "elevation");
15511            invalidateViewProperty(true, false);
15512            mRenderNode.setElevation(elevation);
15513            invalidateViewProperty(false, true);
15514
15515            invalidateParentIfNeededAndWasQuickRejected();
15516        }
15517    }
15518
15519    /**
15520     * The horizontal location of this view relative to its {@link #getLeft() left} position.
15521     * This position is post-layout, in addition to wherever the object's
15522     * layout placed it.
15523     *
15524     * @return The horizontal position of this view relative to its left position, in pixels.
15525     */
15526    @ViewDebug.ExportedProperty(category = "drawing")
15527    public float getTranslationX() {
15528        return mRenderNode.getTranslationX();
15529    }
15530
15531    /**
15532     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
15533     * This effectively positions the object post-layout, in addition to wherever the object's
15534     * layout placed it.
15535     *
15536     * @param translationX The horizontal position of this view relative to its left position,
15537     * in pixels.
15538     *
15539     * @attr ref android.R.styleable#View_translationX
15540     */
15541    public void setTranslationX(float translationX) {
15542        if (translationX != getTranslationX()) {
15543            invalidateViewProperty(true, false);
15544            mRenderNode.setTranslationX(translationX);
15545            invalidateViewProperty(false, true);
15546
15547            invalidateParentIfNeededAndWasQuickRejected();
15548            notifySubtreeAccessibilityStateChangedIfNeeded();
15549        }
15550    }
15551
15552    /**
15553     * The vertical location of this view relative to its {@link #getTop() top} position.
15554     * This position is post-layout, in addition to wherever the object's
15555     * layout placed it.
15556     *
15557     * @return The vertical position of this view relative to its top position,
15558     * in pixels.
15559     */
15560    @ViewDebug.ExportedProperty(category = "drawing")
15561    public float getTranslationY() {
15562        return mRenderNode.getTranslationY();
15563    }
15564
15565    /**
15566     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
15567     * This effectively positions the object post-layout, in addition to wherever the object's
15568     * layout placed it.
15569     *
15570     * @param translationY The vertical position of this view relative to its top position,
15571     * in pixels.
15572     *
15573     * @attr ref android.R.styleable#View_translationY
15574     */
15575    public void setTranslationY(float translationY) {
15576        if (translationY != getTranslationY()) {
15577            invalidateViewProperty(true, false);
15578            mRenderNode.setTranslationY(translationY);
15579            invalidateViewProperty(false, true);
15580
15581            invalidateParentIfNeededAndWasQuickRejected();
15582            notifySubtreeAccessibilityStateChangedIfNeeded();
15583        }
15584    }
15585
15586    /**
15587     * The depth location of this view relative to its {@link #getElevation() elevation}.
15588     *
15589     * @return The depth of this view relative to its elevation.
15590     */
15591    @ViewDebug.ExportedProperty(category = "drawing")
15592    public float getTranslationZ() {
15593        return mRenderNode.getTranslationZ();
15594    }
15595
15596    /**
15597     * Sets the depth location of this view relative to its {@link #getElevation() elevation}.
15598     *
15599     * @attr ref android.R.styleable#View_translationZ
15600     */
15601    public void setTranslationZ(float translationZ) {
15602        if (translationZ != getTranslationZ()) {
15603            translationZ = sanitizeFloatPropertyValue(translationZ, "translationZ");
15604            invalidateViewProperty(true, false);
15605            mRenderNode.setTranslationZ(translationZ);
15606            invalidateViewProperty(false, true);
15607
15608            invalidateParentIfNeededAndWasQuickRejected();
15609        }
15610    }
15611
15612    /** @hide */
15613    public void setAnimationMatrix(Matrix matrix) {
15614        invalidateViewProperty(true, false);
15615        mRenderNode.setAnimationMatrix(matrix);
15616        invalidateViewProperty(false, true);
15617
15618        invalidateParentIfNeededAndWasQuickRejected();
15619    }
15620
15621    /**
15622     * Returns the current StateListAnimator if exists.
15623     *
15624     * @return StateListAnimator or null if it does not exists
15625     * @see    #setStateListAnimator(android.animation.StateListAnimator)
15626     */
15627    public StateListAnimator getStateListAnimator() {
15628        return mStateListAnimator;
15629    }
15630
15631    /**
15632     * Attaches the provided StateListAnimator to this View.
15633     * <p>
15634     * Any previously attached StateListAnimator will be detached.
15635     *
15636     * @param stateListAnimator The StateListAnimator to update the view
15637     * @see android.animation.StateListAnimator
15638     */
15639    public void setStateListAnimator(StateListAnimator stateListAnimator) {
15640        if (mStateListAnimator == stateListAnimator) {
15641            return;
15642        }
15643        if (mStateListAnimator != null) {
15644            mStateListAnimator.setTarget(null);
15645        }
15646        mStateListAnimator = stateListAnimator;
15647        if (stateListAnimator != null) {
15648            stateListAnimator.setTarget(this);
15649            if (isAttachedToWindow()) {
15650                stateListAnimator.setState(getDrawableState());
15651            }
15652        }
15653    }
15654
15655    /**
15656     * Returns whether the Outline should be used to clip the contents of the View.
15657     * <p>
15658     * Note that this flag will only be respected if the View's Outline returns true from
15659     * {@link Outline#canClip()}.
15660     *
15661     * @see #setOutlineProvider(ViewOutlineProvider)
15662     * @see #setClipToOutline(boolean)
15663     */
15664    public final boolean getClipToOutline() {
15665        return mRenderNode.getClipToOutline();
15666    }
15667
15668    /**
15669     * Sets whether the View's Outline should be used to clip the contents of the View.
15670     * <p>
15671     * Only a single non-rectangular clip can be applied on a View at any time.
15672     * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float)
15673     * circular reveal} animation take priority over Outline clipping, and
15674     * child Outline clipping takes priority over Outline clipping done by a
15675     * parent.
15676     * <p>
15677     * Note that this flag will only be respected if the View's Outline returns true from
15678     * {@link Outline#canClip()}.
15679     *
15680     * @see #setOutlineProvider(ViewOutlineProvider)
15681     * @see #getClipToOutline()
15682     */
15683    public void setClipToOutline(boolean clipToOutline) {
15684        damageInParent();
15685        if (getClipToOutline() != clipToOutline) {
15686            mRenderNode.setClipToOutline(clipToOutline);
15687        }
15688    }
15689
15690    // correspond to the enum values of View_outlineProvider
15691    private static final int PROVIDER_BACKGROUND = 0;
15692    private static final int PROVIDER_NONE = 1;
15693    private static final int PROVIDER_BOUNDS = 2;
15694    private static final int PROVIDER_PADDED_BOUNDS = 3;
15695    private void setOutlineProviderFromAttribute(int providerInt) {
15696        switch (providerInt) {
15697            case PROVIDER_BACKGROUND:
15698                setOutlineProvider(ViewOutlineProvider.BACKGROUND);
15699                break;
15700            case PROVIDER_NONE:
15701                setOutlineProvider(null);
15702                break;
15703            case PROVIDER_BOUNDS:
15704                setOutlineProvider(ViewOutlineProvider.BOUNDS);
15705                break;
15706            case PROVIDER_PADDED_BOUNDS:
15707                setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS);
15708                break;
15709        }
15710    }
15711
15712    /**
15713     * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines
15714     * the shape of the shadow it casts, and enables outline clipping.
15715     * <p>
15716     * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline
15717     * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the
15718     * outline provider with this method allows this behavior to be overridden.
15719     * <p>
15720     * If the ViewOutlineProvider is null, if querying it for an outline returns false,
15721     * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast.
15722     * <p>
15723     * Only outlines that return true from {@link Outline#canClip()} may be used for clipping.
15724     *
15725     * @see #setClipToOutline(boolean)
15726     * @see #getClipToOutline()
15727     * @see #getOutlineProvider()
15728     */
15729    public void setOutlineProvider(ViewOutlineProvider provider) {
15730        mOutlineProvider = provider;
15731        invalidateOutline();
15732    }
15733
15734    /**
15735     * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline
15736     * that defines the shape of the shadow it casts, and enables outline clipping.
15737     *
15738     * @see #setOutlineProvider(ViewOutlineProvider)
15739     */
15740    public ViewOutlineProvider getOutlineProvider() {
15741        return mOutlineProvider;
15742    }
15743
15744    /**
15745     * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider}
15746     *
15747     * @see #setOutlineProvider(ViewOutlineProvider)
15748     */
15749    public void invalidateOutline() {
15750        rebuildOutline();
15751
15752        notifySubtreeAccessibilityStateChangedIfNeeded();
15753        invalidateViewProperty(false, false);
15754    }
15755
15756    /**
15757     * Internal version of {@link #invalidateOutline()} which invalidates the
15758     * outline without invalidating the view itself. This is intended to be called from
15759     * within methods in the View class itself which are the result of the view being
15760     * invalidated already. For example, when we are drawing the background of a View,
15761     * we invalidate the outline in case it changed in the meantime, but we do not
15762     * need to invalidate the view because we're already drawing the background as part
15763     * of drawing the view in response to an earlier invalidation of the view.
15764     */
15765    private void rebuildOutline() {
15766        // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow()
15767        if (mAttachInfo == null) return;
15768
15769        if (mOutlineProvider == null) {
15770            // no provider, remove outline
15771            mRenderNode.setOutline(null);
15772        } else {
15773            final Outline outline = mAttachInfo.mTmpOutline;
15774            outline.setEmpty();
15775            outline.setAlpha(1.0f);
15776
15777            mOutlineProvider.getOutline(this, outline);
15778            mRenderNode.setOutline(outline);
15779        }
15780    }
15781
15782    /**
15783     * HierarchyViewer only
15784     *
15785     * @hide
15786     */
15787    @ViewDebug.ExportedProperty(category = "drawing")
15788    public boolean hasShadow() {
15789        return mRenderNode.hasShadow();
15790    }
15791
15792    /**
15793     * Sets the color of the spot shadow that is drawn when the view has a positive Z or
15794     * elevation value.
15795     * <p>
15796     * By default the shadow color is black. Generally, this color will be opaque so the intensity
15797     * of the shadow is consistent between different views with different colors.
15798     * <p>
15799     * The opacity of the final spot shadow is a function of the shadow caster height, the
15800     * alpha channel of the outlineSpotShadowColor (typically opaque), and the
15801     * {@link android.R.attr#spotShadowAlpha} theme attribute.
15802     *
15803     * @attr ref android.R.styleable#View_outlineSpotShadowColor
15804     * @param color The color this View will cast for its elevation spot shadow.
15805     */
15806    public void setOutlineSpotShadowColor(@ColorInt int color) {
15807        if (mRenderNode.setSpotShadowColor(color)) {
15808            invalidateViewProperty(true, true);
15809        }
15810    }
15811
15812    /**
15813     * @return The shadow color set by {@link #setOutlineSpotShadowColor(int)}, or black if nothing
15814     * was set
15815     */
15816    public @ColorInt int getOutlineSpotShadowColor() {
15817        return mRenderNode.getSpotShadowColor();
15818    }
15819
15820    /**
15821     * Sets the color of the ambient shadow that is drawn when the view has a positive Z or
15822     * elevation value.
15823     * <p>
15824     * By default the shadow color is black. Generally, this color will be opaque so the intensity
15825     * of the shadow is consistent between different views with different colors.
15826     * <p>
15827     * The opacity of the final ambient shadow is a function of the shadow caster height, the
15828     * alpha channel of the outlineAmbientShadowColor (typically opaque), and the
15829     * {@link android.R.attr#ambientShadowAlpha} theme attribute.
15830     *
15831     * @attr ref android.R.styleable#View_outlineAmbientShadowColor
15832     * @param color The color this View will cast for its elevation shadow.
15833     */
15834    public void setOutlineAmbientShadowColor(@ColorInt int color) {
15835        if (mRenderNode.setAmbientShadowColor(color)) {
15836            invalidateViewProperty(true, true);
15837        }
15838    }
15839
15840    /**
15841     * @return The shadow color set by {@link #setOutlineAmbientShadowColor(int)}, or black if
15842     * nothing was set
15843     */
15844    public @ColorInt int getOutlineAmbientShadowColor() {
15845        return mRenderNode.getAmbientShadowColor();
15846    }
15847
15848
15849    /** @hide */
15850    public void setRevealClip(boolean shouldClip, float x, float y, float radius) {
15851        mRenderNode.setRevealClip(shouldClip, x, y, radius);
15852        invalidateViewProperty(false, false);
15853    }
15854
15855    /**
15856     * Hit rectangle in parent's coordinates
15857     *
15858     * @param outRect The hit rectangle of the view.
15859     */
15860    public void getHitRect(Rect outRect) {
15861        if (hasIdentityMatrix() || mAttachInfo == null) {
15862            outRect.set(mLeft, mTop, mRight, mBottom);
15863        } else {
15864            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
15865            tmpRect.set(0, 0, getWidth(), getHeight());
15866            getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect)
15867            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
15868                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
15869        }
15870    }
15871
15872    /**
15873     * Determines whether the given point, in local coordinates is inside the view.
15874     */
15875    /*package*/ final boolean pointInView(float localX, float localY) {
15876        return pointInView(localX, localY, 0);
15877    }
15878
15879    /**
15880     * Utility method to determine whether the given point, in local coordinates,
15881     * is inside the view, where the area of the view is expanded by the slop factor.
15882     * This method is called while processing touch-move events to determine if the event
15883     * is still within the view.
15884     *
15885     * @hide
15886     */
15887    public boolean pointInView(float localX, float localY, float slop) {
15888        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
15889                localY < ((mBottom - mTop) + slop);
15890    }
15891
15892    /**
15893     * When a view has focus and the user navigates away from it, the next view is searched for
15894     * starting from the rectangle filled in by this method.
15895     *
15896     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
15897     * of the view.  However, if your view maintains some idea of internal selection,
15898     * such as a cursor, or a selected row or column, you should override this method and
15899     * fill in a more specific rectangle.
15900     *
15901     * @param r The rectangle to fill in, in this view's coordinates.
15902     */
15903    public void getFocusedRect(Rect r) {
15904        getDrawingRect(r);
15905    }
15906
15907    /**
15908     * If some part of this view is not clipped by any of its parents, then
15909     * return that area in r in global (root) coordinates. To convert r to local
15910     * coordinates (without taking possible View rotations into account), offset
15911     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
15912     * If the view is completely clipped or translated out, return false.
15913     *
15914     * @param r If true is returned, r holds the global coordinates of the
15915     *        visible portion of this view.
15916     * @param globalOffset If true is returned, globalOffset holds the dx,dy
15917     *        between this view and its root. globalOffet may be null.
15918     * @return true if r is non-empty (i.e. part of the view is visible at the
15919     *         root level.
15920     */
15921    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
15922        int width = mRight - mLeft;
15923        int height = mBottom - mTop;
15924        if (width > 0 && height > 0) {
15925            r.set(0, 0, width, height);
15926            if (globalOffset != null) {
15927                globalOffset.set(-mScrollX, -mScrollY);
15928            }
15929            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
15930        }
15931        return false;
15932    }
15933
15934    public final boolean getGlobalVisibleRect(Rect r) {
15935        return getGlobalVisibleRect(r, null);
15936    }
15937
15938    public final boolean getLocalVisibleRect(Rect r) {
15939        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
15940        if (getGlobalVisibleRect(r, offset)) {
15941            r.offset(-offset.x, -offset.y); // make r local
15942            return true;
15943        }
15944        return false;
15945    }
15946
15947    /**
15948     * Offset this view's vertical location by the specified number of pixels.
15949     *
15950     * @param offset the number of pixels to offset the view by
15951     */
15952    public void offsetTopAndBottom(int offset) {
15953        if (offset != 0) {
15954            final boolean matrixIsIdentity = hasIdentityMatrix();
15955            if (matrixIsIdentity) {
15956                if (isHardwareAccelerated()) {
15957                    invalidateViewProperty(false, false);
15958                } else {
15959                    final ViewParent p = mParent;
15960                    if (p != null && mAttachInfo != null) {
15961                        final Rect r = mAttachInfo.mTmpInvalRect;
15962                        int minTop;
15963                        int maxBottom;
15964                        int yLoc;
15965                        if (offset < 0) {
15966                            minTop = mTop + offset;
15967                            maxBottom = mBottom;
15968                            yLoc = offset;
15969                        } else {
15970                            minTop = mTop;
15971                            maxBottom = mBottom + offset;
15972                            yLoc = 0;
15973                        }
15974                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
15975                        p.invalidateChild(this, r);
15976                    }
15977                }
15978            } else {
15979                invalidateViewProperty(false, false);
15980            }
15981
15982            mTop += offset;
15983            mBottom += offset;
15984            mRenderNode.offsetTopAndBottom(offset);
15985            if (isHardwareAccelerated()) {
15986                invalidateViewProperty(false, false);
15987                invalidateParentIfNeededAndWasQuickRejected();
15988            } else {
15989                if (!matrixIsIdentity) {
15990                    invalidateViewProperty(false, true);
15991                }
15992                invalidateParentIfNeeded();
15993            }
15994            notifySubtreeAccessibilityStateChangedIfNeeded();
15995        }
15996    }
15997
15998    /**
15999     * Offset this view's horizontal location by the specified amount of pixels.
16000     *
16001     * @param offset the number of pixels to offset the view by
16002     */
16003    public void offsetLeftAndRight(int offset) {
16004        if (offset != 0) {
16005            final boolean matrixIsIdentity = hasIdentityMatrix();
16006            if (matrixIsIdentity) {
16007                if (isHardwareAccelerated()) {
16008                    invalidateViewProperty(false, false);
16009                } else {
16010                    final ViewParent p = mParent;
16011                    if (p != null && mAttachInfo != null) {
16012                        final Rect r = mAttachInfo.mTmpInvalRect;
16013                        int minLeft;
16014                        int maxRight;
16015                        if (offset < 0) {
16016                            minLeft = mLeft + offset;
16017                            maxRight = mRight;
16018                        } else {
16019                            minLeft = mLeft;
16020                            maxRight = mRight + offset;
16021                        }
16022                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
16023                        p.invalidateChild(this, r);
16024                    }
16025                }
16026            } else {
16027                invalidateViewProperty(false, false);
16028            }
16029
16030            mLeft += offset;
16031            mRight += offset;
16032            mRenderNode.offsetLeftAndRight(offset);
16033            if (isHardwareAccelerated()) {
16034                invalidateViewProperty(false, false);
16035                invalidateParentIfNeededAndWasQuickRejected();
16036            } else {
16037                if (!matrixIsIdentity) {
16038                    invalidateViewProperty(false, true);
16039                }
16040                invalidateParentIfNeeded();
16041            }
16042            notifySubtreeAccessibilityStateChangedIfNeeded();
16043        }
16044    }
16045
16046    /**
16047     * Get the LayoutParams associated with this view. All views should have
16048     * layout parameters. These supply parameters to the <i>parent</i> of this
16049     * view specifying how it should be arranged. There are many subclasses of
16050     * ViewGroup.LayoutParams, and these correspond to the different subclasses
16051     * of ViewGroup that are responsible for arranging their children.
16052     *
16053     * This method may return null if this View is not attached to a parent
16054     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
16055     * was not invoked successfully. When a View is attached to a parent
16056     * ViewGroup, this method must not return null.
16057     *
16058     * @return The LayoutParams associated with this view, or null if no
16059     *         parameters have been set yet
16060     */
16061    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
16062    public ViewGroup.LayoutParams getLayoutParams() {
16063        return mLayoutParams;
16064    }
16065
16066    /**
16067     * Set the layout parameters associated with this view. These supply
16068     * parameters to the <i>parent</i> of this view specifying how it should be
16069     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
16070     * correspond to the different subclasses of ViewGroup that are responsible
16071     * for arranging their children.
16072     *
16073     * @param params The layout parameters for this view, cannot be null
16074     */
16075    public void setLayoutParams(ViewGroup.LayoutParams params) {
16076        if (params == null) {
16077            throw new NullPointerException("Layout parameters cannot be null");
16078        }
16079        mLayoutParams = params;
16080        resolveLayoutParams();
16081        if (mParent instanceof ViewGroup) {
16082            ((ViewGroup) mParent).onSetLayoutParams(this, params);
16083        }
16084        requestLayout();
16085    }
16086
16087    /**
16088     * Resolve the layout parameters depending on the resolved layout direction
16089     *
16090     * @hide
16091     */
16092    public void resolveLayoutParams() {
16093        if (mLayoutParams != null) {
16094            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
16095        }
16096    }
16097
16098    /**
16099     * Set the scrolled position of your view. This will cause a call to
16100     * {@link #onScrollChanged(int, int, int, int)} and the view will be
16101     * invalidated.
16102     * @param x the x position to scroll to
16103     * @param y the y position to scroll to
16104     */
16105    public void scrollTo(int x, int y) {
16106        if (mScrollX != x || mScrollY != y) {
16107            int oldX = mScrollX;
16108            int oldY = mScrollY;
16109            mScrollX = x;
16110            mScrollY = y;
16111            invalidateParentCaches();
16112            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
16113            if (!awakenScrollBars()) {
16114                postInvalidateOnAnimation();
16115            }
16116        }
16117    }
16118
16119    /**
16120     * Move the scrolled position of your view. This will cause a call to
16121     * {@link #onScrollChanged(int, int, int, int)} and the view will be
16122     * invalidated.
16123     * @param x the amount of pixels to scroll by horizontally
16124     * @param y the amount of pixels to scroll by vertically
16125     */
16126    public void scrollBy(int x, int y) {
16127        scrollTo(mScrollX + x, mScrollY + y);
16128    }
16129
16130    /**
16131     * <p>Trigger the scrollbars to draw. When invoked this method starts an
16132     * animation to fade the scrollbars out after a default delay. If a subclass
16133     * provides animated scrolling, the start delay should equal the duration
16134     * of the scrolling animation.</p>
16135     *
16136     * <p>The animation starts only if at least one of the scrollbars is
16137     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
16138     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
16139     * this method returns true, and false otherwise. If the animation is
16140     * started, this method calls {@link #invalidate()}; in that case the
16141     * caller should not call {@link #invalidate()}.</p>
16142     *
16143     * <p>This method should be invoked every time a subclass directly updates
16144     * the scroll parameters.</p>
16145     *
16146     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
16147     * and {@link #scrollTo(int, int)}.</p>
16148     *
16149     * @return true if the animation is played, false otherwise
16150     *
16151     * @see #awakenScrollBars(int)
16152     * @see #scrollBy(int, int)
16153     * @see #scrollTo(int, int)
16154     * @see #isHorizontalScrollBarEnabled()
16155     * @see #isVerticalScrollBarEnabled()
16156     * @see #setHorizontalScrollBarEnabled(boolean)
16157     * @see #setVerticalScrollBarEnabled(boolean)
16158     */
16159    protected boolean awakenScrollBars() {
16160        return mScrollCache != null &&
16161                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
16162    }
16163
16164    /**
16165     * Trigger the scrollbars to draw.
16166     * This method differs from awakenScrollBars() only in its default duration.
16167     * initialAwakenScrollBars() will show the scroll bars for longer than
16168     * usual to give the user more of a chance to notice them.
16169     *
16170     * @return true if the animation is played, false otherwise.
16171     */
16172    private boolean initialAwakenScrollBars() {
16173        return mScrollCache != null &&
16174                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
16175    }
16176
16177    /**
16178     * <p>
16179     * Trigger the scrollbars to draw. When invoked this method starts an
16180     * animation to fade the scrollbars out after a fixed delay. If a subclass
16181     * provides animated scrolling, the start delay should equal the duration of
16182     * the scrolling animation.
16183     * </p>
16184     *
16185     * <p>
16186     * The animation starts only if at least one of the scrollbars is enabled,
16187     * as specified by {@link #isHorizontalScrollBarEnabled()} and
16188     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
16189     * this method returns true, and false otherwise. If the animation is
16190     * started, this method calls {@link #invalidate()}; in that case the caller
16191     * should not call {@link #invalidate()}.
16192     * </p>
16193     *
16194     * <p>
16195     * This method should be invoked every time a subclass directly updates the
16196     * scroll parameters.
16197     * </p>
16198     *
16199     * @param startDelay the delay, in milliseconds, after which the animation
16200     *        should start; when the delay is 0, the animation starts
16201     *        immediately
16202     * @return true if the animation is played, false otherwise
16203     *
16204     * @see #scrollBy(int, int)
16205     * @see #scrollTo(int, int)
16206     * @see #isHorizontalScrollBarEnabled()
16207     * @see #isVerticalScrollBarEnabled()
16208     * @see #setHorizontalScrollBarEnabled(boolean)
16209     * @see #setVerticalScrollBarEnabled(boolean)
16210     */
16211    protected boolean awakenScrollBars(int startDelay) {
16212        return awakenScrollBars(startDelay, true);
16213    }
16214
16215    /**
16216     * <p>
16217     * Trigger the scrollbars to draw. When invoked this method starts an
16218     * animation to fade the scrollbars out after a fixed delay. If a subclass
16219     * provides animated scrolling, the start delay should equal the duration of
16220     * the scrolling animation.
16221     * </p>
16222     *
16223     * <p>
16224     * The animation starts only if at least one of the scrollbars is enabled,
16225     * as specified by {@link #isHorizontalScrollBarEnabled()} and
16226     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
16227     * this method returns true, and false otherwise. If the animation is
16228     * started, this method calls {@link #invalidate()} if the invalidate parameter
16229     * is set to true; in that case the caller
16230     * should not call {@link #invalidate()}.
16231     * </p>
16232     *
16233     * <p>
16234     * This method should be invoked every time a subclass directly updates the
16235     * scroll parameters.
16236     * </p>
16237     *
16238     * @param startDelay the delay, in milliseconds, after which the animation
16239     *        should start; when the delay is 0, the animation starts
16240     *        immediately
16241     *
16242     * @param invalidate Whether this method should call invalidate
16243     *
16244     * @return true if the animation is played, false otherwise
16245     *
16246     * @see #scrollBy(int, int)
16247     * @see #scrollTo(int, int)
16248     * @see #isHorizontalScrollBarEnabled()
16249     * @see #isVerticalScrollBarEnabled()
16250     * @see #setHorizontalScrollBarEnabled(boolean)
16251     * @see #setVerticalScrollBarEnabled(boolean)
16252     */
16253    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
16254        final ScrollabilityCache scrollCache = mScrollCache;
16255
16256        if (scrollCache == null || !scrollCache.fadeScrollBars) {
16257            return false;
16258        }
16259
16260        if (scrollCache.scrollBar == null) {
16261            scrollCache.scrollBar = new ScrollBarDrawable();
16262            scrollCache.scrollBar.setState(getDrawableState());
16263            scrollCache.scrollBar.setCallback(this);
16264        }
16265
16266        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
16267
16268            if (invalidate) {
16269                // Invalidate to show the scrollbars
16270                postInvalidateOnAnimation();
16271            }
16272
16273            if (scrollCache.state == ScrollabilityCache.OFF) {
16274                // FIXME: this is copied from WindowManagerService.
16275                // We should get this value from the system when it
16276                // is possible to do so.
16277                final int KEY_REPEAT_FIRST_DELAY = 750;
16278                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
16279            }
16280
16281            // Tell mScrollCache when we should start fading. This may
16282            // extend the fade start time if one was already scheduled
16283            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
16284            scrollCache.fadeStartTime = fadeStartTime;
16285            scrollCache.state = ScrollabilityCache.ON;
16286
16287            // Schedule our fader to run, unscheduling any old ones first
16288            if (mAttachInfo != null) {
16289                mAttachInfo.mHandler.removeCallbacks(scrollCache);
16290                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
16291            }
16292
16293            return true;
16294        }
16295
16296        return false;
16297    }
16298
16299    /**
16300     * Do not invalidate views which are not visible and which are not running an animation. They
16301     * will not get drawn and they should not set dirty flags as if they will be drawn
16302     */
16303    private boolean skipInvalidate() {
16304        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
16305                (!(mParent instanceof ViewGroup) ||
16306                        !((ViewGroup) mParent).isViewTransitioning(this));
16307    }
16308
16309    /**
16310     * Mark the area defined by dirty as needing to be drawn. If the view is
16311     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
16312     * point in the future.
16313     * <p>
16314     * This must be called from a UI thread. To call from a non-UI thread, call
16315     * {@link #postInvalidate()}.
16316     * <p>
16317     * <b>WARNING:</b> In API 19 and below, this method may be destructive to
16318     * {@code dirty}.
16319     *
16320     * @param dirty the rectangle representing the bounds of the dirty region
16321     *
16322     * @deprecated The switch to hardware accelerated rendering in API 14 reduced
16323     * the importance of the dirty rectangle. In API 21 the given rectangle is
16324     * ignored entirely in favor of an internally-calculated area instead.
16325     * Because of this, clients are encouraged to just call {@link #invalidate()}.
16326     */
16327    @Deprecated
16328    public void invalidate(Rect dirty) {
16329        final int scrollX = mScrollX;
16330        final int scrollY = mScrollY;
16331        invalidateInternal(dirty.left - scrollX, dirty.top - scrollY,
16332                dirty.right - scrollX, dirty.bottom - scrollY, true, false);
16333    }
16334
16335    /**
16336     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The
16337     * coordinates of the dirty rect are relative to the view. If the view is
16338     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
16339     * point in the future.
16340     * <p>
16341     * This must be called from a UI thread. To call from a non-UI thread, call
16342     * {@link #postInvalidate()}.
16343     *
16344     * @param l the left position of the dirty region
16345     * @param t the top position of the dirty region
16346     * @param r the right position of the dirty region
16347     * @param b the bottom position of the dirty region
16348     *
16349     * @deprecated The switch to hardware accelerated rendering in API 14 reduced
16350     * the importance of the dirty rectangle. In API 21 the given rectangle is
16351     * ignored entirely in favor of an internally-calculated area instead.
16352     * Because of this, clients are encouraged to just call {@link #invalidate()}.
16353     */
16354    @Deprecated
16355    public void invalidate(int l, int t, int r, int b) {
16356        final int scrollX = mScrollX;
16357        final int scrollY = mScrollY;
16358        invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false);
16359    }
16360
16361    /**
16362     * Invalidate the whole view. If the view is visible,
16363     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
16364     * the future.
16365     * <p>
16366     * This must be called from a UI thread. To call from a non-UI thread, call
16367     * {@link #postInvalidate()}.
16368     */
16369    public void invalidate() {
16370        invalidate(true);
16371    }
16372
16373    /**
16374     * This is where the invalidate() work actually happens. A full invalidate()
16375     * causes the drawing cache to be invalidated, but this function can be
16376     * called with invalidateCache set to false to skip that invalidation step
16377     * for cases that do not need it (for example, a component that remains at
16378     * the same dimensions with the same content).
16379     *
16380     * @param invalidateCache Whether the drawing cache for this view should be
16381     *            invalidated as well. This is usually true for a full
16382     *            invalidate, but may be set to false if the View's contents or
16383     *            dimensions have not changed.
16384     * @hide
16385     */
16386    public void invalidate(boolean invalidateCache) {
16387        invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
16388    }
16389
16390    void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
16391            boolean fullInvalidate) {
16392        if (mGhostView != null) {
16393            mGhostView.invalidate(true);
16394            return;
16395        }
16396
16397        if (skipInvalidate()) {
16398            return;
16399        }
16400
16401        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)
16402                || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID)
16403                || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED
16404                || (fullInvalidate && isOpaque() != mLastIsOpaque)) {
16405            if (fullInvalidate) {
16406                mLastIsOpaque = isOpaque();
16407                mPrivateFlags &= ~PFLAG_DRAWN;
16408            }
16409
16410            mPrivateFlags |= PFLAG_DIRTY;
16411
16412            if (invalidateCache) {
16413                mPrivateFlags |= PFLAG_INVALIDATED;
16414                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
16415            }
16416
16417            // Propagate the damage rectangle to the parent view.
16418            final AttachInfo ai = mAttachInfo;
16419            final ViewParent p = mParent;
16420            if (p != null && ai != null && l < r && t < b) {
16421                final Rect damage = ai.mTmpInvalRect;
16422                damage.set(l, t, r, b);
16423                p.invalidateChild(this, damage);
16424            }
16425
16426            // Damage the entire projection receiver, if necessary.
16427            if (mBackground != null && mBackground.isProjected()) {
16428                final View receiver = getProjectionReceiver();
16429                if (receiver != null) {
16430                    receiver.damageInParent();
16431                }
16432            }
16433        }
16434    }
16435
16436    /**
16437     * @return this view's projection receiver, or {@code null} if none exists
16438     */
16439    private View getProjectionReceiver() {
16440        ViewParent p = getParent();
16441        while (p != null && p instanceof View) {
16442            final View v = (View) p;
16443            if (v.isProjectionReceiver()) {
16444                return v;
16445            }
16446            p = p.getParent();
16447        }
16448
16449        return null;
16450    }
16451
16452    /**
16453     * @return whether the view is a projection receiver
16454     */
16455    private boolean isProjectionReceiver() {
16456        return mBackground != null;
16457    }
16458
16459    /**
16460     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
16461     * set any flags or handle all of the cases handled by the default invalidation methods.
16462     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
16463     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
16464     * walk up the hierarchy, transforming the dirty rect as necessary.
16465     *
16466     * The method also handles normal invalidation logic if display list properties are not
16467     * being used in this view. The invalidateParent and forceRedraw flags are used by that
16468     * backup approach, to handle these cases used in the various property-setting methods.
16469     *
16470     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
16471     * are not being used in this view
16472     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
16473     * list properties are not being used in this view
16474     */
16475    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
16476        if (!isHardwareAccelerated()
16477                || !mRenderNode.isValid()
16478                || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) {
16479            if (invalidateParent) {
16480                invalidateParentCaches();
16481            }
16482            if (forceRedraw) {
16483                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
16484            }
16485            invalidate(false);
16486        } else {
16487            damageInParent();
16488        }
16489    }
16490
16491    /**
16492     * Tells the parent view to damage this view's bounds.
16493     *
16494     * @hide
16495     */
16496    protected void damageInParent() {
16497        if (mParent != null && mAttachInfo != null) {
16498            mParent.onDescendantInvalidated(this, this);
16499        }
16500    }
16501
16502    /**
16503     * Utility method to transform a given Rect by the current matrix of this view.
16504     */
16505    void transformRect(final Rect rect) {
16506        if (!getMatrix().isIdentity()) {
16507            RectF boundingRect = mAttachInfo.mTmpTransformRect;
16508            boundingRect.set(rect);
16509            getMatrix().mapRect(boundingRect);
16510            rect.set((int) Math.floor(boundingRect.left),
16511                    (int) Math.floor(boundingRect.top),
16512                    (int) Math.ceil(boundingRect.right),
16513                    (int) Math.ceil(boundingRect.bottom));
16514        }
16515    }
16516
16517    /**
16518     * Used to indicate that the parent of this view should clear its caches. This functionality
16519     * is used to force the parent to rebuild its display list (when hardware-accelerated),
16520     * which is necessary when various parent-managed properties of the view change, such as
16521     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
16522     * clears the parent caches and does not causes an invalidate event.
16523     *
16524     * @hide
16525     */
16526    protected void invalidateParentCaches() {
16527        if (mParent instanceof View) {
16528            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
16529        }
16530    }
16531
16532    /**
16533     * Used to indicate that the parent of this view should be invalidated. This functionality
16534     * is used to force the parent to rebuild its display list (when hardware-accelerated),
16535     * which is necessary when various parent-managed properties of the view change, such as
16536     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
16537     * an invalidation event to the parent.
16538     *
16539     * @hide
16540     */
16541    protected void invalidateParentIfNeeded() {
16542        if (isHardwareAccelerated() && mParent instanceof View) {
16543            ((View) mParent).invalidate(true);
16544        }
16545    }
16546
16547    /**
16548     * @hide
16549     */
16550    protected void invalidateParentIfNeededAndWasQuickRejected() {
16551        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) {
16552            // View was rejected last time it was drawn by its parent; this may have changed
16553            invalidateParentIfNeeded();
16554        }
16555    }
16556
16557    /**
16558     * Indicates whether this View is opaque. An opaque View guarantees that it will
16559     * draw all the pixels overlapping its bounds using a fully opaque color.
16560     *
16561     * Subclasses of View should override this method whenever possible to indicate
16562     * whether an instance is opaque. Opaque Views are treated in a special way by
16563     * the View hierarchy, possibly allowing it to perform optimizations during
16564     * invalidate/draw passes.
16565     *
16566     * @return True if this View is guaranteed to be fully opaque, false otherwise.
16567     */
16568    @ViewDebug.ExportedProperty(category = "drawing")
16569    public boolean isOpaque() {
16570        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
16571                getFinalAlpha() >= 1.0f;
16572    }
16573
16574    /**
16575     * @hide
16576     */
16577    protected void computeOpaqueFlags() {
16578        // Opaque if:
16579        //   - Has a background
16580        //   - Background is opaque
16581        //   - Doesn't have scrollbars or scrollbars overlay
16582
16583        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
16584            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
16585        } else {
16586            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
16587        }
16588
16589        final int flags = mViewFlags;
16590        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
16591                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
16592                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
16593            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
16594        } else {
16595            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
16596        }
16597    }
16598
16599    /**
16600     * @hide
16601     */
16602    protected boolean hasOpaqueScrollbars() {
16603        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
16604    }
16605
16606    /**
16607     * @return A handler associated with the thread running the View. This
16608     * handler can be used to pump events in the UI events queue.
16609     */
16610    public Handler getHandler() {
16611        final AttachInfo attachInfo = mAttachInfo;
16612        if (attachInfo != null) {
16613            return attachInfo.mHandler;
16614        }
16615        return null;
16616    }
16617
16618    /**
16619     * Returns the queue of runnable for this view.
16620     *
16621     * @return the queue of runnables for this view
16622     */
16623    private HandlerActionQueue getRunQueue() {
16624        if (mRunQueue == null) {
16625            mRunQueue = new HandlerActionQueue();
16626        }
16627        return mRunQueue;
16628    }
16629
16630    /**
16631     * Gets the view root associated with the View.
16632     * @return The view root, or null if none.
16633     * @hide
16634     */
16635    public ViewRootImpl getViewRootImpl() {
16636        if (mAttachInfo != null) {
16637            return mAttachInfo.mViewRootImpl;
16638        }
16639        return null;
16640    }
16641
16642    /**
16643     * @hide
16644     */
16645    public ThreadedRenderer getThreadedRenderer() {
16646        return mAttachInfo != null ? mAttachInfo.mThreadedRenderer : null;
16647    }
16648
16649    /**
16650     * <p>Causes the Runnable to be added to the message queue.
16651     * The runnable will be run on the user interface thread.</p>
16652     *
16653     * @param action The Runnable that will be executed.
16654     *
16655     * @return Returns true if the Runnable was successfully placed in to the
16656     *         message queue.  Returns false on failure, usually because the
16657     *         looper processing the message queue is exiting.
16658     *
16659     * @see #postDelayed
16660     * @see #removeCallbacks
16661     */
16662    public boolean post(Runnable action) {
16663        final AttachInfo attachInfo = mAttachInfo;
16664        if (attachInfo != null) {
16665            return attachInfo.mHandler.post(action);
16666        }
16667
16668        // Postpone the runnable until we know on which thread it needs to run.
16669        // Assume that the runnable will be successfully placed after attach.
16670        getRunQueue().post(action);
16671        return true;
16672    }
16673
16674    /**
16675     * <p>Causes the Runnable to be added to the message queue, to be run
16676     * after the specified amount of time elapses.
16677     * The runnable will be run on the user interface thread.</p>
16678     *
16679     * @param action The Runnable that will be executed.
16680     * @param delayMillis The delay (in milliseconds) until the Runnable
16681     *        will be executed.
16682     *
16683     * @return true if the Runnable was successfully placed in to the
16684     *         message queue.  Returns false on failure, usually because the
16685     *         looper processing the message queue is exiting.  Note that a
16686     *         result of true does not mean the Runnable will be processed --
16687     *         if the looper is quit before the delivery time of the message
16688     *         occurs then the message will be dropped.
16689     *
16690     * @see #post
16691     * @see #removeCallbacks
16692     */
16693    public boolean postDelayed(Runnable action, long delayMillis) {
16694        final AttachInfo attachInfo = mAttachInfo;
16695        if (attachInfo != null) {
16696            return attachInfo.mHandler.postDelayed(action, delayMillis);
16697        }
16698
16699        // Postpone the runnable until we know on which thread it needs to run.
16700        // Assume that the runnable will be successfully placed after attach.
16701        getRunQueue().postDelayed(action, delayMillis);
16702        return true;
16703    }
16704
16705    /**
16706     * <p>Causes the Runnable to execute on the next animation time step.
16707     * The runnable will be run on the user interface thread.</p>
16708     *
16709     * @param action The Runnable that will be executed.
16710     *
16711     * @see #postOnAnimationDelayed
16712     * @see #removeCallbacks
16713     */
16714    public void postOnAnimation(Runnable action) {
16715        final AttachInfo attachInfo = mAttachInfo;
16716        if (attachInfo != null) {
16717            attachInfo.mViewRootImpl.mChoreographer.postCallback(
16718                    Choreographer.CALLBACK_ANIMATION, action, null);
16719        } else {
16720            // Postpone the runnable until we know
16721            // on which thread it needs to run.
16722            getRunQueue().post(action);
16723        }
16724    }
16725
16726    /**
16727     * <p>Causes the Runnable to execute on the next animation time step,
16728     * after the specified amount of time elapses.
16729     * The runnable will be run on the user interface thread.</p>
16730     *
16731     * @param action The Runnable that will be executed.
16732     * @param delayMillis The delay (in milliseconds) until the Runnable
16733     *        will be executed.
16734     *
16735     * @see #postOnAnimation
16736     * @see #removeCallbacks
16737     */
16738    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
16739        final AttachInfo attachInfo = mAttachInfo;
16740        if (attachInfo != null) {
16741            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
16742                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
16743        } else {
16744            // Postpone the runnable until we know
16745            // on which thread it needs to run.
16746            getRunQueue().postDelayed(action, delayMillis);
16747        }
16748    }
16749
16750    /**
16751     * <p>Removes the specified Runnable from the message queue.</p>
16752     *
16753     * @param action The Runnable to remove from the message handling queue
16754     *
16755     * @return true if this view could ask the Handler to remove the Runnable,
16756     *         false otherwise. When the returned value is true, the Runnable
16757     *         may or may not have been actually removed from the message queue
16758     *         (for instance, if the Runnable was not in the queue already.)
16759     *
16760     * @see #post
16761     * @see #postDelayed
16762     * @see #postOnAnimation
16763     * @see #postOnAnimationDelayed
16764     */
16765    public boolean removeCallbacks(Runnable action) {
16766        if (action != null) {
16767            final AttachInfo attachInfo = mAttachInfo;
16768            if (attachInfo != null) {
16769                attachInfo.mHandler.removeCallbacks(action);
16770                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
16771                        Choreographer.CALLBACK_ANIMATION, action, null);
16772            }
16773            getRunQueue().removeCallbacks(action);
16774        }
16775        return true;
16776    }
16777
16778    /**
16779     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
16780     * Use this to invalidate the View from a non-UI thread.</p>
16781     *
16782     * <p>This method can be invoked from outside of the UI thread
16783     * only when this View is attached to a window.</p>
16784     *
16785     * @see #invalidate()
16786     * @see #postInvalidateDelayed(long)
16787     */
16788    public void postInvalidate() {
16789        postInvalidateDelayed(0);
16790    }
16791
16792    /**
16793     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
16794     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
16795     *
16796     * <p>This method can be invoked from outside of the UI thread
16797     * only when this View is attached to a window.</p>
16798     *
16799     * @param left The left coordinate of the rectangle to invalidate.
16800     * @param top The top coordinate of the rectangle to invalidate.
16801     * @param right The right coordinate of the rectangle to invalidate.
16802     * @param bottom The bottom coordinate of the rectangle to invalidate.
16803     *
16804     * @see #invalidate(int, int, int, int)
16805     * @see #invalidate(Rect)
16806     * @see #postInvalidateDelayed(long, int, int, int, int)
16807     */
16808    public void postInvalidate(int left, int top, int right, int bottom) {
16809        postInvalidateDelayed(0, left, top, right, bottom);
16810    }
16811
16812    /**
16813     * <p>Cause an invalidate to happen on a subsequent cycle through the event
16814     * loop. Waits for the specified amount of time.</p>
16815     *
16816     * <p>This method can be invoked from outside of the UI thread
16817     * only when this View is attached to a window.</p>
16818     *
16819     * @param delayMilliseconds the duration in milliseconds to delay the
16820     *         invalidation by
16821     *
16822     * @see #invalidate()
16823     * @see #postInvalidate()
16824     */
16825    public void postInvalidateDelayed(long delayMilliseconds) {
16826        // We try only with the AttachInfo because there's no point in invalidating
16827        // if we are not attached to our window
16828        final AttachInfo attachInfo = mAttachInfo;
16829        if (attachInfo != null) {
16830            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
16831        }
16832    }
16833
16834    /**
16835     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
16836     * through the event loop. Waits for the specified amount of time.</p>
16837     *
16838     * <p>This method can be invoked from outside of the UI thread
16839     * only when this View is attached to a window.</p>
16840     *
16841     * @param delayMilliseconds the duration in milliseconds to delay the
16842     *         invalidation by
16843     * @param left The left coordinate of the rectangle to invalidate.
16844     * @param top The top coordinate of the rectangle to invalidate.
16845     * @param right The right coordinate of the rectangle to invalidate.
16846     * @param bottom The bottom coordinate of the rectangle to invalidate.
16847     *
16848     * @see #invalidate(int, int, int, int)
16849     * @see #invalidate(Rect)
16850     * @see #postInvalidate(int, int, int, int)
16851     */
16852    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
16853            int right, int bottom) {
16854
16855        // We try only with the AttachInfo because there's no point in invalidating
16856        // if we are not attached to our window
16857        final AttachInfo attachInfo = mAttachInfo;
16858        if (attachInfo != null) {
16859            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
16860            info.target = this;
16861            info.left = left;
16862            info.top = top;
16863            info.right = right;
16864            info.bottom = bottom;
16865
16866            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
16867        }
16868    }
16869
16870    /**
16871     * <p>Cause an invalidate to happen on the next animation time step, typically the
16872     * next display frame.</p>
16873     *
16874     * <p>This method can be invoked from outside of the UI thread
16875     * only when this View is attached to a window.</p>
16876     *
16877     * @see #invalidate()
16878     */
16879    public void postInvalidateOnAnimation() {
16880        // We try only with the AttachInfo because there's no point in invalidating
16881        // if we are not attached to our window
16882        final AttachInfo attachInfo = mAttachInfo;
16883        if (attachInfo != null) {
16884            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
16885        }
16886    }
16887
16888    /**
16889     * <p>Cause an invalidate of the specified area to happen on the next animation
16890     * time step, typically the next display frame.</p>
16891     *
16892     * <p>This method can be invoked from outside of the UI thread
16893     * only when this View is attached to a window.</p>
16894     *
16895     * @param left The left coordinate of the rectangle to invalidate.
16896     * @param top The top coordinate of the rectangle to invalidate.
16897     * @param right The right coordinate of the rectangle to invalidate.
16898     * @param bottom The bottom coordinate of the rectangle to invalidate.
16899     *
16900     * @see #invalidate(int, int, int, int)
16901     * @see #invalidate(Rect)
16902     */
16903    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
16904        // We try only with the AttachInfo because there's no point in invalidating
16905        // if we are not attached to our window
16906        final AttachInfo attachInfo = mAttachInfo;
16907        if (attachInfo != null) {
16908            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
16909            info.target = this;
16910            info.left = left;
16911            info.top = top;
16912            info.right = right;
16913            info.bottom = bottom;
16914
16915            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
16916        }
16917    }
16918
16919    /**
16920     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
16921     * This event is sent at most once every
16922     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
16923     */
16924    private void postSendViewScrolledAccessibilityEventCallback(int dx, int dy) {
16925        if (mSendViewScrolledAccessibilityEvent == null) {
16926            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
16927        }
16928        mSendViewScrolledAccessibilityEvent.post(dx, dy);
16929    }
16930
16931    /**
16932     * Called by a parent to request that a child update its values for mScrollX
16933     * and mScrollY if necessary. This will typically be done if the child is
16934     * animating a scroll using a {@link android.widget.Scroller Scroller}
16935     * object.
16936     */
16937    public void computeScroll() {
16938    }
16939
16940    /**
16941     * <p>Indicate whether the horizontal edges are faded when the view is
16942     * scrolled horizontally.</p>
16943     *
16944     * @return true if the horizontal edges should are faded on scroll, false
16945     *         otherwise
16946     *
16947     * @see #setHorizontalFadingEdgeEnabled(boolean)
16948     *
16949     * @attr ref android.R.styleable#View_requiresFadingEdge
16950     */
16951    public boolean isHorizontalFadingEdgeEnabled() {
16952        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
16953    }
16954
16955    /**
16956     * <p>Define whether the horizontal edges should be faded when this view
16957     * is scrolled horizontally.</p>
16958     *
16959     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
16960     *                                    be faded when the view is scrolled
16961     *                                    horizontally
16962     *
16963     * @see #isHorizontalFadingEdgeEnabled()
16964     *
16965     * @attr ref android.R.styleable#View_requiresFadingEdge
16966     */
16967    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
16968        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
16969            if (horizontalFadingEdgeEnabled) {
16970                initScrollCache();
16971            }
16972
16973            mViewFlags ^= FADING_EDGE_HORIZONTAL;
16974        }
16975    }
16976
16977    /**
16978     * <p>Indicate whether the vertical edges are faded when the view is
16979     * scrolled horizontally.</p>
16980     *
16981     * @return true if the vertical edges should are faded on scroll, false
16982     *         otherwise
16983     *
16984     * @see #setVerticalFadingEdgeEnabled(boolean)
16985     *
16986     * @attr ref android.R.styleable#View_requiresFadingEdge
16987     */
16988    public boolean isVerticalFadingEdgeEnabled() {
16989        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
16990    }
16991
16992    /**
16993     * <p>Define whether the vertical edges should be faded when this view
16994     * is scrolled vertically.</p>
16995     *
16996     * @param verticalFadingEdgeEnabled true if the vertical edges should
16997     *                                  be faded when the view is scrolled
16998     *                                  vertically
16999     *
17000     * @see #isVerticalFadingEdgeEnabled()
17001     *
17002     * @attr ref android.R.styleable#View_requiresFadingEdge
17003     */
17004    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
17005        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
17006            if (verticalFadingEdgeEnabled) {
17007                initScrollCache();
17008            }
17009
17010            mViewFlags ^= FADING_EDGE_VERTICAL;
17011        }
17012    }
17013
17014    /**
17015     * Returns the strength, or intensity, of the top faded edge. The strength is
17016     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
17017     * returns 0.0 or 1.0 but no value in between.
17018     *
17019     * Subclasses should override this method to provide a smoother fade transition
17020     * when scrolling occurs.
17021     *
17022     * @return the intensity of the top fade as a float between 0.0f and 1.0f
17023     */
17024    protected float getTopFadingEdgeStrength() {
17025        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
17026    }
17027
17028    /**
17029     * Returns the strength, or intensity, of the bottom faded edge. The strength is
17030     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
17031     * returns 0.0 or 1.0 but no value in between.
17032     *
17033     * Subclasses should override this method to provide a smoother fade transition
17034     * when scrolling occurs.
17035     *
17036     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
17037     */
17038    protected float getBottomFadingEdgeStrength() {
17039        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
17040                computeVerticalScrollRange() ? 1.0f : 0.0f;
17041    }
17042
17043    /**
17044     * Returns the strength, or intensity, of the left faded edge. The strength is
17045     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
17046     * returns 0.0 or 1.0 but no value in between.
17047     *
17048     * Subclasses should override this method to provide a smoother fade transition
17049     * when scrolling occurs.
17050     *
17051     * @return the intensity of the left fade as a float between 0.0f and 1.0f
17052     */
17053    protected float getLeftFadingEdgeStrength() {
17054        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
17055    }
17056
17057    /**
17058     * Returns the strength, or intensity, of the right faded edge. The strength is
17059     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
17060     * returns 0.0 or 1.0 but no value in between.
17061     *
17062     * Subclasses should override this method to provide a smoother fade transition
17063     * when scrolling occurs.
17064     *
17065     * @return the intensity of the right fade as a float between 0.0f and 1.0f
17066     */
17067    protected float getRightFadingEdgeStrength() {
17068        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
17069                computeHorizontalScrollRange() ? 1.0f : 0.0f;
17070    }
17071
17072    /**
17073     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
17074     * scrollbar is not drawn by default.</p>
17075     *
17076     * @return true if the horizontal scrollbar should be painted, false
17077     *         otherwise
17078     *
17079     * @see #setHorizontalScrollBarEnabled(boolean)
17080     */
17081    public boolean isHorizontalScrollBarEnabled() {
17082        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
17083    }
17084
17085    /**
17086     * <p>Define whether the horizontal scrollbar should be drawn or not. The
17087     * scrollbar is not drawn by default.</p>
17088     *
17089     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
17090     *                                   be painted
17091     *
17092     * @see #isHorizontalScrollBarEnabled()
17093     */
17094    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
17095        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
17096            mViewFlags ^= SCROLLBARS_HORIZONTAL;
17097            computeOpaqueFlags();
17098            resolvePadding();
17099        }
17100    }
17101
17102    /**
17103     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
17104     * scrollbar is not drawn by default.</p>
17105     *
17106     * @return true if the vertical scrollbar should be painted, false
17107     *         otherwise
17108     *
17109     * @see #setVerticalScrollBarEnabled(boolean)
17110     */
17111    public boolean isVerticalScrollBarEnabled() {
17112        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
17113    }
17114
17115    /**
17116     * <p>Define whether the vertical scrollbar should be drawn or not. The
17117     * scrollbar is not drawn by default.</p>
17118     *
17119     * @param verticalScrollBarEnabled true if the vertical scrollbar should
17120     *                                 be painted
17121     *
17122     * @see #isVerticalScrollBarEnabled()
17123     */
17124    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
17125        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
17126            mViewFlags ^= SCROLLBARS_VERTICAL;
17127            computeOpaqueFlags();
17128            resolvePadding();
17129        }
17130    }
17131
17132    /**
17133     * @hide
17134     */
17135    protected void recomputePadding() {
17136        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
17137    }
17138
17139    /**
17140     * Define whether scrollbars will fade when the view is not scrolling.
17141     *
17142     * @param fadeScrollbars whether to enable fading
17143     *
17144     * @attr ref android.R.styleable#View_fadeScrollbars
17145     */
17146    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
17147        initScrollCache();
17148        final ScrollabilityCache scrollabilityCache = mScrollCache;
17149        scrollabilityCache.fadeScrollBars = fadeScrollbars;
17150        if (fadeScrollbars) {
17151            scrollabilityCache.state = ScrollabilityCache.OFF;
17152        } else {
17153            scrollabilityCache.state = ScrollabilityCache.ON;
17154        }
17155    }
17156
17157    /**
17158     *
17159     * Returns true if scrollbars will fade when this view is not scrolling
17160     *
17161     * @return true if scrollbar fading is enabled
17162     *
17163     * @attr ref android.R.styleable#View_fadeScrollbars
17164     */
17165    public boolean isScrollbarFadingEnabled() {
17166        return mScrollCache != null && mScrollCache.fadeScrollBars;
17167    }
17168
17169    /**
17170     *
17171     * Returns the delay before scrollbars fade.
17172     *
17173     * @return the delay before scrollbars fade
17174     *
17175     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
17176     */
17177    public int getScrollBarDefaultDelayBeforeFade() {
17178        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
17179                mScrollCache.scrollBarDefaultDelayBeforeFade;
17180    }
17181
17182    /**
17183     * Define the delay before scrollbars fade.
17184     *
17185     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
17186     *
17187     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
17188     */
17189    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
17190        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
17191    }
17192
17193    /**
17194     *
17195     * Returns the scrollbar fade duration.
17196     *
17197     * @return the scrollbar fade duration, in milliseconds
17198     *
17199     * @attr ref android.R.styleable#View_scrollbarFadeDuration
17200     */
17201    public int getScrollBarFadeDuration() {
17202        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
17203                mScrollCache.scrollBarFadeDuration;
17204    }
17205
17206    /**
17207     * Define the scrollbar fade duration.
17208     *
17209     * @param scrollBarFadeDuration - the scrollbar fade duration, in milliseconds
17210     *
17211     * @attr ref android.R.styleable#View_scrollbarFadeDuration
17212     */
17213    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
17214        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
17215    }
17216
17217    /**
17218     *
17219     * Returns the scrollbar size.
17220     *
17221     * @return the scrollbar size
17222     *
17223     * @attr ref android.R.styleable#View_scrollbarSize
17224     */
17225    public int getScrollBarSize() {
17226        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
17227                mScrollCache.scrollBarSize;
17228    }
17229
17230    /**
17231     * Define the scrollbar size.
17232     *
17233     * @param scrollBarSize - the scrollbar size
17234     *
17235     * @attr ref android.R.styleable#View_scrollbarSize
17236     */
17237    public void setScrollBarSize(int scrollBarSize) {
17238        getScrollCache().scrollBarSize = scrollBarSize;
17239    }
17240
17241    /**
17242     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
17243     * inset. When inset, they add to the padding of the view. And the scrollbars
17244     * can be drawn inside the padding area or on the edge of the view. For example,
17245     * if a view has a background drawable and you want to draw the scrollbars
17246     * inside the padding specified by the drawable, you can use
17247     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
17248     * appear at the edge of the view, ignoring the padding, then you can use
17249     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
17250     * @param style the style of the scrollbars. Should be one of
17251     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
17252     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
17253     * @see #SCROLLBARS_INSIDE_OVERLAY
17254     * @see #SCROLLBARS_INSIDE_INSET
17255     * @see #SCROLLBARS_OUTSIDE_OVERLAY
17256     * @see #SCROLLBARS_OUTSIDE_INSET
17257     *
17258     * @attr ref android.R.styleable#View_scrollbarStyle
17259     */
17260    public void setScrollBarStyle(@ScrollBarStyle int style) {
17261        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
17262            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
17263            computeOpaqueFlags();
17264            resolvePadding();
17265        }
17266    }
17267
17268    /**
17269     * <p>Returns the current scrollbar style.</p>
17270     * @return the current scrollbar style
17271     * @see #SCROLLBARS_INSIDE_OVERLAY
17272     * @see #SCROLLBARS_INSIDE_INSET
17273     * @see #SCROLLBARS_OUTSIDE_OVERLAY
17274     * @see #SCROLLBARS_OUTSIDE_INSET
17275     *
17276     * @attr ref android.R.styleable#View_scrollbarStyle
17277     */
17278    @ViewDebug.ExportedProperty(mapping = {
17279            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
17280            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
17281            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
17282            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
17283    })
17284    @ScrollBarStyle
17285    public int getScrollBarStyle() {
17286        return mViewFlags & SCROLLBARS_STYLE_MASK;
17287    }
17288
17289    /**
17290     * <p>Compute the horizontal range that the horizontal scrollbar
17291     * represents.</p>
17292     *
17293     * <p>The range is expressed in arbitrary units that must be the same as the
17294     * units used by {@link #computeHorizontalScrollExtent()} and
17295     * {@link #computeHorizontalScrollOffset()}.</p>
17296     *
17297     * <p>The default range is the drawing width of this view.</p>
17298     *
17299     * @return the total horizontal range represented by the horizontal
17300     *         scrollbar
17301     *
17302     * @see #computeHorizontalScrollExtent()
17303     * @see #computeHorizontalScrollOffset()
17304     * @see android.widget.ScrollBarDrawable
17305     */
17306    protected int computeHorizontalScrollRange() {
17307        return getWidth();
17308    }
17309
17310    /**
17311     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
17312     * within the horizontal range. This value is used to compute the position
17313     * of the thumb within the scrollbar's track.</p>
17314     *
17315     * <p>The range is expressed in arbitrary units that must be the same as the
17316     * units used by {@link #computeHorizontalScrollRange()} and
17317     * {@link #computeHorizontalScrollExtent()}.</p>
17318     *
17319     * <p>The default offset is the scroll offset of this view.</p>
17320     *
17321     * @return the horizontal offset of the scrollbar's thumb
17322     *
17323     * @see #computeHorizontalScrollRange()
17324     * @see #computeHorizontalScrollExtent()
17325     * @see android.widget.ScrollBarDrawable
17326     */
17327    protected int computeHorizontalScrollOffset() {
17328        return mScrollX;
17329    }
17330
17331    /**
17332     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
17333     * within the horizontal range. This value is used to compute the length
17334     * of the thumb within the scrollbar's track.</p>
17335     *
17336     * <p>The range is expressed in arbitrary units that must be the same as the
17337     * units used by {@link #computeHorizontalScrollRange()} and
17338     * {@link #computeHorizontalScrollOffset()}.</p>
17339     *
17340     * <p>The default extent is the drawing width of this view.</p>
17341     *
17342     * @return the horizontal extent of the scrollbar's thumb
17343     *
17344     * @see #computeHorizontalScrollRange()
17345     * @see #computeHorizontalScrollOffset()
17346     * @see android.widget.ScrollBarDrawable
17347     */
17348    protected int computeHorizontalScrollExtent() {
17349        return getWidth();
17350    }
17351
17352    /**
17353     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
17354     *
17355     * <p>The range is expressed in arbitrary units that must be the same as the
17356     * units used by {@link #computeVerticalScrollExtent()} and
17357     * {@link #computeVerticalScrollOffset()}.</p>
17358     *
17359     * @return the total vertical range represented by the vertical scrollbar
17360     *
17361     * <p>The default range is the drawing height of this view.</p>
17362     *
17363     * @see #computeVerticalScrollExtent()
17364     * @see #computeVerticalScrollOffset()
17365     * @see android.widget.ScrollBarDrawable
17366     */
17367    protected int computeVerticalScrollRange() {
17368        return getHeight();
17369    }
17370
17371    /**
17372     * <p>Compute the vertical offset of the vertical scrollbar's thumb
17373     * within the horizontal range. This value is used to compute the position
17374     * of the thumb within the scrollbar's track.</p>
17375     *
17376     * <p>The range is expressed in arbitrary units that must be the same as the
17377     * units used by {@link #computeVerticalScrollRange()} and
17378     * {@link #computeVerticalScrollExtent()}.</p>
17379     *
17380     * <p>The default offset is the scroll offset of this view.</p>
17381     *
17382     * @return the vertical offset of the scrollbar's thumb
17383     *
17384     * @see #computeVerticalScrollRange()
17385     * @see #computeVerticalScrollExtent()
17386     * @see android.widget.ScrollBarDrawable
17387     */
17388    protected int computeVerticalScrollOffset() {
17389        return mScrollY;
17390    }
17391
17392    /**
17393     * <p>Compute the vertical extent of the vertical scrollbar's thumb
17394     * within the vertical range. This value is used to compute the length
17395     * of the thumb within the scrollbar's track.</p>
17396     *
17397     * <p>The range is expressed in arbitrary units that must be the same as the
17398     * units used by {@link #computeVerticalScrollRange()} and
17399     * {@link #computeVerticalScrollOffset()}.</p>
17400     *
17401     * <p>The default extent is the drawing height of this view.</p>
17402     *
17403     * @return the vertical extent of the scrollbar's thumb
17404     *
17405     * @see #computeVerticalScrollRange()
17406     * @see #computeVerticalScrollOffset()
17407     * @see android.widget.ScrollBarDrawable
17408     */
17409    protected int computeVerticalScrollExtent() {
17410        return getHeight();
17411    }
17412
17413    /**
17414     * Check if this view can be scrolled horizontally in a certain direction.
17415     *
17416     * @param direction Negative to check scrolling left, positive to check scrolling right.
17417     * @return true if this view can be scrolled in the specified direction, false otherwise.
17418     */
17419    public boolean canScrollHorizontally(int direction) {
17420        final int offset = computeHorizontalScrollOffset();
17421        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
17422        if (range == 0) return false;
17423        if (direction < 0) {
17424            return offset > 0;
17425        } else {
17426            return offset < range - 1;
17427        }
17428    }
17429
17430    /**
17431     * Check if this view can be scrolled vertically in a certain direction.
17432     *
17433     * @param direction Negative to check scrolling up, positive to check scrolling down.
17434     * @return true if this view can be scrolled in the specified direction, false otherwise.
17435     */
17436    public boolean canScrollVertically(int direction) {
17437        final int offset = computeVerticalScrollOffset();
17438        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
17439        if (range == 0) return false;
17440        if (direction < 0) {
17441            return offset > 0;
17442        } else {
17443            return offset < range - 1;
17444        }
17445    }
17446
17447    void getScrollIndicatorBounds(@NonNull Rect out) {
17448        out.left = mScrollX;
17449        out.right = mScrollX + mRight - mLeft;
17450        out.top = mScrollY;
17451        out.bottom = mScrollY + mBottom - mTop;
17452    }
17453
17454    private void onDrawScrollIndicators(Canvas c) {
17455        if ((mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK) == 0) {
17456            // No scroll indicators enabled.
17457            return;
17458        }
17459
17460        final Drawable dr = mScrollIndicatorDrawable;
17461        if (dr == null) {
17462            // Scroll indicators aren't supported here.
17463            return;
17464        }
17465
17466        final int h = dr.getIntrinsicHeight();
17467        final int w = dr.getIntrinsicWidth();
17468        final Rect rect = mAttachInfo.mTmpInvalRect;
17469        getScrollIndicatorBounds(rect);
17470
17471        if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_TOP) != 0) {
17472            final boolean canScrollUp = canScrollVertically(-1);
17473            if (canScrollUp) {
17474                dr.setBounds(rect.left, rect.top, rect.right, rect.top + h);
17475                dr.draw(c);
17476            }
17477        }
17478
17479        if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_BOTTOM) != 0) {
17480            final boolean canScrollDown = canScrollVertically(1);
17481            if (canScrollDown) {
17482                dr.setBounds(rect.left, rect.bottom - h, rect.right, rect.bottom);
17483                dr.draw(c);
17484            }
17485        }
17486
17487        final int leftRtl;
17488        final int rightRtl;
17489        if (getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
17490            leftRtl = PFLAG3_SCROLL_INDICATOR_END;
17491            rightRtl = PFLAG3_SCROLL_INDICATOR_START;
17492        } else {
17493            leftRtl = PFLAG3_SCROLL_INDICATOR_START;
17494            rightRtl = PFLAG3_SCROLL_INDICATOR_END;
17495        }
17496
17497        final int leftMask = PFLAG3_SCROLL_INDICATOR_LEFT | leftRtl;
17498        if ((mPrivateFlags3 & leftMask) != 0) {
17499            final boolean canScrollLeft = canScrollHorizontally(-1);
17500            if (canScrollLeft) {
17501                dr.setBounds(rect.left, rect.top, rect.left + w, rect.bottom);
17502                dr.draw(c);
17503            }
17504        }
17505
17506        final int rightMask = PFLAG3_SCROLL_INDICATOR_RIGHT | rightRtl;
17507        if ((mPrivateFlags3 & rightMask) != 0) {
17508            final boolean canScrollRight = canScrollHorizontally(1);
17509            if (canScrollRight) {
17510                dr.setBounds(rect.right - w, rect.top, rect.right, rect.bottom);
17511                dr.draw(c);
17512            }
17513        }
17514    }
17515
17516    private void getHorizontalScrollBarBounds(@Nullable Rect drawBounds,
17517            @Nullable Rect touchBounds) {
17518        final Rect bounds = drawBounds != null ? drawBounds : touchBounds;
17519        if (bounds == null) {
17520            return;
17521        }
17522        final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
17523        final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled()
17524                && !isVerticalScrollBarHidden();
17525        final int size = getHorizontalScrollbarHeight();
17526        final int verticalScrollBarGap = drawVerticalScrollBar ?
17527                getVerticalScrollbarWidth() : 0;
17528        final int width = mRight - mLeft;
17529        final int height = mBottom - mTop;
17530        bounds.top = mScrollY + height - size - (mUserPaddingBottom & inside);
17531        bounds.left = mScrollX + (mPaddingLeft & inside);
17532        bounds.right = mScrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
17533        bounds.bottom = bounds.top + size;
17534
17535        if (touchBounds == null) {
17536            return;
17537        }
17538        if (touchBounds != bounds) {
17539            touchBounds.set(bounds);
17540        }
17541        final int minTouchTarget = mScrollCache.scrollBarMinTouchTarget;
17542        if (touchBounds.height() < minTouchTarget) {
17543            final int adjust = (minTouchTarget - touchBounds.height()) / 2;
17544            touchBounds.bottom = Math.min(touchBounds.bottom + adjust, mScrollY + height);
17545            touchBounds.top = touchBounds.bottom - minTouchTarget;
17546        }
17547        if (touchBounds.width() < minTouchTarget) {
17548            final int adjust = (minTouchTarget - touchBounds.width()) / 2;
17549            touchBounds.left -= adjust;
17550            touchBounds.right = touchBounds.left + minTouchTarget;
17551        }
17552    }
17553
17554    private void getVerticalScrollBarBounds(@Nullable Rect bounds, @Nullable Rect touchBounds) {
17555        if (mRoundScrollbarRenderer == null) {
17556            getStraightVerticalScrollBarBounds(bounds, touchBounds);
17557        } else {
17558            getRoundVerticalScrollBarBounds(bounds != null ? bounds : touchBounds);
17559        }
17560    }
17561
17562    private void getRoundVerticalScrollBarBounds(Rect bounds) {
17563        final int width = mRight - mLeft;
17564        final int height = mBottom - mTop;
17565        // Do not take padding into account as we always want the scrollbars
17566        // to hug the screen for round wearable devices.
17567        bounds.left = mScrollX;
17568        bounds.top = mScrollY;
17569        bounds.right = bounds.left + width;
17570        bounds.bottom = mScrollY + height;
17571    }
17572
17573    private void getStraightVerticalScrollBarBounds(@Nullable Rect drawBounds,
17574            @Nullable Rect touchBounds) {
17575        final Rect bounds = drawBounds != null ? drawBounds : touchBounds;
17576        if (bounds == null) {
17577            return;
17578        }
17579        final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
17580        final int size = getVerticalScrollbarWidth();
17581        int verticalScrollbarPosition = mVerticalScrollbarPosition;
17582        if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
17583            verticalScrollbarPosition = isLayoutRtl() ?
17584                    SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
17585        }
17586        final int width = mRight - mLeft;
17587        final int height = mBottom - mTop;
17588        switch (verticalScrollbarPosition) {
17589            default:
17590            case SCROLLBAR_POSITION_RIGHT:
17591                bounds.left = mScrollX + width - size - (mUserPaddingRight & inside);
17592                break;
17593            case SCROLLBAR_POSITION_LEFT:
17594                bounds.left = mScrollX + (mUserPaddingLeft & inside);
17595                break;
17596        }
17597        bounds.top = mScrollY + (mPaddingTop & inside);
17598        bounds.right = bounds.left + size;
17599        bounds.bottom = mScrollY + height - (mUserPaddingBottom & inside);
17600
17601        if (touchBounds == null) {
17602            return;
17603        }
17604        if (touchBounds != bounds) {
17605            touchBounds.set(bounds);
17606        }
17607        final int minTouchTarget = mScrollCache.scrollBarMinTouchTarget;
17608        if (touchBounds.width() < minTouchTarget) {
17609            final int adjust = (minTouchTarget - touchBounds.width()) / 2;
17610            if (verticalScrollbarPosition == SCROLLBAR_POSITION_RIGHT) {
17611                touchBounds.right = Math.min(touchBounds.right + adjust, mScrollX + width);
17612                touchBounds.left = touchBounds.right - minTouchTarget;
17613            } else {
17614                touchBounds.left = Math.max(touchBounds.left + adjust, mScrollX);
17615                touchBounds.right = touchBounds.left + minTouchTarget;
17616            }
17617        }
17618        if (touchBounds.height() < minTouchTarget) {
17619            final int adjust = (minTouchTarget - touchBounds.height()) / 2;
17620            touchBounds.top -= adjust;
17621            touchBounds.bottom = touchBounds.top + minTouchTarget;
17622        }
17623    }
17624
17625    /**
17626     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
17627     * scrollbars are painted only if they have been awakened first.</p>
17628     *
17629     * @param canvas the canvas on which to draw the scrollbars
17630     *
17631     * @see #awakenScrollBars(int)
17632     */
17633    protected final void onDrawScrollBars(Canvas canvas) {
17634        // scrollbars are drawn only when the animation is running
17635        final ScrollabilityCache cache = mScrollCache;
17636
17637        if (cache != null) {
17638
17639            int state = cache.state;
17640
17641            if (state == ScrollabilityCache.OFF) {
17642                return;
17643            }
17644
17645            boolean invalidate = false;
17646
17647            if (state == ScrollabilityCache.FADING) {
17648                // We're fading -- get our fade interpolation
17649                if (cache.interpolatorValues == null) {
17650                    cache.interpolatorValues = new float[1];
17651                }
17652
17653                float[] values = cache.interpolatorValues;
17654
17655                // Stops the animation if we're done
17656                if (cache.scrollBarInterpolator.timeToValues(values) ==
17657                        Interpolator.Result.FREEZE_END) {
17658                    cache.state = ScrollabilityCache.OFF;
17659                } else {
17660                    cache.scrollBar.mutate().setAlpha(Math.round(values[0]));
17661                }
17662
17663                // This will make the scroll bars inval themselves after
17664                // drawing. We only want this when we're fading so that
17665                // we prevent excessive redraws
17666                invalidate = true;
17667            } else {
17668                // We're just on -- but we may have been fading before so
17669                // reset alpha
17670                cache.scrollBar.mutate().setAlpha(255);
17671            }
17672
17673            final boolean drawHorizontalScrollBar = isHorizontalScrollBarEnabled();
17674            final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled()
17675                    && !isVerticalScrollBarHidden();
17676
17677            // Fork out the scroll bar drawing for round wearable devices.
17678            if (mRoundScrollbarRenderer != null) {
17679                if (drawVerticalScrollBar) {
17680                    final Rect bounds = cache.mScrollBarBounds;
17681                    getVerticalScrollBarBounds(bounds, null);
17682                    mRoundScrollbarRenderer.drawRoundScrollbars(
17683                            canvas, (float) cache.scrollBar.getAlpha() / 255f, bounds);
17684                    if (invalidate) {
17685                        invalidate();
17686                    }
17687                }
17688                // Do not draw horizontal scroll bars for round wearable devices.
17689            } else if (drawVerticalScrollBar || drawHorizontalScrollBar) {
17690                final ScrollBarDrawable scrollBar = cache.scrollBar;
17691
17692                if (drawHorizontalScrollBar) {
17693                    scrollBar.setParameters(computeHorizontalScrollRange(),
17694                            computeHorizontalScrollOffset(),
17695                            computeHorizontalScrollExtent(), false);
17696                    final Rect bounds = cache.mScrollBarBounds;
17697                    getHorizontalScrollBarBounds(bounds, null);
17698                    onDrawHorizontalScrollBar(canvas, scrollBar, bounds.left, bounds.top,
17699                            bounds.right, bounds.bottom);
17700                    if (invalidate) {
17701                        invalidate(bounds);
17702                    }
17703                }
17704
17705                if (drawVerticalScrollBar) {
17706                    scrollBar.setParameters(computeVerticalScrollRange(),
17707                            computeVerticalScrollOffset(),
17708                            computeVerticalScrollExtent(), true);
17709                    final Rect bounds = cache.mScrollBarBounds;
17710                    getVerticalScrollBarBounds(bounds, null);
17711                    onDrawVerticalScrollBar(canvas, scrollBar, bounds.left, bounds.top,
17712                            bounds.right, bounds.bottom);
17713                    if (invalidate) {
17714                        invalidate(bounds);
17715                    }
17716                }
17717            }
17718        }
17719    }
17720
17721    /**
17722     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
17723     * FastScroller is visible.
17724     * @return whether to temporarily hide the vertical scrollbar
17725     * @hide
17726     */
17727    protected boolean isVerticalScrollBarHidden() {
17728        return false;
17729    }
17730
17731    /**
17732     * <p>Draw the horizontal scrollbar if
17733     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
17734     *
17735     * @param canvas the canvas on which to draw the scrollbar
17736     * @param scrollBar the scrollbar's drawable
17737     *
17738     * @see #isHorizontalScrollBarEnabled()
17739     * @see #computeHorizontalScrollRange()
17740     * @see #computeHorizontalScrollExtent()
17741     * @see #computeHorizontalScrollOffset()
17742     * @see android.widget.ScrollBarDrawable
17743     * @hide
17744     */
17745    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
17746            int l, int t, int r, int b) {
17747        scrollBar.setBounds(l, t, r, b);
17748        scrollBar.draw(canvas);
17749    }
17750
17751    /**
17752     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
17753     * returns true.</p>
17754     *
17755     * @param canvas the canvas on which to draw the scrollbar
17756     * @param scrollBar the scrollbar's drawable
17757     *
17758     * @see #isVerticalScrollBarEnabled()
17759     * @see #computeVerticalScrollRange()
17760     * @see #computeVerticalScrollExtent()
17761     * @see #computeVerticalScrollOffset()
17762     * @see android.widget.ScrollBarDrawable
17763     * @hide
17764     */
17765    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
17766            int l, int t, int r, int b) {
17767        scrollBar.setBounds(l, t, r, b);
17768        scrollBar.draw(canvas);
17769    }
17770
17771    /**
17772     * Implement this to do your drawing.
17773     *
17774     * @param canvas the canvas on which the background will be drawn
17775     */
17776    protected void onDraw(Canvas canvas) {
17777    }
17778
17779    /*
17780     * Caller is responsible for calling requestLayout if necessary.
17781     * (This allows addViewInLayout to not request a new layout.)
17782     */
17783    void assignParent(ViewParent parent) {
17784        if (mParent == null) {
17785            mParent = parent;
17786        } else if (parent == null) {
17787            mParent = null;
17788        } else {
17789            throw new RuntimeException("view " + this + " being added, but"
17790                    + " it already has a parent");
17791        }
17792    }
17793
17794    /**
17795     * This is called when the view is attached to a window.  At this point it
17796     * has a Surface and will start drawing.  Note that this function is
17797     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
17798     * however it may be called any time before the first onDraw -- including
17799     * before or after {@link #onMeasure(int, int)}.
17800     *
17801     * @see #onDetachedFromWindow()
17802     */
17803    @CallSuper
17804    protected void onAttachedToWindow() {
17805        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
17806            mParent.requestTransparentRegion(this);
17807        }
17808
17809        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
17810
17811        jumpDrawablesToCurrentState();
17812
17813        resetSubtreeAccessibilityStateChanged();
17814
17815        // rebuild, since Outline not maintained while View is detached
17816        rebuildOutline();
17817
17818        if (isFocused()) {
17819            InputMethodManager imm = InputMethodManager.peekInstance();
17820            if (imm != null) {
17821                imm.focusIn(this);
17822            }
17823        }
17824    }
17825
17826    /**
17827     * Resolve all RTL related properties.
17828     *
17829     * @return true if resolution of RTL properties has been done
17830     *
17831     * @hide
17832     */
17833    public boolean resolveRtlPropertiesIfNeeded() {
17834        if (!needRtlPropertiesResolution()) return false;
17835
17836        // Order is important here: LayoutDirection MUST be resolved first
17837        if (!isLayoutDirectionResolved()) {
17838            resolveLayoutDirection();
17839            resolveLayoutParams();
17840        }
17841        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
17842        if (!isTextDirectionResolved()) {
17843            resolveTextDirection();
17844        }
17845        if (!isTextAlignmentResolved()) {
17846            resolveTextAlignment();
17847        }
17848        // Should resolve Drawables before Padding because we need the layout direction of the
17849        // Drawable to correctly resolve Padding.
17850        if (!areDrawablesResolved()) {
17851            resolveDrawables();
17852        }
17853        if (!isPaddingResolved()) {
17854            resolvePadding();
17855        }
17856        onRtlPropertiesChanged(getLayoutDirection());
17857        return true;
17858    }
17859
17860    /**
17861     * Reset resolution of all RTL related properties.
17862     *
17863     * @hide
17864     */
17865    public void resetRtlProperties() {
17866        resetResolvedLayoutDirection();
17867        resetResolvedTextDirection();
17868        resetResolvedTextAlignment();
17869        resetResolvedPadding();
17870        resetResolvedDrawables();
17871    }
17872
17873    /**
17874     * @see #onScreenStateChanged(int)
17875     */
17876    void dispatchScreenStateChanged(int screenState) {
17877        onScreenStateChanged(screenState);
17878    }
17879
17880    /**
17881     * This method is called whenever the state of the screen this view is
17882     * attached to changes. A state change will usually occurs when the screen
17883     * turns on or off (whether it happens automatically or the user does it
17884     * manually.)
17885     *
17886     * @param screenState The new state of the screen. Can be either
17887     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
17888     */
17889    public void onScreenStateChanged(int screenState) {
17890    }
17891
17892    /**
17893     * @see #onMovedToDisplay(int, Configuration)
17894     */
17895    void dispatchMovedToDisplay(Display display, Configuration config) {
17896        mAttachInfo.mDisplay = display;
17897        mAttachInfo.mDisplayState = display.getState();
17898        onMovedToDisplay(display.getDisplayId(), config);
17899    }
17900
17901    /**
17902     * Called by the system when the hosting activity is moved from one display to another without
17903     * recreation. This means that the activity is declared to handle all changes to configuration
17904     * that happened when it was switched to another display, so it wasn't destroyed and created
17905     * again.
17906     *
17907     * <p>This call will be followed by {@link #onConfigurationChanged(Configuration)} if the
17908     * applied configuration actually changed. It is up to app developer to choose whether to handle
17909     * the change in this method or in the following {@link #onConfigurationChanged(Configuration)}
17910     * call.
17911     *
17912     * <p>Use this callback to track changes to the displays if some functionality relies on an
17913     * association with some display properties.
17914     *
17915     * @param displayId The id of the display to which the view was moved.
17916     * @param config Configuration of the resources on new display after move.
17917     *
17918     * @see #onConfigurationChanged(Configuration)
17919     * @hide
17920     */
17921    public void onMovedToDisplay(int displayId, Configuration config) {
17922    }
17923
17924    /**
17925     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
17926     */
17927    private boolean hasRtlSupport() {
17928        return mContext.getApplicationInfo().hasRtlSupport();
17929    }
17930
17931    /**
17932     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
17933     * RTL not supported)
17934     */
17935    private boolean isRtlCompatibilityMode() {
17936        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
17937        return targetSdkVersion < Build.VERSION_CODES.JELLY_BEAN_MR1 || !hasRtlSupport();
17938    }
17939
17940    /**
17941     * @return true if RTL properties need resolution.
17942     *
17943     */
17944    private boolean needRtlPropertiesResolution() {
17945        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
17946    }
17947
17948    /**
17949     * Called when any RTL property (layout direction or text direction or text alignment) has
17950     * been changed.
17951     *
17952     * Subclasses need to override this method to take care of cached information that depends on the
17953     * resolved layout direction, or to inform child views that inherit their layout direction.
17954     *
17955     * The default implementation does nothing.
17956     *
17957     * @param layoutDirection the direction of the layout
17958     *
17959     * @see #LAYOUT_DIRECTION_LTR
17960     * @see #LAYOUT_DIRECTION_RTL
17961     */
17962    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
17963    }
17964
17965    /**
17966     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
17967     * that the parent directionality can and will be resolved before its children.
17968     *
17969     * @return true if resolution has been done, false otherwise.
17970     *
17971     * @hide
17972     */
17973    public boolean resolveLayoutDirection() {
17974        // Clear any previous layout direction resolution
17975        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
17976
17977        if (hasRtlSupport()) {
17978            // Set resolved depending on layout direction
17979            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
17980                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
17981                case LAYOUT_DIRECTION_INHERIT:
17982                    // We cannot resolve yet. LTR is by default and let the resolution happen again
17983                    // later to get the correct resolved value
17984                    if (!canResolveLayoutDirection()) return false;
17985
17986                    // Parent has not yet resolved, LTR is still the default
17987                    try {
17988                        if (!mParent.isLayoutDirectionResolved()) return false;
17989
17990                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
17991                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
17992                        }
17993                    } catch (AbstractMethodError e) {
17994                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
17995                                " does not fully implement ViewParent", e);
17996                    }
17997                    break;
17998                case LAYOUT_DIRECTION_RTL:
17999                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
18000                    break;
18001                case LAYOUT_DIRECTION_LOCALE:
18002                    if((LAYOUT_DIRECTION_RTL ==
18003                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
18004                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
18005                    }
18006                    break;
18007                default:
18008                    // Nothing to do, LTR by default
18009            }
18010        }
18011
18012        // Set to resolved
18013        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
18014        return true;
18015    }
18016
18017    /**
18018     * Check if layout direction resolution can be done.
18019     *
18020     * @return true if layout direction resolution can be done otherwise return false.
18021     */
18022    public boolean canResolveLayoutDirection() {
18023        switch (getRawLayoutDirection()) {
18024            case LAYOUT_DIRECTION_INHERIT:
18025                if (mParent != null) {
18026                    try {
18027                        return mParent.canResolveLayoutDirection();
18028                    } catch (AbstractMethodError e) {
18029                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18030                                " does not fully implement ViewParent", e);
18031                    }
18032                }
18033                return false;
18034
18035            default:
18036                return true;
18037        }
18038    }
18039
18040    /**
18041     * Reset the resolved layout direction. Layout direction will be resolved during a call to
18042     * {@link #onMeasure(int, int)}.
18043     *
18044     * @hide
18045     */
18046    public void resetResolvedLayoutDirection() {
18047        // Reset the current resolved bits
18048        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
18049    }
18050
18051    /**
18052     * @return true if the layout direction is inherited.
18053     *
18054     * @hide
18055     */
18056    public boolean isLayoutDirectionInherited() {
18057        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
18058    }
18059
18060    /**
18061     * @return true if layout direction has been resolved.
18062     */
18063    public boolean isLayoutDirectionResolved() {
18064        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
18065    }
18066
18067    /**
18068     * Return if padding has been resolved
18069     *
18070     * @hide
18071     */
18072    boolean isPaddingResolved() {
18073        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
18074    }
18075
18076    /**
18077     * Resolves padding depending on layout direction, if applicable, and
18078     * recomputes internal padding values to adjust for scroll bars.
18079     *
18080     * @hide
18081     */
18082    public void resolvePadding() {
18083        final int resolvedLayoutDirection = getLayoutDirection();
18084
18085        if (!isRtlCompatibilityMode()) {
18086            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
18087            // If start / end padding are defined, they will be resolved (hence overriding) to
18088            // left / right or right / left depending on the resolved layout direction.
18089            // If start / end padding are not defined, use the left / right ones.
18090            if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
18091                Rect padding = sThreadLocal.get();
18092                if (padding == null) {
18093                    padding = new Rect();
18094                    sThreadLocal.set(padding);
18095                }
18096                mBackground.getPadding(padding);
18097                if (!mLeftPaddingDefined) {
18098                    mUserPaddingLeftInitial = padding.left;
18099                }
18100                if (!mRightPaddingDefined) {
18101                    mUserPaddingRightInitial = padding.right;
18102                }
18103            }
18104            switch (resolvedLayoutDirection) {
18105                case LAYOUT_DIRECTION_RTL:
18106                    if (mUserPaddingStart != UNDEFINED_PADDING) {
18107                        mUserPaddingRight = mUserPaddingStart;
18108                    } else {
18109                        mUserPaddingRight = mUserPaddingRightInitial;
18110                    }
18111                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
18112                        mUserPaddingLeft = mUserPaddingEnd;
18113                    } else {
18114                        mUserPaddingLeft = mUserPaddingLeftInitial;
18115                    }
18116                    break;
18117                case LAYOUT_DIRECTION_LTR:
18118                default:
18119                    if (mUserPaddingStart != UNDEFINED_PADDING) {
18120                        mUserPaddingLeft = mUserPaddingStart;
18121                    } else {
18122                        mUserPaddingLeft = mUserPaddingLeftInitial;
18123                    }
18124                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
18125                        mUserPaddingRight = mUserPaddingEnd;
18126                    } else {
18127                        mUserPaddingRight = mUserPaddingRightInitial;
18128                    }
18129            }
18130
18131            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
18132        }
18133
18134        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
18135        onRtlPropertiesChanged(resolvedLayoutDirection);
18136
18137        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
18138    }
18139
18140    /**
18141     * Reset the resolved layout direction.
18142     *
18143     * @hide
18144     */
18145    public void resetResolvedPadding() {
18146        resetResolvedPaddingInternal();
18147    }
18148
18149    /**
18150     * Used when we only want to reset *this* view's padding and not trigger overrides
18151     * in ViewGroup that reset children too.
18152     */
18153    void resetResolvedPaddingInternal() {
18154        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
18155    }
18156
18157    /**
18158     * This is called when the view is detached from a window.  At this point it
18159     * no longer has a surface for drawing.
18160     *
18161     * @see #onAttachedToWindow()
18162     */
18163    @CallSuper
18164    protected void onDetachedFromWindow() {
18165    }
18166
18167    /**
18168     * This is a framework-internal mirror of onDetachedFromWindow() that's called
18169     * after onDetachedFromWindow().
18170     *
18171     * If you override this you *MUST* call super.onDetachedFromWindowInternal()!
18172     * The super method should be called at the end of the overridden method to ensure
18173     * subclasses are destroyed first
18174     *
18175     * @hide
18176     */
18177    @CallSuper
18178    protected void onDetachedFromWindowInternal() {
18179        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
18180        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
18181        mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH;
18182
18183        removeUnsetPressCallback();
18184        removeLongPressCallback();
18185        removePerformClickCallback();
18186        cancel(mSendViewScrolledAccessibilityEvent);
18187        stopNestedScroll();
18188
18189        // Anything that started animating right before detach should already
18190        // be in its final state when re-attached.
18191        jumpDrawablesToCurrentState();
18192
18193        destroyDrawingCache();
18194
18195        cleanupDraw();
18196        mCurrentAnimation = null;
18197
18198        if ((mViewFlags & TOOLTIP) == TOOLTIP) {
18199            hideTooltip();
18200        }
18201    }
18202
18203    private void cleanupDraw() {
18204        resetDisplayList();
18205        if (mAttachInfo != null) {
18206            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
18207        }
18208    }
18209
18210    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
18211    }
18212
18213    /**
18214     * @return The number of times this view has been attached to a window
18215     */
18216    protected int getWindowAttachCount() {
18217        return mWindowAttachCount;
18218    }
18219
18220    /**
18221     * Retrieve a unique token identifying the window this view is attached to.
18222     * @return Return the window's token for use in
18223     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
18224     */
18225    public IBinder getWindowToken() {
18226        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
18227    }
18228
18229    /**
18230     * Retrieve the {@link WindowId} for the window this view is
18231     * currently attached to.
18232     */
18233    public WindowId getWindowId() {
18234        AttachInfo ai = mAttachInfo;
18235        if (ai == null) {
18236            return null;
18237        }
18238        if (ai.mWindowId == null) {
18239            try {
18240                ai.mIWindowId = ai.mSession.getWindowId(ai.mWindowToken);
18241                if (ai.mIWindowId != null) {
18242                    ai.mWindowId = new WindowId(ai.mIWindowId);
18243                }
18244            } catch (RemoteException e) {
18245            }
18246        }
18247        return ai.mWindowId;
18248    }
18249
18250    /**
18251     * Retrieve a unique token identifying the top-level "real" window of
18252     * the window that this view is attached to.  That is, this is like
18253     * {@link #getWindowToken}, except if the window this view in is a panel
18254     * window (attached to another containing window), then the token of
18255     * the containing window is returned instead.
18256     *
18257     * @return Returns the associated window token, either
18258     * {@link #getWindowToken()} or the containing window's token.
18259     */
18260    public IBinder getApplicationWindowToken() {
18261        AttachInfo ai = mAttachInfo;
18262        if (ai != null) {
18263            IBinder appWindowToken = ai.mPanelParentWindowToken;
18264            if (appWindowToken == null) {
18265                appWindowToken = ai.mWindowToken;
18266            }
18267            return appWindowToken;
18268        }
18269        return null;
18270    }
18271
18272    /**
18273     * Gets the logical display to which the view's window has been attached.
18274     *
18275     * @return The logical display, or null if the view is not currently attached to a window.
18276     */
18277    public Display getDisplay() {
18278        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
18279    }
18280
18281    /**
18282     * Retrieve private session object this view hierarchy is using to
18283     * communicate with the window manager.
18284     * @return the session object to communicate with the window manager
18285     */
18286    /*package*/ IWindowSession getWindowSession() {
18287        return mAttachInfo != null ? mAttachInfo.mSession : null;
18288    }
18289
18290    /**
18291     * Return the window this view is currently attached to. Used in
18292     * {@link android.app.ActivityView} to communicate with WM.
18293     * @hide
18294     */
18295    protected IWindow getWindow() {
18296        return mAttachInfo != null ? mAttachInfo.mWindow : null;
18297    }
18298
18299    /**
18300     * Return the visibility value of the least visible component passed.
18301     */
18302    int combineVisibility(int vis1, int vis2) {
18303        // This works because VISIBLE < INVISIBLE < GONE.
18304        return Math.max(vis1, vis2);
18305    }
18306
18307    /**
18308     * @param info the {@link android.view.View.AttachInfo} to associated with
18309     *        this view
18310     */
18311    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
18312        mAttachInfo = info;
18313        if (mOverlay != null) {
18314            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
18315        }
18316        mWindowAttachCount++;
18317        // We will need to evaluate the drawable state at least once.
18318        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
18319        if (mFloatingTreeObserver != null) {
18320            info.mTreeObserver.merge(mFloatingTreeObserver);
18321            mFloatingTreeObserver = null;
18322        }
18323
18324        registerPendingFrameMetricsObservers();
18325
18326        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
18327            mAttachInfo.mScrollContainers.add(this);
18328            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
18329        }
18330        // Transfer all pending runnables.
18331        if (mRunQueue != null) {
18332            mRunQueue.executeActions(info.mHandler);
18333            mRunQueue = null;
18334        }
18335        performCollectViewAttributes(mAttachInfo, visibility);
18336        onAttachedToWindow();
18337
18338        ListenerInfo li = mListenerInfo;
18339        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
18340                li != null ? li.mOnAttachStateChangeListeners : null;
18341        if (listeners != null && listeners.size() > 0) {
18342            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
18343            // perform the dispatching. The iterator is a safe guard against listeners that
18344            // could mutate the list by calling the various add/remove methods. This prevents
18345            // the array from being modified while we iterate it.
18346            for (OnAttachStateChangeListener listener : listeners) {
18347                listener.onViewAttachedToWindow(this);
18348            }
18349        }
18350
18351        int vis = info.mWindowVisibility;
18352        if (vis != GONE) {
18353            onWindowVisibilityChanged(vis);
18354            if (isShown()) {
18355                // Calling onVisibilityAggregated directly here since the subtree will also
18356                // receive dispatchAttachedToWindow and this same call
18357                onVisibilityAggregated(vis == VISIBLE);
18358            }
18359        }
18360
18361        // Send onVisibilityChanged directly instead of dispatchVisibilityChanged.
18362        // As all views in the subtree will already receive dispatchAttachedToWindow
18363        // traversing the subtree again here is not desired.
18364        onVisibilityChanged(this, visibility);
18365
18366        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
18367            // If nobody has evaluated the drawable state yet, then do it now.
18368            refreshDrawableState();
18369        }
18370        needGlobalAttributesUpdate(false);
18371
18372        notifyEnterOrExitForAutoFillIfNeeded(true);
18373    }
18374
18375    void dispatchDetachedFromWindow() {
18376        AttachInfo info = mAttachInfo;
18377        if (info != null) {
18378            int vis = info.mWindowVisibility;
18379            if (vis != GONE) {
18380                onWindowVisibilityChanged(GONE);
18381                if (isShown()) {
18382                    // Invoking onVisibilityAggregated directly here since the subtree
18383                    // will also receive detached from window
18384                    onVisibilityAggregated(false);
18385                }
18386            }
18387        }
18388
18389        onDetachedFromWindow();
18390        onDetachedFromWindowInternal();
18391
18392        InputMethodManager imm = InputMethodManager.peekInstance();
18393        if (imm != null) {
18394            imm.onViewDetachedFromWindow(this);
18395        }
18396
18397        ListenerInfo li = mListenerInfo;
18398        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
18399                li != null ? li.mOnAttachStateChangeListeners : null;
18400        if (listeners != null && listeners.size() > 0) {
18401            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
18402            // perform the dispatching. The iterator is a safe guard against listeners that
18403            // could mutate the list by calling the various add/remove methods. This prevents
18404            // the array from being modified while we iterate it.
18405            for (OnAttachStateChangeListener listener : listeners) {
18406                listener.onViewDetachedFromWindow(this);
18407            }
18408        }
18409
18410        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
18411            mAttachInfo.mScrollContainers.remove(this);
18412            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
18413        }
18414
18415        mAttachInfo = null;
18416        if (mOverlay != null) {
18417            mOverlay.getOverlayView().dispatchDetachedFromWindow();
18418        }
18419
18420        notifyEnterOrExitForAutoFillIfNeeded(false);
18421    }
18422
18423    /**
18424     * Cancel any deferred high-level input events that were previously posted to the event queue.
18425     *
18426     * <p>Many views post high-level events such as click handlers to the event queue
18427     * to run deferred in order to preserve a desired user experience - clearing visible
18428     * pressed states before executing, etc. This method will abort any events of this nature
18429     * that are currently in flight.</p>
18430     *
18431     * <p>Custom views that generate their own high-level deferred input events should override
18432     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
18433     *
18434     * <p>This will also cancel pending input events for any child views.</p>
18435     *
18436     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
18437     * This will not impact newer events posted after this call that may occur as a result of
18438     * lower-level input events still waiting in the queue. If you are trying to prevent
18439     * double-submitted  events for the duration of some sort of asynchronous transaction
18440     * you should also take other steps to protect against unexpected double inputs e.g. calling
18441     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
18442     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
18443     */
18444    public final void cancelPendingInputEvents() {
18445        dispatchCancelPendingInputEvents();
18446    }
18447
18448    /**
18449     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
18450     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
18451     */
18452    void dispatchCancelPendingInputEvents() {
18453        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
18454        onCancelPendingInputEvents();
18455        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
18456            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
18457                    " did not call through to super.onCancelPendingInputEvents()");
18458        }
18459    }
18460
18461    /**
18462     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
18463     * a parent view.
18464     *
18465     * <p>This method is responsible for removing any pending high-level input events that were
18466     * posted to the event queue to run later. Custom view classes that post their own deferred
18467     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
18468     * {@link android.os.Handler} should override this method, call
18469     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
18470     * </p>
18471     */
18472    public void onCancelPendingInputEvents() {
18473        removePerformClickCallback();
18474        cancelLongPress();
18475        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
18476    }
18477
18478    /**
18479     * Store this view hierarchy's frozen state into the given container.
18480     *
18481     * @param container The SparseArray in which to save the view's state.
18482     *
18483     * @see #restoreHierarchyState(android.util.SparseArray)
18484     * @see #dispatchSaveInstanceState(android.util.SparseArray)
18485     * @see #onSaveInstanceState()
18486     */
18487    public void saveHierarchyState(SparseArray<Parcelable> container) {
18488        dispatchSaveInstanceState(container);
18489    }
18490
18491    /**
18492     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
18493     * this view and its children. May be overridden to modify how freezing happens to a
18494     * view's children; for example, some views may want to not store state for their children.
18495     *
18496     * @param container The SparseArray in which to save the view's state.
18497     *
18498     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
18499     * @see #saveHierarchyState(android.util.SparseArray)
18500     * @see #onSaveInstanceState()
18501     */
18502    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
18503        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
18504            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
18505            Parcelable state = onSaveInstanceState();
18506            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
18507                throw new IllegalStateException(
18508                        "Derived class did not call super.onSaveInstanceState()");
18509            }
18510            if (state != null) {
18511                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
18512                // + ": " + state);
18513                container.put(mID, state);
18514            }
18515        }
18516    }
18517
18518    /**
18519     * Hook allowing a view to generate a representation of its internal state
18520     * that can later be used to create a new instance with that same state.
18521     * This state should only contain information that is not persistent or can
18522     * not be reconstructed later. For example, you will never store your
18523     * current position on screen because that will be computed again when a
18524     * new instance of the view is placed in its view hierarchy.
18525     * <p>
18526     * Some examples of things you may store here: the current cursor position
18527     * in a text view (but usually not the text itself since that is stored in a
18528     * content provider or other persistent storage), the currently selected
18529     * item in a list view.
18530     *
18531     * @return Returns a Parcelable object containing the view's current dynamic
18532     *         state, or null if there is nothing interesting to save.
18533     * @see #onRestoreInstanceState(Parcelable)
18534     * @see #saveHierarchyState(SparseArray)
18535     * @see #dispatchSaveInstanceState(SparseArray)
18536     * @see #setSaveEnabled(boolean)
18537     */
18538    @CallSuper
18539    @Nullable protected Parcelable onSaveInstanceState() {
18540        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
18541        if (mStartActivityRequestWho != null || isAutofilled()
18542                || mAutofillViewId > LAST_APP_AUTOFILL_ID) {
18543            BaseSavedState state = new BaseSavedState(AbsSavedState.EMPTY_STATE);
18544
18545            if (mStartActivityRequestWho != null) {
18546                state.mSavedData |= BaseSavedState.START_ACTIVITY_REQUESTED_WHO_SAVED;
18547            }
18548
18549            if (isAutofilled()) {
18550                state.mSavedData |= BaseSavedState.IS_AUTOFILLED;
18551            }
18552
18553            if (mAutofillViewId > LAST_APP_AUTOFILL_ID) {
18554                state.mSavedData |= BaseSavedState.AUTOFILL_ID;
18555            }
18556
18557            state.mStartActivityRequestWhoSaved = mStartActivityRequestWho;
18558            state.mIsAutofilled = isAutofilled();
18559            state.mAutofillViewId = mAutofillViewId;
18560            return state;
18561        }
18562        return BaseSavedState.EMPTY_STATE;
18563    }
18564
18565    /**
18566     * Restore this view hierarchy's frozen state from the given container.
18567     *
18568     * @param container The SparseArray which holds previously frozen states.
18569     *
18570     * @see #saveHierarchyState(android.util.SparseArray)
18571     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
18572     * @see #onRestoreInstanceState(android.os.Parcelable)
18573     */
18574    public void restoreHierarchyState(SparseArray<Parcelable> container) {
18575        dispatchRestoreInstanceState(container);
18576    }
18577
18578    /**
18579     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
18580     * state for this view and its children. May be overridden to modify how restoring
18581     * happens to a view's children; for example, some views may want to not store state
18582     * for their children.
18583     *
18584     * @param container The SparseArray which holds previously saved state.
18585     *
18586     * @see #dispatchSaveInstanceState(android.util.SparseArray)
18587     * @see #restoreHierarchyState(android.util.SparseArray)
18588     * @see #onRestoreInstanceState(android.os.Parcelable)
18589     */
18590    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
18591        if (mID != NO_ID) {
18592            Parcelable state = container.get(mID);
18593            if (state != null) {
18594                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
18595                // + ": " + state);
18596                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
18597                onRestoreInstanceState(state);
18598                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
18599                    throw new IllegalStateException(
18600                            "Derived class did not call super.onRestoreInstanceState()");
18601                }
18602            }
18603        }
18604    }
18605
18606    /**
18607     * Hook allowing a view to re-apply a representation of its internal state that had previously
18608     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
18609     * null state.
18610     *
18611     * @param state The frozen state that had previously been returned by
18612     *        {@link #onSaveInstanceState}.
18613     *
18614     * @see #onSaveInstanceState()
18615     * @see #restoreHierarchyState(android.util.SparseArray)
18616     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
18617     */
18618    @CallSuper
18619    protected void onRestoreInstanceState(Parcelable state) {
18620        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
18621        if (state != null && !(state instanceof AbsSavedState)) {
18622            throw new IllegalArgumentException("Wrong state class, expecting View State but "
18623                    + "received " + state.getClass().toString() + " instead. This usually happens "
18624                    + "when two views of different type have the same id in the same hierarchy. "
18625                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
18626                    + "other views do not use the same id.");
18627        }
18628        if (state != null && state instanceof BaseSavedState) {
18629            BaseSavedState baseState = (BaseSavedState) state;
18630
18631            if ((baseState.mSavedData & BaseSavedState.START_ACTIVITY_REQUESTED_WHO_SAVED) != 0) {
18632                mStartActivityRequestWho = baseState.mStartActivityRequestWhoSaved;
18633            }
18634            if ((baseState.mSavedData & BaseSavedState.IS_AUTOFILLED) != 0) {
18635                setAutofilled(baseState.mIsAutofilled);
18636            }
18637            if ((baseState.mSavedData & BaseSavedState.AUTOFILL_ID) != 0) {
18638                // It can happen that views have the same view id and the restoration path will not
18639                // be able to distinguish between them. The autofill id needs to be unique though.
18640                // Hence prevent the same autofill view id from being restored multiple times.
18641                ((BaseSavedState) state).mSavedData &= ~BaseSavedState.AUTOFILL_ID;
18642
18643                if ((mPrivateFlags3 & PFLAG3_AUTOFILLID_EXPLICITLY_SET) != 0) {
18644                    // Ignore when view already set it through setAutofillId();
18645                    if (android.view.autofill.Helper.sDebug) {
18646                        Log.d(VIEW_LOG_TAG, "onRestoreInstanceState(): not setting autofillId to "
18647                                + baseState.mAutofillViewId + " because view explicitly set it to "
18648                                + mAutofillId);
18649                    }
18650                } else {
18651                    mAutofillViewId = baseState.mAutofillViewId;
18652                    mAutofillId = null; // will be set on demand by getAutofillId()
18653                }
18654            }
18655        }
18656    }
18657
18658    /**
18659     * <p>Return the time at which the drawing of the view hierarchy started.</p>
18660     *
18661     * @return the drawing start time in milliseconds
18662     */
18663    public long getDrawingTime() {
18664        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
18665    }
18666
18667    /**
18668     * <p>Enables or disables the duplication of the parent's state into this view. When
18669     * duplication is enabled, this view gets its drawable state from its parent rather
18670     * than from its own internal properties.</p>
18671     *
18672     * <p>Note: in the current implementation, setting this property to true after the
18673     * view was added to a ViewGroup might have no effect at all. This property should
18674     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
18675     *
18676     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
18677     * property is enabled, an exception will be thrown.</p>
18678     *
18679     * <p>Note: if the child view uses and updates additional states which are unknown to the
18680     * parent, these states should not be affected by this method.</p>
18681     *
18682     * @param enabled True to enable duplication of the parent's drawable state, false
18683     *                to disable it.
18684     *
18685     * @see #getDrawableState()
18686     * @see #isDuplicateParentStateEnabled()
18687     */
18688    public void setDuplicateParentStateEnabled(boolean enabled) {
18689        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
18690    }
18691
18692    /**
18693     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
18694     *
18695     * @return True if this view's drawable state is duplicated from the parent,
18696     *         false otherwise
18697     *
18698     * @see #getDrawableState()
18699     * @see #setDuplicateParentStateEnabled(boolean)
18700     */
18701    public boolean isDuplicateParentStateEnabled() {
18702        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
18703    }
18704
18705    /**
18706     * <p>Specifies the type of layer backing this view. The layer can be
18707     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
18708     * {@link #LAYER_TYPE_HARDWARE}.</p>
18709     *
18710     * <p>A layer is associated with an optional {@link android.graphics.Paint}
18711     * instance that controls how the layer is composed on screen. The following
18712     * properties of the paint are taken into account when composing the layer:</p>
18713     * <ul>
18714     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
18715     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
18716     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
18717     * </ul>
18718     *
18719     * <p>If this view has an alpha value set to < 1.0 by calling
18720     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superseded
18721     * by this view's alpha value.</p>
18722     *
18723     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
18724     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
18725     * for more information on when and how to use layers.</p>
18726     *
18727     * @param layerType The type of layer to use with this view, must be one of
18728     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
18729     *        {@link #LAYER_TYPE_HARDWARE}
18730     * @param paint The paint used to compose the layer. This argument is optional
18731     *        and can be null. It is ignored when the layer type is
18732     *        {@link #LAYER_TYPE_NONE}
18733     *
18734     * @see #getLayerType()
18735     * @see #LAYER_TYPE_NONE
18736     * @see #LAYER_TYPE_SOFTWARE
18737     * @see #LAYER_TYPE_HARDWARE
18738     * @see #setAlpha(float)
18739     *
18740     * @attr ref android.R.styleable#View_layerType
18741     */
18742    public void setLayerType(int layerType, @Nullable Paint paint) {
18743        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
18744            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
18745                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
18746        }
18747
18748        boolean typeChanged = mRenderNode.setLayerType(layerType);
18749
18750        if (!typeChanged) {
18751            setLayerPaint(paint);
18752            return;
18753        }
18754
18755        if (layerType != LAYER_TYPE_SOFTWARE) {
18756            // Destroy any previous software drawing cache if present
18757            // NOTE: even if previous layer type is HW, we do this to ensure we've cleaned up
18758            // drawing cache created in View#draw when drawing to a SW canvas.
18759            destroyDrawingCache();
18760        }
18761
18762        mLayerType = layerType;
18763        mLayerPaint = mLayerType == LAYER_TYPE_NONE ? null : paint;
18764        mRenderNode.setLayerPaint(mLayerPaint);
18765
18766        // draw() behaves differently if we are on a layer, so we need to
18767        // invalidate() here
18768        invalidateParentCaches();
18769        invalidate(true);
18770    }
18771
18772    /**
18773     * Updates the {@link Paint} object used with the current layer (used only if the current
18774     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
18775     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
18776     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
18777     * ensure that the view gets redrawn immediately.
18778     *
18779     * <p>A layer is associated with an optional {@link android.graphics.Paint}
18780     * instance that controls how the layer is composed on screen. The following
18781     * properties of the paint are taken into account when composing the layer:</p>
18782     * <ul>
18783     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
18784     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
18785     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
18786     * </ul>
18787     *
18788     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
18789     * alpha value of the layer's paint is superseded by this view's alpha value.</p>
18790     *
18791     * @param paint The paint used to compose the layer. This argument is optional
18792     *        and can be null. It is ignored when the layer type is
18793     *        {@link #LAYER_TYPE_NONE}
18794     *
18795     * @see #setLayerType(int, android.graphics.Paint)
18796     */
18797    public void setLayerPaint(@Nullable Paint paint) {
18798        int layerType = getLayerType();
18799        if (layerType != LAYER_TYPE_NONE) {
18800            mLayerPaint = paint;
18801            if (layerType == LAYER_TYPE_HARDWARE) {
18802                if (mRenderNode.setLayerPaint(paint)) {
18803                    invalidateViewProperty(false, false);
18804                }
18805            } else {
18806                invalidate();
18807            }
18808        }
18809    }
18810
18811    /**
18812     * Indicates what type of layer is currently associated with this view. By default
18813     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
18814     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
18815     * for more information on the different types of layers.
18816     *
18817     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
18818     *         {@link #LAYER_TYPE_HARDWARE}
18819     *
18820     * @see #setLayerType(int, android.graphics.Paint)
18821     * @see #buildLayer()
18822     * @see #LAYER_TYPE_NONE
18823     * @see #LAYER_TYPE_SOFTWARE
18824     * @see #LAYER_TYPE_HARDWARE
18825     */
18826    public int getLayerType() {
18827        return mLayerType;
18828    }
18829
18830    /**
18831     * Forces this view's layer to be created and this view to be rendered
18832     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
18833     * invoking this method will have no effect.
18834     *
18835     * This method can for instance be used to render a view into its layer before
18836     * starting an animation. If this view is complex, rendering into the layer
18837     * before starting the animation will avoid skipping frames.
18838     *
18839     * @throws IllegalStateException If this view is not attached to a window
18840     *
18841     * @see #setLayerType(int, android.graphics.Paint)
18842     */
18843    public void buildLayer() {
18844        if (mLayerType == LAYER_TYPE_NONE) return;
18845
18846        final AttachInfo attachInfo = mAttachInfo;
18847        if (attachInfo == null) {
18848            throw new IllegalStateException("This view must be attached to a window first");
18849        }
18850
18851        if (getWidth() == 0 || getHeight() == 0) {
18852            return;
18853        }
18854
18855        switch (mLayerType) {
18856            case LAYER_TYPE_HARDWARE:
18857                updateDisplayListIfDirty();
18858                if (attachInfo.mThreadedRenderer != null && mRenderNode.isValid()) {
18859                    attachInfo.mThreadedRenderer.buildLayer(mRenderNode);
18860                }
18861                break;
18862            case LAYER_TYPE_SOFTWARE:
18863                buildDrawingCache(true);
18864                break;
18865        }
18866    }
18867
18868    /**
18869     * Destroys all hardware rendering resources. This method is invoked
18870     * when the system needs to reclaim resources. Upon execution of this
18871     * method, you should free any OpenGL resources created by the view.
18872     *
18873     * Note: you <strong>must</strong> call
18874     * <code>super.destroyHardwareResources()</code> when overriding
18875     * this method.
18876     *
18877     * @hide
18878     */
18879    @CallSuper
18880    protected void destroyHardwareResources() {
18881        if (mOverlay != null) {
18882            mOverlay.getOverlayView().destroyHardwareResources();
18883        }
18884        if (mGhostView != null) {
18885            mGhostView.destroyHardwareResources();
18886        }
18887    }
18888
18889    /**
18890     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
18891     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
18892     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
18893     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
18894     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
18895     * null.</p>
18896     *
18897     * <p>Enabling the drawing cache is similar to
18898     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
18899     * acceleration is turned off. When hardware acceleration is turned on, enabling the
18900     * drawing cache has no effect on rendering because the system uses a different mechanism
18901     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
18902     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
18903     * for information on how to enable software and hardware layers.</p>
18904     *
18905     * <p>This API can be used to manually generate
18906     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
18907     * {@link #getDrawingCache()}.</p>
18908     *
18909     * @param enabled true to enable the drawing cache, false otherwise
18910     *
18911     * @see #isDrawingCacheEnabled()
18912     * @see #getDrawingCache()
18913     * @see #buildDrawingCache()
18914     * @see #setLayerType(int, android.graphics.Paint)
18915     *
18916     * @deprecated The view drawing cache was largely made obsolete with the introduction of
18917     * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
18918     * layers are largely unnecessary and can easily result in a net loss in performance due to the
18919     * cost of creating and updating the layer. In the rare cases where caching layers are useful,
18920     * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
18921     * rendering. For software-rendered snapshots of a small part of the View hierarchy or
18922     * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
18923     * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
18924     * software-rendered usages are discouraged and have compatibility issues with hardware-only
18925     * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
18926     * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
18927     * reports or unit testing the {@link PixelCopy} API is recommended.
18928     */
18929    @Deprecated
18930    public void setDrawingCacheEnabled(boolean enabled) {
18931        mCachingFailed = false;
18932        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
18933    }
18934
18935    /**
18936     * <p>Indicates whether the drawing cache is enabled for this view.</p>
18937     *
18938     * @return true if the drawing cache is enabled
18939     *
18940     * @see #setDrawingCacheEnabled(boolean)
18941     * @see #getDrawingCache()
18942     *
18943     * @deprecated The view drawing cache was largely made obsolete with the introduction of
18944     * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
18945     * layers are largely unnecessary and can easily result in a net loss in performance due to the
18946     * cost of creating and updating the layer. In the rare cases where caching layers are useful,
18947     * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
18948     * rendering. For software-rendered snapshots of a small part of the View hierarchy or
18949     * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
18950     * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
18951     * software-rendered usages are discouraged and have compatibility issues with hardware-only
18952     * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
18953     * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
18954     * reports or unit testing the {@link PixelCopy} API is recommended.
18955     */
18956    @Deprecated
18957    @ViewDebug.ExportedProperty(category = "drawing")
18958    public boolean isDrawingCacheEnabled() {
18959        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
18960    }
18961
18962    /**
18963     * Debugging utility which recursively outputs the dirty state of a view and its
18964     * descendants.
18965     *
18966     * @hide
18967     */
18968    @SuppressWarnings({"UnusedDeclaration"})
18969    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
18970        Log.d(VIEW_LOG_TAG, indent + this + "             DIRTY("
18971                + (mPrivateFlags & View.PFLAG_DIRTY_MASK)
18972                + ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID("
18973                + (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID)
18974                + ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
18975        if (clear) {
18976            mPrivateFlags &= clearMask;
18977        }
18978        if (this instanceof ViewGroup) {
18979            ViewGroup parent = (ViewGroup) this;
18980            final int count = parent.getChildCount();
18981            for (int i = 0; i < count; i++) {
18982                final View child = parent.getChildAt(i);
18983                child.outputDirtyFlags(indent + "  ", clear, clearMask);
18984            }
18985        }
18986    }
18987
18988    /**
18989     * This method is used by ViewGroup to cause its children to restore or recreate their
18990     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
18991     * to recreate its own display list, which would happen if it went through the normal
18992     * draw/dispatchDraw mechanisms.
18993     *
18994     * @hide
18995     */
18996    protected void dispatchGetDisplayList() {}
18997
18998    /**
18999     * A view that is not attached or hardware accelerated cannot create a display list.
19000     * This method checks these conditions and returns the appropriate result.
19001     *
19002     * @return true if view has the ability to create a display list, false otherwise.
19003     *
19004     * @hide
19005     */
19006    public boolean canHaveDisplayList() {
19007        return !(mAttachInfo == null || mAttachInfo.mThreadedRenderer == null);
19008    }
19009
19010    /**
19011     * Gets the RenderNode for the view, and updates its DisplayList (if needed and supported)
19012     * @hide
19013     */
19014    @NonNull
19015    public RenderNode updateDisplayListIfDirty() {
19016        final RenderNode renderNode = mRenderNode;
19017        if (!canHaveDisplayList()) {
19018            // can't populate RenderNode, don't try
19019            return renderNode;
19020        }
19021
19022        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0
19023                || !renderNode.isValid()
19024                || (mRecreateDisplayList)) {
19025            // Don't need to recreate the display list, just need to tell our
19026            // children to restore/recreate theirs
19027            if (renderNode.isValid()
19028                    && !mRecreateDisplayList) {
19029                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
19030                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
19031                dispatchGetDisplayList();
19032
19033                return renderNode; // no work needed
19034            }
19035
19036            // If we got here, we're recreating it. Mark it as such to ensure that
19037            // we copy in child display lists into ours in drawChild()
19038            mRecreateDisplayList = true;
19039
19040            int width = mRight - mLeft;
19041            int height = mBottom - mTop;
19042            int layerType = getLayerType();
19043
19044            final DisplayListCanvas canvas = renderNode.start(width, height);
19045
19046            try {
19047                if (layerType == LAYER_TYPE_SOFTWARE) {
19048                    buildDrawingCache(true);
19049                    Bitmap cache = getDrawingCache(true);
19050                    if (cache != null) {
19051                        canvas.drawBitmap(cache, 0, 0, mLayerPaint);
19052                    }
19053                } else {
19054                    computeScroll();
19055
19056                    canvas.translate(-mScrollX, -mScrollY);
19057                    mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
19058                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
19059
19060                    // Fast path for layouts with no backgrounds
19061                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
19062                        dispatchDraw(canvas);
19063                        drawAutofilledHighlight(canvas);
19064                        if (mOverlay != null && !mOverlay.isEmpty()) {
19065                            mOverlay.getOverlayView().draw(canvas);
19066                        }
19067                        if (debugDraw()) {
19068                            debugDrawFocus(canvas);
19069                        }
19070                    } else {
19071                        draw(canvas);
19072                    }
19073                }
19074            } finally {
19075                renderNode.end(canvas);
19076                setDisplayListProperties(renderNode);
19077            }
19078        } else {
19079            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
19080            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
19081        }
19082        return renderNode;
19083    }
19084
19085    private void resetDisplayList() {
19086        mRenderNode.discardDisplayList();
19087        if (mBackgroundRenderNode != null) {
19088            mBackgroundRenderNode.discardDisplayList();
19089        }
19090    }
19091
19092    /**
19093     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
19094     *
19095     * @return A non-scaled bitmap representing this view or null if cache is disabled.
19096     *
19097     * @see #getDrawingCache(boolean)
19098     *
19099     * @deprecated The view drawing cache was largely made obsolete with the introduction of
19100     * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
19101     * layers are largely unnecessary and can easily result in a net loss in performance due to the
19102     * cost of creating and updating the layer. In the rare cases where caching layers are useful,
19103     * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
19104     * rendering. For software-rendered snapshots of a small part of the View hierarchy or
19105     * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
19106     * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
19107     * software-rendered usages are discouraged and have compatibility issues with hardware-only
19108     * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
19109     * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
19110     * reports or unit testing the {@link PixelCopy} API is recommended.
19111     */
19112    @Deprecated
19113    public Bitmap getDrawingCache() {
19114        return getDrawingCache(false);
19115    }
19116
19117    /**
19118     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
19119     * is null when caching is disabled. If caching is enabled and the cache is not ready,
19120     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
19121     * draw from the cache when the cache is enabled. To benefit from the cache, you must
19122     * request the drawing cache by calling this method and draw it on screen if the
19123     * returned bitmap is not null.</p>
19124     *
19125     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
19126     * this method will create a bitmap of the same size as this view. Because this bitmap
19127     * will be drawn scaled by the parent ViewGroup, the result on screen might show
19128     * scaling artifacts. To avoid such artifacts, you should call this method by setting
19129     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
19130     * size than the view. This implies that your application must be able to handle this
19131     * size.</p>
19132     *
19133     * @param autoScale Indicates whether the generated bitmap should be scaled based on
19134     *        the current density of the screen when the application is in compatibility
19135     *        mode.
19136     *
19137     * @return A bitmap representing this view or null if cache is disabled.
19138     *
19139     * @see #setDrawingCacheEnabled(boolean)
19140     * @see #isDrawingCacheEnabled()
19141     * @see #buildDrawingCache(boolean)
19142     * @see #destroyDrawingCache()
19143     *
19144     * @deprecated The view drawing cache was largely made obsolete with the introduction of
19145     * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
19146     * layers are largely unnecessary and can easily result in a net loss in performance due to the
19147     * cost of creating and updating the layer. In the rare cases where caching layers are useful,
19148     * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
19149     * rendering. For software-rendered snapshots of a small part of the View hierarchy or
19150     * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
19151     * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
19152     * software-rendered usages are discouraged and have compatibility issues with hardware-only
19153     * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
19154     * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
19155     * reports or unit testing the {@link PixelCopy} API is recommended.
19156     */
19157    @Deprecated
19158    public Bitmap getDrawingCache(boolean autoScale) {
19159        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
19160            return null;
19161        }
19162        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
19163            buildDrawingCache(autoScale);
19164        }
19165        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
19166    }
19167
19168    /**
19169     * <p>Frees the resources used by the drawing cache. If you call
19170     * {@link #buildDrawingCache()} manually without calling
19171     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
19172     * should cleanup the cache with this method afterwards.</p>
19173     *
19174     * @see #setDrawingCacheEnabled(boolean)
19175     * @see #buildDrawingCache()
19176     * @see #getDrawingCache()
19177     *
19178     * @deprecated The view drawing cache was largely made obsolete with the introduction of
19179     * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
19180     * layers are largely unnecessary and can easily result in a net loss in performance due to the
19181     * cost of creating and updating the layer. In the rare cases where caching layers are useful,
19182     * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
19183     * rendering. For software-rendered snapshots of a small part of the View hierarchy or
19184     * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
19185     * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
19186     * software-rendered usages are discouraged and have compatibility issues with hardware-only
19187     * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
19188     * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
19189     * reports or unit testing the {@link PixelCopy} API is recommended.
19190     */
19191    @Deprecated
19192    public void destroyDrawingCache() {
19193        if (mDrawingCache != null) {
19194            mDrawingCache.recycle();
19195            mDrawingCache = null;
19196        }
19197        if (mUnscaledDrawingCache != null) {
19198            mUnscaledDrawingCache.recycle();
19199            mUnscaledDrawingCache = null;
19200        }
19201    }
19202
19203    /**
19204     * Setting a solid background color for the drawing cache's bitmaps will improve
19205     * performance and memory usage. Note, though that this should only be used if this
19206     * view will always be drawn on top of a solid color.
19207     *
19208     * @param color The background color to use for the drawing cache's bitmap
19209     *
19210     * @see #setDrawingCacheEnabled(boolean)
19211     * @see #buildDrawingCache()
19212     * @see #getDrawingCache()
19213     *
19214     * @deprecated The view drawing cache was largely made obsolete with the introduction of
19215     * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
19216     * layers are largely unnecessary and can easily result in a net loss in performance due to the
19217     * cost of creating and updating the layer. In the rare cases where caching layers are useful,
19218     * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
19219     * rendering. For software-rendered snapshots of a small part of the View hierarchy or
19220     * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
19221     * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
19222     * software-rendered usages are discouraged and have compatibility issues with hardware-only
19223     * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
19224     * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
19225     * reports or unit testing the {@link PixelCopy} API is recommended.
19226     */
19227    @Deprecated
19228    public void setDrawingCacheBackgroundColor(@ColorInt int color) {
19229        if (color != mDrawingCacheBackgroundColor) {
19230            mDrawingCacheBackgroundColor = color;
19231            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
19232        }
19233    }
19234
19235    /**
19236     * @see #setDrawingCacheBackgroundColor(int)
19237     *
19238     * @return The background color to used for the drawing cache's bitmap
19239     *
19240     * @deprecated The view drawing cache was largely made obsolete with the introduction of
19241     * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
19242     * layers are largely unnecessary and can easily result in a net loss in performance due to the
19243     * cost of creating and updating the layer. In the rare cases where caching layers are useful,
19244     * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
19245     * rendering. For software-rendered snapshots of a small part of the View hierarchy or
19246     * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
19247     * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
19248     * software-rendered usages are discouraged and have compatibility issues with hardware-only
19249     * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
19250     * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
19251     * reports or unit testing the {@link PixelCopy} API is recommended.
19252     */
19253    @Deprecated
19254    @ColorInt
19255    public int getDrawingCacheBackgroundColor() {
19256        return mDrawingCacheBackgroundColor;
19257    }
19258
19259    /**
19260     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
19261     *
19262     * @see #buildDrawingCache(boolean)
19263     *
19264     * @deprecated The view drawing cache was largely made obsolete with the introduction of
19265     * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
19266     * layers are largely unnecessary and can easily result in a net loss in performance due to the
19267     * cost of creating and updating the layer. In the rare cases where caching layers are useful,
19268     * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
19269     * rendering. For software-rendered snapshots of a small part of the View hierarchy or
19270     * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
19271     * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
19272     * software-rendered usages are discouraged and have compatibility issues with hardware-only
19273     * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
19274     * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
19275     * reports or unit testing the {@link PixelCopy} API is recommended.
19276     */
19277    @Deprecated
19278    public void buildDrawingCache() {
19279        buildDrawingCache(false);
19280    }
19281
19282    /**
19283     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
19284     *
19285     * <p>If you call {@link #buildDrawingCache()} manually without calling
19286     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
19287     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
19288     *
19289     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
19290     * this method will create a bitmap of the same size as this view. Because this bitmap
19291     * will be drawn scaled by the parent ViewGroup, the result on screen might show
19292     * scaling artifacts. To avoid such artifacts, you should call this method by setting
19293     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
19294     * size than the view. This implies that your application must be able to handle this
19295     * size.</p>
19296     *
19297     * <p>You should avoid calling this method when hardware acceleration is enabled. If
19298     * you do not need the drawing cache bitmap, calling this method will increase memory
19299     * usage and cause the view to be rendered in software once, thus negatively impacting
19300     * performance.</p>
19301     *
19302     * @see #getDrawingCache()
19303     * @see #destroyDrawingCache()
19304     *
19305     * @deprecated The view drawing cache was largely made obsolete with the introduction of
19306     * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache
19307     * layers are largely unnecessary and can easily result in a net loss in performance due to the
19308     * cost of creating and updating the layer. In the rare cases where caching layers are useful,
19309     * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware
19310     * rendering. For software-rendered snapshots of a small part of the View hierarchy or
19311     * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or
19312     * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these
19313     * software-rendered usages are discouraged and have compatibility issues with hardware-only
19314     * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE}
19315     * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback
19316     * reports or unit testing the {@link PixelCopy} API is recommended.
19317     */
19318    @Deprecated
19319    public void buildDrawingCache(boolean autoScale) {
19320        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
19321                mDrawingCache == null : mUnscaledDrawingCache == null)) {
19322            if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) {
19323                Trace.traceBegin(Trace.TRACE_TAG_VIEW,
19324                        "buildDrawingCache/SW Layer for " + getClass().getSimpleName());
19325            }
19326            try {
19327                buildDrawingCacheImpl(autoScale);
19328            } finally {
19329                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
19330            }
19331        }
19332    }
19333
19334    /**
19335     * private, internal implementation of buildDrawingCache, used to enable tracing
19336     */
19337    private void buildDrawingCacheImpl(boolean autoScale) {
19338        mCachingFailed = false;
19339
19340        int width = mRight - mLeft;
19341        int height = mBottom - mTop;
19342
19343        final AttachInfo attachInfo = mAttachInfo;
19344        final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
19345
19346        if (autoScale && scalingRequired) {
19347            width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
19348            height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
19349        }
19350
19351        final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
19352        final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
19353        final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
19354
19355        final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
19356        final long drawingCacheSize =
19357                ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
19358        if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
19359            if (width > 0 && height > 0) {
19360                Log.w(VIEW_LOG_TAG, getClass().getSimpleName() + " not displayed because it is"
19361                        + " too large to fit into a software layer (or drawing cache), needs "
19362                        + projectedBitmapSize + " bytes, only "
19363                        + drawingCacheSize + " available");
19364            }
19365            destroyDrawingCache();
19366            mCachingFailed = true;
19367            return;
19368        }
19369
19370        boolean clear = true;
19371        Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
19372
19373        if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
19374            Bitmap.Config quality;
19375            if (!opaque) {
19376                // Never pick ARGB_4444 because it looks awful
19377                // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
19378                switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
19379                    case DRAWING_CACHE_QUALITY_AUTO:
19380                    case DRAWING_CACHE_QUALITY_LOW:
19381                    case DRAWING_CACHE_QUALITY_HIGH:
19382                    default:
19383                        quality = Bitmap.Config.ARGB_8888;
19384                        break;
19385                }
19386            } else {
19387                // Optimization for translucent windows
19388                // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
19389                quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
19390            }
19391
19392            // Try to cleanup memory
19393            if (bitmap != null) bitmap.recycle();
19394
19395            try {
19396                bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
19397                        width, height, quality);
19398                bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
19399                if (autoScale) {
19400                    mDrawingCache = bitmap;
19401                } else {
19402                    mUnscaledDrawingCache = bitmap;
19403                }
19404                if (opaque && use32BitCache) bitmap.setHasAlpha(false);
19405            } catch (OutOfMemoryError e) {
19406                // If there is not enough memory to create the bitmap cache, just
19407                // ignore the issue as bitmap caches are not required to draw the
19408                // view hierarchy
19409                if (autoScale) {
19410                    mDrawingCache = null;
19411                } else {
19412                    mUnscaledDrawingCache = null;
19413                }
19414                mCachingFailed = true;
19415                return;
19416            }
19417
19418            clear = drawingCacheBackgroundColor != 0;
19419        }
19420
19421        Canvas canvas;
19422        if (attachInfo != null) {
19423            canvas = attachInfo.mCanvas;
19424            if (canvas == null) {
19425                canvas = new Canvas();
19426            }
19427            canvas.setBitmap(bitmap);
19428            // Temporarily clobber the cached Canvas in case one of our children
19429            // is also using a drawing cache. Without this, the children would
19430            // steal the canvas by attaching their own bitmap to it and bad, bad
19431            // thing would happen (invisible views, corrupted drawings, etc.)
19432            attachInfo.mCanvas = null;
19433        } else {
19434            // This case should hopefully never or seldom happen
19435            canvas = new Canvas(bitmap);
19436        }
19437
19438        if (clear) {
19439            bitmap.eraseColor(drawingCacheBackgroundColor);
19440        }
19441
19442        computeScroll();
19443        final int restoreCount = canvas.save();
19444
19445        if (autoScale && scalingRequired) {
19446            final float scale = attachInfo.mApplicationScale;
19447            canvas.scale(scale, scale);
19448        }
19449
19450        canvas.translate(-mScrollX, -mScrollY);
19451
19452        mPrivateFlags |= PFLAG_DRAWN;
19453        if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
19454                mLayerType != LAYER_TYPE_NONE) {
19455            mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
19456        }
19457
19458        // Fast path for layouts with no backgrounds
19459        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
19460            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
19461            dispatchDraw(canvas);
19462            drawAutofilledHighlight(canvas);
19463            if (mOverlay != null && !mOverlay.isEmpty()) {
19464                mOverlay.getOverlayView().draw(canvas);
19465            }
19466        } else {
19467            draw(canvas);
19468        }
19469
19470        canvas.restoreToCount(restoreCount);
19471        canvas.setBitmap(null);
19472
19473        if (attachInfo != null) {
19474            // Restore the cached Canvas for our siblings
19475            attachInfo.mCanvas = canvas;
19476        }
19477    }
19478
19479    /**
19480     * Create a snapshot of the view into a bitmap.  We should probably make
19481     * some form of this public, but should think about the API.
19482     *
19483     * @hide
19484     */
19485    public Bitmap createSnapshot(ViewDebug.CanvasProvider canvasProvider, boolean skipChildren) {
19486        int width = mRight - mLeft;
19487        int height = mBottom - mTop;
19488
19489        final AttachInfo attachInfo = mAttachInfo;
19490        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
19491        width = (int) ((width * scale) + 0.5f);
19492        height = (int) ((height * scale) + 0.5f);
19493
19494        Canvas oldCanvas = null;
19495        try {
19496            Canvas canvas = canvasProvider.getCanvas(this,
19497                    width > 0 ? width : 1, height > 0 ? height : 1);
19498
19499            if (attachInfo != null) {
19500                oldCanvas = attachInfo.mCanvas;
19501                // Temporarily clobber the cached Canvas in case one of our children
19502                // is also using a drawing cache. Without this, the children would
19503                // steal the canvas by attaching their own bitmap to it and bad, bad
19504                // things would happen (invisible views, corrupted drawings, etc.)
19505                attachInfo.mCanvas = null;
19506            }
19507
19508            computeScroll();
19509            final int restoreCount = canvas.save();
19510            canvas.scale(scale, scale);
19511            canvas.translate(-mScrollX, -mScrollY);
19512
19513            // Temporarily remove the dirty mask
19514            int flags = mPrivateFlags;
19515            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
19516
19517            // Fast path for layouts with no backgrounds
19518            if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
19519                dispatchDraw(canvas);
19520                drawAutofilledHighlight(canvas);
19521                if (mOverlay != null && !mOverlay.isEmpty()) {
19522                    mOverlay.getOverlayView().draw(canvas);
19523                }
19524            } else {
19525                draw(canvas);
19526            }
19527
19528            mPrivateFlags = flags;
19529            canvas.restoreToCount(restoreCount);
19530            return canvasProvider.createBitmap();
19531        } finally {
19532            if (oldCanvas != null) {
19533                attachInfo.mCanvas = oldCanvas;
19534            }
19535        }
19536    }
19537
19538    /**
19539     * Indicates whether this View is currently in edit mode. A View is usually
19540     * in edit mode when displayed within a developer tool. For instance, if
19541     * this View is being drawn by a visual user interface builder, this method
19542     * should return true.
19543     *
19544     * Subclasses should check the return value of this method to provide
19545     * different behaviors if their normal behavior might interfere with the
19546     * host environment. For instance: the class spawns a thread in its
19547     * constructor, the drawing code relies on device-specific features, etc.
19548     *
19549     * This method is usually checked in the drawing code of custom widgets.
19550     *
19551     * @return True if this View is in edit mode, false otherwise.
19552     */
19553    public boolean isInEditMode() {
19554        return false;
19555    }
19556
19557    /**
19558     * If the View draws content inside its padding and enables fading edges,
19559     * it needs to support padding offsets. Padding offsets are added to the
19560     * fading edges to extend the length of the fade so that it covers pixels
19561     * drawn inside the padding.
19562     *
19563     * Subclasses of this class should override this method if they need
19564     * to draw content inside the padding.
19565     *
19566     * @return True if padding offset must be applied, false otherwise.
19567     *
19568     * @see #getLeftPaddingOffset()
19569     * @see #getRightPaddingOffset()
19570     * @see #getTopPaddingOffset()
19571     * @see #getBottomPaddingOffset()
19572     *
19573     * @since CURRENT
19574     */
19575    protected boolean isPaddingOffsetRequired() {
19576        return false;
19577    }
19578
19579    /**
19580     * Amount by which to extend the left fading region. Called only when
19581     * {@link #isPaddingOffsetRequired()} returns true.
19582     *
19583     * @return The left padding offset in pixels.
19584     *
19585     * @see #isPaddingOffsetRequired()
19586     *
19587     * @since CURRENT
19588     */
19589    protected int getLeftPaddingOffset() {
19590        return 0;
19591    }
19592
19593    /**
19594     * Amount by which to extend the right fading region. Called only when
19595     * {@link #isPaddingOffsetRequired()} returns true.
19596     *
19597     * @return The right padding offset in pixels.
19598     *
19599     * @see #isPaddingOffsetRequired()
19600     *
19601     * @since CURRENT
19602     */
19603    protected int getRightPaddingOffset() {
19604        return 0;
19605    }
19606
19607    /**
19608     * Amount by which to extend the top fading region. Called only when
19609     * {@link #isPaddingOffsetRequired()} returns true.
19610     *
19611     * @return The top padding offset in pixels.
19612     *
19613     * @see #isPaddingOffsetRequired()
19614     *
19615     * @since CURRENT
19616     */
19617    protected int getTopPaddingOffset() {
19618        return 0;
19619    }
19620
19621    /**
19622     * Amount by which to extend the bottom fading region. Called only when
19623     * {@link #isPaddingOffsetRequired()} returns true.
19624     *
19625     * @return The bottom padding offset in pixels.
19626     *
19627     * @see #isPaddingOffsetRequired()
19628     *
19629     * @since CURRENT
19630     */
19631    protected int getBottomPaddingOffset() {
19632        return 0;
19633    }
19634
19635    /**
19636     * @hide
19637     * @param offsetRequired
19638     */
19639    protected int getFadeTop(boolean offsetRequired) {
19640        int top = mPaddingTop;
19641        if (offsetRequired) top += getTopPaddingOffset();
19642        return top;
19643    }
19644
19645    /**
19646     * @hide
19647     * @param offsetRequired
19648     */
19649    protected int getFadeHeight(boolean offsetRequired) {
19650        int padding = mPaddingTop;
19651        if (offsetRequired) padding += getTopPaddingOffset();
19652        return mBottom - mTop - mPaddingBottom - padding;
19653    }
19654
19655    /**
19656     * <p>Indicates whether this view is attached to a hardware accelerated
19657     * window or not.</p>
19658     *
19659     * <p>Even if this method returns true, it does not mean that every call
19660     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
19661     * accelerated {@link android.graphics.Canvas}. For instance, if this view
19662     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
19663     * window is hardware accelerated,
19664     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
19665     * return false, and this method will return true.</p>
19666     *
19667     * @return True if the view is attached to a window and the window is
19668     *         hardware accelerated; false in any other case.
19669     */
19670    @ViewDebug.ExportedProperty(category = "drawing")
19671    public boolean isHardwareAccelerated() {
19672        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
19673    }
19674
19675    /**
19676     * Sets a rectangular area on this view to which the view will be clipped
19677     * when it is drawn. Setting the value to null will remove the clip bounds
19678     * and the view will draw normally, using its full bounds.
19679     *
19680     * @param clipBounds The rectangular area, in the local coordinates of
19681     * this view, to which future drawing operations will be clipped.
19682     */
19683    public void setClipBounds(Rect clipBounds) {
19684        if (clipBounds == mClipBounds
19685                || (clipBounds != null && clipBounds.equals(mClipBounds))) {
19686            return;
19687        }
19688        if (clipBounds != null) {
19689            if (mClipBounds == null) {
19690                mClipBounds = new Rect(clipBounds);
19691            } else {
19692                mClipBounds.set(clipBounds);
19693            }
19694        } else {
19695            mClipBounds = null;
19696        }
19697        mRenderNode.setClipBounds(mClipBounds);
19698        invalidateViewProperty(false, false);
19699    }
19700
19701    /**
19702     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
19703     *
19704     * @return A copy of the current clip bounds if clip bounds are set,
19705     * otherwise null.
19706     */
19707    public Rect getClipBounds() {
19708        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
19709    }
19710
19711
19712    /**
19713     * Populates an output rectangle with the clip bounds of the view,
19714     * returning {@code true} if successful or {@code false} if the view's
19715     * clip bounds are {@code null}.
19716     *
19717     * @param outRect rectangle in which to place the clip bounds of the view
19718     * @return {@code true} if successful or {@code false} if the view's
19719     *         clip bounds are {@code null}
19720     */
19721    public boolean getClipBounds(Rect outRect) {
19722        if (mClipBounds != null) {
19723            outRect.set(mClipBounds);
19724            return true;
19725        }
19726        return false;
19727    }
19728
19729    /**
19730     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
19731     * case of an active Animation being run on the view.
19732     */
19733    private boolean applyLegacyAnimation(ViewGroup parent, long drawingTime,
19734            Animation a, boolean scalingRequired) {
19735        Transformation invalidationTransform;
19736        final int flags = parent.mGroupFlags;
19737        final boolean initialized = a.isInitialized();
19738        if (!initialized) {
19739            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
19740            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
19741            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
19742            onAnimationStart();
19743        }
19744
19745        final Transformation t = parent.getChildTransformation();
19746        boolean more = a.getTransformation(drawingTime, t, 1f);
19747        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
19748            if (parent.mInvalidationTransformation == null) {
19749                parent.mInvalidationTransformation = new Transformation();
19750            }
19751            invalidationTransform = parent.mInvalidationTransformation;
19752            a.getTransformation(drawingTime, invalidationTransform, 1f);
19753        } else {
19754            invalidationTransform = t;
19755        }
19756
19757        if (more) {
19758            if (!a.willChangeBounds()) {
19759                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
19760                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
19761                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
19762                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
19763                    // The child need to draw an animation, potentially offscreen, so
19764                    // make sure we do not cancel invalidate requests
19765                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
19766                    parent.invalidate(mLeft, mTop, mRight, mBottom);
19767                }
19768            } else {
19769                if (parent.mInvalidateRegion == null) {
19770                    parent.mInvalidateRegion = new RectF();
19771                }
19772                final RectF region = parent.mInvalidateRegion;
19773                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
19774                        invalidationTransform);
19775
19776                // The child need to draw an animation, potentially offscreen, so
19777                // make sure we do not cancel invalidate requests
19778                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
19779
19780                final int left = mLeft + (int) region.left;
19781                final int top = mTop + (int) region.top;
19782                parent.invalidate(left, top, left + (int) (region.width() + .5f),
19783                        top + (int) (region.height() + .5f));
19784            }
19785        }
19786        return more;
19787    }
19788
19789    /**
19790     * This method is called by getDisplayList() when a display list is recorded for a View.
19791     * It pushes any properties to the RenderNode that aren't managed by the RenderNode.
19792     */
19793    void setDisplayListProperties(RenderNode renderNode) {
19794        if (renderNode != null) {
19795            renderNode.setHasOverlappingRendering(getHasOverlappingRendering());
19796            renderNode.setClipToBounds(mParent instanceof ViewGroup
19797                    && ((ViewGroup) mParent).getClipChildren());
19798
19799            float alpha = 1;
19800            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
19801                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
19802                ViewGroup parentVG = (ViewGroup) mParent;
19803                final Transformation t = parentVG.getChildTransformation();
19804                if (parentVG.getChildStaticTransformation(this, t)) {
19805                    final int transformType = t.getTransformationType();
19806                    if (transformType != Transformation.TYPE_IDENTITY) {
19807                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
19808                            alpha = t.getAlpha();
19809                        }
19810                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
19811                            renderNode.setStaticMatrix(t.getMatrix());
19812                        }
19813                    }
19814                }
19815            }
19816            if (mTransformationInfo != null) {
19817                alpha *= getFinalAlpha();
19818                if (alpha < 1) {
19819                    final int multipliedAlpha = (int) (255 * alpha);
19820                    if (onSetAlpha(multipliedAlpha)) {
19821                        alpha = 1;
19822                    }
19823                }
19824                renderNode.setAlpha(alpha);
19825            } else if (alpha < 1) {
19826                renderNode.setAlpha(alpha);
19827            }
19828        }
19829    }
19830
19831    /**
19832     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
19833     *
19834     * This is where the View specializes rendering behavior based on layer type,
19835     * and hardware acceleration.
19836     */
19837    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
19838        final boolean hardwareAcceleratedCanvas = canvas.isHardwareAccelerated();
19839        /* If an attached view draws to a HW canvas, it may use its RenderNode + DisplayList.
19840         *
19841         * If a view is dettached, its DisplayList shouldn't exist. If the canvas isn't
19842         * HW accelerated, it can't handle drawing RenderNodes.
19843         */
19844        boolean drawingWithRenderNode = mAttachInfo != null
19845                && mAttachInfo.mHardwareAccelerated
19846                && hardwareAcceleratedCanvas;
19847
19848        boolean more = false;
19849        final boolean childHasIdentityMatrix = hasIdentityMatrix();
19850        final int parentFlags = parent.mGroupFlags;
19851
19852        if ((parentFlags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) != 0) {
19853            parent.getChildTransformation().clear();
19854            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
19855        }
19856
19857        Transformation transformToApply = null;
19858        boolean concatMatrix = false;
19859        final boolean scalingRequired = mAttachInfo != null && mAttachInfo.mScalingRequired;
19860        final Animation a = getAnimation();
19861        if (a != null) {
19862            more = applyLegacyAnimation(parent, drawingTime, a, scalingRequired);
19863            concatMatrix = a.willChangeTransformationMatrix();
19864            if (concatMatrix) {
19865                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
19866            }
19867            transformToApply = parent.getChildTransformation();
19868        } else {
19869            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) {
19870                // No longer animating: clear out old animation matrix
19871                mRenderNode.setAnimationMatrix(null);
19872                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
19873            }
19874            if (!drawingWithRenderNode
19875                    && (parentFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
19876                final Transformation t = parent.getChildTransformation();
19877                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
19878                if (hasTransform) {
19879                    final int transformType = t.getTransformationType();
19880                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
19881                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
19882                }
19883            }
19884        }
19885
19886        concatMatrix |= !childHasIdentityMatrix;
19887
19888        // Sets the flag as early as possible to allow draw() implementations
19889        // to call invalidate() successfully when doing animations
19890        mPrivateFlags |= PFLAG_DRAWN;
19891
19892        if (!concatMatrix &&
19893                (parentFlags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
19894                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
19895                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
19896                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
19897            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
19898            return more;
19899        }
19900        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
19901
19902        if (hardwareAcceleratedCanvas) {
19903            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
19904            // retain the flag's value temporarily in the mRecreateDisplayList flag
19905            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) != 0;
19906            mPrivateFlags &= ~PFLAG_INVALIDATED;
19907        }
19908
19909        RenderNode renderNode = null;
19910        Bitmap cache = null;
19911        int layerType = getLayerType(); // TODO: signify cache state with just 'cache' local
19912        if (layerType == LAYER_TYPE_SOFTWARE || !drawingWithRenderNode) {
19913             if (layerType != LAYER_TYPE_NONE) {
19914                 // If not drawing with RenderNode, treat HW layers as SW
19915                 layerType = LAYER_TYPE_SOFTWARE;
19916                 buildDrawingCache(true);
19917            }
19918            cache = getDrawingCache(true);
19919        }
19920
19921        if (drawingWithRenderNode) {
19922            // Delay getting the display list until animation-driven alpha values are
19923            // set up and possibly passed on to the view
19924            renderNode = updateDisplayListIfDirty();
19925            if (!renderNode.isValid()) {
19926                // Uncommon, but possible. If a view is removed from the hierarchy during the call
19927                // to getDisplayList(), the display list will be marked invalid and we should not
19928                // try to use it again.
19929                renderNode = null;
19930                drawingWithRenderNode = false;
19931            }
19932        }
19933
19934        int sx = 0;
19935        int sy = 0;
19936        if (!drawingWithRenderNode) {
19937            computeScroll();
19938            sx = mScrollX;
19939            sy = mScrollY;
19940        }
19941
19942        final boolean drawingWithDrawingCache = cache != null && !drawingWithRenderNode;
19943        final boolean offsetForScroll = cache == null && !drawingWithRenderNode;
19944
19945        int restoreTo = -1;
19946        if (!drawingWithRenderNode || transformToApply != null) {
19947            restoreTo = canvas.save();
19948        }
19949        if (offsetForScroll) {
19950            canvas.translate(mLeft - sx, mTop - sy);
19951        } else {
19952            if (!drawingWithRenderNode) {
19953                canvas.translate(mLeft, mTop);
19954            }
19955            if (scalingRequired) {
19956                if (drawingWithRenderNode) {
19957                    // TODO: Might not need this if we put everything inside the DL
19958                    restoreTo = canvas.save();
19959                }
19960                // mAttachInfo cannot be null, otherwise scalingRequired == false
19961                final float scale = 1.0f / mAttachInfo.mApplicationScale;
19962                canvas.scale(scale, scale);
19963            }
19964        }
19965
19966        float alpha = drawingWithRenderNode ? 1 : (getAlpha() * getTransitionAlpha());
19967        if (transformToApply != null
19968                || alpha < 1
19969                || !hasIdentityMatrix()
19970                || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
19971            if (transformToApply != null || !childHasIdentityMatrix) {
19972                int transX = 0;
19973                int transY = 0;
19974
19975                if (offsetForScroll) {
19976                    transX = -sx;
19977                    transY = -sy;
19978                }
19979
19980                if (transformToApply != null) {
19981                    if (concatMatrix) {
19982                        if (drawingWithRenderNode) {
19983                            renderNode.setAnimationMatrix(transformToApply.getMatrix());
19984                        } else {
19985                            // Undo the scroll translation, apply the transformation matrix,
19986                            // then redo the scroll translate to get the correct result.
19987                            canvas.translate(-transX, -transY);
19988                            canvas.concat(transformToApply.getMatrix());
19989                            canvas.translate(transX, transY);
19990                        }
19991                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
19992                    }
19993
19994                    float transformAlpha = transformToApply.getAlpha();
19995                    if (transformAlpha < 1) {
19996                        alpha *= transformAlpha;
19997                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
19998                    }
19999                }
20000
20001                if (!childHasIdentityMatrix && !drawingWithRenderNode) {
20002                    canvas.translate(-transX, -transY);
20003                    canvas.concat(getMatrix());
20004                    canvas.translate(transX, transY);
20005                }
20006            }
20007
20008            // Deal with alpha if it is or used to be <1
20009            if (alpha < 1 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
20010                if (alpha < 1) {
20011                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
20012                } else {
20013                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
20014                }
20015                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
20016                if (!drawingWithDrawingCache) {
20017                    final int multipliedAlpha = (int) (255 * alpha);
20018                    if (!onSetAlpha(multipliedAlpha)) {
20019                        if (drawingWithRenderNode) {
20020                            renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha());
20021                        } else if (layerType == LAYER_TYPE_NONE) {
20022                            canvas.saveLayerAlpha(sx, sy, sx + getWidth(), sy + getHeight(),
20023                                    multipliedAlpha);
20024                        }
20025                    } else {
20026                        // Alpha is handled by the child directly, clobber the layer's alpha
20027                        mPrivateFlags |= PFLAG_ALPHA_SET;
20028                    }
20029                }
20030            }
20031        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
20032            onSetAlpha(255);
20033            mPrivateFlags &= ~PFLAG_ALPHA_SET;
20034        }
20035
20036        if (!drawingWithRenderNode) {
20037            // apply clips directly, since RenderNode won't do it for this draw
20038            if ((parentFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 && cache == null) {
20039                if (offsetForScroll) {
20040                    canvas.clipRect(sx, sy, sx + getWidth(), sy + getHeight());
20041                } else {
20042                    if (!scalingRequired || cache == null) {
20043                        canvas.clipRect(0, 0, getWidth(), getHeight());
20044                    } else {
20045                        canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
20046                    }
20047                }
20048            }
20049
20050            if (mClipBounds != null) {
20051                // clip bounds ignore scroll
20052                canvas.clipRect(mClipBounds);
20053            }
20054        }
20055
20056        if (!drawingWithDrawingCache) {
20057            if (drawingWithRenderNode) {
20058                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
20059                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
20060            } else {
20061                // Fast path for layouts with no backgrounds
20062                if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
20063                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
20064                    dispatchDraw(canvas);
20065                } else {
20066                    draw(canvas);
20067                }
20068            }
20069        } else if (cache != null) {
20070            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
20071            if (layerType == LAYER_TYPE_NONE || mLayerPaint == null) {
20072                // no layer paint, use temporary paint to draw bitmap
20073                Paint cachePaint = parent.mCachePaint;
20074                if (cachePaint == null) {
20075                    cachePaint = new Paint();
20076                    cachePaint.setDither(false);
20077                    parent.mCachePaint = cachePaint;
20078                }
20079                cachePaint.setAlpha((int) (alpha * 255));
20080                canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
20081            } else {
20082                // use layer paint to draw the bitmap, merging the two alphas, but also restore
20083                int layerPaintAlpha = mLayerPaint.getAlpha();
20084                if (alpha < 1) {
20085                    mLayerPaint.setAlpha((int) (alpha * layerPaintAlpha));
20086                }
20087                canvas.drawBitmap(cache, 0.0f, 0.0f, mLayerPaint);
20088                if (alpha < 1) {
20089                    mLayerPaint.setAlpha(layerPaintAlpha);
20090                }
20091            }
20092        }
20093
20094        if (restoreTo >= 0) {
20095            canvas.restoreToCount(restoreTo);
20096        }
20097
20098        if (a != null && !more) {
20099            if (!hardwareAcceleratedCanvas && !a.getFillAfter()) {
20100                onSetAlpha(255);
20101            }
20102            parent.finishAnimatingView(this, a);
20103        }
20104
20105        if (more && hardwareAcceleratedCanvas) {
20106            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
20107                // alpha animations should cause the child to recreate its display list
20108                invalidate(true);
20109            }
20110        }
20111
20112        mRecreateDisplayList = false;
20113
20114        return more;
20115    }
20116
20117    static Paint getDebugPaint() {
20118        if (sDebugPaint == null) {
20119            sDebugPaint = new Paint();
20120            sDebugPaint.setAntiAlias(false);
20121        }
20122        return sDebugPaint;
20123    }
20124
20125    final int dipsToPixels(int dips) {
20126        float scale = getContext().getResources().getDisplayMetrics().density;
20127        return (int) (dips * scale + 0.5f);
20128    }
20129
20130    final private void debugDrawFocus(Canvas canvas) {
20131        if (isFocused()) {
20132            final int cornerSquareSize = dipsToPixels(DEBUG_CORNERS_SIZE_DIP);
20133            final int l = mScrollX;
20134            final int r = l + mRight - mLeft;
20135            final int t = mScrollY;
20136            final int b = t + mBottom - mTop;
20137
20138            final Paint paint = getDebugPaint();
20139            paint.setColor(DEBUG_CORNERS_COLOR);
20140
20141            // Draw squares in corners.
20142            paint.setStyle(Paint.Style.FILL);
20143            canvas.drawRect(l, t, l + cornerSquareSize, t + cornerSquareSize, paint);
20144            canvas.drawRect(r - cornerSquareSize, t, r, t + cornerSquareSize, paint);
20145            canvas.drawRect(l, b - cornerSquareSize, l + cornerSquareSize, b, paint);
20146            canvas.drawRect(r - cornerSquareSize, b - cornerSquareSize, r, b, paint);
20147
20148            // Draw big X across the view.
20149            paint.setStyle(Paint.Style.STROKE);
20150            canvas.drawLine(l, t, r, b, paint);
20151            canvas.drawLine(l, b, r, t, paint);
20152        }
20153    }
20154
20155    /**
20156     * Manually render this view (and all of its children) to the given Canvas.
20157     * The view must have already done a full layout before this function is
20158     * called.  When implementing a view, implement
20159     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
20160     * If you do need to override this method, call the superclass version.
20161     *
20162     * @param canvas The Canvas to which the View is rendered.
20163     */
20164    @CallSuper
20165    public void draw(Canvas canvas) {
20166        final int privateFlags = mPrivateFlags;
20167        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
20168                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
20169        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
20170
20171        /*
20172         * Draw traversal performs several drawing steps which must be executed
20173         * in the appropriate order:
20174         *
20175         *      1. Draw the background
20176         *      2. If necessary, save the canvas' layers to prepare for fading
20177         *      3. Draw view's content
20178         *      4. Draw children
20179         *      5. If necessary, draw the fading edges and restore layers
20180         *      6. Draw decorations (scrollbars for instance)
20181         */
20182
20183        // Step 1, draw the background, if needed
20184        int saveCount;
20185
20186        if (!dirtyOpaque) {
20187            drawBackground(canvas);
20188        }
20189
20190        // skip step 2 & 5 if possible (common case)
20191        final int viewFlags = mViewFlags;
20192        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
20193        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
20194        if (!verticalEdges && !horizontalEdges) {
20195            // Step 3, draw the content
20196            if (!dirtyOpaque) onDraw(canvas);
20197
20198            // Step 4, draw the children
20199            dispatchDraw(canvas);
20200
20201            drawAutofilledHighlight(canvas);
20202
20203            // Overlay is part of the content and draws beneath Foreground
20204            if (mOverlay != null && !mOverlay.isEmpty()) {
20205                mOverlay.getOverlayView().dispatchDraw(canvas);
20206            }
20207
20208            // Step 6, draw decorations (foreground, scrollbars)
20209            onDrawForeground(canvas);
20210
20211            // Step 7, draw the default focus highlight
20212            drawDefaultFocusHighlight(canvas);
20213
20214            if (debugDraw()) {
20215                debugDrawFocus(canvas);
20216            }
20217
20218            // we're done...
20219            return;
20220        }
20221
20222        /*
20223         * Here we do the full fledged routine...
20224         * (this is an uncommon case where speed matters less,
20225         * this is why we repeat some of the tests that have been
20226         * done above)
20227         */
20228
20229        boolean drawTop = false;
20230        boolean drawBottom = false;
20231        boolean drawLeft = false;
20232        boolean drawRight = false;
20233
20234        float topFadeStrength = 0.0f;
20235        float bottomFadeStrength = 0.0f;
20236        float leftFadeStrength = 0.0f;
20237        float rightFadeStrength = 0.0f;
20238
20239        // Step 2, save the canvas' layers
20240        int paddingLeft = mPaddingLeft;
20241
20242        final boolean offsetRequired = isPaddingOffsetRequired();
20243        if (offsetRequired) {
20244            paddingLeft += getLeftPaddingOffset();
20245        }
20246
20247        int left = mScrollX + paddingLeft;
20248        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
20249        int top = mScrollY + getFadeTop(offsetRequired);
20250        int bottom = top + getFadeHeight(offsetRequired);
20251
20252        if (offsetRequired) {
20253            right += getRightPaddingOffset();
20254            bottom += getBottomPaddingOffset();
20255        }
20256
20257        final ScrollabilityCache scrollabilityCache = mScrollCache;
20258        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
20259        int length = (int) fadeHeight;
20260
20261        // clip the fade length if top and bottom fades overlap
20262        // overlapping fades produce odd-looking artifacts
20263        if (verticalEdges && (top + length > bottom - length)) {
20264            length = (bottom - top) / 2;
20265        }
20266
20267        // also clip horizontal fades if necessary
20268        if (horizontalEdges && (left + length > right - length)) {
20269            length = (right - left) / 2;
20270        }
20271
20272        if (verticalEdges) {
20273            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
20274            drawTop = topFadeStrength * fadeHeight > 1.0f;
20275            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
20276            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
20277        }
20278
20279        if (horizontalEdges) {
20280            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
20281            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
20282            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
20283            drawRight = rightFadeStrength * fadeHeight > 1.0f;
20284        }
20285
20286        saveCount = canvas.getSaveCount();
20287
20288        int solidColor = getSolidColor();
20289        if (solidColor == 0) {
20290            if (drawTop) {
20291                canvas.saveUnclippedLayer(left, top, right, top + length);
20292            }
20293
20294            if (drawBottom) {
20295                canvas.saveUnclippedLayer(left, bottom - length, right, bottom);
20296            }
20297
20298            if (drawLeft) {
20299                canvas.saveUnclippedLayer(left, top, left + length, bottom);
20300            }
20301
20302            if (drawRight) {
20303                canvas.saveUnclippedLayer(right - length, top, right, bottom);
20304            }
20305        } else {
20306            scrollabilityCache.setFadeColor(solidColor);
20307        }
20308
20309        // Step 3, draw the content
20310        if (!dirtyOpaque) onDraw(canvas);
20311
20312        // Step 4, draw the children
20313        dispatchDraw(canvas);
20314
20315        // Step 5, draw the fade effect and restore layers
20316        final Paint p = scrollabilityCache.paint;
20317        final Matrix matrix = scrollabilityCache.matrix;
20318        final Shader fade = scrollabilityCache.shader;
20319
20320        if (drawTop) {
20321            matrix.setScale(1, fadeHeight * topFadeStrength);
20322            matrix.postTranslate(left, top);
20323            fade.setLocalMatrix(matrix);
20324            p.setShader(fade);
20325            canvas.drawRect(left, top, right, top + length, p);
20326        }
20327
20328        if (drawBottom) {
20329            matrix.setScale(1, fadeHeight * bottomFadeStrength);
20330            matrix.postRotate(180);
20331            matrix.postTranslate(left, bottom);
20332            fade.setLocalMatrix(matrix);
20333            p.setShader(fade);
20334            canvas.drawRect(left, bottom - length, right, bottom, p);
20335        }
20336
20337        if (drawLeft) {
20338            matrix.setScale(1, fadeHeight * leftFadeStrength);
20339            matrix.postRotate(-90);
20340            matrix.postTranslate(left, top);
20341            fade.setLocalMatrix(matrix);
20342            p.setShader(fade);
20343            canvas.drawRect(left, top, left + length, bottom, p);
20344        }
20345
20346        if (drawRight) {
20347            matrix.setScale(1, fadeHeight * rightFadeStrength);
20348            matrix.postRotate(90);
20349            matrix.postTranslate(right, top);
20350            fade.setLocalMatrix(matrix);
20351            p.setShader(fade);
20352            canvas.drawRect(right - length, top, right, bottom, p);
20353        }
20354
20355        canvas.restoreToCount(saveCount);
20356
20357        drawAutofilledHighlight(canvas);
20358
20359        // Overlay is part of the content and draws beneath Foreground
20360        if (mOverlay != null && !mOverlay.isEmpty()) {
20361            mOverlay.getOverlayView().dispatchDraw(canvas);
20362        }
20363
20364        // Step 6, draw decorations (foreground, scrollbars)
20365        onDrawForeground(canvas);
20366
20367        if (debugDraw()) {
20368            debugDrawFocus(canvas);
20369        }
20370    }
20371
20372    /**
20373     * Draws the background onto the specified canvas.
20374     *
20375     * @param canvas Canvas on which to draw the background
20376     */
20377    private void drawBackground(Canvas canvas) {
20378        final Drawable background = mBackground;
20379        if (background == null) {
20380            return;
20381        }
20382
20383        setBackgroundBounds();
20384
20385        // Attempt to use a display list if requested.
20386        if (canvas.isHardwareAccelerated() && mAttachInfo != null
20387                && mAttachInfo.mThreadedRenderer != null) {
20388            mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode);
20389
20390            final RenderNode renderNode = mBackgroundRenderNode;
20391            if (renderNode != null && renderNode.isValid()) {
20392                setBackgroundRenderNodeProperties(renderNode);
20393                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
20394                return;
20395            }
20396        }
20397
20398        final int scrollX = mScrollX;
20399        final int scrollY = mScrollY;
20400        if ((scrollX | scrollY) == 0) {
20401            background.draw(canvas);
20402        } else {
20403            canvas.translate(scrollX, scrollY);
20404            background.draw(canvas);
20405            canvas.translate(-scrollX, -scrollY);
20406        }
20407    }
20408
20409    /**
20410     * Sets the correct background bounds and rebuilds the outline, if needed.
20411     * <p/>
20412     * This is called by LayoutLib.
20413     */
20414    void setBackgroundBounds() {
20415        if (mBackgroundSizeChanged && mBackground != null) {
20416            mBackground.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
20417            mBackgroundSizeChanged = false;
20418            rebuildOutline();
20419        }
20420    }
20421
20422    private void setBackgroundRenderNodeProperties(RenderNode renderNode) {
20423        renderNode.setTranslationX(mScrollX);
20424        renderNode.setTranslationY(mScrollY);
20425    }
20426
20427    /**
20428     * Creates a new display list or updates the existing display list for the
20429     * specified Drawable.
20430     *
20431     * @param drawable Drawable for which to create a display list
20432     * @param renderNode Existing RenderNode, or {@code null}
20433     * @return A valid display list for the specified drawable
20434     */
20435    private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) {
20436        if (renderNode == null) {
20437            renderNode = RenderNode.create(drawable.getClass().getName(), this);
20438        }
20439
20440        final Rect bounds = drawable.getBounds();
20441        final int width = bounds.width();
20442        final int height = bounds.height();
20443        final DisplayListCanvas canvas = renderNode.start(width, height);
20444
20445        // Reverse left/top translation done by drawable canvas, which will
20446        // instead be applied by rendernode's LTRB bounds below. This way, the
20447        // drawable's bounds match with its rendernode bounds and its content
20448        // will lie within those bounds in the rendernode tree.
20449        canvas.translate(-bounds.left, -bounds.top);
20450
20451        try {
20452            drawable.draw(canvas);
20453        } finally {
20454            renderNode.end(canvas);
20455        }
20456
20457        // Set up drawable properties that are view-independent.
20458        renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
20459        renderNode.setProjectBackwards(drawable.isProjected());
20460        renderNode.setProjectionReceiver(true);
20461        renderNode.setClipToBounds(false);
20462        return renderNode;
20463    }
20464
20465    /**
20466     * Returns the overlay for this view, creating it if it does not yet exist.
20467     * Adding drawables to the overlay will cause them to be displayed whenever
20468     * the view itself is redrawn. Objects in the overlay should be actively
20469     * managed: remove them when they should not be displayed anymore. The
20470     * overlay will always have the same size as its host view.
20471     *
20472     * <p>Note: Overlays do not currently work correctly with {@link
20473     * SurfaceView} or {@link TextureView}; contents in overlays for these
20474     * types of views may not display correctly.</p>
20475     *
20476     * @return The ViewOverlay object for this view.
20477     * @see ViewOverlay
20478     */
20479    public ViewOverlay getOverlay() {
20480        if (mOverlay == null) {
20481            mOverlay = new ViewOverlay(mContext, this);
20482        }
20483        return mOverlay;
20484    }
20485
20486    /**
20487     * Override this if your view is known to always be drawn on top of a solid color background,
20488     * and needs to draw fading edges. Returning a non-zero color enables the view system to
20489     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
20490     * should be set to 0xFF.
20491     *
20492     * @see #setVerticalFadingEdgeEnabled(boolean)
20493     * @see #setHorizontalFadingEdgeEnabled(boolean)
20494     *
20495     * @return The known solid color background for this view, or 0 if the color may vary
20496     */
20497    @ViewDebug.ExportedProperty(category = "drawing")
20498    @ColorInt
20499    public int getSolidColor() {
20500        return 0;
20501    }
20502
20503    /**
20504     * Build a human readable string representation of the specified view flags.
20505     *
20506     * @param flags the view flags to convert to a string
20507     * @return a String representing the supplied flags
20508     */
20509    private static String printFlags(int flags) {
20510        String output = "";
20511        int numFlags = 0;
20512        if ((flags & FOCUSABLE) == FOCUSABLE) {
20513            output += "TAKES_FOCUS";
20514            numFlags++;
20515        }
20516
20517        switch (flags & VISIBILITY_MASK) {
20518        case INVISIBLE:
20519            if (numFlags > 0) {
20520                output += " ";
20521            }
20522            output += "INVISIBLE";
20523            // USELESS HERE numFlags++;
20524            break;
20525        case GONE:
20526            if (numFlags > 0) {
20527                output += " ";
20528            }
20529            output += "GONE";
20530            // USELESS HERE numFlags++;
20531            break;
20532        default:
20533            break;
20534        }
20535        return output;
20536    }
20537
20538    /**
20539     * Build a human readable string representation of the specified private
20540     * view flags.
20541     *
20542     * @param privateFlags the private view flags to convert to a string
20543     * @return a String representing the supplied flags
20544     */
20545    private static String printPrivateFlags(int privateFlags) {
20546        String output = "";
20547        int numFlags = 0;
20548
20549        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
20550            output += "WANTS_FOCUS";
20551            numFlags++;
20552        }
20553
20554        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
20555            if (numFlags > 0) {
20556                output += " ";
20557            }
20558            output += "FOCUSED";
20559            numFlags++;
20560        }
20561
20562        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
20563            if (numFlags > 0) {
20564                output += " ";
20565            }
20566            output += "SELECTED";
20567            numFlags++;
20568        }
20569
20570        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
20571            if (numFlags > 0) {
20572                output += " ";
20573            }
20574            output += "IS_ROOT_NAMESPACE";
20575            numFlags++;
20576        }
20577
20578        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
20579            if (numFlags > 0) {
20580                output += " ";
20581            }
20582            output += "HAS_BOUNDS";
20583            numFlags++;
20584        }
20585
20586        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
20587            if (numFlags > 0) {
20588                output += " ";
20589            }
20590            output += "DRAWN";
20591            // USELESS HERE numFlags++;
20592        }
20593        return output;
20594    }
20595
20596    /**
20597     * <p>Indicates whether or not this view's layout will be requested during
20598     * the next hierarchy layout pass.</p>
20599     *
20600     * @return true if the layout will be forced during next layout pass
20601     */
20602    public boolean isLayoutRequested() {
20603        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
20604    }
20605
20606    /**
20607     * Return true if o is a ViewGroup that is laying out using optical bounds.
20608     * @hide
20609     */
20610    public static boolean isLayoutModeOptical(Object o) {
20611        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
20612    }
20613
20614    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
20615        Insets parentInsets = mParent instanceof View ?
20616                ((View) mParent).getOpticalInsets() : Insets.NONE;
20617        Insets childInsets = getOpticalInsets();
20618        return setFrame(
20619                left   + parentInsets.left - childInsets.left,
20620                top    + parentInsets.top  - childInsets.top,
20621                right  + parentInsets.left + childInsets.right,
20622                bottom + parentInsets.top  + childInsets.bottom);
20623    }
20624
20625    /**
20626     * Assign a size and position to a view and all of its
20627     * descendants
20628     *
20629     * <p>This is the second phase of the layout mechanism.
20630     * (The first is measuring). In this phase, each parent calls
20631     * layout on all of its children to position them.
20632     * This is typically done using the child measurements
20633     * that were stored in the measure pass().</p>
20634     *
20635     * <p>Derived classes should not override this method.
20636     * Derived classes with children should override
20637     * onLayout. In that method, they should
20638     * call layout on each of their children.</p>
20639     *
20640     * @param l Left position, relative to parent
20641     * @param t Top position, relative to parent
20642     * @param r Right position, relative to parent
20643     * @param b Bottom position, relative to parent
20644     */
20645    @SuppressWarnings({"unchecked"})
20646    public void layout(int l, int t, int r, int b) {
20647        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
20648            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
20649            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
20650        }
20651
20652        int oldL = mLeft;
20653        int oldT = mTop;
20654        int oldB = mBottom;
20655        int oldR = mRight;
20656
20657        boolean changed = isLayoutModeOptical(mParent) ?
20658                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
20659
20660        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
20661            onLayout(changed, l, t, r, b);
20662
20663            if (shouldDrawRoundScrollbar()) {
20664                if(mRoundScrollbarRenderer == null) {
20665                    mRoundScrollbarRenderer = new RoundScrollbarRenderer(this);
20666                }
20667            } else {
20668                mRoundScrollbarRenderer = null;
20669            }
20670
20671            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
20672
20673            ListenerInfo li = mListenerInfo;
20674            if (li != null && li.mOnLayoutChangeListeners != null) {
20675                ArrayList<OnLayoutChangeListener> listenersCopy =
20676                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
20677                int numListeners = listenersCopy.size();
20678                for (int i = 0; i < numListeners; ++i) {
20679                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
20680                }
20681            }
20682        }
20683
20684        final boolean wasLayoutValid = isLayoutValid();
20685
20686        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
20687        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
20688
20689        if (!wasLayoutValid && isFocused()) {
20690            mPrivateFlags &= ~PFLAG_WANTS_FOCUS;
20691            if (canTakeFocus()) {
20692                // We have a robust focus, so parents should no longer be wanting focus.
20693                clearParentsWantFocus();
20694            } else if (!getViewRootImpl().isInLayout()) {
20695                // This is a weird case. Most-likely the user, rather than ViewRootImpl, called
20696                // layout. In this case, there's no guarantee that parent layouts will be evaluated
20697                // and thus the safest action is to clear focus here.
20698                clearFocusInternal(null, /* propagate */ true, /* refocus */ false);
20699                clearParentsWantFocus();
20700            } else if (!hasParentWantsFocus()) {
20701                // original requestFocus was likely on this view directly, so just clear focus
20702                clearFocusInternal(null, /* propagate */ true, /* refocus */ false);
20703            }
20704            // otherwise, we let parents handle re-assigning focus during their layout passes.
20705        } else if ((mPrivateFlags & PFLAG_WANTS_FOCUS) != 0) {
20706            mPrivateFlags &= ~PFLAG_WANTS_FOCUS;
20707            View focused = findFocus();
20708            if (focused != null) {
20709                // Try to restore focus as close as possible to our starting focus.
20710                if (!restoreDefaultFocus() && !hasParentWantsFocus()) {
20711                    // Give up and clear focus once we've reached the top-most parent which wants
20712                    // focus.
20713                    focused.clearFocusInternal(null, /* propagate */ true, /* refocus */ false);
20714                }
20715            }
20716        }
20717
20718        if ((mPrivateFlags3 & PFLAG3_NOTIFY_AUTOFILL_ENTER_ON_LAYOUT) != 0) {
20719            mPrivateFlags3 &= ~PFLAG3_NOTIFY_AUTOFILL_ENTER_ON_LAYOUT;
20720            notifyEnterOrExitForAutoFillIfNeeded(true);
20721        }
20722    }
20723
20724    private boolean hasParentWantsFocus() {
20725        ViewParent parent = mParent;
20726        while (parent instanceof ViewGroup) {
20727            ViewGroup pv = (ViewGroup) parent;
20728            if ((pv.mPrivateFlags & PFLAG_WANTS_FOCUS) != 0) {
20729                return true;
20730            }
20731            parent = pv.mParent;
20732        }
20733        return false;
20734    }
20735
20736    /**
20737     * Called from layout when this view should
20738     * assign a size and position to each of its children.
20739     *
20740     * Derived classes with children should override
20741     * this method and call layout on each of
20742     * their children.
20743     * @param changed This is a new size or position for this view
20744     * @param left Left position, relative to parent
20745     * @param top Top position, relative to parent
20746     * @param right Right position, relative to parent
20747     * @param bottom Bottom position, relative to parent
20748     */
20749    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
20750    }
20751
20752    /**
20753     * Assign a size and position to this view.
20754     *
20755     * This is called from layout.
20756     *
20757     * @param left Left position, relative to parent
20758     * @param top Top position, relative to parent
20759     * @param right Right position, relative to parent
20760     * @param bottom Bottom position, relative to parent
20761     * @return true if the new size and position are different than the
20762     *         previous ones
20763     * {@hide}
20764     */
20765    protected boolean setFrame(int left, int top, int right, int bottom) {
20766        boolean changed = false;
20767
20768        if (DBG) {
20769            Log.d(VIEW_LOG_TAG, this + " View.setFrame(" + left + "," + top + ","
20770                    + right + "," + bottom + ")");
20771        }
20772
20773        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
20774            changed = true;
20775
20776            // Remember our drawn bit
20777            int drawn = mPrivateFlags & PFLAG_DRAWN;
20778
20779            int oldWidth = mRight - mLeft;
20780            int oldHeight = mBottom - mTop;
20781            int newWidth = right - left;
20782            int newHeight = bottom - top;
20783            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
20784
20785            // Invalidate our old position
20786            invalidate(sizeChanged);
20787
20788            mLeft = left;
20789            mTop = top;
20790            mRight = right;
20791            mBottom = bottom;
20792            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
20793
20794            mPrivateFlags |= PFLAG_HAS_BOUNDS;
20795
20796
20797            if (sizeChanged) {
20798                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
20799            }
20800
20801            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) {
20802                // If we are visible, force the DRAWN bit to on so that
20803                // this invalidate will go through (at least to our parent).
20804                // This is because someone may have invalidated this view
20805                // before this call to setFrame came in, thereby clearing
20806                // the DRAWN bit.
20807                mPrivateFlags |= PFLAG_DRAWN;
20808                invalidate(sizeChanged);
20809                // parent display list may need to be recreated based on a change in the bounds
20810                // of any child
20811                invalidateParentCaches();
20812            }
20813
20814            // Reset drawn bit to original value (invalidate turns it off)
20815            mPrivateFlags |= drawn;
20816
20817            mBackgroundSizeChanged = true;
20818            mDefaultFocusHighlightSizeChanged = true;
20819            if (mForegroundInfo != null) {
20820                mForegroundInfo.mBoundsChanged = true;
20821            }
20822
20823            notifySubtreeAccessibilityStateChangedIfNeeded();
20824        }
20825        return changed;
20826    }
20827
20828    /**
20829     * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}.
20830     * @hide
20831     */
20832    public void setLeftTopRightBottom(int left, int top, int right, int bottom) {
20833        setFrame(left, top, right, bottom);
20834    }
20835
20836    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
20837        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
20838        if (mOverlay != null) {
20839            mOverlay.getOverlayView().setRight(newWidth);
20840            mOverlay.getOverlayView().setBottom(newHeight);
20841        }
20842        // If this isn't laid out yet, focus assignment will be handled during the "deferment/
20843        // backtracking" of requestFocus during layout, so don't touch focus here.
20844        if (!sCanFocusZeroSized && isLayoutValid()) {
20845            if (newWidth <= 0 || newHeight <= 0) {
20846                if (hasFocus()) {
20847                    clearFocus();
20848                    if (mParent instanceof ViewGroup) {
20849                        ((ViewGroup) mParent).clearFocusedInCluster();
20850                    }
20851                }
20852                clearAccessibilityFocus();
20853            } else if (oldWidth <= 0 || oldHeight <= 0) {
20854                if (mParent != null && canTakeFocus()) {
20855                    mParent.focusableViewAvailable(this);
20856                }
20857            }
20858        }
20859        rebuildOutline();
20860    }
20861
20862    /**
20863     * Finalize inflating a view from XML.  This is called as the last phase
20864     * of inflation, after all child views have been added.
20865     *
20866     * <p>Even if the subclass overrides onFinishInflate, they should always be
20867     * sure to call the super method, so that we get called.
20868     */
20869    @CallSuper
20870    protected void onFinishInflate() {
20871    }
20872
20873    /**
20874     * Returns the resources associated with this view.
20875     *
20876     * @return Resources object.
20877     */
20878    public Resources getResources() {
20879        return mResources;
20880    }
20881
20882    /**
20883     * Invalidates the specified Drawable.
20884     *
20885     * @param drawable the drawable to invalidate
20886     */
20887    @Override
20888    public void invalidateDrawable(@NonNull Drawable drawable) {
20889        if (verifyDrawable(drawable)) {
20890            final Rect dirty = drawable.getDirtyBounds();
20891            final int scrollX = mScrollX;
20892            final int scrollY = mScrollY;
20893
20894            invalidate(dirty.left + scrollX, dirty.top + scrollY,
20895                    dirty.right + scrollX, dirty.bottom + scrollY);
20896            rebuildOutline();
20897        }
20898    }
20899
20900    /**
20901     * Schedules an action on a drawable to occur at a specified time.
20902     *
20903     * @param who the recipient of the action
20904     * @param what the action to run on the drawable
20905     * @param when the time at which the action must occur. Uses the
20906     *        {@link SystemClock#uptimeMillis} timebase.
20907     */
20908    @Override
20909    public void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when) {
20910        if (verifyDrawable(who) && what != null) {
20911            final long delay = when - SystemClock.uptimeMillis();
20912            if (mAttachInfo != null) {
20913                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
20914                        Choreographer.CALLBACK_ANIMATION, what, who,
20915                        Choreographer.subtractFrameDelay(delay));
20916            } else {
20917                // Postpone the runnable until we know
20918                // on which thread it needs to run.
20919                getRunQueue().postDelayed(what, delay);
20920            }
20921        }
20922    }
20923
20924    /**
20925     * Cancels a scheduled action on a drawable.
20926     *
20927     * @param who the recipient of the action
20928     * @param what the action to cancel
20929     */
20930    @Override
20931    public void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what) {
20932        if (verifyDrawable(who) && what != null) {
20933            if (mAttachInfo != null) {
20934                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
20935                        Choreographer.CALLBACK_ANIMATION, what, who);
20936            }
20937            getRunQueue().removeCallbacks(what);
20938        }
20939    }
20940
20941    /**
20942     * Unschedule any events associated with the given Drawable.  This can be
20943     * used when selecting a new Drawable into a view, so that the previous
20944     * one is completely unscheduled.
20945     *
20946     * @param who The Drawable to unschedule.
20947     *
20948     * @see #drawableStateChanged
20949     */
20950    public void unscheduleDrawable(Drawable who) {
20951        if (mAttachInfo != null && who != null) {
20952            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
20953                    Choreographer.CALLBACK_ANIMATION, null, who);
20954        }
20955    }
20956
20957    /**
20958     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
20959     * that the View directionality can and will be resolved before its Drawables.
20960     *
20961     * Will call {@link View#onResolveDrawables} when resolution is done.
20962     *
20963     * @hide
20964     */
20965    protected void resolveDrawables() {
20966        // Drawables resolution may need to happen before resolving the layout direction (which is
20967        // done only during the measure() call).
20968        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
20969        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
20970        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
20971        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
20972        // direction to be resolved as its resolved value will be the same as its raw value.
20973        if (!isLayoutDirectionResolved() &&
20974                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
20975            return;
20976        }
20977
20978        final int layoutDirection = isLayoutDirectionResolved() ?
20979                getLayoutDirection() : getRawLayoutDirection();
20980
20981        if (mBackground != null) {
20982            mBackground.setLayoutDirection(layoutDirection);
20983        }
20984        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
20985            mForegroundInfo.mDrawable.setLayoutDirection(layoutDirection);
20986        }
20987        if (mDefaultFocusHighlight != null) {
20988            mDefaultFocusHighlight.setLayoutDirection(layoutDirection);
20989        }
20990        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
20991        onResolveDrawables(layoutDirection);
20992    }
20993
20994    boolean areDrawablesResolved() {
20995        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
20996    }
20997
20998    /**
20999     * Called when layout direction has been resolved.
21000     *
21001     * The default implementation does nothing.
21002     *
21003     * @param layoutDirection The resolved layout direction.
21004     *
21005     * @see #LAYOUT_DIRECTION_LTR
21006     * @see #LAYOUT_DIRECTION_RTL
21007     *
21008     * @hide
21009     */
21010    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
21011    }
21012
21013    /**
21014     * @hide
21015     */
21016    protected void resetResolvedDrawables() {
21017        resetResolvedDrawablesInternal();
21018    }
21019
21020    void resetResolvedDrawablesInternal() {
21021        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
21022    }
21023
21024    /**
21025     * If your view subclass is displaying its own Drawable objects, it should
21026     * override this function and return true for any Drawable it is
21027     * displaying.  This allows animations for those drawables to be
21028     * scheduled.
21029     *
21030     * <p>Be sure to call through to the super class when overriding this
21031     * function.
21032     *
21033     * @param who The Drawable to verify.  Return true if it is one you are
21034     *            displaying, else return the result of calling through to the
21035     *            super class.
21036     *
21037     * @return boolean If true than the Drawable is being displayed in the
21038     *         view; else false and it is not allowed to animate.
21039     *
21040     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
21041     * @see #drawableStateChanged()
21042     */
21043    @CallSuper
21044    protected boolean verifyDrawable(@NonNull Drawable who) {
21045        // Avoid verifying the scroll bar drawable so that we don't end up in
21046        // an invalidation loop. This effectively prevents the scroll bar
21047        // drawable from triggering invalidations and scheduling runnables.
21048        return who == mBackground || (mForegroundInfo != null && mForegroundInfo.mDrawable == who)
21049                || (mDefaultFocusHighlight == who);
21050    }
21051
21052    /**
21053     * This function is called whenever the state of the view changes in such
21054     * a way that it impacts the state of drawables being shown.
21055     * <p>
21056     * If the View has a StateListAnimator, it will also be called to run necessary state
21057     * change animations.
21058     * <p>
21059     * Be sure to call through to the superclass when overriding this function.
21060     *
21061     * @see Drawable#setState(int[])
21062     */
21063    @CallSuper
21064    protected void drawableStateChanged() {
21065        final int[] state = getDrawableState();
21066        boolean changed = false;
21067
21068        final Drawable bg = mBackground;
21069        if (bg != null && bg.isStateful()) {
21070            changed |= bg.setState(state);
21071        }
21072
21073        final Drawable hl = mDefaultFocusHighlight;
21074        if (hl != null && hl.isStateful()) {
21075            changed |= hl.setState(state);
21076        }
21077
21078        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
21079        if (fg != null && fg.isStateful()) {
21080            changed |= fg.setState(state);
21081        }
21082
21083        if (mScrollCache != null) {
21084            final Drawable scrollBar = mScrollCache.scrollBar;
21085            if (scrollBar != null && scrollBar.isStateful()) {
21086                changed |= scrollBar.setState(state)
21087                        && mScrollCache.state != ScrollabilityCache.OFF;
21088            }
21089        }
21090
21091        if (mStateListAnimator != null) {
21092            mStateListAnimator.setState(state);
21093        }
21094
21095        if (changed) {
21096            invalidate();
21097        }
21098    }
21099
21100    /**
21101     * This function is called whenever the view hotspot changes and needs to
21102     * be propagated to drawables or child views managed by the view.
21103     * <p>
21104     * Dispatching to child views is handled by
21105     * {@link #dispatchDrawableHotspotChanged(float, float)}.
21106     * <p>
21107     * Be sure to call through to the superclass when overriding this function.
21108     *
21109     * @param x hotspot x coordinate
21110     * @param y hotspot y coordinate
21111     */
21112    @CallSuper
21113    public void drawableHotspotChanged(float x, float y) {
21114        if (mBackground != null) {
21115            mBackground.setHotspot(x, y);
21116        }
21117        if (mDefaultFocusHighlight != null) {
21118            mDefaultFocusHighlight.setHotspot(x, y);
21119        }
21120        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
21121            mForegroundInfo.mDrawable.setHotspot(x, y);
21122        }
21123
21124        dispatchDrawableHotspotChanged(x, y);
21125    }
21126
21127    /**
21128     * Dispatches drawableHotspotChanged to all of this View's children.
21129     *
21130     * @param x hotspot x coordinate
21131     * @param y hotspot y coordinate
21132     * @see #drawableHotspotChanged(float, float)
21133     */
21134    public void dispatchDrawableHotspotChanged(float x, float y) {
21135    }
21136
21137    /**
21138     * Call this to force a view to update its drawable state. This will cause
21139     * drawableStateChanged to be called on this view. Views that are interested
21140     * in the new state should call getDrawableState.
21141     *
21142     * @see #drawableStateChanged
21143     * @see #getDrawableState
21144     */
21145    public void refreshDrawableState() {
21146        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
21147        drawableStateChanged();
21148
21149        ViewParent parent = mParent;
21150        if (parent != null) {
21151            parent.childDrawableStateChanged(this);
21152        }
21153    }
21154
21155    /**
21156     * Create a default focus highlight if it doesn't exist.
21157     * @return a default focus highlight.
21158     */
21159    private Drawable getDefaultFocusHighlightDrawable() {
21160        if (mDefaultFocusHighlightCache == null) {
21161            if (mContext != null) {
21162                final int[] attrs = new int[] { android.R.attr.selectableItemBackground };
21163                final TypedArray ta = mContext.obtainStyledAttributes(attrs);
21164                mDefaultFocusHighlightCache = ta.getDrawable(0);
21165                ta.recycle();
21166            }
21167        }
21168        return mDefaultFocusHighlightCache;
21169    }
21170
21171    /**
21172     * Set the current default focus highlight.
21173     * @param highlight the highlight drawable, or {@code null} if it's no longer needed.
21174     */
21175    private void setDefaultFocusHighlight(Drawable highlight) {
21176        mDefaultFocusHighlight = highlight;
21177        mDefaultFocusHighlightSizeChanged = true;
21178        if (highlight != null) {
21179            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
21180                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
21181            }
21182            highlight.setLayoutDirection(getLayoutDirection());
21183            if (highlight.isStateful()) {
21184                highlight.setState(getDrawableState());
21185            }
21186            if (isAttachedToWindow()) {
21187                highlight.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
21188            }
21189            // Set callback last, since the view may still be initializing.
21190            highlight.setCallback(this);
21191        } else if ((mViewFlags & WILL_NOT_DRAW) != 0 && mBackground == null
21192                && (mForegroundInfo == null || mForegroundInfo.mDrawable == null)) {
21193            mPrivateFlags |= PFLAG_SKIP_DRAW;
21194        }
21195        invalidate();
21196    }
21197
21198    /**
21199     * Check whether we need to draw a default focus highlight when this view gets focused,
21200     * which requires:
21201     * <ul>
21202     *     <li>In both background and foreground, {@link android.R.attr#state_focused}
21203     *         is not defined.</li>
21204     *     <li>This view is not in touch mode.</li>
21205     *     <li>This view doesn't opt out for a default focus highlight, via
21206     *         {@link #setDefaultFocusHighlightEnabled(boolean)}.</li>
21207     *     <li>This view is attached to window.</li>
21208     * </ul>
21209     * @return {@code true} if a default focus highlight is needed.
21210     * @hide
21211     */
21212    @TestApi
21213    public boolean isDefaultFocusHighlightNeeded(Drawable background, Drawable foreground) {
21214        final boolean lackFocusState = (background == null || !background.isStateful()
21215                || !background.hasFocusStateSpecified())
21216                && (foreground == null || !foreground.isStateful()
21217                || !foreground.hasFocusStateSpecified());
21218        return !isInTouchMode() && getDefaultFocusHighlightEnabled() && lackFocusState
21219                && isAttachedToWindow() && sUseDefaultFocusHighlight;
21220    }
21221
21222    /**
21223     * When this view is focused, switches on/off the default focused highlight.
21224     * <p>
21225     * This always happens when this view is focused, and only at this moment the default focus
21226     * highlight can be visible.
21227     */
21228    private void switchDefaultFocusHighlight() {
21229        if (isFocused()) {
21230            final boolean needed = isDefaultFocusHighlightNeeded(mBackground,
21231                    mForegroundInfo == null ? null : mForegroundInfo.mDrawable);
21232            final boolean active = mDefaultFocusHighlight != null;
21233            if (needed && !active) {
21234                setDefaultFocusHighlight(getDefaultFocusHighlightDrawable());
21235            } else if (!needed && active) {
21236                // The highlight is no longer needed, so tear it down.
21237                setDefaultFocusHighlight(null);
21238            }
21239        }
21240    }
21241
21242    /**
21243     * Draw the default focus highlight onto the canvas.
21244     * @param canvas the canvas where we're drawing the highlight.
21245     */
21246    private void drawDefaultFocusHighlight(Canvas canvas) {
21247        if (mDefaultFocusHighlight != null) {
21248            if (mDefaultFocusHighlightSizeChanged) {
21249                mDefaultFocusHighlightSizeChanged = false;
21250                final int l = mScrollX;
21251                final int r = l + mRight - mLeft;
21252                final int t = mScrollY;
21253                final int b = t + mBottom - mTop;
21254                mDefaultFocusHighlight.setBounds(l, t, r, b);
21255            }
21256            mDefaultFocusHighlight.draw(canvas);
21257        }
21258    }
21259
21260    /**
21261     * Return an array of resource IDs of the drawable states representing the
21262     * current state of the view.
21263     *
21264     * @return The current drawable state
21265     *
21266     * @see Drawable#setState(int[])
21267     * @see #drawableStateChanged()
21268     * @see #onCreateDrawableState(int)
21269     */
21270    public final int[] getDrawableState() {
21271        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
21272            return mDrawableState;
21273        } else {
21274            mDrawableState = onCreateDrawableState(0);
21275            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
21276            return mDrawableState;
21277        }
21278    }
21279
21280    /**
21281     * Generate the new {@link android.graphics.drawable.Drawable} state for
21282     * this view. This is called by the view
21283     * system when the cached Drawable state is determined to be invalid.  To
21284     * retrieve the current state, you should use {@link #getDrawableState}.
21285     *
21286     * @param extraSpace if non-zero, this is the number of extra entries you
21287     * would like in the returned array in which you can place your own
21288     * states.
21289     *
21290     * @return Returns an array holding the current {@link Drawable} state of
21291     * the view.
21292     *
21293     * @see #mergeDrawableStates(int[], int[])
21294     */
21295    protected int[] onCreateDrawableState(int extraSpace) {
21296        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
21297                mParent instanceof View) {
21298            return ((View) mParent).onCreateDrawableState(extraSpace);
21299        }
21300
21301        int[] drawableState;
21302
21303        int privateFlags = mPrivateFlags;
21304
21305        int viewStateIndex = 0;
21306        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= StateSet.VIEW_STATE_PRESSED;
21307        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= StateSet.VIEW_STATE_ENABLED;
21308        if (isFocused()) viewStateIndex |= StateSet.VIEW_STATE_FOCUSED;
21309        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= StateSet.VIEW_STATE_SELECTED;
21310        if (hasWindowFocus()) viewStateIndex |= StateSet.VIEW_STATE_WINDOW_FOCUSED;
21311        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= StateSet.VIEW_STATE_ACTIVATED;
21312        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
21313                ThreadedRenderer.isAvailable()) {
21314            // This is set if HW acceleration is requested, even if the current
21315            // process doesn't allow it.  This is just to allow app preview
21316            // windows to better match their app.
21317            viewStateIndex |= StateSet.VIEW_STATE_ACCELERATED;
21318        }
21319        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= StateSet.VIEW_STATE_HOVERED;
21320
21321        final int privateFlags2 = mPrivateFlags2;
21322        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) {
21323            viewStateIndex |= StateSet.VIEW_STATE_DRAG_CAN_ACCEPT;
21324        }
21325        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) {
21326            viewStateIndex |= StateSet.VIEW_STATE_DRAG_HOVERED;
21327        }
21328
21329        drawableState = StateSet.get(viewStateIndex);
21330
21331        //noinspection ConstantIfStatement
21332        if (false) {
21333            Log.i("View", "drawableStateIndex=" + viewStateIndex);
21334            Log.i("View", toString()
21335                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
21336                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
21337                    + " fo=" + hasFocus()
21338                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
21339                    + " wf=" + hasWindowFocus()
21340                    + ": " + Arrays.toString(drawableState));
21341        }
21342
21343        if (extraSpace == 0) {
21344            return drawableState;
21345        }
21346
21347        final int[] fullState;
21348        if (drawableState != null) {
21349            fullState = new int[drawableState.length + extraSpace];
21350            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
21351        } else {
21352            fullState = new int[extraSpace];
21353        }
21354
21355        return fullState;
21356    }
21357
21358    /**
21359     * Merge your own state values in <var>additionalState</var> into the base
21360     * state values <var>baseState</var> that were returned by
21361     * {@link #onCreateDrawableState(int)}.
21362     *
21363     * @param baseState The base state values returned by
21364     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
21365     * own additional state values.
21366     *
21367     * @param additionalState The additional state values you would like
21368     * added to <var>baseState</var>; this array is not modified.
21369     *
21370     * @return As a convenience, the <var>baseState</var> array you originally
21371     * passed into the function is returned.
21372     *
21373     * @see #onCreateDrawableState(int)
21374     */
21375    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
21376        final int N = baseState.length;
21377        int i = N - 1;
21378        while (i >= 0 && baseState[i] == 0) {
21379            i--;
21380        }
21381        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
21382        return baseState;
21383    }
21384
21385    /**
21386     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
21387     * on all Drawable objects associated with this view.
21388     * <p>
21389     * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator
21390     * attached to this view.
21391     */
21392    @CallSuper
21393    public void jumpDrawablesToCurrentState() {
21394        if (mBackground != null) {
21395            mBackground.jumpToCurrentState();
21396        }
21397        if (mStateListAnimator != null) {
21398            mStateListAnimator.jumpToCurrentState();
21399        }
21400        if (mDefaultFocusHighlight != null) {
21401            mDefaultFocusHighlight.jumpToCurrentState();
21402        }
21403        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
21404            mForegroundInfo.mDrawable.jumpToCurrentState();
21405        }
21406    }
21407
21408    /**
21409     * Sets the background color for this view.
21410     * @param color the color of the background
21411     */
21412    @RemotableViewMethod
21413    public void setBackgroundColor(@ColorInt int color) {
21414        if (mBackground instanceof ColorDrawable) {
21415            ((ColorDrawable) mBackground.mutate()).setColor(color);
21416            computeOpaqueFlags();
21417            mBackgroundResource = 0;
21418        } else {
21419            setBackground(new ColorDrawable(color));
21420        }
21421    }
21422
21423    /**
21424     * Set the background to a given resource. The resource should refer to
21425     * a Drawable object or 0 to remove the background.
21426     * @param resid The identifier of the resource.
21427     *
21428     * @attr ref android.R.styleable#View_background
21429     */
21430    @RemotableViewMethod
21431    public void setBackgroundResource(@DrawableRes int resid) {
21432        if (resid != 0 && resid == mBackgroundResource) {
21433            return;
21434        }
21435
21436        Drawable d = null;
21437        if (resid != 0) {
21438            d = mContext.getDrawable(resid);
21439        }
21440        setBackground(d);
21441
21442        mBackgroundResource = resid;
21443    }
21444
21445    /**
21446     * Set the background to a given Drawable, or remove the background. If the
21447     * background has padding, this View's padding is set to the background's
21448     * padding. However, when a background is removed, this View's padding isn't
21449     * touched. If setting the padding is desired, please use
21450     * {@link #setPadding(int, int, int, int)}.
21451     *
21452     * @param background The Drawable to use as the background, or null to remove the
21453     *        background
21454     */
21455    public void setBackground(Drawable background) {
21456        //noinspection deprecation
21457        setBackgroundDrawable(background);
21458    }
21459
21460    /**
21461     * @deprecated use {@link #setBackground(Drawable)} instead
21462     */
21463    @Deprecated
21464    public void setBackgroundDrawable(Drawable background) {
21465        computeOpaqueFlags();
21466
21467        if (background == mBackground) {
21468            return;
21469        }
21470
21471        boolean requestLayout = false;
21472
21473        mBackgroundResource = 0;
21474
21475        /*
21476         * Regardless of whether we're setting a new background or not, we want
21477         * to clear the previous drawable. setVisible first while we still have the callback set.
21478         */
21479        if (mBackground != null) {
21480            if (isAttachedToWindow()) {
21481                mBackground.setVisible(false, false);
21482            }
21483            mBackground.setCallback(null);
21484            unscheduleDrawable(mBackground);
21485        }
21486
21487        if (background != null) {
21488            Rect padding = sThreadLocal.get();
21489            if (padding == null) {
21490                padding = new Rect();
21491                sThreadLocal.set(padding);
21492            }
21493            resetResolvedDrawablesInternal();
21494            background.setLayoutDirection(getLayoutDirection());
21495            if (background.getPadding(padding)) {
21496                resetResolvedPaddingInternal();
21497                switch (background.getLayoutDirection()) {
21498                    case LAYOUT_DIRECTION_RTL:
21499                        mUserPaddingLeftInitial = padding.right;
21500                        mUserPaddingRightInitial = padding.left;
21501                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
21502                        break;
21503                    case LAYOUT_DIRECTION_LTR:
21504                    default:
21505                        mUserPaddingLeftInitial = padding.left;
21506                        mUserPaddingRightInitial = padding.right;
21507                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
21508                }
21509                mLeftPaddingDefined = false;
21510                mRightPaddingDefined = false;
21511            }
21512
21513            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
21514            // if it has a different minimum size, we should layout again
21515            if (mBackground == null
21516                    || mBackground.getMinimumHeight() != background.getMinimumHeight()
21517                    || mBackground.getMinimumWidth() != background.getMinimumWidth()) {
21518                requestLayout = true;
21519            }
21520
21521            // Set mBackground before we set this as the callback and start making other
21522            // background drawable state change calls. In particular, the setVisible call below
21523            // can result in drawables attempting to start animations or otherwise invalidate,
21524            // which requires the view set as the callback (us) to recognize the drawable as
21525            // belonging to it as per verifyDrawable.
21526            mBackground = background;
21527            if (background.isStateful()) {
21528                background.setState(getDrawableState());
21529            }
21530            if (isAttachedToWindow()) {
21531                background.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
21532            }
21533
21534            applyBackgroundTint();
21535
21536            // Set callback last, since the view may still be initializing.
21537            background.setCallback(this);
21538
21539            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
21540                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
21541                requestLayout = true;
21542            }
21543        } else {
21544            /* Remove the background */
21545            mBackground = null;
21546            if ((mViewFlags & WILL_NOT_DRAW) != 0
21547                    && (mDefaultFocusHighlight == null)
21548                    && (mForegroundInfo == null || mForegroundInfo.mDrawable == null)) {
21549                mPrivateFlags |= PFLAG_SKIP_DRAW;
21550            }
21551
21552            /*
21553             * When the background is set, we try to apply its padding to this
21554             * View. When the background is removed, we don't touch this View's
21555             * padding. This is noted in the Javadocs. Hence, we don't need to
21556             * requestLayout(), the invalidate() below is sufficient.
21557             */
21558
21559            // The old background's minimum size could have affected this
21560            // View's layout, so let's requestLayout
21561            requestLayout = true;
21562        }
21563
21564        computeOpaqueFlags();
21565
21566        if (requestLayout) {
21567            requestLayout();
21568        }
21569
21570        mBackgroundSizeChanged = true;
21571        invalidate(true);
21572        invalidateOutline();
21573    }
21574
21575    /**
21576     * Gets the background drawable
21577     *
21578     * @return The drawable used as the background for this view, if any.
21579     *
21580     * @see #setBackground(Drawable)
21581     *
21582     * @attr ref android.R.styleable#View_background
21583     */
21584    public Drawable getBackground() {
21585        return mBackground;
21586    }
21587
21588    /**
21589     * Applies a tint to the background drawable. Does not modify the current tint
21590     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
21591     * <p>
21592     * Subsequent calls to {@link #setBackground(Drawable)} will automatically
21593     * mutate the drawable and apply the specified tint and tint mode using
21594     * {@link Drawable#setTintList(ColorStateList)}.
21595     *
21596     * @param tint the tint to apply, may be {@code null} to clear tint
21597     *
21598     * @attr ref android.R.styleable#View_backgroundTint
21599     * @see #getBackgroundTintList()
21600     * @see Drawable#setTintList(ColorStateList)
21601     */
21602    public void setBackgroundTintList(@Nullable ColorStateList tint) {
21603        if (mBackgroundTint == null) {
21604            mBackgroundTint = new TintInfo();
21605        }
21606        mBackgroundTint.mTintList = tint;
21607        mBackgroundTint.mHasTintList = true;
21608
21609        applyBackgroundTint();
21610    }
21611
21612    /**
21613     * Return the tint applied to the background drawable, if specified.
21614     *
21615     * @return the tint applied to the background drawable
21616     * @attr ref android.R.styleable#View_backgroundTint
21617     * @see #setBackgroundTintList(ColorStateList)
21618     */
21619    @Nullable
21620    public ColorStateList getBackgroundTintList() {
21621        return mBackgroundTint != null ? mBackgroundTint.mTintList : null;
21622    }
21623
21624    /**
21625     * Specifies the blending mode used to apply the tint specified by
21626     * {@link #setBackgroundTintList(ColorStateList)}} to the background
21627     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
21628     *
21629     * @param tintMode the blending mode used to apply the tint, may be
21630     *                 {@code null} to clear tint
21631     * @attr ref android.R.styleable#View_backgroundTintMode
21632     * @see #getBackgroundTintMode()
21633     * @see Drawable#setTintMode(PorterDuff.Mode)
21634     */
21635    public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) {
21636        if (mBackgroundTint == null) {
21637            mBackgroundTint = new TintInfo();
21638        }
21639        mBackgroundTint.mTintMode = tintMode;
21640        mBackgroundTint.mHasTintMode = true;
21641
21642        applyBackgroundTint();
21643    }
21644
21645    /**
21646     * Return the blending mode used to apply the tint to the background
21647     * drawable, if specified.
21648     *
21649     * @return the blending mode used to apply the tint to the background
21650     *         drawable
21651     * @attr ref android.R.styleable#View_backgroundTintMode
21652     * @see #setBackgroundTintMode(PorterDuff.Mode)
21653     */
21654    @Nullable
21655    public PorterDuff.Mode getBackgroundTintMode() {
21656        return mBackgroundTint != null ? mBackgroundTint.mTintMode : null;
21657    }
21658
21659    private void applyBackgroundTint() {
21660        if (mBackground != null && mBackgroundTint != null) {
21661            final TintInfo tintInfo = mBackgroundTint;
21662            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
21663                mBackground = mBackground.mutate();
21664
21665                if (tintInfo.mHasTintList) {
21666                    mBackground.setTintList(tintInfo.mTintList);
21667                }
21668
21669                if (tintInfo.mHasTintMode) {
21670                    mBackground.setTintMode(tintInfo.mTintMode);
21671                }
21672
21673                // The drawable (or one of its children) may not have been
21674                // stateful before applying the tint, so let's try again.
21675                if (mBackground.isStateful()) {
21676                    mBackground.setState(getDrawableState());
21677                }
21678            }
21679        }
21680    }
21681
21682    /**
21683     * Returns the drawable used as the foreground of this View. The
21684     * foreground drawable, if non-null, is always drawn on top of the view's content.
21685     *
21686     * @return a Drawable or null if no foreground was set
21687     *
21688     * @see #onDrawForeground(Canvas)
21689     */
21690    public Drawable getForeground() {
21691        return mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
21692    }
21693
21694    /**
21695     * Supply a Drawable that is to be rendered on top of all of the content in the view.
21696     *
21697     * @param foreground the Drawable to be drawn on top of the children
21698     *
21699     * @attr ref android.R.styleable#View_foreground
21700     */
21701    public void setForeground(Drawable foreground) {
21702        if (mForegroundInfo == null) {
21703            if (foreground == null) {
21704                // Nothing to do.
21705                return;
21706            }
21707            mForegroundInfo = new ForegroundInfo();
21708        }
21709
21710        if (foreground == mForegroundInfo.mDrawable) {
21711            // Nothing to do
21712            return;
21713        }
21714
21715        if (mForegroundInfo.mDrawable != null) {
21716            if (isAttachedToWindow()) {
21717                mForegroundInfo.mDrawable.setVisible(false, false);
21718            }
21719            mForegroundInfo.mDrawable.setCallback(null);
21720            unscheduleDrawable(mForegroundInfo.mDrawable);
21721        }
21722
21723        mForegroundInfo.mDrawable = foreground;
21724        mForegroundInfo.mBoundsChanged = true;
21725        if (foreground != null) {
21726            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
21727                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
21728            }
21729            foreground.setLayoutDirection(getLayoutDirection());
21730            if (foreground.isStateful()) {
21731                foreground.setState(getDrawableState());
21732            }
21733            applyForegroundTint();
21734            if (isAttachedToWindow()) {
21735                foreground.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
21736            }
21737            // Set callback last, since the view may still be initializing.
21738            foreground.setCallback(this);
21739        } else if ((mViewFlags & WILL_NOT_DRAW) != 0 && mBackground == null
21740                && (mDefaultFocusHighlight == null)) {
21741            mPrivateFlags |= PFLAG_SKIP_DRAW;
21742        }
21743        requestLayout();
21744        invalidate();
21745    }
21746
21747    /**
21748     * Magic bit used to support features of framework-internal window decor implementation details.
21749     * This used to live exclusively in FrameLayout.
21750     *
21751     * @return true if the foreground should draw inside the padding region or false
21752     *         if it should draw inset by the view's padding
21753     * @hide internal use only; only used by FrameLayout and internal screen layouts.
21754     */
21755    public boolean isForegroundInsidePadding() {
21756        return mForegroundInfo != null ? mForegroundInfo.mInsidePadding : true;
21757    }
21758
21759    /**
21760     * Describes how the foreground is positioned.
21761     *
21762     * @return foreground gravity.
21763     *
21764     * @see #setForegroundGravity(int)
21765     *
21766     * @attr ref android.R.styleable#View_foregroundGravity
21767     */
21768    public int getForegroundGravity() {
21769        return mForegroundInfo != null ? mForegroundInfo.mGravity
21770                : Gravity.START | Gravity.TOP;
21771    }
21772
21773    /**
21774     * Describes how the foreground is positioned. Defaults to START and TOP.
21775     *
21776     * @param gravity see {@link android.view.Gravity}
21777     *
21778     * @see #getForegroundGravity()
21779     *
21780     * @attr ref android.R.styleable#View_foregroundGravity
21781     */
21782    public void setForegroundGravity(int gravity) {
21783        if (mForegroundInfo == null) {
21784            mForegroundInfo = new ForegroundInfo();
21785        }
21786
21787        if (mForegroundInfo.mGravity != gravity) {
21788            if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) {
21789                gravity |= Gravity.START;
21790            }
21791
21792            if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) {
21793                gravity |= Gravity.TOP;
21794            }
21795
21796            mForegroundInfo.mGravity = gravity;
21797            requestLayout();
21798        }
21799    }
21800
21801    /**
21802     * Applies a tint to the foreground drawable. Does not modify the current tint
21803     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
21804     * <p>
21805     * Subsequent calls to {@link #setForeground(Drawable)} will automatically
21806     * mutate the drawable and apply the specified tint and tint mode using
21807     * {@link Drawable#setTintList(ColorStateList)}.
21808     *
21809     * @param tint the tint to apply, may be {@code null} to clear tint
21810     *
21811     * @attr ref android.R.styleable#View_foregroundTint
21812     * @see #getForegroundTintList()
21813     * @see Drawable#setTintList(ColorStateList)
21814     */
21815    public void setForegroundTintList(@Nullable ColorStateList tint) {
21816        if (mForegroundInfo == null) {
21817            mForegroundInfo = new ForegroundInfo();
21818        }
21819        if (mForegroundInfo.mTintInfo == null) {
21820            mForegroundInfo.mTintInfo = new TintInfo();
21821        }
21822        mForegroundInfo.mTintInfo.mTintList = tint;
21823        mForegroundInfo.mTintInfo.mHasTintList = true;
21824
21825        applyForegroundTint();
21826    }
21827
21828    /**
21829     * Return the tint applied to the foreground drawable, if specified.
21830     *
21831     * @return the tint applied to the foreground drawable
21832     * @attr ref android.R.styleable#View_foregroundTint
21833     * @see #setForegroundTintList(ColorStateList)
21834     */
21835    @Nullable
21836    public ColorStateList getForegroundTintList() {
21837        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
21838                ? mForegroundInfo.mTintInfo.mTintList : null;
21839    }
21840
21841    /**
21842     * Specifies the blending mode used to apply the tint specified by
21843     * {@link #setForegroundTintList(ColorStateList)}} to the background
21844     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
21845     *
21846     * @param tintMode the blending mode used to apply the tint, may be
21847     *                 {@code null} to clear tint
21848     * @attr ref android.R.styleable#View_foregroundTintMode
21849     * @see #getForegroundTintMode()
21850     * @see Drawable#setTintMode(PorterDuff.Mode)
21851     */
21852    public void setForegroundTintMode(@Nullable PorterDuff.Mode tintMode) {
21853        if (mForegroundInfo == null) {
21854            mForegroundInfo = new ForegroundInfo();
21855        }
21856        if (mForegroundInfo.mTintInfo == null) {
21857            mForegroundInfo.mTintInfo = new TintInfo();
21858        }
21859        mForegroundInfo.mTintInfo.mTintMode = tintMode;
21860        mForegroundInfo.mTintInfo.mHasTintMode = true;
21861
21862        applyForegroundTint();
21863    }
21864
21865    /**
21866     * Return the blending mode used to apply the tint to the foreground
21867     * drawable, if specified.
21868     *
21869     * @return the blending mode used to apply the tint to the foreground
21870     *         drawable
21871     * @attr ref android.R.styleable#View_foregroundTintMode
21872     * @see #setForegroundTintMode(PorterDuff.Mode)
21873     */
21874    @Nullable
21875    public PorterDuff.Mode getForegroundTintMode() {
21876        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
21877                ? mForegroundInfo.mTintInfo.mTintMode : null;
21878    }
21879
21880    private void applyForegroundTint() {
21881        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
21882                && mForegroundInfo.mTintInfo != null) {
21883            final TintInfo tintInfo = mForegroundInfo.mTintInfo;
21884            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
21885                mForegroundInfo.mDrawable = mForegroundInfo.mDrawable.mutate();
21886
21887                if (tintInfo.mHasTintList) {
21888                    mForegroundInfo.mDrawable.setTintList(tintInfo.mTintList);
21889                }
21890
21891                if (tintInfo.mHasTintMode) {
21892                    mForegroundInfo.mDrawable.setTintMode(tintInfo.mTintMode);
21893                }
21894
21895                // The drawable (or one of its children) may not have been
21896                // stateful before applying the tint, so let's try again.
21897                if (mForegroundInfo.mDrawable.isStateful()) {
21898                    mForegroundInfo.mDrawable.setState(getDrawableState());
21899                }
21900            }
21901        }
21902    }
21903
21904    /**
21905     * Get the drawable to be overlayed when a view is autofilled
21906     *
21907     * @return The drawable
21908     *
21909     * @throws IllegalStateException if the drawable could not be found.
21910     */
21911    @Nullable private Drawable getAutofilledDrawable() {
21912        if (mAttachInfo == null) {
21913            return null;
21914        }
21915        // Lazily load the isAutofilled drawable.
21916        if (mAttachInfo.mAutofilledDrawable == null) {
21917            Context rootContext = getRootView().getContext();
21918            TypedArray a = rootContext.getTheme().obtainStyledAttributes(AUTOFILL_HIGHLIGHT_ATTR);
21919            int attributeResourceId = a.getResourceId(0, 0);
21920            mAttachInfo.mAutofilledDrawable = rootContext.getDrawable(attributeResourceId);
21921            a.recycle();
21922        }
21923
21924        return mAttachInfo.mAutofilledDrawable;
21925    }
21926
21927    /**
21928     * Draw {@link View#isAutofilled()} highlight over view if the view is autofilled.
21929     *
21930     * @param canvas The canvas to draw on
21931     */
21932    private void drawAutofilledHighlight(@NonNull Canvas canvas) {
21933        if (isAutofilled()) {
21934            Drawable autofilledHighlight = getAutofilledDrawable();
21935
21936            if (autofilledHighlight != null) {
21937                autofilledHighlight.setBounds(0, 0, getWidth(), getHeight());
21938                autofilledHighlight.draw(canvas);
21939            }
21940        }
21941    }
21942
21943    /**
21944     * Draw any foreground content for this view.
21945     *
21946     * <p>Foreground content may consist of scroll bars, a {@link #setForeground foreground}
21947     * drawable or other view-specific decorations. The foreground is drawn on top of the
21948     * primary view content.</p>
21949     *
21950     * @param canvas canvas to draw into
21951     */
21952    public void onDrawForeground(Canvas canvas) {
21953        onDrawScrollIndicators(canvas);
21954        onDrawScrollBars(canvas);
21955
21956        final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
21957        if (foreground != null) {
21958            if (mForegroundInfo.mBoundsChanged) {
21959                mForegroundInfo.mBoundsChanged = false;
21960                final Rect selfBounds = mForegroundInfo.mSelfBounds;
21961                final Rect overlayBounds = mForegroundInfo.mOverlayBounds;
21962
21963                if (mForegroundInfo.mInsidePadding) {
21964                    selfBounds.set(0, 0, getWidth(), getHeight());
21965                } else {
21966                    selfBounds.set(getPaddingLeft(), getPaddingTop(),
21967                            getWidth() - getPaddingRight(), getHeight() - getPaddingBottom());
21968                }
21969
21970                final int ld = getLayoutDirection();
21971                Gravity.apply(mForegroundInfo.mGravity, foreground.getIntrinsicWidth(),
21972                        foreground.getIntrinsicHeight(), selfBounds, overlayBounds, ld);
21973                foreground.setBounds(overlayBounds);
21974            }
21975
21976            foreground.draw(canvas);
21977        }
21978    }
21979
21980    /**
21981     * Sets the padding. The view may add on the space required to display
21982     * the scrollbars, depending on the style and visibility of the scrollbars.
21983     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
21984     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
21985     * from the values set in this call.
21986     *
21987     * @attr ref android.R.styleable#View_padding
21988     * @attr ref android.R.styleable#View_paddingBottom
21989     * @attr ref android.R.styleable#View_paddingLeft
21990     * @attr ref android.R.styleable#View_paddingRight
21991     * @attr ref android.R.styleable#View_paddingTop
21992     * @param left the left padding in pixels
21993     * @param top the top padding in pixels
21994     * @param right the right padding in pixels
21995     * @param bottom the bottom padding in pixels
21996     */
21997    public void setPadding(int left, int top, int right, int bottom) {
21998        resetResolvedPaddingInternal();
21999
22000        mUserPaddingStart = UNDEFINED_PADDING;
22001        mUserPaddingEnd = UNDEFINED_PADDING;
22002
22003        mUserPaddingLeftInitial = left;
22004        mUserPaddingRightInitial = right;
22005
22006        mLeftPaddingDefined = true;
22007        mRightPaddingDefined = true;
22008
22009        internalSetPadding(left, top, right, bottom);
22010    }
22011
22012    /**
22013     * @hide
22014     */
22015    protected void internalSetPadding(int left, int top, int right, int bottom) {
22016        mUserPaddingLeft = left;
22017        mUserPaddingRight = right;
22018        mUserPaddingBottom = bottom;
22019
22020        final int viewFlags = mViewFlags;
22021        boolean changed = false;
22022
22023        // Common case is there are no scroll bars.
22024        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
22025            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
22026                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
22027                        ? 0 : getVerticalScrollbarWidth();
22028                switch (mVerticalScrollbarPosition) {
22029                    case SCROLLBAR_POSITION_DEFAULT:
22030                        if (isLayoutRtl()) {
22031                            left += offset;
22032                        } else {
22033                            right += offset;
22034                        }
22035                        break;
22036                    case SCROLLBAR_POSITION_RIGHT:
22037                        right += offset;
22038                        break;
22039                    case SCROLLBAR_POSITION_LEFT:
22040                        left += offset;
22041                        break;
22042                }
22043            }
22044            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
22045                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
22046                        ? 0 : getHorizontalScrollbarHeight();
22047            }
22048        }
22049
22050        if (mPaddingLeft != left) {
22051            changed = true;
22052            mPaddingLeft = left;
22053        }
22054        if (mPaddingTop != top) {
22055            changed = true;
22056            mPaddingTop = top;
22057        }
22058        if (mPaddingRight != right) {
22059            changed = true;
22060            mPaddingRight = right;
22061        }
22062        if (mPaddingBottom != bottom) {
22063            changed = true;
22064            mPaddingBottom = bottom;
22065        }
22066
22067        if (changed) {
22068            requestLayout();
22069            invalidateOutline();
22070        }
22071    }
22072
22073    /**
22074     * Sets the relative padding. The view may add on the space required to display
22075     * the scrollbars, depending on the style and visibility of the scrollbars.
22076     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
22077     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
22078     * from the values set in this call.
22079     *
22080     * @attr ref android.R.styleable#View_padding
22081     * @attr ref android.R.styleable#View_paddingBottom
22082     * @attr ref android.R.styleable#View_paddingStart
22083     * @attr ref android.R.styleable#View_paddingEnd
22084     * @attr ref android.R.styleable#View_paddingTop
22085     * @param start the start padding in pixels
22086     * @param top the top padding in pixels
22087     * @param end the end padding in pixels
22088     * @param bottom the bottom padding in pixels
22089     */
22090    public void setPaddingRelative(int start, int top, int end, int bottom) {
22091        resetResolvedPaddingInternal();
22092
22093        mUserPaddingStart = start;
22094        mUserPaddingEnd = end;
22095        mLeftPaddingDefined = true;
22096        mRightPaddingDefined = true;
22097
22098        switch(getLayoutDirection()) {
22099            case LAYOUT_DIRECTION_RTL:
22100                mUserPaddingLeftInitial = end;
22101                mUserPaddingRightInitial = start;
22102                internalSetPadding(end, top, start, bottom);
22103                break;
22104            case LAYOUT_DIRECTION_LTR:
22105            default:
22106                mUserPaddingLeftInitial = start;
22107                mUserPaddingRightInitial = end;
22108                internalSetPadding(start, top, end, bottom);
22109        }
22110    }
22111
22112    /**
22113     * Returns the top padding of this view.
22114     *
22115     * @return the top padding in pixels
22116     */
22117    public int getPaddingTop() {
22118        return mPaddingTop;
22119    }
22120
22121    /**
22122     * Returns the bottom padding of this view. If there are inset and enabled
22123     * scrollbars, this value may include the space required to display the
22124     * scrollbars as well.
22125     *
22126     * @return the bottom padding in pixels
22127     */
22128    public int getPaddingBottom() {
22129        return mPaddingBottom;
22130    }
22131
22132    /**
22133     * Returns the left padding of this view. If there are inset and enabled
22134     * scrollbars, this value may include the space required to display the
22135     * scrollbars as well.
22136     *
22137     * @return the left padding in pixels
22138     */
22139    public int getPaddingLeft() {
22140        if (!isPaddingResolved()) {
22141            resolvePadding();
22142        }
22143        return mPaddingLeft;
22144    }
22145
22146    /**
22147     * Returns the start padding of this view depending on its resolved layout direction.
22148     * If there are inset and enabled scrollbars, this value may include the space
22149     * required to display the scrollbars as well.
22150     *
22151     * @return the start padding in pixels
22152     */
22153    public int getPaddingStart() {
22154        if (!isPaddingResolved()) {
22155            resolvePadding();
22156        }
22157        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
22158                mPaddingRight : mPaddingLeft;
22159    }
22160
22161    /**
22162     * Returns the right padding of this view. If there are inset and enabled
22163     * scrollbars, this value may include the space required to display the
22164     * scrollbars as well.
22165     *
22166     * @return the right padding in pixels
22167     */
22168    public int getPaddingRight() {
22169        if (!isPaddingResolved()) {
22170            resolvePadding();
22171        }
22172        return mPaddingRight;
22173    }
22174
22175    /**
22176     * Returns the end padding of this view depending on its resolved layout direction.
22177     * If there are inset and enabled scrollbars, this value may include the space
22178     * required to display the scrollbars as well.
22179     *
22180     * @return the end padding in pixels
22181     */
22182    public int getPaddingEnd() {
22183        if (!isPaddingResolved()) {
22184            resolvePadding();
22185        }
22186        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
22187                mPaddingLeft : mPaddingRight;
22188    }
22189
22190    /**
22191     * Return if the padding has been set through relative values
22192     * {@link #setPaddingRelative(int, int, int, int)} or through
22193     * @attr ref android.R.styleable#View_paddingStart or
22194     * @attr ref android.R.styleable#View_paddingEnd
22195     *
22196     * @return true if the padding is relative or false if it is not.
22197     */
22198    public boolean isPaddingRelative() {
22199        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
22200    }
22201
22202    Insets computeOpticalInsets() {
22203        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
22204    }
22205
22206    /**
22207     * @hide
22208     */
22209    public void resetPaddingToInitialValues() {
22210        if (isRtlCompatibilityMode()) {
22211            mPaddingLeft = mUserPaddingLeftInitial;
22212            mPaddingRight = mUserPaddingRightInitial;
22213            return;
22214        }
22215        if (isLayoutRtl()) {
22216            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
22217            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
22218        } else {
22219            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
22220            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
22221        }
22222    }
22223
22224    /**
22225     * @hide
22226     */
22227    public Insets getOpticalInsets() {
22228        if (mLayoutInsets == null) {
22229            mLayoutInsets = computeOpticalInsets();
22230        }
22231        return mLayoutInsets;
22232    }
22233
22234    /**
22235     * Set this view's optical insets.
22236     *
22237     * <p>This method should be treated similarly to setMeasuredDimension and not as a general
22238     * property. Views that compute their own optical insets should call it as part of measurement.
22239     * This method does not request layout. If you are setting optical insets outside of
22240     * measure/layout itself you will want to call requestLayout() yourself.
22241     * </p>
22242     * @hide
22243     */
22244    public void setOpticalInsets(Insets insets) {
22245        mLayoutInsets = insets;
22246    }
22247
22248    /**
22249     * Changes the selection state of this view. A view can be selected or not.
22250     * Note that selection is not the same as focus. Views are typically
22251     * selected in the context of an AdapterView like ListView or GridView;
22252     * the selected view is the view that is highlighted.
22253     *
22254     * @param selected true if the view must be selected, false otherwise
22255     */
22256    public void setSelected(boolean selected) {
22257        //noinspection DoubleNegation
22258        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
22259            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
22260            if (!selected) resetPressedState();
22261            invalidate(true);
22262            refreshDrawableState();
22263            dispatchSetSelected(selected);
22264            if (selected) {
22265                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
22266            } else {
22267                notifyViewAccessibilityStateChangedIfNeeded(
22268                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
22269            }
22270        }
22271    }
22272
22273    /**
22274     * Dispatch setSelected to all of this View's children.
22275     *
22276     * @see #setSelected(boolean)
22277     *
22278     * @param selected The new selected state
22279     */
22280    protected void dispatchSetSelected(boolean selected) {
22281    }
22282
22283    /**
22284     * Indicates the selection state of this view.
22285     *
22286     * @return true if the view is selected, false otherwise
22287     */
22288    @ViewDebug.ExportedProperty
22289    public boolean isSelected() {
22290        return (mPrivateFlags & PFLAG_SELECTED) != 0;
22291    }
22292
22293    /**
22294     * Changes the activated state of this view. A view can be activated or not.
22295     * Note that activation is not the same as selection.  Selection is
22296     * a transient property, representing the view (hierarchy) the user is
22297     * currently interacting with.  Activation is a longer-term state that the
22298     * user can move views in and out of.  For example, in a list view with
22299     * single or multiple selection enabled, the views in the current selection
22300     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
22301     * here.)  The activated state is propagated down to children of the view it
22302     * is set on.
22303     *
22304     * @param activated true if the view must be activated, false otherwise
22305     */
22306    public void setActivated(boolean activated) {
22307        //noinspection DoubleNegation
22308        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
22309            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
22310            invalidate(true);
22311            refreshDrawableState();
22312            dispatchSetActivated(activated);
22313        }
22314    }
22315
22316    /**
22317     * Dispatch setActivated to all of this View's children.
22318     *
22319     * @see #setActivated(boolean)
22320     *
22321     * @param activated The new activated state
22322     */
22323    protected void dispatchSetActivated(boolean activated) {
22324    }
22325
22326    /**
22327     * Indicates the activation state of this view.
22328     *
22329     * @return true if the view is activated, false otherwise
22330     */
22331    @ViewDebug.ExportedProperty
22332    public boolean isActivated() {
22333        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
22334    }
22335
22336    /**
22337     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
22338     * observer can be used to get notifications when global events, like
22339     * layout, happen.
22340     *
22341     * The returned ViewTreeObserver observer is not guaranteed to remain
22342     * valid for the lifetime of this View. If the caller of this method keeps
22343     * a long-lived reference to ViewTreeObserver, it should always check for
22344     * the return value of {@link ViewTreeObserver#isAlive()}.
22345     *
22346     * @return The ViewTreeObserver for this view's hierarchy.
22347     */
22348    public ViewTreeObserver getViewTreeObserver() {
22349        if (mAttachInfo != null) {
22350            return mAttachInfo.mTreeObserver;
22351        }
22352        if (mFloatingTreeObserver == null) {
22353            mFloatingTreeObserver = new ViewTreeObserver(mContext);
22354        }
22355        return mFloatingTreeObserver;
22356    }
22357
22358    /**
22359     * <p>Finds the topmost view in the current view hierarchy.</p>
22360     *
22361     * @return the topmost view containing this view
22362     */
22363    public View getRootView() {
22364        if (mAttachInfo != null) {
22365            final View v = mAttachInfo.mRootView;
22366            if (v != null) {
22367                return v;
22368            }
22369        }
22370
22371        View parent = this;
22372
22373        while (parent.mParent != null && parent.mParent instanceof View) {
22374            parent = (View) parent.mParent;
22375        }
22376
22377        return parent;
22378    }
22379
22380    /**
22381     * Transforms a motion event from view-local coordinates to on-screen
22382     * coordinates.
22383     *
22384     * @param ev the view-local motion event
22385     * @return false if the transformation could not be applied
22386     * @hide
22387     */
22388    public boolean toGlobalMotionEvent(MotionEvent ev) {
22389        final AttachInfo info = mAttachInfo;
22390        if (info == null) {
22391            return false;
22392        }
22393
22394        final Matrix m = info.mTmpMatrix;
22395        m.set(Matrix.IDENTITY_MATRIX);
22396        transformMatrixToGlobal(m);
22397        ev.transform(m);
22398        return true;
22399    }
22400
22401    /**
22402     * Transforms a motion event from on-screen coordinates to view-local
22403     * coordinates.
22404     *
22405     * @param ev the on-screen motion event
22406     * @return false if the transformation could not be applied
22407     * @hide
22408     */
22409    public boolean toLocalMotionEvent(MotionEvent ev) {
22410        final AttachInfo info = mAttachInfo;
22411        if (info == null) {
22412            return false;
22413        }
22414
22415        final Matrix m = info.mTmpMatrix;
22416        m.set(Matrix.IDENTITY_MATRIX);
22417        transformMatrixToLocal(m);
22418        ev.transform(m);
22419        return true;
22420    }
22421
22422    /**
22423     * Modifies the input matrix such that it maps view-local coordinates to
22424     * on-screen coordinates.
22425     *
22426     * @param m input matrix to modify
22427     * @hide
22428     */
22429    public void transformMatrixToGlobal(Matrix m) {
22430        final ViewParent parent = mParent;
22431        if (parent instanceof View) {
22432            final View vp = (View) parent;
22433            vp.transformMatrixToGlobal(m);
22434            m.preTranslate(-vp.mScrollX, -vp.mScrollY);
22435        } else if (parent instanceof ViewRootImpl) {
22436            final ViewRootImpl vr = (ViewRootImpl) parent;
22437            vr.transformMatrixToGlobal(m);
22438            m.preTranslate(0, -vr.mCurScrollY);
22439        }
22440
22441        m.preTranslate(mLeft, mTop);
22442
22443        if (!hasIdentityMatrix()) {
22444            m.preConcat(getMatrix());
22445        }
22446    }
22447
22448    /**
22449     * Modifies the input matrix such that it maps on-screen coordinates to
22450     * view-local coordinates.
22451     *
22452     * @param m input matrix to modify
22453     * @hide
22454     */
22455    public void transformMatrixToLocal(Matrix m) {
22456        final ViewParent parent = mParent;
22457        if (parent instanceof View) {
22458            final View vp = (View) parent;
22459            vp.transformMatrixToLocal(m);
22460            m.postTranslate(vp.mScrollX, vp.mScrollY);
22461        } else if (parent instanceof ViewRootImpl) {
22462            final ViewRootImpl vr = (ViewRootImpl) parent;
22463            vr.transformMatrixToLocal(m);
22464            m.postTranslate(0, vr.mCurScrollY);
22465        }
22466
22467        m.postTranslate(-mLeft, -mTop);
22468
22469        if (!hasIdentityMatrix()) {
22470            m.postConcat(getInverseMatrix());
22471        }
22472    }
22473
22474    /**
22475     * @hide
22476     */
22477    @ViewDebug.ExportedProperty(category = "layout", indexMapping = {
22478            @ViewDebug.IntToString(from = 0, to = "x"),
22479            @ViewDebug.IntToString(from = 1, to = "y")
22480    })
22481    public int[] getLocationOnScreen() {
22482        int[] location = new int[2];
22483        getLocationOnScreen(location);
22484        return location;
22485    }
22486
22487    /**
22488     * <p>Computes the coordinates of this view on the screen. The argument
22489     * must be an array of two integers. After the method returns, the array
22490     * contains the x and y location in that order.</p>
22491     *
22492     * @param outLocation an array of two integers in which to hold the coordinates
22493     */
22494    public void getLocationOnScreen(@Size(2) int[] outLocation) {
22495        getLocationInWindow(outLocation);
22496
22497        final AttachInfo info = mAttachInfo;
22498        if (info != null) {
22499            outLocation[0] += info.mWindowLeft;
22500            outLocation[1] += info.mWindowTop;
22501        }
22502    }
22503
22504    /**
22505     * <p>Computes the coordinates of this view in its window. The argument
22506     * must be an array of two integers. After the method returns, the array
22507     * contains the x and y location in that order.</p>
22508     *
22509     * @param outLocation an array of two integers in which to hold the coordinates
22510     */
22511    public void getLocationInWindow(@Size(2) int[] outLocation) {
22512        if (outLocation == null || outLocation.length < 2) {
22513            throw new IllegalArgumentException("outLocation must be an array of two integers");
22514        }
22515
22516        outLocation[0] = 0;
22517        outLocation[1] = 0;
22518
22519        transformFromViewToWindowSpace(outLocation);
22520    }
22521
22522    /** @hide */
22523    public void transformFromViewToWindowSpace(@Size(2) int[] inOutLocation) {
22524        if (inOutLocation == null || inOutLocation.length < 2) {
22525            throw new IllegalArgumentException("inOutLocation must be an array of two integers");
22526        }
22527
22528        if (mAttachInfo == null) {
22529            // When the view is not attached to a window, this method does not make sense
22530            inOutLocation[0] = inOutLocation[1] = 0;
22531            return;
22532        }
22533
22534        float position[] = mAttachInfo.mTmpTransformLocation;
22535        position[0] = inOutLocation[0];
22536        position[1] = inOutLocation[1];
22537
22538        if (!hasIdentityMatrix()) {
22539            getMatrix().mapPoints(position);
22540        }
22541
22542        position[0] += mLeft;
22543        position[1] += mTop;
22544
22545        ViewParent viewParent = mParent;
22546        while (viewParent instanceof View) {
22547            final View view = (View) viewParent;
22548
22549            position[0] -= view.mScrollX;
22550            position[1] -= view.mScrollY;
22551
22552            if (!view.hasIdentityMatrix()) {
22553                view.getMatrix().mapPoints(position);
22554            }
22555
22556            position[0] += view.mLeft;
22557            position[1] += view.mTop;
22558
22559            viewParent = view.mParent;
22560         }
22561
22562        if (viewParent instanceof ViewRootImpl) {
22563            // *cough*
22564            final ViewRootImpl vr = (ViewRootImpl) viewParent;
22565            position[1] -= vr.mCurScrollY;
22566        }
22567
22568        inOutLocation[0] = Math.round(position[0]);
22569        inOutLocation[1] = Math.round(position[1]);
22570    }
22571
22572    /**
22573     * @param id the id of the view to be found
22574     * @return the view of the specified id, null if cannot be found
22575     * @hide
22576     */
22577    protected <T extends View> T findViewTraversal(@IdRes int id) {
22578        if (id == mID) {
22579            return (T) this;
22580        }
22581        return null;
22582    }
22583
22584    /**
22585     * @param tag the tag of the view to be found
22586     * @return the view of specified tag, null if cannot be found
22587     * @hide
22588     */
22589    protected <T extends View> T findViewWithTagTraversal(Object tag) {
22590        if (tag != null && tag.equals(mTag)) {
22591            return (T) this;
22592        }
22593        return null;
22594    }
22595
22596    /**
22597     * @param predicate The predicate to evaluate.
22598     * @param childToSkip If not null, ignores this child during the recursive traversal.
22599     * @return The first view that matches the predicate or null.
22600     * @hide
22601     */
22602    protected <T extends View> T findViewByPredicateTraversal(Predicate<View> predicate,
22603            View childToSkip) {
22604        if (predicate.test(this)) {
22605            return (T) this;
22606        }
22607        return null;
22608    }
22609
22610    /**
22611     * Finds the first descendant view with the given ID, the view itself if
22612     * the ID matches {@link #getId()}, or {@code null} if the ID is invalid
22613     * (< 0) or there is no matching view in the hierarchy.
22614     * <p>
22615     * <strong>Note:</strong> In most cases -- depending on compiler support --
22616     * the resulting view is automatically cast to the target class type. If
22617     * the target class type is unconstrained, an explicit cast may be
22618     * necessary.
22619     *
22620     * @param id the ID to search for
22621     * @return a view with given ID if found, or {@code null} otherwise
22622     * @see View#requireViewById(int)
22623     */
22624    @Nullable
22625    public final <T extends View> T findViewById(@IdRes int id) {
22626        if (id == NO_ID) {
22627            return null;
22628        }
22629        return findViewTraversal(id);
22630    }
22631
22632    /**
22633     * Finds the first descendant view with the given ID, the view itself if the ID matches
22634     * {@link #getId()}, or throws an IllegalArgumentException if the ID is invalid or there is no
22635     * matching view in the hierarchy.
22636     * <p>
22637     * <strong>Note:</strong> In most cases -- depending on compiler support --
22638     * the resulting view is automatically cast to the target class type. If
22639     * the target class type is unconstrained, an explicit cast may be
22640     * necessary.
22641     *
22642     * @param id the ID to search for
22643     * @return a view with given ID
22644     * @see View#findViewById(int)
22645     */
22646    @NonNull
22647    public final <T extends View> T requireViewById(@IdRes int id) {
22648        T view = findViewById(id);
22649        if (view == null) {
22650            throw new IllegalArgumentException("ID does not reference a View inside this View");
22651        }
22652        return view;
22653    }
22654
22655    /**
22656     * Finds a view by its unuque and stable accessibility id.
22657     *
22658     * @param accessibilityId The searched accessibility id.
22659     * @return The found view.
22660     */
22661    final <T extends View> T findViewByAccessibilityId(int accessibilityId) {
22662        if (accessibilityId < 0) {
22663            return null;
22664        }
22665        T view = findViewByAccessibilityIdTraversal(accessibilityId);
22666        if (view != null) {
22667            return view.includeForAccessibility() ? view : null;
22668        }
22669        return null;
22670    }
22671
22672    /**
22673     * Performs the traversal to find a view by its unique and stable accessibility id.
22674     *
22675     * <strong>Note:</strong>This method does not stop at the root namespace
22676     * boundary since the user can touch the screen at an arbitrary location
22677     * potentially crossing the root namespace boundary which will send an
22678     * accessibility event to accessibility services and they should be able
22679     * to obtain the event source. Also accessibility ids are guaranteed to be
22680     * unique in the window.
22681     *
22682     * @param accessibilityId The accessibility id.
22683     * @return The found view.
22684     * @hide
22685     */
22686    public <T extends View> T findViewByAccessibilityIdTraversal(int accessibilityId) {
22687        if (getAccessibilityViewId() == accessibilityId) {
22688            return (T) this;
22689        }
22690        return null;
22691    }
22692
22693    /**
22694     * Performs the traversal to find a view by its autofill id.
22695     *
22696     * <strong>Note:</strong>This method does not stop at the root namespace
22697     * boundary.
22698     *
22699     * @param autofillId The autofill id.
22700     * @return The found view.
22701     * @hide
22702     */
22703    public <T extends View> T findViewByAutofillIdTraversal(int autofillId) {
22704        if (getAutofillViewId() == autofillId) {
22705            return (T) this;
22706        }
22707        return null;
22708    }
22709
22710    /**
22711     * Look for a child view with the given tag.  If this view has the given
22712     * tag, return this view.
22713     *
22714     * @param tag The tag to search for, using "tag.equals(getTag())".
22715     * @return The View that has the given tag in the hierarchy or null
22716     */
22717    public final <T extends View> T findViewWithTag(Object tag) {
22718        if (tag == null) {
22719            return null;
22720        }
22721        return findViewWithTagTraversal(tag);
22722    }
22723
22724    /**
22725     * Look for a child view that matches the specified predicate.
22726     * If this view matches the predicate, return this view.
22727     *
22728     * @param predicate The predicate to evaluate.
22729     * @return The first view that matches the predicate or null.
22730     * @hide
22731     */
22732    public final <T extends View> T findViewByPredicate(Predicate<View> predicate) {
22733        return findViewByPredicateTraversal(predicate, null);
22734    }
22735
22736    /**
22737     * Look for a child view that matches the specified predicate,
22738     * starting with the specified view and its descendents and then
22739     * recusively searching the ancestors and siblings of that view
22740     * until this view is reached.
22741     *
22742     * This method is useful in cases where the predicate does not match
22743     * a single unique view (perhaps multiple views use the same id)
22744     * and we are trying to find the view that is "closest" in scope to the
22745     * starting view.
22746     *
22747     * @param start The view to start from.
22748     * @param predicate The predicate to evaluate.
22749     * @return The first view that matches the predicate or null.
22750     * @hide
22751     */
22752    public final <T extends View> T findViewByPredicateInsideOut(
22753            View start, Predicate<View> predicate) {
22754        View childToSkip = null;
22755        for (;;) {
22756            T view = start.findViewByPredicateTraversal(predicate, childToSkip);
22757            if (view != null || start == this) {
22758                return view;
22759            }
22760
22761            ViewParent parent = start.getParent();
22762            if (parent == null || !(parent instanceof View)) {
22763                return null;
22764            }
22765
22766            childToSkip = start;
22767            start = (View) parent;
22768        }
22769    }
22770
22771    /**
22772     * Sets the identifier for this view. The identifier does not have to be
22773     * unique in this view's hierarchy. The identifier should be a positive
22774     * number.
22775     *
22776     * @see #NO_ID
22777     * @see #getId()
22778     * @see #findViewById(int)
22779     *
22780     * @param id a number used to identify the view
22781     *
22782     * @attr ref android.R.styleable#View_id
22783     */
22784    public void setId(@IdRes int id) {
22785        mID = id;
22786        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
22787            mID = generateViewId();
22788        }
22789    }
22790
22791    /**
22792     * {@hide}
22793     *
22794     * @param isRoot true if the view belongs to the root namespace, false
22795     *        otherwise
22796     */
22797    public void setIsRootNamespace(boolean isRoot) {
22798        if (isRoot) {
22799            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
22800        } else {
22801            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
22802        }
22803    }
22804
22805    /**
22806     * {@hide}
22807     *
22808     * @return true if the view belongs to the root namespace, false otherwise
22809     */
22810    public boolean isRootNamespace() {
22811        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
22812    }
22813
22814    /**
22815     * Returns this view's identifier.
22816     *
22817     * @return a positive integer used to identify the view or {@link #NO_ID}
22818     *         if the view has no ID
22819     *
22820     * @see #setId(int)
22821     * @see #findViewById(int)
22822     * @attr ref android.R.styleable#View_id
22823     */
22824    @IdRes
22825    @ViewDebug.CapturedViewProperty
22826    public int getId() {
22827        return mID;
22828    }
22829
22830    /**
22831     * Returns this view's tag.
22832     *
22833     * @return the Object stored in this view as a tag, or {@code null} if not
22834     *         set
22835     *
22836     * @see #setTag(Object)
22837     * @see #getTag(int)
22838     */
22839    @ViewDebug.ExportedProperty
22840    public Object getTag() {
22841        return mTag;
22842    }
22843
22844    /**
22845     * Sets the tag associated with this view. A tag can be used to mark
22846     * a view in its hierarchy and does not have to be unique within the
22847     * hierarchy. Tags can also be used to store data within a view without
22848     * resorting to another data structure.
22849     *
22850     * @param tag an Object to tag the view with
22851     *
22852     * @see #getTag()
22853     * @see #setTag(int, Object)
22854     */
22855    public void setTag(final Object tag) {
22856        mTag = tag;
22857    }
22858
22859    /**
22860     * Returns the tag associated with this view and the specified key.
22861     *
22862     * @param key The key identifying the tag
22863     *
22864     * @return the Object stored in this view as a tag, or {@code null} if not
22865     *         set
22866     *
22867     * @see #setTag(int, Object)
22868     * @see #getTag()
22869     */
22870    public Object getTag(int key) {
22871        if (mKeyedTags != null) return mKeyedTags.get(key);
22872        return null;
22873    }
22874
22875    /**
22876     * Sets a tag associated with this view and a key. A tag can be used
22877     * to mark a view in its hierarchy and does not have to be unique within
22878     * the hierarchy. Tags can also be used to store data within a view
22879     * without resorting to another data structure.
22880     *
22881     * The specified key should be an id declared in the resources of the
22882     * application to ensure it is unique (see the <a
22883     * href="{@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
22884     * Keys identified as belonging to
22885     * the Android framework or not associated with any package will cause
22886     * an {@link IllegalArgumentException} to be thrown.
22887     *
22888     * @param key The key identifying the tag
22889     * @param tag An Object to tag the view with
22890     *
22891     * @throws IllegalArgumentException If they specified key is not valid
22892     *
22893     * @see #setTag(Object)
22894     * @see #getTag(int)
22895     */
22896    public void setTag(int key, final Object tag) {
22897        // If the package id is 0x00 or 0x01, it's either an undefined package
22898        // or a framework id
22899        if ((key >>> 24) < 2) {
22900            throw new IllegalArgumentException("The key must be an application-specific "
22901                    + "resource id.");
22902        }
22903
22904        setKeyedTag(key, tag);
22905    }
22906
22907    /**
22908     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
22909     * framework id.
22910     *
22911     * @hide
22912     */
22913    public void setTagInternal(int key, Object tag) {
22914        if ((key >>> 24) != 0x1) {
22915            throw new IllegalArgumentException("The key must be a framework-specific "
22916                    + "resource id.");
22917        }
22918
22919        setKeyedTag(key, tag);
22920    }
22921
22922    private void setKeyedTag(int key, Object tag) {
22923        if (mKeyedTags == null) {
22924            mKeyedTags = new SparseArray<Object>(2);
22925        }
22926
22927        mKeyedTags.put(key, tag);
22928    }
22929
22930    /**
22931     * Prints information about this view in the log output, with the tag
22932     * {@link #VIEW_LOG_TAG}.
22933     *
22934     * @hide
22935     */
22936    public void debug() {
22937        debug(0);
22938    }
22939
22940    /**
22941     * Prints information about this view in the log output, with the tag
22942     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
22943     * indentation defined by the <code>depth</code>.
22944     *
22945     * @param depth the indentation level
22946     *
22947     * @hide
22948     */
22949    protected void debug(int depth) {
22950        String output = debugIndent(depth - 1);
22951
22952        output += "+ " + this;
22953        int id = getId();
22954        if (id != -1) {
22955            output += " (id=" + id + ")";
22956        }
22957        Object tag = getTag();
22958        if (tag != null) {
22959            output += " (tag=" + tag + ")";
22960        }
22961        Log.d(VIEW_LOG_TAG, output);
22962
22963        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
22964            output = debugIndent(depth) + " FOCUSED";
22965            Log.d(VIEW_LOG_TAG, output);
22966        }
22967
22968        output = debugIndent(depth);
22969        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
22970                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
22971                + "} ";
22972        Log.d(VIEW_LOG_TAG, output);
22973
22974        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
22975                || mPaddingBottom != 0) {
22976            output = debugIndent(depth);
22977            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
22978                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
22979            Log.d(VIEW_LOG_TAG, output);
22980        }
22981
22982        output = debugIndent(depth);
22983        output += "mMeasureWidth=" + mMeasuredWidth +
22984                " mMeasureHeight=" + mMeasuredHeight;
22985        Log.d(VIEW_LOG_TAG, output);
22986
22987        output = debugIndent(depth);
22988        if (mLayoutParams == null) {
22989            output += "BAD! no layout params";
22990        } else {
22991            output = mLayoutParams.debug(output);
22992        }
22993        Log.d(VIEW_LOG_TAG, output);
22994
22995        output = debugIndent(depth);
22996        output += "flags={";
22997        output += View.printFlags(mViewFlags);
22998        output += "}";
22999        Log.d(VIEW_LOG_TAG, output);
23000
23001        output = debugIndent(depth);
23002        output += "privateFlags={";
23003        output += View.printPrivateFlags(mPrivateFlags);
23004        output += "}";
23005        Log.d(VIEW_LOG_TAG, output);
23006    }
23007
23008    /**
23009     * Creates a string of whitespaces used for indentation.
23010     *
23011     * @param depth the indentation level
23012     * @return a String containing (depth * 2 + 3) * 2 white spaces
23013     *
23014     * @hide
23015     */
23016    protected static String debugIndent(int depth) {
23017        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
23018        for (int i = 0; i < (depth * 2) + 3; i++) {
23019            spaces.append(' ').append(' ');
23020        }
23021        return spaces.toString();
23022    }
23023
23024    /**
23025     * <p>Return the offset of the widget's text baseline from the widget's top
23026     * boundary. If this widget does not support baseline alignment, this
23027     * method returns -1. </p>
23028     *
23029     * @return the offset of the baseline within the widget's bounds or -1
23030     *         if baseline alignment is not supported
23031     */
23032    @ViewDebug.ExportedProperty(category = "layout")
23033    public int getBaseline() {
23034        return -1;
23035    }
23036
23037    /**
23038     * Returns whether the view hierarchy is currently undergoing a layout pass. This
23039     * information is useful to avoid situations such as calling {@link #requestLayout()} during
23040     * a layout pass.
23041     *
23042     * @return whether the view hierarchy is currently undergoing a layout pass
23043     */
23044    public boolean isInLayout() {
23045        ViewRootImpl viewRoot = getViewRootImpl();
23046        return (viewRoot != null && viewRoot.isInLayout());
23047    }
23048
23049    /**
23050     * Call this when something has changed which has invalidated the
23051     * layout of this view. This will schedule a layout pass of the view
23052     * tree. This should not be called while the view hierarchy is currently in a layout
23053     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
23054     * end of the current layout pass (and then layout will run again) or after the current
23055     * frame is drawn and the next layout occurs.
23056     *
23057     * <p>Subclasses which override this method should call the superclass method to
23058     * handle possible request-during-layout errors correctly.</p>
23059     */
23060    @CallSuper
23061    public void requestLayout() {
23062        if (mMeasureCache != null) mMeasureCache.clear();
23063
23064        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
23065            // Only trigger request-during-layout logic if this is the view requesting it,
23066            // not the views in its parent hierarchy
23067            ViewRootImpl viewRoot = getViewRootImpl();
23068            if (viewRoot != null && viewRoot.isInLayout()) {
23069                if (!viewRoot.requestLayoutDuringLayout(this)) {
23070                    return;
23071                }
23072            }
23073            mAttachInfo.mViewRequestingLayout = this;
23074        }
23075
23076        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
23077        mPrivateFlags |= PFLAG_INVALIDATED;
23078
23079        if (mParent != null && !mParent.isLayoutRequested()) {
23080            mParent.requestLayout();
23081        }
23082        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
23083            mAttachInfo.mViewRequestingLayout = null;
23084        }
23085    }
23086
23087    /**
23088     * Forces this view to be laid out during the next layout pass.
23089     * This method does not call requestLayout() or forceLayout()
23090     * on the parent.
23091     */
23092    public void forceLayout() {
23093        if (mMeasureCache != null) mMeasureCache.clear();
23094
23095        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
23096        mPrivateFlags |= PFLAG_INVALIDATED;
23097    }
23098
23099    /**
23100     * <p>
23101     * This is called to find out how big a view should be. The parent
23102     * supplies constraint information in the width and height parameters.
23103     * </p>
23104     *
23105     * <p>
23106     * The actual measurement work of a view is performed in
23107     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
23108     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
23109     * </p>
23110     *
23111     *
23112     * @param widthMeasureSpec Horizontal space requirements as imposed by the
23113     *        parent
23114     * @param heightMeasureSpec Vertical space requirements as imposed by the
23115     *        parent
23116     *
23117     * @see #onMeasure(int, int)
23118     */
23119    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
23120        boolean optical = isLayoutModeOptical(this);
23121        if (optical != isLayoutModeOptical(mParent)) {
23122            Insets insets = getOpticalInsets();
23123            int oWidth  = insets.left + insets.right;
23124            int oHeight = insets.top  + insets.bottom;
23125            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
23126            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
23127        }
23128
23129        // Suppress sign extension for the low bytes
23130        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
23131        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
23132
23133        final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
23134
23135        // Optimize layout by avoiding an extra EXACTLY pass when the view is
23136        // already measured as the correct size. In API 23 and below, this
23137        // extra pass is required to make LinearLayout re-distribute weight.
23138        final boolean specChanged = widthMeasureSpec != mOldWidthMeasureSpec
23139                || heightMeasureSpec != mOldHeightMeasureSpec;
23140        final boolean isSpecExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY
23141                && MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY;
23142        final boolean matchesSpecSize = getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec)
23143                && getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec);
23144        final boolean needsLayout = specChanged
23145                && (sAlwaysRemeasureExactly || !isSpecExactly || !matchesSpecSize);
23146
23147        if (forceLayout || needsLayout) {
23148            // first clears the measured dimension flag
23149            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
23150
23151            resolveRtlPropertiesIfNeeded();
23152
23153            int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key);
23154            if (cacheIndex < 0 || sIgnoreMeasureCache) {
23155                // measure ourselves, this should set the measured dimension flag back
23156                onMeasure(widthMeasureSpec, heightMeasureSpec);
23157                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
23158            } else {
23159                long value = mMeasureCache.valueAt(cacheIndex);
23160                // Casting a long to int drops the high 32 bits, no mask needed
23161                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
23162                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
23163            }
23164
23165            // flag not set, setMeasuredDimension() was not invoked, we raise
23166            // an exception to warn the developer
23167            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
23168                throw new IllegalStateException("View with id " + getId() + ": "
23169                        + getClass().getName() + "#onMeasure() did not set the"
23170                        + " measured dimension by calling"
23171                        + " setMeasuredDimension()");
23172            }
23173
23174            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
23175        }
23176
23177        mOldWidthMeasureSpec = widthMeasureSpec;
23178        mOldHeightMeasureSpec = heightMeasureSpec;
23179
23180        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
23181                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
23182    }
23183
23184    /**
23185     * <p>
23186     * Measure the view and its content to determine the measured width and the
23187     * measured height. This method is invoked by {@link #measure(int, int)} and
23188     * should be overridden by subclasses to provide accurate and efficient
23189     * measurement of their contents.
23190     * </p>
23191     *
23192     * <p>
23193     * <strong>CONTRACT:</strong> When overriding this method, you
23194     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
23195     * measured width and height of this view. Failure to do so will trigger an
23196     * <code>IllegalStateException</code>, thrown by
23197     * {@link #measure(int, int)}. Calling the superclass'
23198     * {@link #onMeasure(int, int)} is a valid use.
23199     * </p>
23200     *
23201     * <p>
23202     * The base class implementation of measure defaults to the background size,
23203     * unless a larger size is allowed by the MeasureSpec. Subclasses should
23204     * override {@link #onMeasure(int, int)} to provide better measurements of
23205     * their content.
23206     * </p>
23207     *
23208     * <p>
23209     * If this method is overridden, it is the subclass's responsibility to make
23210     * sure the measured height and width are at least the view's minimum height
23211     * and width ({@link #getSuggestedMinimumHeight()} and
23212     * {@link #getSuggestedMinimumWidth()}).
23213     * </p>
23214     *
23215     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
23216     *                         The requirements are encoded with
23217     *                         {@link android.view.View.MeasureSpec}.
23218     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
23219     *                         The requirements are encoded with
23220     *                         {@link android.view.View.MeasureSpec}.
23221     *
23222     * @see #getMeasuredWidth()
23223     * @see #getMeasuredHeight()
23224     * @see #setMeasuredDimension(int, int)
23225     * @see #getSuggestedMinimumHeight()
23226     * @see #getSuggestedMinimumWidth()
23227     * @see android.view.View.MeasureSpec#getMode(int)
23228     * @see android.view.View.MeasureSpec#getSize(int)
23229     */
23230    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
23231        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
23232                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
23233    }
23234
23235    /**
23236     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
23237     * measured width and measured height. Failing to do so will trigger an
23238     * exception at measurement time.</p>
23239     *
23240     * @param measuredWidth The measured width of this view.  May be a complex
23241     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
23242     * {@link #MEASURED_STATE_TOO_SMALL}.
23243     * @param measuredHeight The measured height of this view.  May be a complex
23244     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
23245     * {@link #MEASURED_STATE_TOO_SMALL}.
23246     */
23247    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
23248        boolean optical = isLayoutModeOptical(this);
23249        if (optical != isLayoutModeOptical(mParent)) {
23250            Insets insets = getOpticalInsets();
23251            int opticalWidth  = insets.left + insets.right;
23252            int opticalHeight = insets.top  + insets.bottom;
23253
23254            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
23255            measuredHeight += optical ? opticalHeight : -opticalHeight;
23256        }
23257        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
23258    }
23259
23260    /**
23261     * Sets the measured dimension without extra processing for things like optical bounds.
23262     * Useful for reapplying consistent values that have already been cooked with adjustments
23263     * for optical bounds, etc. such as those from the measurement cache.
23264     *
23265     * @param measuredWidth The measured width of this view.  May be a complex
23266     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
23267     * {@link #MEASURED_STATE_TOO_SMALL}.
23268     * @param measuredHeight The measured height of this view.  May be a complex
23269     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
23270     * {@link #MEASURED_STATE_TOO_SMALL}.
23271     */
23272    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
23273        mMeasuredWidth = measuredWidth;
23274        mMeasuredHeight = measuredHeight;
23275
23276        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
23277    }
23278
23279    /**
23280     * Merge two states as returned by {@link #getMeasuredState()}.
23281     * @param curState The current state as returned from a view or the result
23282     * of combining multiple views.
23283     * @param newState The new view state to combine.
23284     * @return Returns a new integer reflecting the combination of the two
23285     * states.
23286     */
23287    public static int combineMeasuredStates(int curState, int newState) {
23288        return curState | newState;
23289    }
23290
23291    /**
23292     * Version of {@link #resolveSizeAndState(int, int, int)}
23293     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
23294     */
23295    public static int resolveSize(int size, int measureSpec) {
23296        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
23297    }
23298
23299    /**
23300     * Utility to reconcile a desired size and state, with constraints imposed
23301     * by a MeasureSpec. Will take the desired size, unless a different size
23302     * is imposed by the constraints. The returned value is a compound integer,
23303     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
23304     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the
23305     * resulting size is smaller than the size the view wants to be.
23306     *
23307     * @param size How big the view wants to be.
23308     * @param measureSpec Constraints imposed by the parent.
23309     * @param childMeasuredState Size information bit mask for the view's
23310     *                           children.
23311     * @return Size information bit mask as defined by
23312     *         {@link #MEASURED_SIZE_MASK} and
23313     *         {@link #MEASURED_STATE_TOO_SMALL}.
23314     */
23315    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
23316        final int specMode = MeasureSpec.getMode(measureSpec);
23317        final int specSize = MeasureSpec.getSize(measureSpec);
23318        final int result;
23319        switch (specMode) {
23320            case MeasureSpec.AT_MOST:
23321                if (specSize < size) {
23322                    result = specSize | MEASURED_STATE_TOO_SMALL;
23323                } else {
23324                    result = size;
23325                }
23326                break;
23327            case MeasureSpec.EXACTLY:
23328                result = specSize;
23329                break;
23330            case MeasureSpec.UNSPECIFIED:
23331            default:
23332                result = size;
23333        }
23334        return result | (childMeasuredState & MEASURED_STATE_MASK);
23335    }
23336
23337    /**
23338     * Utility to return a default size. Uses the supplied size if the
23339     * MeasureSpec imposed no constraints. Will get larger if allowed
23340     * by the MeasureSpec.
23341     *
23342     * @param size Default size for this view
23343     * @param measureSpec Constraints imposed by the parent
23344     * @return The size this view should be.
23345     */
23346    public static int getDefaultSize(int size, int measureSpec) {
23347        int result = size;
23348        int specMode = MeasureSpec.getMode(measureSpec);
23349        int specSize = MeasureSpec.getSize(measureSpec);
23350
23351        switch (specMode) {
23352        case MeasureSpec.UNSPECIFIED:
23353            result = size;
23354            break;
23355        case MeasureSpec.AT_MOST:
23356        case MeasureSpec.EXACTLY:
23357            result = specSize;
23358            break;
23359        }
23360        return result;
23361    }
23362
23363    /**
23364     * Returns the suggested minimum height that the view should use. This
23365     * returns the maximum of the view's minimum height
23366     * and the background's minimum height
23367     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
23368     * <p>
23369     * When being used in {@link #onMeasure(int, int)}, the caller should still
23370     * ensure the returned height is within the requirements of the parent.
23371     *
23372     * @return The suggested minimum height of the view.
23373     */
23374    protected int getSuggestedMinimumHeight() {
23375        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
23376
23377    }
23378
23379    /**
23380     * Returns the suggested minimum width that the view should use. This
23381     * returns the maximum of the view's minimum width
23382     * and the background's minimum width
23383     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
23384     * <p>
23385     * When being used in {@link #onMeasure(int, int)}, the caller should still
23386     * ensure the returned width is within the requirements of the parent.
23387     *
23388     * @return The suggested minimum width of the view.
23389     */
23390    protected int getSuggestedMinimumWidth() {
23391        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
23392    }
23393
23394    /**
23395     * Returns the minimum height of the view.
23396     *
23397     * @return the minimum height the view will try to be, in pixels
23398     *
23399     * @see #setMinimumHeight(int)
23400     *
23401     * @attr ref android.R.styleable#View_minHeight
23402     */
23403    public int getMinimumHeight() {
23404        return mMinHeight;
23405    }
23406
23407    /**
23408     * Sets the minimum height of the view. It is not guaranteed the view will
23409     * be able to achieve this minimum height (for example, if its parent layout
23410     * constrains it with less available height).
23411     *
23412     * @param minHeight The minimum height the view will try to be, in pixels
23413     *
23414     * @see #getMinimumHeight()
23415     *
23416     * @attr ref android.R.styleable#View_minHeight
23417     */
23418    @RemotableViewMethod
23419    public void setMinimumHeight(int minHeight) {
23420        mMinHeight = minHeight;
23421        requestLayout();
23422    }
23423
23424    /**
23425     * Returns the minimum width of the view.
23426     *
23427     * @return the minimum width the view will try to be, in pixels
23428     *
23429     * @see #setMinimumWidth(int)
23430     *
23431     * @attr ref android.R.styleable#View_minWidth
23432     */
23433    public int getMinimumWidth() {
23434        return mMinWidth;
23435    }
23436
23437    /**
23438     * Sets the minimum width of the view. It is not guaranteed the view will
23439     * be able to achieve this minimum width (for example, if its parent layout
23440     * constrains it with less available width).
23441     *
23442     * @param minWidth The minimum width the view will try to be, in pixels
23443     *
23444     * @see #getMinimumWidth()
23445     *
23446     * @attr ref android.R.styleable#View_minWidth
23447     */
23448    public void setMinimumWidth(int minWidth) {
23449        mMinWidth = minWidth;
23450        requestLayout();
23451
23452    }
23453
23454    /**
23455     * Get the animation currently associated with this view.
23456     *
23457     * @return The animation that is currently playing or
23458     *         scheduled to play for this view.
23459     */
23460    public Animation getAnimation() {
23461        return mCurrentAnimation;
23462    }
23463
23464    /**
23465     * Start the specified animation now.
23466     *
23467     * @param animation the animation to start now
23468     */
23469    public void startAnimation(Animation animation) {
23470        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
23471        setAnimation(animation);
23472        invalidateParentCaches();
23473        invalidate(true);
23474    }
23475
23476    /**
23477     * Cancels any animations for this view.
23478     */
23479    public void clearAnimation() {
23480        if (mCurrentAnimation != null) {
23481            mCurrentAnimation.detach();
23482        }
23483        mCurrentAnimation = null;
23484        invalidateParentIfNeeded();
23485    }
23486
23487    /**
23488     * Sets the next animation to play for this view.
23489     * If you want the animation to play immediately, use
23490     * {@link #startAnimation(android.view.animation.Animation)} instead.
23491     * This method provides allows fine-grained
23492     * control over the start time and invalidation, but you
23493     * must make sure that 1) the animation has a start time set, and
23494     * 2) the view's parent (which controls animations on its children)
23495     * will be invalidated when the animation is supposed to
23496     * start.
23497     *
23498     * @param animation The next animation, or null.
23499     */
23500    public void setAnimation(Animation animation) {
23501        mCurrentAnimation = animation;
23502
23503        if (animation != null) {
23504            // If the screen is off assume the animation start time is now instead of
23505            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
23506            // would cause the animation to start when the screen turns back on
23507            if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF
23508                    && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
23509                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
23510            }
23511            animation.reset();
23512        }
23513    }
23514
23515    /**
23516     * Invoked by a parent ViewGroup to notify the start of the animation
23517     * currently associated with this view. If you override this method,
23518     * always call super.onAnimationStart();
23519     *
23520     * @see #setAnimation(android.view.animation.Animation)
23521     * @see #getAnimation()
23522     */
23523    @CallSuper
23524    protected void onAnimationStart() {
23525        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
23526    }
23527
23528    /**
23529     * Invoked by a parent ViewGroup to notify the end of the animation
23530     * currently associated with this view. If you override this method,
23531     * always call super.onAnimationEnd();
23532     *
23533     * @see #setAnimation(android.view.animation.Animation)
23534     * @see #getAnimation()
23535     */
23536    @CallSuper
23537    protected void onAnimationEnd() {
23538        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
23539    }
23540
23541    /**
23542     * Invoked if there is a Transform that involves alpha. Subclass that can
23543     * draw themselves with the specified alpha should return true, and then
23544     * respect that alpha when their onDraw() is called. If this returns false
23545     * then the view may be redirected to draw into an offscreen buffer to
23546     * fulfill the request, which will look fine, but may be slower than if the
23547     * subclass handles it internally. The default implementation returns false.
23548     *
23549     * @param alpha The alpha (0..255) to apply to the view's drawing
23550     * @return true if the view can draw with the specified alpha.
23551     */
23552    protected boolean onSetAlpha(int alpha) {
23553        return false;
23554    }
23555
23556    /**
23557     * This is used by the RootView to perform an optimization when
23558     * the view hierarchy contains one or several SurfaceView.
23559     * SurfaceView is always considered transparent, but its children are not,
23560     * therefore all View objects remove themselves from the global transparent
23561     * region (passed as a parameter to this function).
23562     *
23563     * @param region The transparent region for this ViewAncestor (window).
23564     *
23565     * @return Returns true if the effective visibility of the view at this
23566     * point is opaque, regardless of the transparent region; returns false
23567     * if it is possible for underlying windows to be seen behind the view.
23568     *
23569     * {@hide}
23570     */
23571    public boolean gatherTransparentRegion(Region region) {
23572        final AttachInfo attachInfo = mAttachInfo;
23573        if (region != null && attachInfo != null) {
23574            final int pflags = mPrivateFlags;
23575            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
23576                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
23577                // remove it from the transparent region.
23578                final int[] location = attachInfo.mTransparentLocation;
23579                getLocationInWindow(location);
23580                // When a view has Z value, then it will be better to leave some area below the view
23581                // for drawing shadow. The shadow outset is proportional to the Z value. Note that
23582                // the bottom part needs more offset than the left, top and right parts due to the
23583                // spot light effects.
23584                int shadowOffset = getZ() > 0 ? (int) getZ() : 0;
23585                region.op(location[0] - shadowOffset, location[1] - shadowOffset,
23586                        location[0] + mRight - mLeft + shadowOffset,
23587                        location[1] + mBottom - mTop + (shadowOffset * 3), Region.Op.DIFFERENCE);
23588            } else {
23589                if (mBackground != null && mBackground.getOpacity() != PixelFormat.TRANSPARENT) {
23590                    // The SKIP_DRAW flag IS set and the background drawable exists, we remove
23591                    // the background drawable's non-transparent parts from this transparent region.
23592                    applyDrawableToTransparentRegion(mBackground, region);
23593                }
23594                if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
23595                        && mForegroundInfo.mDrawable.getOpacity() != PixelFormat.TRANSPARENT) {
23596                    // Similarly, we remove the foreground drawable's non-transparent parts.
23597                    applyDrawableToTransparentRegion(mForegroundInfo.mDrawable, region);
23598                }
23599                if (mDefaultFocusHighlight != null
23600                        && mDefaultFocusHighlight.getOpacity() != PixelFormat.TRANSPARENT) {
23601                    // Similarly, we remove the default focus highlight's non-transparent parts.
23602                    applyDrawableToTransparentRegion(mDefaultFocusHighlight, region);
23603                }
23604            }
23605        }
23606        return true;
23607    }
23608
23609    /**
23610     * Play a sound effect for this view.
23611     *
23612     * <p>The framework will play sound effects for some built in actions, such as
23613     * clicking, but you may wish to play these effects in your widget,
23614     * for instance, for internal navigation.
23615     *
23616     * <p>The sound effect will only be played if sound effects are enabled by the user, and
23617     * {@link #isSoundEffectsEnabled()} is true.
23618     *
23619     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
23620     */
23621    public void playSoundEffect(int soundConstant) {
23622        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
23623            return;
23624        }
23625        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
23626    }
23627
23628    /**
23629     * BZZZTT!!1!
23630     *
23631     * <p>Provide haptic feedback to the user for this view.
23632     *
23633     * <p>The framework will provide haptic feedback for some built in actions,
23634     * such as long presses, but you may wish to provide feedback for your
23635     * own widget.
23636     *
23637     * <p>The feedback will only be performed if
23638     * {@link #isHapticFeedbackEnabled()} is true.
23639     *
23640     * @param feedbackConstant One of the constants defined in
23641     * {@link HapticFeedbackConstants}
23642     */
23643    public boolean performHapticFeedback(int feedbackConstant) {
23644        return performHapticFeedback(feedbackConstant, 0);
23645    }
23646
23647    /**
23648     * BZZZTT!!1!
23649     *
23650     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
23651     *
23652     * @param feedbackConstant One of the constants defined in
23653     * {@link HapticFeedbackConstants}
23654     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
23655     */
23656    public boolean performHapticFeedback(int feedbackConstant, int flags) {
23657        if (mAttachInfo == null) {
23658            return false;
23659        }
23660        //noinspection SimplifiableIfStatement
23661        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
23662                && !isHapticFeedbackEnabled()) {
23663            return false;
23664        }
23665        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
23666                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
23667    }
23668
23669    /**
23670     * Request that the visibility of the status bar or other screen/window
23671     * decorations be changed.
23672     *
23673     * <p>This method is used to put the over device UI into temporary modes
23674     * where the user's attention is focused more on the application content,
23675     * by dimming or hiding surrounding system affordances.  This is typically
23676     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
23677     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
23678     * to be placed behind the action bar (and with these flags other system
23679     * affordances) so that smooth transitions between hiding and showing them
23680     * can be done.
23681     *
23682     * <p>Two representative examples of the use of system UI visibility is
23683     * implementing a content browsing application (like a magazine reader)
23684     * and a video playing application.
23685     *
23686     * <p>The first code shows a typical implementation of a View in a content
23687     * browsing application.  In this implementation, the application goes
23688     * into a content-oriented mode by hiding the status bar and action bar,
23689     * and putting the navigation elements into lights out mode.  The user can
23690     * then interact with content while in this mode.  Such an application should
23691     * provide an easy way for the user to toggle out of the mode (such as to
23692     * check information in the status bar or access notifications).  In the
23693     * implementation here, this is done simply by tapping on the content.
23694     *
23695     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
23696     *      content}
23697     *
23698     * <p>This second code sample shows a typical implementation of a View
23699     * in a video playing application.  In this situation, while the video is
23700     * playing the application would like to go into a complete full-screen mode,
23701     * to use as much of the display as possible for the video.  When in this state
23702     * the user can not interact with the application; the system intercepts
23703     * touching on the screen to pop the UI out of full screen mode.  See
23704     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
23705     *
23706     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
23707     *      content}
23708     *
23709     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
23710     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
23711     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
23712     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
23713     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
23714     */
23715    public void setSystemUiVisibility(int visibility) {
23716        if (visibility != mSystemUiVisibility) {
23717            mSystemUiVisibility = visibility;
23718            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
23719                mParent.recomputeViewAttributes(this);
23720            }
23721        }
23722    }
23723
23724    /**
23725     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
23726     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
23727     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
23728     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
23729     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
23730     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
23731     */
23732    public int getSystemUiVisibility() {
23733        return mSystemUiVisibility;
23734    }
23735
23736    /**
23737     * Returns the current system UI visibility that is currently set for
23738     * the entire window.  This is the combination of the
23739     * {@link #setSystemUiVisibility(int)} values supplied by all of the
23740     * views in the window.
23741     */
23742    public int getWindowSystemUiVisibility() {
23743        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
23744    }
23745
23746    /**
23747     * Override to find out when the window's requested system UI visibility
23748     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
23749     * This is different from the callbacks received through
23750     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
23751     * in that this is only telling you about the local request of the window,
23752     * not the actual values applied by the system.
23753     */
23754    public void onWindowSystemUiVisibilityChanged(int visible) {
23755    }
23756
23757    /**
23758     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
23759     * the view hierarchy.
23760     */
23761    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
23762        onWindowSystemUiVisibilityChanged(visible);
23763    }
23764
23765    /**
23766     * Set a listener to receive callbacks when the visibility of the system bar changes.
23767     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
23768     */
23769    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
23770        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
23771        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
23772            mParent.recomputeViewAttributes(this);
23773        }
23774    }
23775
23776    /**
23777     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
23778     * the view hierarchy.
23779     */
23780    public void dispatchSystemUiVisibilityChanged(int visibility) {
23781        ListenerInfo li = mListenerInfo;
23782        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
23783            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
23784                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
23785        }
23786    }
23787
23788    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
23789        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
23790        if (val != mSystemUiVisibility) {
23791            setSystemUiVisibility(val);
23792            return true;
23793        }
23794        return false;
23795    }
23796
23797    /** @hide */
23798    public void setDisabledSystemUiVisibility(int flags) {
23799        if (mAttachInfo != null) {
23800            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
23801                mAttachInfo.mDisabledSystemUiVisibility = flags;
23802                if (mParent != null) {
23803                    mParent.recomputeViewAttributes(this);
23804                }
23805            }
23806        }
23807    }
23808
23809    /**
23810     * Creates an image that the system displays during the drag and drop
23811     * operation. This is called a &quot;drag shadow&quot;. The default implementation
23812     * for a DragShadowBuilder based on a View returns an image that has exactly the same
23813     * appearance as the given View. The default also positions the center of the drag shadow
23814     * directly under the touch point. If no View is provided (the constructor with no parameters
23815     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
23816     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overridden, then the
23817     * default is an invisible drag shadow.
23818     * <p>
23819     * You are not required to use the View you provide to the constructor as the basis of the
23820     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
23821     * anything you want as the drag shadow.
23822     * </p>
23823     * <p>
23824     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
23825     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
23826     *  size and position of the drag shadow. It uses this data to construct a
23827     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
23828     *  so that your application can draw the shadow image in the Canvas.
23829     * </p>
23830     *
23831     * <div class="special reference">
23832     * <h3>Developer Guides</h3>
23833     * <p>For a guide to implementing drag and drop features, read the
23834     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
23835     * </div>
23836     */
23837    public static class DragShadowBuilder {
23838        private final WeakReference<View> mView;
23839
23840        /**
23841         * Constructs a shadow image builder based on a View. By default, the resulting drag
23842         * shadow will have the same appearance and dimensions as the View, with the touch point
23843         * over the center of the View.
23844         * @param view A View. Any View in scope can be used.
23845         */
23846        public DragShadowBuilder(View view) {
23847            mView = new WeakReference<View>(view);
23848        }
23849
23850        /**
23851         * Construct a shadow builder object with no associated View.  This
23852         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
23853         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
23854         * to supply the drag shadow's dimensions and appearance without
23855         * reference to any View object.
23856         */
23857        public DragShadowBuilder() {
23858            mView = new WeakReference<View>(null);
23859        }
23860
23861        /**
23862         * Returns the View object that had been passed to the
23863         * {@link #View.DragShadowBuilder(View)}
23864         * constructor.  If that View parameter was {@code null} or if the
23865         * {@link #View.DragShadowBuilder()}
23866         * constructor was used to instantiate the builder object, this method will return
23867         * null.
23868         *
23869         * @return The View object associate with this builder object.
23870         */
23871        @SuppressWarnings({"JavadocReference"})
23872        final public View getView() {
23873            return mView.get();
23874        }
23875
23876        /**
23877         * Provides the metrics for the shadow image. These include the dimensions of
23878         * the shadow image, and the point within that shadow that should
23879         * be centered under the touch location while dragging.
23880         * <p>
23881         * The default implementation sets the dimensions of the shadow to be the
23882         * same as the dimensions of the View itself and centers the shadow under
23883         * the touch point.
23884         * </p>
23885         *
23886         * @param outShadowSize A {@link android.graphics.Point} containing the width and height
23887         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
23888         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
23889         * image.
23890         *
23891         * @param outShadowTouchPoint A {@link android.graphics.Point} for the position within the
23892         * shadow image that should be underneath the touch point during the drag and drop
23893         * operation. Your application must set {@link android.graphics.Point#x} to the
23894         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
23895         */
23896        public void onProvideShadowMetrics(Point outShadowSize, Point outShadowTouchPoint) {
23897            final View view = mView.get();
23898            if (view != null) {
23899                outShadowSize.set(view.getWidth(), view.getHeight());
23900                outShadowTouchPoint.set(outShadowSize.x / 2, outShadowSize.y / 2);
23901            } else {
23902                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
23903            }
23904        }
23905
23906        /**
23907         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
23908         * based on the dimensions it received from the
23909         * {@link #onProvideShadowMetrics(Point, Point)} callback.
23910         *
23911         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
23912         */
23913        public void onDrawShadow(Canvas canvas) {
23914            final View view = mView.get();
23915            if (view != null) {
23916                view.draw(canvas);
23917            } else {
23918                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
23919            }
23920        }
23921    }
23922
23923    /**
23924     * @deprecated Use {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)
23925     * startDragAndDrop()} for newer platform versions.
23926     */
23927    @Deprecated
23928    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
23929                                   Object myLocalState, int flags) {
23930        return startDragAndDrop(data, shadowBuilder, myLocalState, flags);
23931    }
23932
23933    /**
23934     * Starts a drag and drop operation. When your application calls this method, it passes a
23935     * {@link android.view.View.DragShadowBuilder} object to the system. The
23936     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
23937     * to get metrics for the drag shadow, and then calls the object's
23938     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
23939     * <p>
23940     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
23941     *  drag events to all the View objects in your application that are currently visible. It does
23942     *  this either by calling the View object's drag listener (an implementation of
23943     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
23944     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
23945     *  Both are passed a {@link android.view.DragEvent} object that has a
23946     *  {@link android.view.DragEvent#getAction()} value of
23947     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
23948     * </p>
23949     * <p>
23950     * Your application can invoke {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object,
23951     * int) startDragAndDrop()} on any attached View object. The View object does not need to be
23952     * the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to be related
23953     * to the View the user selected for dragging.
23954     * </p>
23955     * @param data A {@link android.content.ClipData} object pointing to the data to be
23956     * transferred by the drag and drop operation.
23957     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
23958     * drag shadow.
23959     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
23960     * drop operation. When dispatching drag events to views in the same activity this object
23961     * will be available through {@link android.view.DragEvent#getLocalState()}. Views in other
23962     * activities will not have access to this data ({@link android.view.DragEvent#getLocalState()}
23963     * will return null).
23964     * <p>
23965     * myLocalState is a lightweight mechanism for the sending information from the dragged View
23966     * to the target Views. For example, it can contain flags that differentiate between a
23967     * a copy operation and a move operation.
23968     * </p>
23969     * @param flags Flags that control the drag and drop operation. This can be set to 0 for no
23970     * flags, or any combination of the following:
23971     *     <ul>
23972     *         <li>{@link #DRAG_FLAG_GLOBAL}</li>
23973     *         <li>{@link #DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION}</li>
23974     *         <li>{@link #DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION}</li>
23975     *         <li>{@link #DRAG_FLAG_GLOBAL_URI_READ}</li>
23976     *         <li>{@link #DRAG_FLAG_GLOBAL_URI_WRITE}</li>
23977     *         <li>{@link #DRAG_FLAG_OPAQUE}</li>
23978     *     </ul>
23979     * @return {@code true} if the method completes successfully, or
23980     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
23981     * do a drag, and so no drag operation is in progress.
23982     */
23983    public final boolean startDragAndDrop(ClipData data, DragShadowBuilder shadowBuilder,
23984            Object myLocalState, int flags) {
23985        if (ViewDebug.DEBUG_DRAG) {
23986            Log.d(VIEW_LOG_TAG, "startDragAndDrop: data=" + data + " flags=" + flags);
23987        }
23988        if (mAttachInfo == null) {
23989            Log.w(VIEW_LOG_TAG, "startDragAndDrop called on a detached view.");
23990            return false;
23991        }
23992
23993        if (data != null) {
23994            data.prepareToLeaveProcess((flags & View.DRAG_FLAG_GLOBAL) != 0);
23995        }
23996
23997        Point shadowSize = new Point();
23998        Point shadowTouchPoint = new Point();
23999        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
24000
24001        if ((shadowSize.x < 0) || (shadowSize.y < 0)
24002                || (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
24003            throw new IllegalStateException("Drag shadow dimensions must not be negative");
24004        }
24005
24006        // Create 1x1 surface when zero surface size is specified because SurfaceControl.Builder
24007        // does not accept zero size surface.
24008        if (shadowSize.x == 0  || shadowSize.y == 0) {
24009            if (!sAcceptZeroSizeDragShadow) {
24010                throw new IllegalStateException("Drag shadow dimensions must be positive");
24011            }
24012            shadowSize.x = 1;
24013            shadowSize.y = 1;
24014        }
24015
24016        if (ViewDebug.DEBUG_DRAG) {
24017            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
24018                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
24019        }
24020        if (mAttachInfo.mDragSurface != null) {
24021            mAttachInfo.mDragSurface.release();
24022        }
24023        mAttachInfo.mDragSurface = new Surface();
24024        mAttachInfo.mDragToken = null;
24025
24026        final ViewRootImpl root = mAttachInfo.mViewRootImpl;
24027        final SurfaceSession session = new SurfaceSession(root.mSurface);
24028        final SurfaceControl surface = new SurfaceControl.Builder(session)
24029                .setName("drag surface")
24030                .setSize(shadowSize.x, shadowSize.y)
24031                .setFormat(PixelFormat.TRANSLUCENT)
24032                .build();
24033        try {
24034            mAttachInfo.mDragSurface.copyFrom(surface);
24035            final Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null);
24036            try {
24037                canvas.drawColor(0, PorterDuff.Mode.CLEAR);
24038                shadowBuilder.onDrawShadow(canvas);
24039            } finally {
24040                mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas);
24041            }
24042
24043            // Cache the local state object for delivery with DragEvents
24044            root.setLocalDragState(myLocalState);
24045
24046            // repurpose 'shadowSize' for the last touch point
24047            root.getLastTouchPoint(shadowSize);
24048
24049            mAttachInfo.mDragToken = mAttachInfo.mSession.performDrag(
24050                    mAttachInfo.mWindow, flags, surface, root.getLastTouchSource(),
24051                    shadowSize.x, shadowSize.y, shadowTouchPoint.x, shadowTouchPoint.y, data);
24052            if (ViewDebug.DEBUG_DRAG) {
24053                Log.d(VIEW_LOG_TAG, "performDrag returned " + mAttachInfo.mDragToken);
24054            }
24055
24056            return mAttachInfo.mDragToken != null;
24057        } catch (Exception e) {
24058            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
24059            return false;
24060        } finally {
24061            if (mAttachInfo.mDragToken == null) {
24062                mAttachInfo.mDragSurface.destroy();
24063                mAttachInfo.mDragSurface = null;
24064                root.setLocalDragState(null);
24065            }
24066            session.kill();
24067        }
24068    }
24069
24070    /**
24071     * Cancels an ongoing drag and drop operation.
24072     * <p>
24073     * A {@link android.view.DragEvent} object with
24074     * {@link android.view.DragEvent#getAction()} value of
24075     * {@link android.view.DragEvent#ACTION_DRAG_ENDED} and
24076     * {@link android.view.DragEvent#getResult()} value of {@code false}
24077     * will be sent to every
24078     * View that received {@link android.view.DragEvent#ACTION_DRAG_STARTED}
24079     * even if they are not currently visible.
24080     * </p>
24081     * <p>
24082     * This method can be called on any View in the same window as the View on which
24083     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int) startDragAndDrop}
24084     * was called.
24085     * </p>
24086     */
24087    public final void cancelDragAndDrop() {
24088        if (ViewDebug.DEBUG_DRAG) {
24089            Log.d(VIEW_LOG_TAG, "cancelDragAndDrop");
24090        }
24091        if (mAttachInfo == null) {
24092            Log.w(VIEW_LOG_TAG, "cancelDragAndDrop called on a detached view.");
24093            return;
24094        }
24095        if (mAttachInfo.mDragToken != null) {
24096            try {
24097                mAttachInfo.mSession.cancelDragAndDrop(mAttachInfo.mDragToken);
24098            } catch (Exception e) {
24099                Log.e(VIEW_LOG_TAG, "Unable to cancel drag", e);
24100            }
24101            mAttachInfo.mDragToken = null;
24102        } else {
24103            Log.e(VIEW_LOG_TAG, "No active drag to cancel");
24104        }
24105    }
24106
24107    /**
24108     * Updates the drag shadow for the ongoing drag and drop operation.
24109     *
24110     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
24111     * new drag shadow.
24112     */
24113    public final void updateDragShadow(DragShadowBuilder shadowBuilder) {
24114        if (ViewDebug.DEBUG_DRAG) {
24115            Log.d(VIEW_LOG_TAG, "updateDragShadow");
24116        }
24117        if (mAttachInfo == null) {
24118            Log.w(VIEW_LOG_TAG, "updateDragShadow called on a detached view.");
24119            return;
24120        }
24121        if (mAttachInfo.mDragToken != null) {
24122            try {
24123                Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null);
24124                try {
24125                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
24126                    shadowBuilder.onDrawShadow(canvas);
24127                } finally {
24128                    mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas);
24129                }
24130            } catch (Exception e) {
24131                Log.e(VIEW_LOG_TAG, "Unable to update drag shadow", e);
24132            }
24133        } else {
24134            Log.e(VIEW_LOG_TAG, "No active drag");
24135        }
24136    }
24137
24138    /**
24139     * Starts a move from {startX, startY}, the amount of the movement will be the offset
24140     * between {startX, startY} and the new cursor positon.
24141     * @param startX horizontal coordinate where the move started.
24142     * @param startY vertical coordinate where the move started.
24143     * @return whether moving was started successfully.
24144     * @hide
24145     */
24146    public final boolean startMovingTask(float startX, float startY) {
24147        if (ViewDebug.DEBUG_POSITIONING) {
24148            Log.d(VIEW_LOG_TAG, "startMovingTask: {" + startX + "," + startY + "}");
24149        }
24150        try {
24151            return mAttachInfo.mSession.startMovingTask(mAttachInfo.mWindow, startX, startY);
24152        } catch (RemoteException e) {
24153            Log.e(VIEW_LOG_TAG, "Unable to start moving", e);
24154        }
24155        return false;
24156    }
24157
24158    /**
24159     * Handles drag events sent by the system following a call to
24160     * {@link android.view.View#startDragAndDrop(ClipData,DragShadowBuilder,Object,int)
24161     * startDragAndDrop()}.
24162     *<p>
24163     * When the system calls this method, it passes a
24164     * {@link android.view.DragEvent} object. A call to
24165     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
24166     * in DragEvent. The method uses these to determine what is happening in the drag and drop
24167     * operation.
24168     * @param event The {@link android.view.DragEvent} sent by the system.
24169     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
24170     * in DragEvent, indicating the type of drag event represented by this object.
24171     * @return {@code true} if the method was successful, otherwise {@code false}.
24172     * <p>
24173     *  The method should return {@code true} in response to an action type of
24174     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
24175     *  operation.
24176     * </p>
24177     * <p>
24178     *  The method should also return {@code true} in response to an action type of
24179     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
24180     *  {@code false} if it didn't.
24181     * </p>
24182     * <p>
24183     *  For all other events, the return value is ignored.
24184     * </p>
24185     */
24186    public boolean onDragEvent(DragEvent event) {
24187        return false;
24188    }
24189
24190    // Dispatches ACTION_DRAG_ENTERED and ACTION_DRAG_EXITED events for pre-Nougat apps.
24191    boolean dispatchDragEnterExitInPreN(DragEvent event) {
24192        return callDragEventHandler(event);
24193    }
24194
24195    /**
24196     * Detects if this View is enabled and has a drag event listener.
24197     * If both are true, then it calls the drag event listener with the
24198     * {@link android.view.DragEvent} it received. If the drag event listener returns
24199     * {@code true}, then dispatchDragEvent() returns {@code true}.
24200     * <p>
24201     * For all other cases, the method calls the
24202     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
24203     * method and returns its result.
24204     * </p>
24205     * <p>
24206     * This ensures that a drag event is always consumed, even if the View does not have a drag
24207     * event listener. However, if the View has a listener and the listener returns true, then
24208     * onDragEvent() is not called.
24209     * </p>
24210     */
24211    public boolean dispatchDragEvent(DragEvent event) {
24212        event.mEventHandlerWasCalled = true;
24213        if (event.mAction == DragEvent.ACTION_DRAG_LOCATION ||
24214            event.mAction == DragEvent.ACTION_DROP) {
24215            // About to deliver an event with coordinates to this view. Notify that now this view
24216            // has drag focus. This will send exit/enter events as needed.
24217            getViewRootImpl().setDragFocus(this, event);
24218        }
24219        return callDragEventHandler(event);
24220    }
24221
24222    final boolean callDragEventHandler(DragEvent event) {
24223        final boolean result;
24224
24225        ListenerInfo li = mListenerInfo;
24226        //noinspection SimplifiableIfStatement
24227        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
24228                && li.mOnDragListener.onDrag(this, event)) {
24229            result = true;
24230        } else {
24231            result = onDragEvent(event);
24232        }
24233
24234        switch (event.mAction) {
24235            case DragEvent.ACTION_DRAG_ENTERED: {
24236                mPrivateFlags2 |= View.PFLAG2_DRAG_HOVERED;
24237                refreshDrawableState();
24238            } break;
24239            case DragEvent.ACTION_DRAG_EXITED: {
24240                mPrivateFlags2 &= ~View.PFLAG2_DRAG_HOVERED;
24241                refreshDrawableState();
24242            } break;
24243            case DragEvent.ACTION_DRAG_ENDED: {
24244                mPrivateFlags2 &= ~View.DRAG_MASK;
24245                refreshDrawableState();
24246            } break;
24247        }
24248
24249        return result;
24250    }
24251
24252    boolean canAcceptDrag() {
24253        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
24254    }
24255
24256    /**
24257     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
24258     * it is ever exposed at all.
24259     * @hide
24260     */
24261    public void onCloseSystemDialogs(String reason) {
24262    }
24263
24264    /**
24265     * Given a Drawable whose bounds have been set to draw into this view,
24266     * update a Region being computed for
24267     * {@link #gatherTransparentRegion(android.graphics.Region)} so
24268     * that any non-transparent parts of the Drawable are removed from the
24269     * given transparent region.
24270     *
24271     * @param dr The Drawable whose transparency is to be applied to the region.
24272     * @param region A Region holding the current transparency information,
24273     * where any parts of the region that are set are considered to be
24274     * transparent.  On return, this region will be modified to have the
24275     * transparency information reduced by the corresponding parts of the
24276     * Drawable that are not transparent.
24277     * {@hide}
24278     */
24279    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
24280        if (DBG) {
24281            Log.i("View", "Getting transparent region for: " + this);
24282        }
24283        final Region r = dr.getTransparentRegion();
24284        final Rect db = dr.getBounds();
24285        final AttachInfo attachInfo = mAttachInfo;
24286        if (r != null && attachInfo != null) {
24287            final int w = getRight()-getLeft();
24288            final int h = getBottom()-getTop();
24289            if (db.left > 0) {
24290                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
24291                r.op(0, 0, db.left, h, Region.Op.UNION);
24292            }
24293            if (db.right < w) {
24294                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
24295                r.op(db.right, 0, w, h, Region.Op.UNION);
24296            }
24297            if (db.top > 0) {
24298                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
24299                r.op(0, 0, w, db.top, Region.Op.UNION);
24300            }
24301            if (db.bottom < h) {
24302                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
24303                r.op(0, db.bottom, w, h, Region.Op.UNION);
24304            }
24305            final int[] location = attachInfo.mTransparentLocation;
24306            getLocationInWindow(location);
24307            r.translate(location[0], location[1]);
24308            region.op(r, Region.Op.INTERSECT);
24309        } else {
24310            region.op(db, Region.Op.DIFFERENCE);
24311        }
24312    }
24313
24314    private void checkForLongClick(int delayOffset, float x, float y) {
24315        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE || (mViewFlags & TOOLTIP) == TOOLTIP) {
24316            mHasPerformedLongPress = false;
24317
24318            if (mPendingCheckForLongPress == null) {
24319                mPendingCheckForLongPress = new CheckForLongPress();
24320            }
24321            mPendingCheckForLongPress.setAnchor(x, y);
24322            mPendingCheckForLongPress.rememberWindowAttachCount();
24323            mPendingCheckForLongPress.rememberPressedState();
24324            postDelayed(mPendingCheckForLongPress,
24325                    ViewConfiguration.getLongPressTimeout() - delayOffset);
24326        }
24327    }
24328
24329    /**
24330     * Inflate a view from an XML resource.  This convenience method wraps the {@link
24331     * LayoutInflater} class, which provides a full range of options for view inflation.
24332     *
24333     * @param context The Context object for your activity or application.
24334     * @param resource The resource ID to inflate
24335     * @param root A view group that will be the parent.  Used to properly inflate the
24336     * layout_* parameters.
24337     * @see LayoutInflater
24338     */
24339    public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
24340        LayoutInflater factory = LayoutInflater.from(context);
24341        return factory.inflate(resource, root);
24342    }
24343
24344    /**
24345     * Scroll the view with standard behavior for scrolling beyond the normal
24346     * content boundaries. Views that call this method should override
24347     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
24348     * results of an over-scroll operation.
24349     *
24350     * Views can use this method to handle any touch or fling-based scrolling.
24351     *
24352     * @param deltaX Change in X in pixels
24353     * @param deltaY Change in Y in pixels
24354     * @param scrollX Current X scroll value in pixels before applying deltaX
24355     * @param scrollY Current Y scroll value in pixels before applying deltaY
24356     * @param scrollRangeX Maximum content scroll range along the X axis
24357     * @param scrollRangeY Maximum content scroll range along the Y axis
24358     * @param maxOverScrollX Number of pixels to overscroll by in either direction
24359     *          along the X axis.
24360     * @param maxOverScrollY Number of pixels to overscroll by in either direction
24361     *          along the Y axis.
24362     * @param isTouchEvent true if this scroll operation is the result of a touch event.
24363     * @return true if scrolling was clamped to an over-scroll boundary along either
24364     *          axis, false otherwise.
24365     */
24366    @SuppressWarnings({"UnusedParameters"})
24367    protected boolean overScrollBy(int deltaX, int deltaY,
24368            int scrollX, int scrollY,
24369            int scrollRangeX, int scrollRangeY,
24370            int maxOverScrollX, int maxOverScrollY,
24371            boolean isTouchEvent) {
24372        final int overScrollMode = mOverScrollMode;
24373        final boolean canScrollHorizontal =
24374                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
24375        final boolean canScrollVertical =
24376                computeVerticalScrollRange() > computeVerticalScrollExtent();
24377        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
24378                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
24379        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
24380                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
24381
24382        int newScrollX = scrollX + deltaX;
24383        if (!overScrollHorizontal) {
24384            maxOverScrollX = 0;
24385        }
24386
24387        int newScrollY = scrollY + deltaY;
24388        if (!overScrollVertical) {
24389            maxOverScrollY = 0;
24390        }
24391
24392        // Clamp values if at the limits and record
24393        final int left = -maxOverScrollX;
24394        final int right = maxOverScrollX + scrollRangeX;
24395        final int top = -maxOverScrollY;
24396        final int bottom = maxOverScrollY + scrollRangeY;
24397
24398        boolean clampedX = false;
24399        if (newScrollX > right) {
24400            newScrollX = right;
24401            clampedX = true;
24402        } else if (newScrollX < left) {
24403            newScrollX = left;
24404            clampedX = true;
24405        }
24406
24407        boolean clampedY = false;
24408        if (newScrollY > bottom) {
24409            newScrollY = bottom;
24410            clampedY = true;
24411        } else if (newScrollY < top) {
24412            newScrollY = top;
24413            clampedY = true;
24414        }
24415
24416        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
24417
24418        return clampedX || clampedY;
24419    }
24420
24421    /**
24422     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
24423     * respond to the results of an over-scroll operation.
24424     *
24425     * @param scrollX New X scroll value in pixels
24426     * @param scrollY New Y scroll value in pixels
24427     * @param clampedX True if scrollX was clamped to an over-scroll boundary
24428     * @param clampedY True if scrollY was clamped to an over-scroll boundary
24429     */
24430    protected void onOverScrolled(int scrollX, int scrollY,
24431            boolean clampedX, boolean clampedY) {
24432        // Intentionally empty.
24433    }
24434
24435    /**
24436     * Returns the over-scroll mode for this view. The result will be
24437     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
24438     * (allow over-scrolling only if the view content is larger than the container),
24439     * or {@link #OVER_SCROLL_NEVER}.
24440     *
24441     * @return This view's over-scroll mode.
24442     */
24443    public int getOverScrollMode() {
24444        return mOverScrollMode;
24445    }
24446
24447    /**
24448     * Set the over-scroll mode for this view. Valid over-scroll modes are
24449     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
24450     * (allow over-scrolling only if the view content is larger than the container),
24451     * or {@link #OVER_SCROLL_NEVER}.
24452     *
24453     * Setting the over-scroll mode of a view will have an effect only if the
24454     * view is capable of scrolling.
24455     *
24456     * @param overScrollMode The new over-scroll mode for this view.
24457     */
24458    public void setOverScrollMode(int overScrollMode) {
24459        if (overScrollMode != OVER_SCROLL_ALWAYS &&
24460                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
24461                overScrollMode != OVER_SCROLL_NEVER) {
24462            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
24463        }
24464        mOverScrollMode = overScrollMode;
24465    }
24466
24467    /**
24468     * Enable or disable nested scrolling for this view.
24469     *
24470     * <p>If this property is set to true the view will be permitted to initiate nested
24471     * scrolling operations with a compatible parent view in the current hierarchy. If this
24472     * view does not implement nested scrolling this will have no effect. Disabling nested scrolling
24473     * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping}
24474     * the nested scroll.</p>
24475     *
24476     * @param enabled true to enable nested scrolling, false to disable
24477     *
24478     * @see #isNestedScrollingEnabled()
24479     */
24480    public void setNestedScrollingEnabled(boolean enabled) {
24481        if (enabled) {
24482            mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED;
24483        } else {
24484            stopNestedScroll();
24485            mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED;
24486        }
24487    }
24488
24489    /**
24490     * Returns true if nested scrolling is enabled for this view.
24491     *
24492     * <p>If nested scrolling is enabled and this View class implementation supports it,
24493     * this view will act as a nested scrolling child view when applicable, forwarding data
24494     * about the scroll operation in progress to a compatible and cooperating nested scrolling
24495     * parent.</p>
24496     *
24497     * @return true if nested scrolling is enabled
24498     *
24499     * @see #setNestedScrollingEnabled(boolean)
24500     */
24501    public boolean isNestedScrollingEnabled() {
24502        return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) ==
24503                PFLAG3_NESTED_SCROLLING_ENABLED;
24504    }
24505
24506    /**
24507     * Begin a nestable scroll operation along the given axes.
24508     *
24509     * <p>A view starting a nested scroll promises to abide by the following contract:</p>
24510     *
24511     * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case
24512     * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}.
24513     * In the case of touch scrolling the nested scroll will be terminated automatically in
24514     * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}.
24515     * In the event of programmatic scrolling the caller must explicitly call
24516     * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p>
24517     *
24518     * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found.
24519     * If it returns false the caller may ignore the rest of this contract until the next scroll.
24520     * Calling startNestedScroll while a nested scroll is already in progress will return true.</p>
24521     *
24522     * <p>At each incremental step of the scroll the caller should invoke
24523     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll}
24524     * once it has calculated the requested scrolling delta. If it returns true the nested scrolling
24525     * parent at least partially consumed the scroll and the caller should adjust the amount it
24526     * scrolls by.</p>
24527     *
24528     * <p>After applying the remainder of the scroll delta the caller should invoke
24529     * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing
24530     * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat
24531     * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}.
24532     * </p>
24533     *
24534     * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or
24535     *             {@link #SCROLL_AXIS_VERTICAL}.
24536     * @return true if a cooperative parent was found and nested scrolling has been enabled for
24537     *         the current gesture.
24538     *
24539     * @see #stopNestedScroll()
24540     * @see #dispatchNestedPreScroll(int, int, int[], int[])
24541     * @see #dispatchNestedScroll(int, int, int, int, int[])
24542     */
24543    public boolean startNestedScroll(int axes) {
24544        if (hasNestedScrollingParent()) {
24545            // Already in progress
24546            return true;
24547        }
24548        if (isNestedScrollingEnabled()) {
24549            ViewParent p = getParent();
24550            View child = this;
24551            while (p != null) {
24552                try {
24553                    if (p.onStartNestedScroll(child, this, axes)) {
24554                        mNestedScrollingParent = p;
24555                        p.onNestedScrollAccepted(child, this, axes);
24556                        return true;
24557                    }
24558                } catch (AbstractMethodError e) {
24559                    Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " +
24560                            "method onStartNestedScroll", e);
24561                    // Allow the search upward to continue
24562                }
24563                if (p instanceof View) {
24564                    child = (View) p;
24565                }
24566                p = p.getParent();
24567            }
24568        }
24569        return false;
24570    }
24571
24572    /**
24573     * Stop a nested scroll in progress.
24574     *
24575     * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p>
24576     *
24577     * @see #startNestedScroll(int)
24578     */
24579    public void stopNestedScroll() {
24580        if (mNestedScrollingParent != null) {
24581            mNestedScrollingParent.onStopNestedScroll(this);
24582            mNestedScrollingParent = null;
24583        }
24584    }
24585
24586    /**
24587     * Returns true if this view has a nested scrolling parent.
24588     *
24589     * <p>The presence of a nested scrolling parent indicates that this view has initiated
24590     * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p>
24591     *
24592     * @return whether this view has a nested scrolling parent
24593     */
24594    public boolean hasNestedScrollingParent() {
24595        return mNestedScrollingParent != null;
24596    }
24597
24598    /**
24599     * Dispatch one step of a nested scroll in progress.
24600     *
24601     * <p>Implementations of views that support nested scrolling should call this to report
24602     * info about a scroll in progress to the current nested scrolling parent. If a nested scroll
24603     * is not currently in progress or nested scrolling is not
24604     * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p>
24605     *
24606     * <p>Compatible View implementations should also call
24607     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before
24608     * consuming a component of the scroll event themselves.</p>
24609     *
24610     * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step
24611     * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step
24612     * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view
24613     * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view
24614     * @param offsetInWindow Optional. If not null, on return this will contain the offset
24615     *                       in local view coordinates of this view from before this operation
24616     *                       to after it completes. View implementations may use this to adjust
24617     *                       expected input coordinate tracking.
24618     * @return true if the event was dispatched, false if it could not be dispatched.
24619     * @see #dispatchNestedPreScroll(int, int, int[], int[])
24620     */
24621    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed,
24622            int dxUnconsumed, int dyUnconsumed, @Nullable @Size(2) int[] offsetInWindow) {
24623        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
24624            if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) {
24625                int startX = 0;
24626                int startY = 0;
24627                if (offsetInWindow != null) {
24628                    getLocationInWindow(offsetInWindow);
24629                    startX = offsetInWindow[0];
24630                    startY = offsetInWindow[1];
24631                }
24632
24633                mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed,
24634                        dxUnconsumed, dyUnconsumed);
24635
24636                if (offsetInWindow != null) {
24637                    getLocationInWindow(offsetInWindow);
24638                    offsetInWindow[0] -= startX;
24639                    offsetInWindow[1] -= startY;
24640                }
24641                return true;
24642            } else if (offsetInWindow != null) {
24643                // No motion, no dispatch. Keep offsetInWindow up to date.
24644                offsetInWindow[0] = 0;
24645                offsetInWindow[1] = 0;
24646            }
24647        }
24648        return false;
24649    }
24650
24651    /**
24652     * Dispatch one step of a nested scroll in progress before this view consumes any portion of it.
24653     *
24654     * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch.
24655     * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested
24656     * scrolling operation to consume some or all of the scroll operation before the child view
24657     * consumes it.</p>
24658     *
24659     * @param dx Horizontal scroll distance in pixels
24660     * @param dy Vertical scroll distance in pixels
24661     * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx
24662     *                 and consumed[1] the consumed dy.
24663     * @param offsetInWindow Optional. If not null, on return this will contain the offset
24664     *                       in local view coordinates of this view from before this operation
24665     *                       to after it completes. View implementations may use this to adjust
24666     *                       expected input coordinate tracking.
24667     * @return true if the parent consumed some or all of the scroll delta
24668     * @see #dispatchNestedScroll(int, int, int, int, int[])
24669     */
24670    public boolean dispatchNestedPreScroll(int dx, int dy,
24671            @Nullable @Size(2) int[] consumed, @Nullable @Size(2) int[] offsetInWindow) {
24672        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
24673            if (dx != 0 || dy != 0) {
24674                int startX = 0;
24675                int startY = 0;
24676                if (offsetInWindow != null) {
24677                    getLocationInWindow(offsetInWindow);
24678                    startX = offsetInWindow[0];
24679                    startY = offsetInWindow[1];
24680                }
24681
24682                if (consumed == null) {
24683                    if (mTempNestedScrollConsumed == null) {
24684                        mTempNestedScrollConsumed = new int[2];
24685                    }
24686                    consumed = mTempNestedScrollConsumed;
24687                }
24688                consumed[0] = 0;
24689                consumed[1] = 0;
24690                mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed);
24691
24692                if (offsetInWindow != null) {
24693                    getLocationInWindow(offsetInWindow);
24694                    offsetInWindow[0] -= startX;
24695                    offsetInWindow[1] -= startY;
24696                }
24697                return consumed[0] != 0 || consumed[1] != 0;
24698            } else if (offsetInWindow != null) {
24699                offsetInWindow[0] = 0;
24700                offsetInWindow[1] = 0;
24701            }
24702        }
24703        return false;
24704    }
24705
24706    /**
24707     * Dispatch a fling to a nested scrolling parent.
24708     *
24709     * <p>This method should be used to indicate that a nested scrolling child has detected
24710     * suitable conditions for a fling. Generally this means that a touch scroll has ended with a
24711     * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds
24712     * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity}
24713     * along a scrollable axis.</p>
24714     *
24715     * <p>If a nested scrolling child view would normally fling but it is at the edge of
24716     * its own content, it can use this method to delegate the fling to its nested scrolling
24717     * parent instead. The parent may optionally consume the fling or observe a child fling.</p>
24718     *
24719     * @param velocityX Horizontal fling velocity in pixels per second
24720     * @param velocityY Vertical fling velocity in pixels per second
24721     * @param consumed true if the child consumed the fling, false otherwise
24722     * @return true if the nested scrolling parent consumed or otherwise reacted to the fling
24723     */
24724    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
24725        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
24726            return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed);
24727        }
24728        return false;
24729    }
24730
24731    /**
24732     * Dispatch a fling to a nested scrolling parent before it is processed by this view.
24733     *
24734     * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch
24735     * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code>
24736     * offsets an opportunity for the parent view in a nested fling to fully consume the fling
24737     * before the child view consumes it. If this method returns <code>true</code>, a nested
24738     * parent view consumed the fling and this view should not scroll as a result.</p>
24739     *
24740     * <p>For a better user experience, only one view in a nested scrolling chain should consume
24741     * the fling at a time. If a parent view consumed the fling this method will return false.
24742     * Custom view implementations should account for this in two ways:</p>
24743     *
24744     * <ul>
24745     *     <li>If a custom view is paged and needs to settle to a fixed page-point, do not
24746     *     call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid
24747     *     position regardless.</li>
24748     *     <li>If a nested parent does consume the fling, this view should not scroll at all,
24749     *     even to settle back to a valid idle position.</li>
24750     * </ul>
24751     *
24752     * <p>Views should also not offer fling velocities to nested parent views along an axis
24753     * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView}
24754     * should not offer a horizontal fling velocity to its parents since scrolling along that
24755     * axis is not permitted and carrying velocity along that motion does not make sense.</p>
24756     *
24757     * @param velocityX Horizontal fling velocity in pixels per second
24758     * @param velocityY Vertical fling velocity in pixels per second
24759     * @return true if a nested scrolling parent consumed the fling
24760     */
24761    public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
24762        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
24763            return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY);
24764        }
24765        return false;
24766    }
24767
24768    /**
24769     * Gets a scale factor that determines the distance the view should scroll
24770     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
24771     * @return The vertical scroll scale factor.
24772     * @hide
24773     */
24774    protected float getVerticalScrollFactor() {
24775        if (mVerticalScrollFactor == 0) {
24776            TypedValue outValue = new TypedValue();
24777            if (!mContext.getTheme().resolveAttribute(
24778                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
24779                throw new IllegalStateException(
24780                        "Expected theme to define listPreferredItemHeight.");
24781            }
24782            mVerticalScrollFactor = outValue.getDimension(
24783                    mContext.getResources().getDisplayMetrics());
24784        }
24785        return mVerticalScrollFactor;
24786    }
24787
24788    /**
24789     * Gets a scale factor that determines the distance the view should scroll
24790     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
24791     * @return The horizontal scroll scale factor.
24792     * @hide
24793     */
24794    protected float getHorizontalScrollFactor() {
24795        // TODO: Should use something else.
24796        return getVerticalScrollFactor();
24797    }
24798
24799    /**
24800     * Return the value specifying the text direction or policy that was set with
24801     * {@link #setTextDirection(int)}.
24802     *
24803     * @return the defined text direction. It can be one of:
24804     *
24805     * {@link #TEXT_DIRECTION_INHERIT},
24806     * {@link #TEXT_DIRECTION_FIRST_STRONG},
24807     * {@link #TEXT_DIRECTION_ANY_RTL},
24808     * {@link #TEXT_DIRECTION_LTR},
24809     * {@link #TEXT_DIRECTION_RTL},
24810     * {@link #TEXT_DIRECTION_LOCALE},
24811     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
24812     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
24813     *
24814     * @attr ref android.R.styleable#View_textDirection
24815     *
24816     * @hide
24817     */
24818    @ViewDebug.ExportedProperty(category = "text", mapping = {
24819            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
24820            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
24821            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
24822            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
24823            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
24824            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
24825            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
24826            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
24827    })
24828    public int getRawTextDirection() {
24829        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
24830    }
24831
24832    /**
24833     * Set the text direction.
24834     *
24835     * @param textDirection the direction to set. Should be one of:
24836     *
24837     * {@link #TEXT_DIRECTION_INHERIT},
24838     * {@link #TEXT_DIRECTION_FIRST_STRONG},
24839     * {@link #TEXT_DIRECTION_ANY_RTL},
24840     * {@link #TEXT_DIRECTION_LTR},
24841     * {@link #TEXT_DIRECTION_RTL},
24842     * {@link #TEXT_DIRECTION_LOCALE}
24843     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
24844     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL},
24845     *
24846     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
24847     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
24848     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
24849     *
24850     * @attr ref android.R.styleable#View_textDirection
24851     */
24852    public void setTextDirection(int textDirection) {
24853        if (getRawTextDirection() != textDirection) {
24854            // Reset the current text direction and the resolved one
24855            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
24856            resetResolvedTextDirection();
24857            // Set the new text direction
24858            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
24859            // Do resolution
24860            resolveTextDirection();
24861            // Notify change
24862            onRtlPropertiesChanged(getLayoutDirection());
24863            // Refresh
24864            requestLayout();
24865            invalidate(true);
24866        }
24867    }
24868
24869    /**
24870     * Return the resolved text direction.
24871     *
24872     * @return the resolved text direction. Returns one of:
24873     *
24874     * {@link #TEXT_DIRECTION_FIRST_STRONG},
24875     * {@link #TEXT_DIRECTION_ANY_RTL},
24876     * {@link #TEXT_DIRECTION_LTR},
24877     * {@link #TEXT_DIRECTION_RTL},
24878     * {@link #TEXT_DIRECTION_LOCALE},
24879     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
24880     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
24881     *
24882     * @attr ref android.R.styleable#View_textDirection
24883     */
24884    @ViewDebug.ExportedProperty(category = "text", mapping = {
24885            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
24886            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
24887            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
24888            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
24889            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
24890            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
24891            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
24892            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
24893    })
24894    public int getTextDirection() {
24895        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
24896    }
24897
24898    /**
24899     * Resolve the text direction.
24900     *
24901     * @return true if resolution has been done, false otherwise.
24902     *
24903     * @hide
24904     */
24905    public boolean resolveTextDirection() {
24906        // Reset any previous text direction resolution
24907        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
24908
24909        if (hasRtlSupport()) {
24910            // Set resolved text direction flag depending on text direction flag
24911            final int textDirection = getRawTextDirection();
24912            switch(textDirection) {
24913                case TEXT_DIRECTION_INHERIT:
24914                    if (!canResolveTextDirection()) {
24915                        // We cannot do the resolution if there is no parent, so use the default one
24916                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
24917                        // Resolution will need to happen again later
24918                        return false;
24919                    }
24920
24921                    // Parent has not yet resolved, so we still return the default
24922                    try {
24923                        if (!mParent.isTextDirectionResolved()) {
24924                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
24925                            // Resolution will need to happen again later
24926                            return false;
24927                        }
24928                    } catch (AbstractMethodError e) {
24929                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
24930                                " does not fully implement ViewParent", e);
24931                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
24932                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
24933                        return true;
24934                    }
24935
24936                    // Set current resolved direction to the same value as the parent's one
24937                    int parentResolvedDirection;
24938                    try {
24939                        parentResolvedDirection = mParent.getTextDirection();
24940                    } catch (AbstractMethodError e) {
24941                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
24942                                " does not fully implement ViewParent", e);
24943                        parentResolvedDirection = TEXT_DIRECTION_LTR;
24944                    }
24945                    switch (parentResolvedDirection) {
24946                        case TEXT_DIRECTION_FIRST_STRONG:
24947                        case TEXT_DIRECTION_ANY_RTL:
24948                        case TEXT_DIRECTION_LTR:
24949                        case TEXT_DIRECTION_RTL:
24950                        case TEXT_DIRECTION_LOCALE:
24951                        case TEXT_DIRECTION_FIRST_STRONG_LTR:
24952                        case TEXT_DIRECTION_FIRST_STRONG_RTL:
24953                            mPrivateFlags2 |=
24954                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
24955                            break;
24956                        default:
24957                            // Default resolved direction is "first strong" heuristic
24958                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
24959                    }
24960                    break;
24961                case TEXT_DIRECTION_FIRST_STRONG:
24962                case TEXT_DIRECTION_ANY_RTL:
24963                case TEXT_DIRECTION_LTR:
24964                case TEXT_DIRECTION_RTL:
24965                case TEXT_DIRECTION_LOCALE:
24966                case TEXT_DIRECTION_FIRST_STRONG_LTR:
24967                case TEXT_DIRECTION_FIRST_STRONG_RTL:
24968                    // Resolved direction is the same as text direction
24969                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
24970                    break;
24971                default:
24972                    // Default resolved direction is "first strong" heuristic
24973                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
24974            }
24975        } else {
24976            // Default resolved direction is "first strong" heuristic
24977            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
24978        }
24979
24980        // Set to resolved
24981        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
24982        return true;
24983    }
24984
24985    /**
24986     * Check if text direction resolution can be done.
24987     *
24988     * @return true if text direction resolution can be done otherwise return false.
24989     */
24990    public boolean canResolveTextDirection() {
24991        switch (getRawTextDirection()) {
24992            case TEXT_DIRECTION_INHERIT:
24993                if (mParent != null) {
24994                    try {
24995                        return mParent.canResolveTextDirection();
24996                    } catch (AbstractMethodError e) {
24997                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
24998                                " does not fully implement ViewParent", e);
24999                    }
25000                }
25001                return false;
25002
25003            default:
25004                return true;
25005        }
25006    }
25007
25008    /**
25009     * Reset resolved text direction. Text direction will be resolved during a call to
25010     * {@link #onMeasure(int, int)}.
25011     *
25012     * @hide
25013     */
25014    public void resetResolvedTextDirection() {
25015        // Reset any previous text direction resolution
25016        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
25017        // Set to default value
25018        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
25019    }
25020
25021    /**
25022     * @return true if text direction is inherited.
25023     *
25024     * @hide
25025     */
25026    public boolean isTextDirectionInherited() {
25027        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
25028    }
25029
25030    /**
25031     * @return true if text direction is resolved.
25032     */
25033    public boolean isTextDirectionResolved() {
25034        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
25035    }
25036
25037    /**
25038     * Return the value specifying the text alignment or policy that was set with
25039     * {@link #setTextAlignment(int)}.
25040     *
25041     * @return the defined text alignment. It can be one of:
25042     *
25043     * {@link #TEXT_ALIGNMENT_INHERIT},
25044     * {@link #TEXT_ALIGNMENT_GRAVITY},
25045     * {@link #TEXT_ALIGNMENT_CENTER},
25046     * {@link #TEXT_ALIGNMENT_TEXT_START},
25047     * {@link #TEXT_ALIGNMENT_TEXT_END},
25048     * {@link #TEXT_ALIGNMENT_VIEW_START},
25049     * {@link #TEXT_ALIGNMENT_VIEW_END}
25050     *
25051     * @attr ref android.R.styleable#View_textAlignment
25052     *
25053     * @hide
25054     */
25055    @ViewDebug.ExportedProperty(category = "text", mapping = {
25056            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
25057            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
25058            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
25059            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
25060            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
25061            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
25062            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
25063    })
25064    @TextAlignment
25065    public int getRawTextAlignment() {
25066        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
25067    }
25068
25069    /**
25070     * Set the text alignment.
25071     *
25072     * @param textAlignment The text alignment to set. Should be one of
25073     *
25074     * {@link #TEXT_ALIGNMENT_INHERIT},
25075     * {@link #TEXT_ALIGNMENT_GRAVITY},
25076     * {@link #TEXT_ALIGNMENT_CENTER},
25077     * {@link #TEXT_ALIGNMENT_TEXT_START},
25078     * {@link #TEXT_ALIGNMENT_TEXT_END},
25079     * {@link #TEXT_ALIGNMENT_VIEW_START},
25080     * {@link #TEXT_ALIGNMENT_VIEW_END}
25081     *
25082     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
25083     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
25084     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
25085     *
25086     * @attr ref android.R.styleable#View_textAlignment
25087     */
25088    public void setTextAlignment(@TextAlignment int textAlignment) {
25089        if (textAlignment != getRawTextAlignment()) {
25090            // Reset the current and resolved text alignment
25091            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
25092            resetResolvedTextAlignment();
25093            // Set the new text alignment
25094            mPrivateFlags2 |=
25095                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
25096            // Do resolution
25097            resolveTextAlignment();
25098            // Notify change
25099            onRtlPropertiesChanged(getLayoutDirection());
25100            // Refresh
25101            requestLayout();
25102            invalidate(true);
25103        }
25104    }
25105
25106    /**
25107     * Return the resolved text alignment.
25108     *
25109     * @return the resolved text alignment. Returns one of:
25110     *
25111     * {@link #TEXT_ALIGNMENT_GRAVITY},
25112     * {@link #TEXT_ALIGNMENT_CENTER},
25113     * {@link #TEXT_ALIGNMENT_TEXT_START},
25114     * {@link #TEXT_ALIGNMENT_TEXT_END},
25115     * {@link #TEXT_ALIGNMENT_VIEW_START},
25116     * {@link #TEXT_ALIGNMENT_VIEW_END}
25117     *
25118     * @attr ref android.R.styleable#View_textAlignment
25119     */
25120    @ViewDebug.ExportedProperty(category = "text", mapping = {
25121            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
25122            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
25123            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
25124            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
25125            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
25126            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
25127            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
25128    })
25129    @TextAlignment
25130    public int getTextAlignment() {
25131        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
25132                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
25133    }
25134
25135    /**
25136     * Resolve the text alignment.
25137     *
25138     * @return true if resolution has been done, false otherwise.
25139     *
25140     * @hide
25141     */
25142    public boolean resolveTextAlignment() {
25143        // Reset any previous text alignment resolution
25144        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
25145
25146        if (hasRtlSupport()) {
25147            // Set resolved text alignment flag depending on text alignment flag
25148            final int textAlignment = getRawTextAlignment();
25149            switch (textAlignment) {
25150                case TEXT_ALIGNMENT_INHERIT:
25151                    // Check if we can resolve the text alignment
25152                    if (!canResolveTextAlignment()) {
25153                        // We cannot do the resolution if there is no parent so use the default
25154                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
25155                        // Resolution will need to happen again later
25156                        return false;
25157                    }
25158
25159                    // Parent has not yet resolved, so we still return the default
25160                    try {
25161                        if (!mParent.isTextAlignmentResolved()) {
25162                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
25163                            // Resolution will need to happen again later
25164                            return false;
25165                        }
25166                    } catch (AbstractMethodError e) {
25167                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
25168                                " does not fully implement ViewParent", e);
25169                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
25170                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
25171                        return true;
25172                    }
25173
25174                    int parentResolvedTextAlignment;
25175                    try {
25176                        parentResolvedTextAlignment = mParent.getTextAlignment();
25177                    } catch (AbstractMethodError e) {
25178                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
25179                                " does not fully implement ViewParent", e);
25180                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
25181                    }
25182                    switch (parentResolvedTextAlignment) {
25183                        case TEXT_ALIGNMENT_GRAVITY:
25184                        case TEXT_ALIGNMENT_TEXT_START:
25185                        case TEXT_ALIGNMENT_TEXT_END:
25186                        case TEXT_ALIGNMENT_CENTER:
25187                        case TEXT_ALIGNMENT_VIEW_START:
25188                        case TEXT_ALIGNMENT_VIEW_END:
25189                            // Resolved text alignment is the same as the parent resolved
25190                            // text alignment
25191                            mPrivateFlags2 |=
25192                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
25193                            break;
25194                        default:
25195                            // Use default resolved text alignment
25196                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
25197                    }
25198                    break;
25199                case TEXT_ALIGNMENT_GRAVITY:
25200                case TEXT_ALIGNMENT_TEXT_START:
25201                case TEXT_ALIGNMENT_TEXT_END:
25202                case TEXT_ALIGNMENT_CENTER:
25203                case TEXT_ALIGNMENT_VIEW_START:
25204                case TEXT_ALIGNMENT_VIEW_END:
25205                    // Resolved text alignment is the same as text alignment
25206                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
25207                    break;
25208                default:
25209                    // Use default resolved text alignment
25210                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
25211            }
25212        } else {
25213            // Use default resolved text alignment
25214            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
25215        }
25216
25217        // Set the resolved
25218        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
25219        return true;
25220    }
25221
25222    /**
25223     * Check if text alignment resolution can be done.
25224     *
25225     * @return true if text alignment resolution can be done otherwise return false.
25226     */
25227    public boolean canResolveTextAlignment() {
25228        switch (getRawTextAlignment()) {
25229            case TEXT_DIRECTION_INHERIT:
25230                if (mParent != null) {
25231                    try {
25232                        return mParent.canResolveTextAlignment();
25233                    } catch (AbstractMethodError e) {
25234                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
25235                                " does not fully implement ViewParent", e);
25236                    }
25237                }
25238                return false;
25239
25240            default:
25241                return true;
25242        }
25243    }
25244
25245    /**
25246     * Reset resolved text alignment. Text alignment will be resolved during a call to
25247     * {@link #onMeasure(int, int)}.
25248     *
25249     * @hide
25250     */
25251    public void resetResolvedTextAlignment() {
25252        // Reset any previous text alignment resolution
25253        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
25254        // Set to default
25255        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
25256    }
25257
25258    /**
25259     * @return true if text alignment is inherited.
25260     *
25261     * @hide
25262     */
25263    public boolean isTextAlignmentInherited() {
25264        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
25265    }
25266
25267    /**
25268     * @return true if text alignment is resolved.
25269     */
25270    public boolean isTextAlignmentResolved() {
25271        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
25272    }
25273
25274    /**
25275     * Generate a value suitable for use in {@link #setId(int)}.
25276     * This value will not collide with ID values generated at build time by aapt for R.id.
25277     *
25278     * @return a generated ID value
25279     */
25280    public static int generateViewId() {
25281        for (;;) {
25282            final int result = sNextGeneratedId.get();
25283            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
25284            int newValue = result + 1;
25285            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
25286            if (sNextGeneratedId.compareAndSet(result, newValue)) {
25287                return result;
25288            }
25289        }
25290    }
25291
25292    private static boolean isViewIdGenerated(int id) {
25293        return (id & 0xFF000000) == 0 && (id & 0x00FFFFFF) != 0;
25294    }
25295
25296    /**
25297     * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions.
25298     * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and
25299     *                           a normal View or a ViewGroup with
25300     *                           {@link android.view.ViewGroup#isTransitionGroup()} true.
25301     * @hide
25302     */
25303    public void captureTransitioningViews(List<View> transitioningViews) {
25304        if (getVisibility() == View.VISIBLE) {
25305            transitioningViews.add(this);
25306        }
25307    }
25308
25309    /**
25310     * Adds all Views that have {@link #getTransitionName()} non-null to namedElements.
25311     * @param namedElements Will contain all Views in the hierarchy having a transitionName.
25312     * @hide
25313     */
25314    public void findNamedViews(Map<String, View> namedElements) {
25315        if (getVisibility() == VISIBLE || mGhostView != null) {
25316            String transitionName = getTransitionName();
25317            if (transitionName != null) {
25318                namedElements.put(transitionName, this);
25319            }
25320        }
25321    }
25322
25323    /**
25324     * Returns the pointer icon for the motion event, or null if it doesn't specify the icon.
25325     * The default implementation does not care the location or event types, but some subclasses
25326     * may use it (such as WebViews).
25327     * @param event The MotionEvent from a mouse
25328     * @param pointerIndex The index of the pointer for which to retrieve the {@link PointerIcon}.
25329     *                     This will be between 0 and {@link MotionEvent#getPointerCount()}.
25330     * @see PointerIcon
25331     */
25332    public PointerIcon onResolvePointerIcon(MotionEvent event, int pointerIndex) {
25333        final float x = event.getX(pointerIndex);
25334        final float y = event.getY(pointerIndex);
25335        if (isDraggingScrollBar() || isOnScrollbarThumb(x, y)) {
25336            return PointerIcon.getSystemIcon(mContext, PointerIcon.TYPE_ARROW);
25337        }
25338        return mPointerIcon;
25339    }
25340
25341    /**
25342     * Set the pointer icon for the current view.
25343     * Passing {@code null} will restore the pointer icon to its default value.
25344     * @param pointerIcon A PointerIcon instance which will be shown when the mouse hovers.
25345     */
25346    public void setPointerIcon(PointerIcon pointerIcon) {
25347        mPointerIcon = pointerIcon;
25348        if (mAttachInfo == null || mAttachInfo.mHandlingPointerEvent) {
25349            return;
25350        }
25351        try {
25352            mAttachInfo.mSession.updatePointerIcon(mAttachInfo.mWindow);
25353        } catch (RemoteException e) {
25354        }
25355    }
25356
25357    /**
25358     * Gets the pointer icon for the current view.
25359     */
25360    public PointerIcon getPointerIcon() {
25361        return mPointerIcon;
25362    }
25363
25364    /**
25365     * Checks pointer capture status.
25366     *
25367     * @return true if the view has pointer capture.
25368     * @see #requestPointerCapture()
25369     * @see #hasPointerCapture()
25370     */
25371    public boolean hasPointerCapture() {
25372        final ViewRootImpl viewRootImpl = getViewRootImpl();
25373        if (viewRootImpl == null) {
25374            return false;
25375        }
25376        return viewRootImpl.hasPointerCapture();
25377    }
25378
25379    /**
25380     * Requests pointer capture mode.
25381     * <p>
25382     * When the window has pointer capture, the mouse pointer icon will disappear and will not
25383     * change its position. Further mouse will be dispatched with the source
25384     * {@link InputDevice#SOURCE_MOUSE_RELATIVE}, and relative position changes will be available
25385     * through {@link MotionEvent#getX} and {@link MotionEvent#getY}. Non-mouse events
25386     * (touchscreens, or stylus) will not be affected.
25387     * <p>
25388     * If the window already has pointer capture, this call does nothing.
25389     * <p>
25390     * The capture may be released through {@link #releasePointerCapture()}, or will be lost
25391     * automatically when the window loses focus.
25392     *
25393     * @see #releasePointerCapture()
25394     * @see #hasPointerCapture()
25395     */
25396    public void requestPointerCapture() {
25397        final ViewRootImpl viewRootImpl = getViewRootImpl();
25398        if (viewRootImpl != null) {
25399            viewRootImpl.requestPointerCapture(true);
25400        }
25401    }
25402
25403
25404    /**
25405     * Releases the pointer capture.
25406     * <p>
25407     * If the window does not have pointer capture, this call will do nothing.
25408     * @see #requestPointerCapture()
25409     * @see #hasPointerCapture()
25410     */
25411    public void releasePointerCapture() {
25412        final ViewRootImpl viewRootImpl = getViewRootImpl();
25413        if (viewRootImpl != null) {
25414            viewRootImpl.requestPointerCapture(false);
25415        }
25416    }
25417
25418    /**
25419     * Called when the window has just acquired or lost pointer capture.
25420     *
25421     * @param hasCapture True if the view now has pointerCapture, false otherwise.
25422     */
25423    @CallSuper
25424    public void onPointerCaptureChange(boolean hasCapture) {
25425    }
25426
25427    /**
25428     * @see #onPointerCaptureChange
25429     */
25430    public void dispatchPointerCaptureChanged(boolean hasCapture) {
25431        onPointerCaptureChange(hasCapture);
25432    }
25433
25434    /**
25435     * Implement this method to handle captured pointer events
25436     *
25437     * @param event The captured pointer event.
25438     * @return True if the event was handled, false otherwise.
25439     * @see #requestPointerCapture()
25440     */
25441    public boolean onCapturedPointerEvent(MotionEvent event) {
25442        return false;
25443    }
25444
25445    /**
25446     * Interface definition for a callback to be invoked when a captured pointer event
25447     * is being dispatched this view. The callback will be invoked before the event is
25448     * given to the view.
25449     */
25450    public interface OnCapturedPointerListener {
25451        /**
25452         * Called when a captured pointer event is dispatched to a view.
25453         * @param view The view this event has been dispatched to.
25454         * @param event The captured event.
25455         * @return True if the listener has consumed the event, false otherwise.
25456         */
25457        boolean onCapturedPointer(View view, MotionEvent event);
25458    }
25459
25460    /**
25461     * Set a listener to receive callbacks when the pointer capture state of a view changes.
25462     * @param l  The {@link OnCapturedPointerListener} to receive callbacks.
25463     */
25464    public void setOnCapturedPointerListener(OnCapturedPointerListener l) {
25465        getListenerInfo().mOnCapturedPointerListener = l;
25466    }
25467
25468    // Properties
25469    //
25470    /**
25471     * A Property wrapper around the <code>alpha</code> functionality handled by the
25472     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
25473     */
25474    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
25475        @Override
25476        public void setValue(View object, float value) {
25477            object.setAlpha(value);
25478        }
25479
25480        @Override
25481        public Float get(View object) {
25482            return object.getAlpha();
25483        }
25484    };
25485
25486    /**
25487     * A Property wrapper around the <code>translationX</code> functionality handled by the
25488     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
25489     */
25490    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
25491        @Override
25492        public void setValue(View object, float value) {
25493            object.setTranslationX(value);
25494        }
25495
25496                @Override
25497        public Float get(View object) {
25498            return object.getTranslationX();
25499        }
25500    };
25501
25502    /**
25503     * A Property wrapper around the <code>translationY</code> functionality handled by the
25504     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
25505     */
25506    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
25507        @Override
25508        public void setValue(View object, float value) {
25509            object.setTranslationY(value);
25510        }
25511
25512        @Override
25513        public Float get(View object) {
25514            return object.getTranslationY();
25515        }
25516    };
25517
25518    /**
25519     * A Property wrapper around the <code>translationZ</code> functionality handled by the
25520     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
25521     */
25522    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
25523        @Override
25524        public void setValue(View object, float value) {
25525            object.setTranslationZ(value);
25526        }
25527
25528        @Override
25529        public Float get(View object) {
25530            return object.getTranslationZ();
25531        }
25532    };
25533
25534    /**
25535     * A Property wrapper around the <code>x</code> functionality handled by the
25536     * {@link View#setX(float)} and {@link View#getX()} methods.
25537     */
25538    public static final Property<View, Float> X = new FloatProperty<View>("x") {
25539        @Override
25540        public void setValue(View object, float value) {
25541            object.setX(value);
25542        }
25543
25544        @Override
25545        public Float get(View object) {
25546            return object.getX();
25547        }
25548    };
25549
25550    /**
25551     * A Property wrapper around the <code>y</code> functionality handled by the
25552     * {@link View#setY(float)} and {@link View#getY()} methods.
25553     */
25554    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
25555        @Override
25556        public void setValue(View object, float value) {
25557            object.setY(value);
25558        }
25559
25560        @Override
25561        public Float get(View object) {
25562            return object.getY();
25563        }
25564    };
25565
25566    /**
25567     * A Property wrapper around the <code>z</code> functionality handled by the
25568     * {@link View#setZ(float)} and {@link View#getZ()} methods.
25569     */
25570    public static final Property<View, Float> Z = new FloatProperty<View>("z") {
25571        @Override
25572        public void setValue(View object, float value) {
25573            object.setZ(value);
25574        }
25575
25576        @Override
25577        public Float get(View object) {
25578            return object.getZ();
25579        }
25580    };
25581
25582    /**
25583     * A Property wrapper around the <code>rotation</code> functionality handled by the
25584     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
25585     */
25586    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
25587        @Override
25588        public void setValue(View object, float value) {
25589            object.setRotation(value);
25590        }
25591
25592        @Override
25593        public Float get(View object) {
25594            return object.getRotation();
25595        }
25596    };
25597
25598    /**
25599     * A Property wrapper around the <code>rotationX</code> functionality handled by the
25600     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
25601     */
25602    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
25603        @Override
25604        public void setValue(View object, float value) {
25605            object.setRotationX(value);
25606        }
25607
25608        @Override
25609        public Float get(View object) {
25610            return object.getRotationX();
25611        }
25612    };
25613
25614    /**
25615     * A Property wrapper around the <code>rotationY</code> functionality handled by the
25616     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
25617     */
25618    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
25619        @Override
25620        public void setValue(View object, float value) {
25621            object.setRotationY(value);
25622        }
25623
25624        @Override
25625        public Float get(View object) {
25626            return object.getRotationY();
25627        }
25628    };
25629
25630    /**
25631     * A Property wrapper around the <code>scaleX</code> functionality handled by the
25632     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
25633     */
25634    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
25635        @Override
25636        public void setValue(View object, float value) {
25637            object.setScaleX(value);
25638        }
25639
25640        @Override
25641        public Float get(View object) {
25642            return object.getScaleX();
25643        }
25644    };
25645
25646    /**
25647     * A Property wrapper around the <code>scaleY</code> functionality handled by the
25648     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
25649     */
25650    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
25651        @Override
25652        public void setValue(View object, float value) {
25653            object.setScaleY(value);
25654        }
25655
25656        @Override
25657        public Float get(View object) {
25658            return object.getScaleY();
25659        }
25660    };
25661
25662    /**
25663     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
25664     * Each MeasureSpec represents a requirement for either the width or the height.
25665     * A MeasureSpec is comprised of a size and a mode. There are three possible
25666     * modes:
25667     * <dl>
25668     * <dt>UNSPECIFIED</dt>
25669     * <dd>
25670     * The parent has not imposed any constraint on the child. It can be whatever size
25671     * it wants.
25672     * </dd>
25673     *
25674     * <dt>EXACTLY</dt>
25675     * <dd>
25676     * The parent has determined an exact size for the child. The child is going to be
25677     * given those bounds regardless of how big it wants to be.
25678     * </dd>
25679     *
25680     * <dt>AT_MOST</dt>
25681     * <dd>
25682     * The child can be as large as it wants up to the specified size.
25683     * </dd>
25684     * </dl>
25685     *
25686     * MeasureSpecs are implemented as ints to reduce object allocation. This class
25687     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
25688     */
25689    public static class MeasureSpec {
25690        private static final int MODE_SHIFT = 30;
25691        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
25692
25693        /** @hide */
25694        @IntDef({UNSPECIFIED, EXACTLY, AT_MOST})
25695        @Retention(RetentionPolicy.SOURCE)
25696        public @interface MeasureSpecMode {}
25697
25698        /**
25699         * Measure specification mode: The parent has not imposed any constraint
25700         * on the child. It can be whatever size it wants.
25701         */
25702        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
25703
25704        /**
25705         * Measure specification mode: The parent has determined an exact size
25706         * for the child. The child is going to be given those bounds regardless
25707         * of how big it wants to be.
25708         */
25709        public static final int EXACTLY     = 1 << MODE_SHIFT;
25710
25711        /**
25712         * Measure specification mode: The child can be as large as it wants up
25713         * to the specified size.
25714         */
25715        public static final int AT_MOST     = 2 << MODE_SHIFT;
25716
25717        /**
25718         * Creates a measure specification based on the supplied size and mode.
25719         *
25720         * The mode must always be one of the following:
25721         * <ul>
25722         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
25723         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
25724         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
25725         * </ul>
25726         *
25727         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
25728         * implementation was such that the order of arguments did not matter
25729         * and overflow in either value could impact the resulting MeasureSpec.
25730         * {@link android.widget.RelativeLayout} was affected by this bug.
25731         * Apps targeting API levels greater than 17 will get the fixed, more strict
25732         * behavior.</p>
25733         *
25734         * @param size the size of the measure specification
25735         * @param mode the mode of the measure specification
25736         * @return the measure specification based on size and mode
25737         */
25738        public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size,
25739                                          @MeasureSpecMode int mode) {
25740            if (sUseBrokenMakeMeasureSpec) {
25741                return size + mode;
25742            } else {
25743                return (size & ~MODE_MASK) | (mode & MODE_MASK);
25744            }
25745        }
25746
25747        /**
25748         * Like {@link #makeMeasureSpec(int, int)}, but any spec with a mode of UNSPECIFIED
25749         * will automatically get a size of 0. Older apps expect this.
25750         *
25751         * @hide internal use only for compatibility with system widgets and older apps
25752         */
25753        public static int makeSafeMeasureSpec(int size, int mode) {
25754            if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) {
25755                return 0;
25756            }
25757            return makeMeasureSpec(size, mode);
25758        }
25759
25760        /**
25761         * Extracts the mode from the supplied measure specification.
25762         *
25763         * @param measureSpec the measure specification to extract the mode from
25764         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
25765         *         {@link android.view.View.MeasureSpec#AT_MOST} or
25766         *         {@link android.view.View.MeasureSpec#EXACTLY}
25767         */
25768        @MeasureSpecMode
25769        public static int getMode(int measureSpec) {
25770            //noinspection ResourceType
25771            return (measureSpec & MODE_MASK);
25772        }
25773
25774        /**
25775         * Extracts the size from the supplied measure specification.
25776         *
25777         * @param measureSpec the measure specification to extract the size from
25778         * @return the size in pixels defined in the supplied measure specification
25779         */
25780        public static int getSize(int measureSpec) {
25781            return (measureSpec & ~MODE_MASK);
25782        }
25783
25784        static int adjust(int measureSpec, int delta) {
25785            final int mode = getMode(measureSpec);
25786            int size = getSize(measureSpec);
25787            if (mode == UNSPECIFIED) {
25788                // No need to adjust size for UNSPECIFIED mode.
25789                return makeMeasureSpec(size, UNSPECIFIED);
25790            }
25791            size += delta;
25792            if (size < 0) {
25793                Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
25794                        ") spec: " + toString(measureSpec) + " delta: " + delta);
25795                size = 0;
25796            }
25797            return makeMeasureSpec(size, mode);
25798        }
25799
25800        /**
25801         * Returns a String representation of the specified measure
25802         * specification.
25803         *
25804         * @param measureSpec the measure specification to convert to a String
25805         * @return a String with the following format: "MeasureSpec: MODE SIZE"
25806         */
25807        public static String toString(int measureSpec) {
25808            int mode = getMode(measureSpec);
25809            int size = getSize(measureSpec);
25810
25811            StringBuilder sb = new StringBuilder("MeasureSpec: ");
25812
25813            if (mode == UNSPECIFIED)
25814                sb.append("UNSPECIFIED ");
25815            else if (mode == EXACTLY)
25816                sb.append("EXACTLY ");
25817            else if (mode == AT_MOST)
25818                sb.append("AT_MOST ");
25819            else
25820                sb.append(mode).append(" ");
25821
25822            sb.append(size);
25823            return sb.toString();
25824        }
25825    }
25826
25827    private final class CheckForLongPress implements Runnable {
25828        private int mOriginalWindowAttachCount;
25829        private float mX;
25830        private float mY;
25831        private boolean mOriginalPressedState;
25832
25833        @Override
25834        public void run() {
25835            if ((mOriginalPressedState == isPressed()) && (mParent != null)
25836                    && mOriginalWindowAttachCount == mWindowAttachCount) {
25837                if (performLongClick(mX, mY)) {
25838                    mHasPerformedLongPress = true;
25839                }
25840            }
25841        }
25842
25843        public void setAnchor(float x, float y) {
25844            mX = x;
25845            mY = y;
25846        }
25847
25848        public void rememberWindowAttachCount() {
25849            mOriginalWindowAttachCount = mWindowAttachCount;
25850        }
25851
25852        public void rememberPressedState() {
25853            mOriginalPressedState = isPressed();
25854        }
25855    }
25856
25857    private final class CheckForTap implements Runnable {
25858        public float x;
25859        public float y;
25860
25861        @Override
25862        public void run() {
25863            mPrivateFlags &= ~PFLAG_PREPRESSED;
25864            setPressed(true, x, y);
25865            checkForLongClick(ViewConfiguration.getTapTimeout(), x, y);
25866        }
25867    }
25868
25869    private final class PerformClick implements Runnable {
25870        @Override
25871        public void run() {
25872            performClickInternal();
25873        }
25874    }
25875
25876    /**
25877     * This method returns a ViewPropertyAnimator object, which can be used to animate
25878     * specific properties on this View.
25879     *
25880     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
25881     */
25882    public ViewPropertyAnimator animate() {
25883        if (mAnimator == null) {
25884            mAnimator = new ViewPropertyAnimator(this);
25885        }
25886        return mAnimator;
25887    }
25888
25889    /**
25890     * Sets the name of the View to be used to identify Views in Transitions.
25891     * Names should be unique in the View hierarchy.
25892     *
25893     * @param transitionName The name of the View to uniquely identify it for Transitions.
25894     */
25895    public final void setTransitionName(String transitionName) {
25896        mTransitionName = transitionName;
25897    }
25898
25899    /**
25900     * Returns the name of the View to be used to identify Views in Transitions.
25901     * Names should be unique in the View hierarchy.
25902     *
25903     * <p>This returns null if the View has not been given a name.</p>
25904     *
25905     * @return The name used of the View to be used to identify Views in Transitions or null
25906     * if no name has been given.
25907     */
25908    @ViewDebug.ExportedProperty
25909    public String getTransitionName() {
25910        return mTransitionName;
25911    }
25912
25913    /**
25914     * @hide
25915     */
25916    public void requestKeyboardShortcuts(List<KeyboardShortcutGroup> data, int deviceId) {
25917        // Do nothing.
25918    }
25919
25920    /**
25921     * Interface definition for a callback to be invoked when a hardware key event is
25922     * dispatched to this view. The callback will be invoked before the key event is
25923     * given to the view. This is only useful for hardware keyboards; a software input
25924     * method has no obligation to trigger this listener.
25925     */
25926    public interface OnKeyListener {
25927        /**
25928         * Called when a hardware key is dispatched to a view. This allows listeners to
25929         * get a chance to respond before the target view.
25930         * <p>Key presses in software keyboards will generally NOT trigger this method,
25931         * although some may elect to do so in some situations. Do not assume a
25932         * software input method has to be key-based; even if it is, it may use key presses
25933         * in a different way than you expect, so there is no way to reliably catch soft
25934         * input key presses.
25935         *
25936         * @param v The view the key has been dispatched to.
25937         * @param keyCode The code for the physical key that was pressed
25938         * @param event The KeyEvent object containing full information about
25939         *        the event.
25940         * @return True if the listener has consumed the event, false otherwise.
25941         */
25942        boolean onKey(View v, int keyCode, KeyEvent event);
25943    }
25944
25945    /**
25946     * Interface definition for a callback to be invoked when a hardware key event hasn't
25947     * been handled by the view hierarchy.
25948     */
25949    public interface OnUnhandledKeyEventListener {
25950        /**
25951         * Called when a hardware key is dispatched to a view after being unhandled during normal
25952         * {@link KeyEvent} dispatch.
25953         *
25954         * @param v The view the key has been dispatched to.
25955         * @param event The KeyEvent object containing information about the event.
25956         * @return {@code true} if the listener has consumed the event, {@code false} otherwise.
25957         */
25958        boolean onUnhandledKeyEvent(View v, KeyEvent event);
25959    }
25960
25961    /**
25962     * Interface definition for a callback to be invoked when a touch event is
25963     * dispatched to this view. The callback will be invoked before the touch
25964     * event is given to the view.
25965     */
25966    public interface OnTouchListener {
25967        /**
25968         * Called when a touch event is dispatched to a view. This allows listeners to
25969         * get a chance to respond before the target view.
25970         *
25971         * @param v The view the touch event has been dispatched to.
25972         * @param event The MotionEvent object containing full information about
25973         *        the event.
25974         * @return True if the listener has consumed the event, false otherwise.
25975         */
25976        boolean onTouch(View v, MotionEvent event);
25977    }
25978
25979    /**
25980     * Interface definition for a callback to be invoked when a hover event is
25981     * dispatched to this view. The callback will be invoked before the hover
25982     * event is given to the view.
25983     */
25984    public interface OnHoverListener {
25985        /**
25986         * Called when a hover event is dispatched to a view. This allows listeners to
25987         * get a chance to respond before the target view.
25988         *
25989         * @param v The view the hover event has been dispatched to.
25990         * @param event The MotionEvent object containing full information about
25991         *        the event.
25992         * @return True if the listener has consumed the event, false otherwise.
25993         */
25994        boolean onHover(View v, MotionEvent event);
25995    }
25996
25997    /**
25998     * Interface definition for a callback to be invoked when a generic motion event is
25999     * dispatched to this view. The callback will be invoked before the generic motion
26000     * event is given to the view.
26001     */
26002    public interface OnGenericMotionListener {
26003        /**
26004         * Called when a generic motion event is dispatched to a view. This allows listeners to
26005         * get a chance to respond before the target view.
26006         *
26007         * @param v The view the generic motion event has been dispatched to.
26008         * @param event The MotionEvent object containing full information about
26009         *        the event.
26010         * @return True if the listener has consumed the event, false otherwise.
26011         */
26012        boolean onGenericMotion(View v, MotionEvent event);
26013    }
26014
26015    /**
26016     * Interface definition for a callback to be invoked when a view has been clicked and held.
26017     */
26018    public interface OnLongClickListener {
26019        /**
26020         * Called when a view has been clicked and held.
26021         *
26022         * @param v The view that was clicked and held.
26023         *
26024         * @return true if the callback consumed the long click, false otherwise.
26025         */
26026        boolean onLongClick(View v);
26027    }
26028
26029    /**
26030     * Interface definition for a callback to be invoked when a drag is being dispatched
26031     * to this view.  The callback will be invoked before the hosting view's own
26032     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
26033     * onDrag(event) behavior, it should return 'false' from this callback.
26034     *
26035     * <div class="special reference">
26036     * <h3>Developer Guides</h3>
26037     * <p>For a guide to implementing drag and drop features, read the
26038     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
26039     * </div>
26040     */
26041    public interface OnDragListener {
26042        /**
26043         * Called when a drag event is dispatched to a view. This allows listeners
26044         * to get a chance to override base View behavior.
26045         *
26046         * @param v The View that received the drag event.
26047         * @param event The {@link android.view.DragEvent} object for the drag event.
26048         * @return {@code true} if the drag event was handled successfully, or {@code false}
26049         * if the drag event was not handled. Note that {@code false} will trigger the View
26050         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
26051         */
26052        boolean onDrag(View v, DragEvent event);
26053    }
26054
26055    /**
26056     * Interface definition for a callback to be invoked when the focus state of
26057     * a view changed.
26058     */
26059    public interface OnFocusChangeListener {
26060        /**
26061         * Called when the focus state of a view has changed.
26062         *
26063         * @param v The view whose state has changed.
26064         * @param hasFocus The new focus state of v.
26065         */
26066        void onFocusChange(View v, boolean hasFocus);
26067    }
26068
26069    /**
26070     * Interface definition for a callback to be invoked when a view is clicked.
26071     */
26072    public interface OnClickListener {
26073        /**
26074         * Called when a view has been clicked.
26075         *
26076         * @param v The view that was clicked.
26077         */
26078        void onClick(View v);
26079    }
26080
26081    /**
26082     * Interface definition for a callback to be invoked when a view is context clicked.
26083     */
26084    public interface OnContextClickListener {
26085        /**
26086         * Called when a view is context clicked.
26087         *
26088         * @param v The view that has been context clicked.
26089         * @return true if the callback consumed the context click, false otherwise.
26090         */
26091        boolean onContextClick(View v);
26092    }
26093
26094    /**
26095     * Interface definition for a callback to be invoked when the context menu
26096     * for this view is being built.
26097     */
26098    public interface OnCreateContextMenuListener {
26099        /**
26100         * Called when the context menu for this view is being built. It is not
26101         * safe to hold onto the menu after this method returns.
26102         *
26103         * @param menu The context menu that is being built
26104         * @param v The view for which the context menu is being built
26105         * @param menuInfo Extra information about the item for which the
26106         *            context menu should be shown. This information will vary
26107         *            depending on the class of v.
26108         */
26109        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
26110    }
26111
26112    /**
26113     * Interface definition for a callback to be invoked when the status bar changes
26114     * visibility.  This reports <strong>global</strong> changes to the system UI
26115     * state, not what the application is requesting.
26116     *
26117     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
26118     */
26119    public interface OnSystemUiVisibilityChangeListener {
26120        /**
26121         * Called when the status bar changes visibility because of a call to
26122         * {@link View#setSystemUiVisibility(int)}.
26123         *
26124         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
26125         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
26126         * This tells you the <strong>global</strong> state of these UI visibility
26127         * flags, not what your app is currently applying.
26128         */
26129        public void onSystemUiVisibilityChange(int visibility);
26130    }
26131
26132    /**
26133     * Interface definition for a callback to be invoked when this view is attached
26134     * or detached from its window.
26135     */
26136    public interface OnAttachStateChangeListener {
26137        /**
26138         * Called when the view is attached to a window.
26139         * @param v The view that was attached
26140         */
26141        public void onViewAttachedToWindow(View v);
26142        /**
26143         * Called when the view is detached from a window.
26144         * @param v The view that was detached
26145         */
26146        public void onViewDetachedFromWindow(View v);
26147    }
26148
26149    /**
26150     * Listener for applying window insets on a view in a custom way.
26151     *
26152     * <p>Apps may choose to implement this interface if they want to apply custom policy
26153     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
26154     * is set, its
26155     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
26156     * method will be called instead of the View's own
26157     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
26158     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
26159     * the View's normal behavior as part of its own.</p>
26160     */
26161    public interface OnApplyWindowInsetsListener {
26162        /**
26163         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
26164         * on a View, this listener method will be called instead of the view's own
26165         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
26166         *
26167         * @param v The view applying window insets
26168         * @param insets The insets to apply
26169         * @return The insets supplied, minus any insets that were consumed
26170         */
26171        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
26172    }
26173
26174    private final class UnsetPressedState implements Runnable {
26175        @Override
26176        public void run() {
26177            setPressed(false);
26178        }
26179    }
26180
26181    /**
26182     * When a view becomes invisible checks if autofill considers the view invisible too. This
26183     * happens after the regular removal operation to make sure the operation is finished by the
26184     * time this is called.
26185     */
26186    private static class VisibilityChangeForAutofillHandler extends Handler {
26187        private final AutofillManager mAfm;
26188        private final View mView;
26189
26190        private VisibilityChangeForAutofillHandler(@NonNull AutofillManager afm,
26191                @NonNull View view) {
26192            mAfm = afm;
26193            mView = view;
26194        }
26195
26196        @Override
26197        public void handleMessage(Message msg) {
26198            mAfm.notifyViewVisibilityChanged(mView, mView.isShown());
26199        }
26200    }
26201
26202    /**
26203     * Base class for derived classes that want to save and restore their own
26204     * state in {@link android.view.View#onSaveInstanceState()}.
26205     */
26206    public static class BaseSavedState extends AbsSavedState {
26207        static final int START_ACTIVITY_REQUESTED_WHO_SAVED = 0b1;
26208        static final int IS_AUTOFILLED = 0b10;
26209        static final int AUTOFILL_ID = 0b100;
26210
26211        // Flags that describe what data in this state is valid
26212        int mSavedData;
26213        String mStartActivityRequestWhoSaved;
26214        boolean mIsAutofilled;
26215        int mAutofillViewId;
26216
26217        /**
26218         * Constructor used when reading from a parcel. Reads the state of the superclass.
26219         *
26220         * @param source parcel to read from
26221         */
26222        public BaseSavedState(Parcel source) {
26223            this(source, null);
26224        }
26225
26226        /**
26227         * Constructor used when reading from a parcel using a given class loader.
26228         * Reads the state of the superclass.
26229         *
26230         * @param source parcel to read from
26231         * @param loader ClassLoader to use for reading
26232         */
26233        public BaseSavedState(Parcel source, ClassLoader loader) {
26234            super(source, loader);
26235            mSavedData = source.readInt();
26236            mStartActivityRequestWhoSaved = source.readString();
26237            mIsAutofilled = source.readBoolean();
26238            mAutofillViewId = source.readInt();
26239        }
26240
26241        /**
26242         * Constructor called by derived classes when creating their SavedState objects
26243         *
26244         * @param superState The state of the superclass of this view
26245         */
26246        public BaseSavedState(Parcelable superState) {
26247            super(superState);
26248        }
26249
26250        @Override
26251        public void writeToParcel(Parcel out, int flags) {
26252            super.writeToParcel(out, flags);
26253
26254            out.writeInt(mSavedData);
26255            out.writeString(mStartActivityRequestWhoSaved);
26256            out.writeBoolean(mIsAutofilled);
26257            out.writeInt(mAutofillViewId);
26258        }
26259
26260        public static final Parcelable.Creator<BaseSavedState> CREATOR
26261                = new Parcelable.ClassLoaderCreator<BaseSavedState>() {
26262            @Override
26263            public BaseSavedState createFromParcel(Parcel in) {
26264                return new BaseSavedState(in);
26265            }
26266
26267            @Override
26268            public BaseSavedState createFromParcel(Parcel in, ClassLoader loader) {
26269                return new BaseSavedState(in, loader);
26270            }
26271
26272            @Override
26273            public BaseSavedState[] newArray(int size) {
26274                return new BaseSavedState[size];
26275            }
26276        };
26277    }
26278
26279    /**
26280     * A set of information given to a view when it is attached to its parent
26281     * window.
26282     */
26283    final static class AttachInfo {
26284        interface Callbacks {
26285            void playSoundEffect(int effectId);
26286            boolean performHapticFeedback(int effectId, boolean always);
26287        }
26288
26289        /**
26290         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
26291         * to a Handler. This class contains the target (View) to invalidate and
26292         * the coordinates of the dirty rectangle.
26293         *
26294         * For performance purposes, this class also implements a pool of up to
26295         * POOL_LIMIT objects that get reused. This reduces memory allocations
26296         * whenever possible.
26297         */
26298        static class InvalidateInfo {
26299            private static final int POOL_LIMIT = 10;
26300
26301            private static final SynchronizedPool<InvalidateInfo> sPool =
26302                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
26303
26304            View target;
26305
26306            int left;
26307            int top;
26308            int right;
26309            int bottom;
26310
26311            public static InvalidateInfo obtain() {
26312                InvalidateInfo instance = sPool.acquire();
26313                return (instance != null) ? instance : new InvalidateInfo();
26314            }
26315
26316            public void recycle() {
26317                target = null;
26318                sPool.release(this);
26319            }
26320        }
26321
26322        final IWindowSession mSession;
26323
26324        final IWindow mWindow;
26325
26326        final IBinder mWindowToken;
26327
26328        Display mDisplay;
26329
26330        final Callbacks mRootCallbacks;
26331
26332        IWindowId mIWindowId;
26333        WindowId mWindowId;
26334
26335        /**
26336         * The top view of the hierarchy.
26337         */
26338        View mRootView;
26339
26340        IBinder mPanelParentWindowToken;
26341
26342        boolean mHardwareAccelerated;
26343        boolean mHardwareAccelerationRequested;
26344        ThreadedRenderer mThreadedRenderer;
26345        List<RenderNode> mPendingAnimatingRenderNodes;
26346
26347        /**
26348         * The state of the display to which the window is attached, as reported
26349         * by {@link Display#getState()}.  Note that the display state constants
26350         * declared by {@link Display} do not exactly line up with the screen state
26351         * constants declared by {@link View} (there are more display states than
26352         * screen states).
26353         */
26354        int mDisplayState = Display.STATE_UNKNOWN;
26355
26356        /**
26357         * Scale factor used by the compatibility mode
26358         */
26359        float mApplicationScale;
26360
26361        /**
26362         * Indicates whether the application is in compatibility mode
26363         */
26364        boolean mScalingRequired;
26365
26366        /**
26367         * Left position of this view's window
26368         */
26369        int mWindowLeft;
26370
26371        /**
26372         * Top position of this view's window
26373         */
26374        int mWindowTop;
26375
26376        /**
26377         * Indicates whether views need to use 32-bit drawing caches
26378         */
26379        boolean mUse32BitDrawingCache;
26380
26381        /**
26382         * For windows that are full-screen but using insets to layout inside
26383         * of the screen areas, these are the current insets to appear inside
26384         * the overscan area of the display.
26385         */
26386        final Rect mOverscanInsets = new Rect();
26387
26388        /**
26389         * For windows that are full-screen but using insets to layout inside
26390         * of the screen decorations, these are the current insets for the
26391         * content of the window.
26392         */
26393        final Rect mContentInsets = new Rect();
26394
26395        /**
26396         * For windows that are full-screen but using insets to layout inside
26397         * of the screen decorations, these are the current insets for the
26398         * actual visible parts of the window.
26399         */
26400        final Rect mVisibleInsets = new Rect();
26401
26402        /**
26403         * For windows that are full-screen but using insets to layout inside
26404         * of the screen decorations, these are the current insets for the
26405         * stable system windows.
26406         */
26407        final Rect mStableInsets = new Rect();
26408
26409        final DisplayCutout.ParcelableWrapper mDisplayCutout =
26410                new DisplayCutout.ParcelableWrapper(DisplayCutout.NO_CUTOUT);
26411
26412        /**
26413         * For windows that include areas that are not covered by real surface these are the outsets
26414         * for real surface.
26415         */
26416        final Rect mOutsets = new Rect();
26417
26418        /**
26419         * In multi-window we force show the navigation bar. Because we don't want that the surface
26420         * size changes in this mode, we instead have a flag whether the navigation bar size should
26421         * always be consumed, so the app is treated like there is no virtual navigation bar at all.
26422         */
26423        boolean mAlwaysConsumeNavBar;
26424
26425        /**
26426         * The internal insets given by this window.  This value is
26427         * supplied by the client (through
26428         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
26429         * be given to the window manager when changed to be used in laying
26430         * out windows behind it.
26431         */
26432        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
26433                = new ViewTreeObserver.InternalInsetsInfo();
26434
26435        /**
26436         * Set to true when mGivenInternalInsets is non-empty.
26437         */
26438        boolean mHasNonEmptyGivenInternalInsets;
26439
26440        /**
26441         * All views in the window's hierarchy that serve as scroll containers,
26442         * used to determine if the window can be resized or must be panned
26443         * to adjust for a soft input area.
26444         */
26445        final ArrayList<View> mScrollContainers = new ArrayList<View>();
26446
26447        final KeyEvent.DispatcherState mKeyDispatchState
26448                = new KeyEvent.DispatcherState();
26449
26450        /**
26451         * Indicates whether the view's window currently has the focus.
26452         */
26453        boolean mHasWindowFocus;
26454
26455        /**
26456         * The current visibility of the window.
26457         */
26458        int mWindowVisibility;
26459
26460        /**
26461         * Indicates the time at which drawing started to occur.
26462         */
26463        long mDrawingTime;
26464
26465        /**
26466         * Indicates whether or not ignoring the DIRTY_MASK flags.
26467         */
26468        boolean mIgnoreDirtyState;
26469
26470        /**
26471         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
26472         * to avoid clearing that flag prematurely.
26473         */
26474        boolean mSetIgnoreDirtyState = false;
26475
26476        /**
26477         * Indicates whether the view's window is currently in touch mode.
26478         */
26479        boolean mInTouchMode;
26480
26481        /**
26482         * Indicates whether the view has requested unbuffered input dispatching for the current
26483         * event stream.
26484         */
26485        boolean mUnbufferedDispatchRequested;
26486
26487        /**
26488         * Indicates that ViewAncestor should trigger a global layout change
26489         * the next time it performs a traversal
26490         */
26491        boolean mRecomputeGlobalAttributes;
26492
26493        /**
26494         * Always report new attributes at next traversal.
26495         */
26496        boolean mForceReportNewAttributes;
26497
26498        /**
26499         * Set during a traveral if any views want to keep the screen on.
26500         */
26501        boolean mKeepScreenOn;
26502
26503        /**
26504         * Set during a traveral if the light center needs to be updated.
26505         */
26506        boolean mNeedsUpdateLightCenter;
26507
26508        /**
26509         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
26510         */
26511        int mSystemUiVisibility;
26512
26513        /**
26514         * Hack to force certain system UI visibility flags to be cleared.
26515         */
26516        int mDisabledSystemUiVisibility;
26517
26518        /**
26519         * Last global system UI visibility reported by the window manager.
26520         */
26521        int mGlobalSystemUiVisibility = -1;
26522
26523        /**
26524         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
26525         * attached.
26526         */
26527        boolean mHasSystemUiListeners;
26528
26529        /**
26530         * Set if the window has requested to extend into the overscan region
26531         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
26532         */
26533        boolean mOverscanRequested;
26534
26535        /**
26536         * Set if the visibility of any views has changed.
26537         */
26538        boolean mViewVisibilityChanged;
26539
26540        /**
26541         * Set to true if a view has been scrolled.
26542         */
26543        boolean mViewScrollChanged;
26544
26545        /**
26546         * Set to true if a pointer event is currently being handled.
26547         */
26548        boolean mHandlingPointerEvent;
26549
26550        /**
26551         * Global to the view hierarchy used as a temporary for dealing with
26552         * x/y points in the transparent region computations.
26553         */
26554        final int[] mTransparentLocation = new int[2];
26555
26556        /**
26557         * Global to the view hierarchy used as a temporary for dealing with
26558         * x/y points in the ViewGroup.invalidateChild implementation.
26559         */
26560        final int[] mInvalidateChildLocation = new int[2];
26561
26562        /**
26563         * Global to the view hierarchy used as a temporary for dealing with
26564         * computing absolute on-screen location.
26565         */
26566        final int[] mTmpLocation = new int[2];
26567
26568        /**
26569         * Global to the view hierarchy used as a temporary for dealing with
26570         * x/y location when view is transformed.
26571         */
26572        final float[] mTmpTransformLocation = new float[2];
26573
26574        /**
26575         * The view tree observer used to dispatch global events like
26576         * layout, pre-draw, touch mode change, etc.
26577         */
26578        final ViewTreeObserver mTreeObserver;
26579
26580        /**
26581         * A Canvas used by the view hierarchy to perform bitmap caching.
26582         */
26583        Canvas mCanvas;
26584
26585        /**
26586         * The view root impl.
26587         */
26588        final ViewRootImpl mViewRootImpl;
26589
26590        /**
26591         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
26592         * handler can be used to pump events in the UI events queue.
26593         */
26594        final Handler mHandler;
26595
26596        /**
26597         * Temporary for use in computing invalidate rectangles while
26598         * calling up the hierarchy.
26599         */
26600        final Rect mTmpInvalRect = new Rect();
26601
26602        /**
26603         * Temporary for use in computing hit areas with transformed views
26604         */
26605        final RectF mTmpTransformRect = new RectF();
26606
26607        /**
26608         * Temporary for use in computing hit areas with transformed views
26609         */
26610        final RectF mTmpTransformRect1 = new RectF();
26611
26612        /**
26613         * Temporary list of rectanges.
26614         */
26615        final List<RectF> mTmpRectList = new ArrayList<>();
26616
26617        /**
26618         * Temporary for use in transforming invalidation rect
26619         */
26620        final Matrix mTmpMatrix = new Matrix();
26621
26622        /**
26623         * Temporary for use in transforming invalidation rect
26624         */
26625        final Transformation mTmpTransformation = new Transformation();
26626
26627        /**
26628         * Temporary for use in querying outlines from OutlineProviders
26629         */
26630        final Outline mTmpOutline = new Outline();
26631
26632        /**
26633         * Temporary list for use in collecting focusable descendents of a view.
26634         */
26635        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
26636
26637        /**
26638         * The id of the window for accessibility purposes.
26639         */
26640        int mAccessibilityWindowId = AccessibilityWindowInfo.UNDEFINED_WINDOW_ID;
26641
26642        /**
26643         * Flags related to accessibility processing.
26644         *
26645         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
26646         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
26647         */
26648        int mAccessibilityFetchFlags;
26649
26650        /**
26651         * The drawable for highlighting accessibility focus.
26652         */
26653        Drawable mAccessibilityFocusDrawable;
26654
26655        /**
26656         * The drawable for highlighting autofilled views.
26657         *
26658         * @see #isAutofilled()
26659         */
26660        Drawable mAutofilledDrawable;
26661
26662        /**
26663         * Show where the margins, bounds and layout bounds are for each view.
26664         */
26665        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
26666
26667        /**
26668         * Point used to compute visible regions.
26669         */
26670        final Point mPoint = new Point();
26671
26672        /**
26673         * Used to track which View originated a requestLayout() call, used when
26674         * requestLayout() is called during layout.
26675         */
26676        View mViewRequestingLayout;
26677
26678        /**
26679         * Used to track views that need (at least) a partial relayout at their current size
26680         * during the next traversal.
26681         */
26682        List<View> mPartialLayoutViews = new ArrayList<>();
26683
26684        /**
26685         * Swapped with mPartialLayoutViews during layout to avoid concurrent
26686         * modification. Lazily assigned during ViewRootImpl layout.
26687         */
26688        List<View> mEmptyPartialLayoutViews;
26689
26690        /**
26691         * Used to track the identity of the current drag operation.
26692         */
26693        IBinder mDragToken;
26694
26695        /**
26696         * The drag shadow surface for the current drag operation.
26697         */
26698        public Surface mDragSurface;
26699
26700
26701        /**
26702         * The view that currently has a tooltip displayed.
26703         */
26704        View mTooltipHost;
26705
26706        /**
26707         * Creates a new set of attachment information with the specified
26708         * events handler and thread.
26709         *
26710         * @param handler the events handler the view must use
26711         */
26712        AttachInfo(IWindowSession session, IWindow window, Display display,
26713                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer,
26714                Context context) {
26715            mSession = session;
26716            mWindow = window;
26717            mWindowToken = window.asBinder();
26718            mDisplay = display;
26719            mViewRootImpl = viewRootImpl;
26720            mHandler = handler;
26721            mRootCallbacks = effectPlayer;
26722            mTreeObserver = new ViewTreeObserver(context);
26723        }
26724    }
26725
26726    /**
26727     * <p>ScrollabilityCache holds various fields used by a View when scrolling
26728     * is supported. This avoids keeping too many unused fields in most
26729     * instances of View.</p>
26730     */
26731    private static class ScrollabilityCache implements Runnable {
26732
26733        /**
26734         * Scrollbars are not visible
26735         */
26736        public static final int OFF = 0;
26737
26738        /**
26739         * Scrollbars are visible
26740         */
26741        public static final int ON = 1;
26742
26743        /**
26744         * Scrollbars are fading away
26745         */
26746        public static final int FADING = 2;
26747
26748        public boolean fadeScrollBars;
26749
26750        public int fadingEdgeLength;
26751        public int scrollBarDefaultDelayBeforeFade;
26752        public int scrollBarFadeDuration;
26753
26754        public int scrollBarSize;
26755        public int scrollBarMinTouchTarget;
26756        public ScrollBarDrawable scrollBar;
26757        public float[] interpolatorValues;
26758        public View host;
26759
26760        public final Paint paint;
26761        public final Matrix matrix;
26762        public Shader shader;
26763
26764        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
26765
26766        private static final float[] OPAQUE = { 255 };
26767        private static final float[] TRANSPARENT = { 0.0f };
26768
26769        /**
26770         * When fading should start. This time moves into the future every time
26771         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
26772         */
26773        public long fadeStartTime;
26774
26775
26776        /**
26777         * The current state of the scrollbars: ON, OFF, or FADING
26778         */
26779        public int state = OFF;
26780
26781        private int mLastColor;
26782
26783        public final Rect mScrollBarBounds = new Rect();
26784        public final Rect mScrollBarTouchBounds = new Rect();
26785
26786        public static final int NOT_DRAGGING = 0;
26787        public static final int DRAGGING_VERTICAL_SCROLL_BAR = 1;
26788        public static final int DRAGGING_HORIZONTAL_SCROLL_BAR = 2;
26789        public int mScrollBarDraggingState = NOT_DRAGGING;
26790
26791        public float mScrollBarDraggingPos = 0;
26792
26793        public ScrollabilityCache(ViewConfiguration configuration, View host) {
26794            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
26795            scrollBarSize = configuration.getScaledScrollBarSize();
26796            scrollBarMinTouchTarget = configuration.getScaledMinScrollbarTouchTarget();
26797            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
26798            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
26799
26800            paint = new Paint();
26801            matrix = new Matrix();
26802            // use use a height of 1, and then wack the matrix each time we
26803            // actually use it.
26804            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
26805            paint.setShader(shader);
26806            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
26807
26808            this.host = host;
26809        }
26810
26811        public void setFadeColor(int color) {
26812            if (color != mLastColor) {
26813                mLastColor = color;
26814
26815                if (color != 0) {
26816                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
26817                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
26818                    paint.setShader(shader);
26819                    // Restore the default transfer mode (src_over)
26820                    paint.setXfermode(null);
26821                } else {
26822                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
26823                    paint.setShader(shader);
26824                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
26825                }
26826            }
26827        }
26828
26829        public void run() {
26830            long now = AnimationUtils.currentAnimationTimeMillis();
26831            if (now >= fadeStartTime) {
26832
26833                // the animation fades the scrollbars out by changing
26834                // the opacity (alpha) from fully opaque to fully
26835                // transparent
26836                int nextFrame = (int) now;
26837                int framesCount = 0;
26838
26839                Interpolator interpolator = scrollBarInterpolator;
26840
26841                // Start opaque
26842                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
26843
26844                // End transparent
26845                nextFrame += scrollBarFadeDuration;
26846                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
26847
26848                state = FADING;
26849
26850                // Kick off the fade animation
26851                host.invalidate(true);
26852            }
26853        }
26854    }
26855
26856    /**
26857     * Resuable callback for sending
26858     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
26859     */
26860    private class SendViewScrolledAccessibilityEvent implements Runnable {
26861        public volatile boolean mIsPending;
26862        public int mDeltaX;
26863        public int mDeltaY;
26864
26865        public void post(int dx, int dy) {
26866            mDeltaX += dx;
26867            mDeltaY += dy;
26868            if (!mIsPending) {
26869                mIsPending = true;
26870                postDelayed(this, ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
26871            }
26872        }
26873
26874        @Override
26875        public void run() {
26876            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
26877                AccessibilityEvent event = AccessibilityEvent.obtain(
26878                        AccessibilityEvent.TYPE_VIEW_SCROLLED);
26879                event.setScrollDeltaX(mDeltaX);
26880                event.setScrollDeltaY(mDeltaY);
26881                sendAccessibilityEventUnchecked(event);
26882            }
26883            reset();
26884        }
26885
26886        private void reset() {
26887            mIsPending = false;
26888            mDeltaX = 0;
26889            mDeltaY = 0;
26890        }
26891    }
26892
26893    /**
26894     * Remove the pending callback for sending a
26895     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
26896     */
26897    private void cancel(@Nullable SendViewScrolledAccessibilityEvent callback) {
26898        if (callback == null || !callback.mIsPending) return;
26899        removeCallbacks(callback);
26900        callback.reset();
26901    }
26902
26903    /**
26904     * <p>
26905     * This class represents a delegate that can be registered in a {@link View}
26906     * to enhance accessibility support via composition rather via inheritance.
26907     * It is specifically targeted to widget developers that extend basic View
26908     * classes i.e. classes in package android.view, that would like their
26909     * applications to be backwards compatible.
26910     * </p>
26911     * <div class="special reference">
26912     * <h3>Developer Guides</h3>
26913     * <p>For more information about making applications accessible, read the
26914     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
26915     * developer guide.</p>
26916     * </div>
26917     * <p>
26918     * A scenario in which a developer would like to use an accessibility delegate
26919     * is overriding a method introduced in a later API version than the minimal API
26920     * version supported by the application. For example, the method
26921     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
26922     * in API version 4 when the accessibility APIs were first introduced. If a
26923     * developer would like his application to run on API version 4 devices (assuming
26924     * all other APIs used by the application are version 4 or lower) and take advantage
26925     * of this method, instead of overriding the method which would break the application's
26926     * backwards compatibility, he can override the corresponding method in this
26927     * delegate and register the delegate in the target View if the API version of
26928     * the system is high enough, i.e. the API version is the same as or higher than the API
26929     * version that introduced
26930     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
26931     * </p>
26932     * <p>
26933     * Here is an example implementation:
26934     * </p>
26935     * <code><pre><p>
26936     * if (Build.VERSION.SDK_INT >= 14) {
26937     *     // If the API version is equal of higher than the version in
26938     *     // which onInitializeAccessibilityNodeInfo was introduced we
26939     *     // register a delegate with a customized implementation.
26940     *     View view = findViewById(R.id.view_id);
26941     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
26942     *         public void onInitializeAccessibilityNodeInfo(View host,
26943     *                 AccessibilityNodeInfo info) {
26944     *             // Let the default implementation populate the info.
26945     *             super.onInitializeAccessibilityNodeInfo(host, info);
26946     *             // Set some other information.
26947     *             info.setEnabled(host.isEnabled());
26948     *         }
26949     *     });
26950     * }
26951     * </code></pre></p>
26952     * <p>
26953     * This delegate contains methods that correspond to the accessibility methods
26954     * in View. If a delegate has been specified the implementation in View hands
26955     * off handling to the corresponding method in this delegate. The default
26956     * implementation the delegate methods behaves exactly as the corresponding
26957     * method in View for the case of no accessibility delegate been set. Hence,
26958     * to customize the behavior of a View method, clients can override only the
26959     * corresponding delegate method without altering the behavior of the rest
26960     * accessibility related methods of the host view.
26961     * </p>
26962     * <p>
26963     * <strong>Note:</strong> On platform versions prior to
26964     * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on
26965     * views in the {@code android.widget.*} package are called <i>before</i>
26966     * host methods. This prevents certain properties such as class name from
26967     * being modified by overriding
26968     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)},
26969     * as any changes will be overwritten by the host class.
26970     * <p>
26971     * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate
26972     * methods are called <i>after</i> host methods, which all properties to be
26973     * modified without being overwritten by the host class.
26974     */
26975    public static class AccessibilityDelegate {
26976
26977        /**
26978         * Sends an accessibility event of the given type. If accessibility is not
26979         * enabled this method has no effect.
26980         * <p>
26981         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
26982         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
26983         * been set.
26984         * </p>
26985         *
26986         * @param host The View hosting the delegate.
26987         * @param eventType The type of the event to send.
26988         *
26989         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
26990         */
26991        public void sendAccessibilityEvent(View host, int eventType) {
26992            host.sendAccessibilityEventInternal(eventType);
26993        }
26994
26995        /**
26996         * Performs the specified accessibility action on the view. For
26997         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
26998         * <p>
26999         * The default implementation behaves as
27000         * {@link View#performAccessibilityAction(int, Bundle)
27001         *  View#performAccessibilityAction(int, Bundle)} for the case of
27002         *  no accessibility delegate been set.
27003         * </p>
27004         *
27005         * @param action The action to perform.
27006         * @return Whether the action was performed.
27007         *
27008         * @see View#performAccessibilityAction(int, Bundle)
27009         *      View#performAccessibilityAction(int, Bundle)
27010         */
27011        public boolean performAccessibilityAction(View host, int action, Bundle args) {
27012            return host.performAccessibilityActionInternal(action, args);
27013        }
27014
27015        /**
27016         * Sends an accessibility event. This method behaves exactly as
27017         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
27018         * empty {@link AccessibilityEvent} and does not perform a check whether
27019         * accessibility is enabled.
27020         * <p>
27021         * The default implementation behaves as
27022         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
27023         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
27024         * the case of no accessibility delegate been set.
27025         * </p>
27026         *
27027         * @param host The View hosting the delegate.
27028         * @param event The event to send.
27029         *
27030         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
27031         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
27032         */
27033        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
27034            host.sendAccessibilityEventUncheckedInternal(event);
27035        }
27036
27037        /**
27038         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
27039         * to its children for adding their text content to the event.
27040         * <p>
27041         * The default implementation behaves as
27042         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
27043         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
27044         * the case of no accessibility delegate been set.
27045         * </p>
27046         *
27047         * @param host The View hosting the delegate.
27048         * @param event The event.
27049         * @return True if the event population was completed.
27050         *
27051         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
27052         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
27053         */
27054        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
27055            return host.dispatchPopulateAccessibilityEventInternal(event);
27056        }
27057
27058        /**
27059         * Gives a chance to the host View to populate the accessibility event with its
27060         * text content.
27061         * <p>
27062         * The default implementation behaves as
27063         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
27064         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
27065         * the case of no accessibility delegate been set.
27066         * </p>
27067         *
27068         * @param host The View hosting the delegate.
27069         * @param event The accessibility event which to populate.
27070         *
27071         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
27072         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
27073         */
27074        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
27075            host.onPopulateAccessibilityEventInternal(event);
27076        }
27077
27078        /**
27079         * Initializes an {@link AccessibilityEvent} with information about the
27080         * the host View which is the event source.
27081         * <p>
27082         * The default implementation behaves as
27083         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
27084         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
27085         * the case of no accessibility delegate been set.
27086         * </p>
27087         *
27088         * @param host The View hosting the delegate.
27089         * @param event The event to initialize.
27090         *
27091         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
27092         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
27093         */
27094        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
27095            host.onInitializeAccessibilityEventInternal(event);
27096        }
27097
27098        /**
27099         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
27100         * <p>
27101         * The default implementation behaves as
27102         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
27103         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
27104         * the case of no accessibility delegate been set.
27105         * </p>
27106         *
27107         * @param host The View hosting the delegate.
27108         * @param info The instance to initialize.
27109         *
27110         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
27111         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
27112         */
27113        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
27114            host.onInitializeAccessibilityNodeInfoInternal(info);
27115        }
27116
27117        /**
27118         * Adds extra data to an {@link AccessibilityNodeInfo} based on an explicit request for the
27119         * additional data.
27120         * <p>
27121         * This method only needs to be implemented if the View offers to provide additional data.
27122         * </p>
27123         * <p>
27124         * The default implementation behaves as
27125         * {@link View#addExtraDataToAccessibilityNodeInfo(AccessibilityNodeInfo, String, Bundle)
27126         * for the case where no accessibility delegate is set.
27127         * </p>
27128         *
27129         * @param host The View hosting the delegate. Never {@code null}.
27130         * @param info The info to which to add the extra data. Never {@code null}.
27131         * @param extraDataKey A key specifying the type of extra data to add to the info. The
27132         *                     extra data should be added to the {@link Bundle} returned by
27133         *                     the info's {@link AccessibilityNodeInfo#getExtras} method.  Never
27134         *                     {@code null}.
27135         * @param arguments A {@link Bundle} holding any arguments relevant for this request.
27136         *                  May be {@code null} if the if the service provided no arguments.
27137         *
27138         * @see AccessibilityNodeInfo#setExtraAvailableData
27139         */
27140        public void addExtraDataToAccessibilityNodeInfo(@NonNull View host,
27141                @NonNull AccessibilityNodeInfo info, @NonNull String extraDataKey,
27142                @Nullable Bundle arguments) {
27143            host.addExtraDataToAccessibilityNodeInfo(info, extraDataKey, arguments);
27144        }
27145
27146        /**
27147         * Called when a child of the host View has requested sending an
27148         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
27149         * to augment the event.
27150         * <p>
27151         * The default implementation behaves as
27152         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
27153         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
27154         * the case of no accessibility delegate been set.
27155         * </p>
27156         *
27157         * @param host The View hosting the delegate.
27158         * @param child The child which requests sending the event.
27159         * @param event The event to be sent.
27160         * @return True if the event should be sent
27161         *
27162         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
27163         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
27164         */
27165        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
27166                AccessibilityEvent event) {
27167            return host.onRequestSendAccessibilityEventInternal(child, event);
27168        }
27169
27170        /**
27171         * Gets the provider for managing a virtual view hierarchy rooted at this View
27172         * and reported to {@link android.accessibilityservice.AccessibilityService}s
27173         * that explore the window content.
27174         * <p>
27175         * The default implementation behaves as
27176         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
27177         * the case of no accessibility delegate been set.
27178         * </p>
27179         *
27180         * @return The provider.
27181         *
27182         * @see AccessibilityNodeProvider
27183         */
27184        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
27185            return null;
27186        }
27187
27188        /**
27189         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
27190         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
27191         * This method is responsible for obtaining an accessibility node info from a
27192         * pool of reusable instances and calling
27193         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
27194         * view to initialize the former.
27195         * <p>
27196         * <strong>Note:</strong> The client is responsible for recycling the obtained
27197         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
27198         * creation.
27199         * </p>
27200         * <p>
27201         * The default implementation behaves as
27202         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
27203         * the case of no accessibility delegate been set.
27204         * </p>
27205         * @return A populated {@link AccessibilityNodeInfo}.
27206         *
27207         * @see AccessibilityNodeInfo
27208         *
27209         * @hide
27210         */
27211        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
27212            return host.createAccessibilityNodeInfoInternal();
27213        }
27214    }
27215
27216    private static class MatchIdPredicate implements Predicate<View> {
27217        public int mId;
27218
27219        @Override
27220        public boolean test(View view) {
27221            return (view.mID == mId);
27222        }
27223    }
27224
27225    private static class MatchLabelForPredicate implements Predicate<View> {
27226        private int mLabeledId;
27227
27228        @Override
27229        public boolean test(View view) {
27230            return (view.mLabelForId == mLabeledId);
27231        }
27232    }
27233
27234    /**
27235     * Dump all private flags in readable format, useful for documentation and
27236     * sanity checking.
27237     */
27238    private static void dumpFlags() {
27239        final HashMap<String, String> found = Maps.newHashMap();
27240        try {
27241            for (Field field : View.class.getDeclaredFields()) {
27242                final int modifiers = field.getModifiers();
27243                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
27244                    if (field.getType().equals(int.class)) {
27245                        final int value = field.getInt(null);
27246                        dumpFlag(found, field.getName(), value);
27247                    } else if (field.getType().equals(int[].class)) {
27248                        final int[] values = (int[]) field.get(null);
27249                        for (int i = 0; i < values.length; i++) {
27250                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
27251                        }
27252                    }
27253                }
27254            }
27255        } catch (IllegalAccessException e) {
27256            throw new RuntimeException(e);
27257        }
27258
27259        final ArrayList<String> keys = Lists.newArrayList();
27260        keys.addAll(found.keySet());
27261        Collections.sort(keys);
27262        for (String key : keys) {
27263            Log.d(VIEW_LOG_TAG, found.get(key));
27264        }
27265    }
27266
27267    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
27268        // Sort flags by prefix, then by bits, always keeping unique keys
27269        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
27270        final int prefix = name.indexOf('_');
27271        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
27272        final String output = bits + " " + name;
27273        found.put(key, output);
27274    }
27275
27276    /** {@hide} */
27277    public void encode(@NonNull ViewHierarchyEncoder stream) {
27278        stream.beginObject(this);
27279        encodeProperties(stream);
27280        stream.endObject();
27281    }
27282
27283    /** {@hide} */
27284    @CallSuper
27285    protected void encodeProperties(@NonNull ViewHierarchyEncoder stream) {
27286        Object resolveId = ViewDebug.resolveId(getContext(), mID);
27287        if (resolveId instanceof String) {
27288            stream.addProperty("id", (String) resolveId);
27289        } else {
27290            stream.addProperty("id", mID);
27291        }
27292
27293        stream.addProperty("misc:transformation.alpha",
27294                mTransformationInfo != null ? mTransformationInfo.mAlpha : 0);
27295        stream.addProperty("misc:transitionName", getTransitionName());
27296
27297        // layout
27298        stream.addProperty("layout:left", mLeft);
27299        stream.addProperty("layout:right", mRight);
27300        stream.addProperty("layout:top", mTop);
27301        stream.addProperty("layout:bottom", mBottom);
27302        stream.addProperty("layout:width", getWidth());
27303        stream.addProperty("layout:height", getHeight());
27304        stream.addProperty("layout:layoutDirection", getLayoutDirection());
27305        stream.addProperty("layout:layoutRtl", isLayoutRtl());
27306        stream.addProperty("layout:hasTransientState", hasTransientState());
27307        stream.addProperty("layout:baseline", getBaseline());
27308
27309        // layout params
27310        ViewGroup.LayoutParams layoutParams = getLayoutParams();
27311        if (layoutParams != null) {
27312            stream.addPropertyKey("layoutParams");
27313            layoutParams.encode(stream);
27314        }
27315
27316        // scrolling
27317        stream.addProperty("scrolling:scrollX", mScrollX);
27318        stream.addProperty("scrolling:scrollY", mScrollY);
27319
27320        // padding
27321        stream.addProperty("padding:paddingLeft", mPaddingLeft);
27322        stream.addProperty("padding:paddingRight", mPaddingRight);
27323        stream.addProperty("padding:paddingTop", mPaddingTop);
27324        stream.addProperty("padding:paddingBottom", mPaddingBottom);
27325        stream.addProperty("padding:userPaddingRight", mUserPaddingRight);
27326        stream.addProperty("padding:userPaddingLeft", mUserPaddingLeft);
27327        stream.addProperty("padding:userPaddingBottom", mUserPaddingBottom);
27328        stream.addProperty("padding:userPaddingStart", mUserPaddingStart);
27329        stream.addProperty("padding:userPaddingEnd", mUserPaddingEnd);
27330
27331        // measurement
27332        stream.addProperty("measurement:minHeight", mMinHeight);
27333        stream.addProperty("measurement:minWidth", mMinWidth);
27334        stream.addProperty("measurement:measuredWidth", mMeasuredWidth);
27335        stream.addProperty("measurement:measuredHeight", mMeasuredHeight);
27336
27337        // drawing
27338        stream.addProperty("drawing:elevation", getElevation());
27339        stream.addProperty("drawing:translationX", getTranslationX());
27340        stream.addProperty("drawing:translationY", getTranslationY());
27341        stream.addProperty("drawing:translationZ", getTranslationZ());
27342        stream.addProperty("drawing:rotation", getRotation());
27343        stream.addProperty("drawing:rotationX", getRotationX());
27344        stream.addProperty("drawing:rotationY", getRotationY());
27345        stream.addProperty("drawing:scaleX", getScaleX());
27346        stream.addProperty("drawing:scaleY", getScaleY());
27347        stream.addProperty("drawing:pivotX", getPivotX());
27348        stream.addProperty("drawing:pivotY", getPivotY());
27349        stream.addProperty("drawing:clipBounds",
27350                mClipBounds == null ? null : mClipBounds.toString());
27351        stream.addProperty("drawing:opaque", isOpaque());
27352        stream.addProperty("drawing:alpha", getAlpha());
27353        stream.addProperty("drawing:transitionAlpha", getTransitionAlpha());
27354        stream.addProperty("drawing:shadow", hasShadow());
27355        stream.addProperty("drawing:solidColor", getSolidColor());
27356        stream.addProperty("drawing:layerType", mLayerType);
27357        stream.addProperty("drawing:willNotDraw", willNotDraw());
27358        stream.addProperty("drawing:hardwareAccelerated", isHardwareAccelerated());
27359        stream.addProperty("drawing:willNotCacheDrawing", willNotCacheDrawing());
27360        stream.addProperty("drawing:drawingCacheEnabled", isDrawingCacheEnabled());
27361        stream.addProperty("drawing:overlappingRendering", hasOverlappingRendering());
27362        stream.addProperty("drawing:outlineAmbientShadowColor", getOutlineAmbientShadowColor());
27363        stream.addProperty("drawing:outlineSpotShadowColor", getOutlineSpotShadowColor());
27364
27365        // focus
27366        stream.addProperty("focus:hasFocus", hasFocus());
27367        stream.addProperty("focus:isFocused", isFocused());
27368        stream.addProperty("focus:focusable", getFocusable());
27369        stream.addProperty("focus:isFocusable", isFocusable());
27370        stream.addProperty("focus:isFocusableInTouchMode", isFocusableInTouchMode());
27371
27372        stream.addProperty("misc:clickable", isClickable());
27373        stream.addProperty("misc:pressed", isPressed());
27374        stream.addProperty("misc:selected", isSelected());
27375        stream.addProperty("misc:touchMode", isInTouchMode());
27376        stream.addProperty("misc:hovered", isHovered());
27377        stream.addProperty("misc:activated", isActivated());
27378
27379        stream.addProperty("misc:visibility", getVisibility());
27380        stream.addProperty("misc:fitsSystemWindows", getFitsSystemWindows());
27381        stream.addProperty("misc:filterTouchesWhenObscured", getFilterTouchesWhenObscured());
27382
27383        stream.addProperty("misc:enabled", isEnabled());
27384        stream.addProperty("misc:soundEffectsEnabled", isSoundEffectsEnabled());
27385        stream.addProperty("misc:hapticFeedbackEnabled", isHapticFeedbackEnabled());
27386
27387        // theme attributes
27388        Resources.Theme theme = getContext().getTheme();
27389        if (theme != null) {
27390            stream.addPropertyKey("theme");
27391            theme.encode(stream);
27392        }
27393
27394        // view attribute information
27395        int n = mAttributes != null ? mAttributes.length : 0;
27396        stream.addProperty("meta:__attrCount__", n/2);
27397        for (int i = 0; i < n; i += 2) {
27398            stream.addProperty("meta:__attr__" + mAttributes[i], mAttributes[i+1]);
27399        }
27400
27401        stream.addProperty("misc:scrollBarStyle", getScrollBarStyle());
27402
27403        // text
27404        stream.addProperty("text:textDirection", getTextDirection());
27405        stream.addProperty("text:textAlignment", getTextAlignment());
27406
27407        // accessibility
27408        CharSequence contentDescription = getContentDescription();
27409        stream.addProperty("accessibility:contentDescription",
27410                contentDescription == null ? "" : contentDescription.toString());
27411        stream.addProperty("accessibility:labelFor", getLabelFor());
27412        stream.addProperty("accessibility:importantForAccessibility", getImportantForAccessibility());
27413    }
27414
27415    /**
27416     * Determine if this view is rendered on a round wearable device and is the main view
27417     * on the screen.
27418     */
27419    boolean shouldDrawRoundScrollbar() {
27420        if (!mResources.getConfiguration().isScreenRound() || mAttachInfo == null) {
27421            return false;
27422        }
27423
27424        final View rootView = getRootView();
27425        final WindowInsets insets = getRootWindowInsets();
27426
27427        int height = getHeight();
27428        int width = getWidth();
27429        int displayHeight = rootView.getHeight();
27430        int displayWidth = rootView.getWidth();
27431
27432        if (height != displayHeight || width != displayWidth) {
27433            return false;
27434        }
27435
27436        getLocationInWindow(mAttachInfo.mTmpLocation);
27437        return mAttachInfo.mTmpLocation[0] == insets.getStableInsetLeft()
27438                && mAttachInfo.mTmpLocation[1] == insets.getStableInsetTop();
27439    }
27440
27441    /**
27442     * Sets the tooltip text which will be displayed in a small popup next to the view.
27443     * <p>
27444     * The tooltip will be displayed:
27445     * <ul>
27446     * <li>On long click, unless it is handled otherwise (by OnLongClickListener or a context
27447     * menu). </li>
27448     * <li>On hover, after a brief delay since the pointer has stopped moving </li>
27449     * </ul>
27450     * <p>
27451     * <strong>Note:</strong> Do not override this method, as it will have no
27452     * effect on the text displayed in the tooltip.
27453     *
27454     * @param tooltipText the tooltip text, or null if no tooltip is required
27455     * @see #getTooltipText()
27456     * @attr ref android.R.styleable#View_tooltipText
27457     */
27458    public void setTooltipText(@Nullable CharSequence tooltipText) {
27459        if (TextUtils.isEmpty(tooltipText)) {
27460            setFlags(0, TOOLTIP);
27461            hideTooltip();
27462            mTooltipInfo = null;
27463        } else {
27464            setFlags(TOOLTIP, TOOLTIP);
27465            if (mTooltipInfo == null) {
27466                mTooltipInfo = new TooltipInfo();
27467                mTooltipInfo.mShowTooltipRunnable = this::showHoverTooltip;
27468                mTooltipInfo.mHideTooltipRunnable = this::hideTooltip;
27469                mTooltipInfo.mHoverSlop = ViewConfiguration.get(mContext).getScaledHoverSlop();
27470                mTooltipInfo.clearAnchorPos();
27471            }
27472            mTooltipInfo.mTooltipText = tooltipText;
27473        }
27474    }
27475
27476    /**
27477     * @hide Binary compatibility stub. To be removed when we finalize O APIs.
27478     */
27479    public void setTooltip(@Nullable CharSequence tooltipText) {
27480        setTooltipText(tooltipText);
27481    }
27482
27483    /**
27484     * Returns the view's tooltip text.
27485     *
27486     * <strong>Note:</strong> Do not override this method, as it will have no
27487     * effect on the text displayed in the tooltip. You must call
27488     * {@link #setTooltipText(CharSequence)} to modify the tooltip text.
27489     *
27490     * @return the tooltip text
27491     * @see #setTooltipText(CharSequence)
27492     * @attr ref android.R.styleable#View_tooltipText
27493     */
27494    @Nullable
27495    public CharSequence getTooltipText() {
27496        return mTooltipInfo != null ? mTooltipInfo.mTooltipText : null;
27497    }
27498
27499    /**
27500     * @hide Binary compatibility stub. To be removed when we finalize O APIs.
27501     */
27502    @Nullable
27503    public CharSequence getTooltip() {
27504        return getTooltipText();
27505    }
27506
27507    private boolean showTooltip(int x, int y, boolean fromLongClick) {
27508        if (mAttachInfo == null || mTooltipInfo == null) {
27509            return false;
27510        }
27511        if (fromLongClick && (mViewFlags & ENABLED_MASK) != ENABLED) {
27512            return false;
27513        }
27514        if (TextUtils.isEmpty(mTooltipInfo.mTooltipText)) {
27515            return false;
27516        }
27517        hideTooltip();
27518        mTooltipInfo.mTooltipFromLongClick = fromLongClick;
27519        mTooltipInfo.mTooltipPopup = new TooltipPopup(getContext());
27520        final boolean fromTouch = (mPrivateFlags3 & PFLAG3_FINGER_DOWN) == PFLAG3_FINGER_DOWN;
27521        mTooltipInfo.mTooltipPopup.show(this, x, y, fromTouch, mTooltipInfo.mTooltipText);
27522        mAttachInfo.mTooltipHost = this;
27523        // The available accessibility actions have changed
27524        notifyViewAccessibilityStateChangedIfNeeded(CONTENT_CHANGE_TYPE_UNDEFINED);
27525        return true;
27526    }
27527
27528    void hideTooltip() {
27529        if (mTooltipInfo == null) {
27530            return;
27531        }
27532        removeCallbacks(mTooltipInfo.mShowTooltipRunnable);
27533        if (mTooltipInfo.mTooltipPopup == null) {
27534            return;
27535        }
27536        mTooltipInfo.mTooltipPopup.hide();
27537        mTooltipInfo.mTooltipPopup = null;
27538        mTooltipInfo.mTooltipFromLongClick = false;
27539        mTooltipInfo.clearAnchorPos();
27540        if (mAttachInfo != null) {
27541            mAttachInfo.mTooltipHost = null;
27542        }
27543        // The available accessibility actions have changed
27544        notifyViewAccessibilityStateChangedIfNeeded(CONTENT_CHANGE_TYPE_UNDEFINED);
27545    }
27546
27547    private boolean showLongClickTooltip(int x, int y) {
27548        removeCallbacks(mTooltipInfo.mShowTooltipRunnable);
27549        removeCallbacks(mTooltipInfo.mHideTooltipRunnable);
27550        return showTooltip(x, y, true);
27551    }
27552
27553    private boolean showHoverTooltip() {
27554        return showTooltip(mTooltipInfo.mAnchorX, mTooltipInfo.mAnchorY, false);
27555    }
27556
27557    boolean dispatchTooltipHoverEvent(MotionEvent event) {
27558        if (mTooltipInfo == null) {
27559            return false;
27560        }
27561        switch(event.getAction()) {
27562            case MotionEvent.ACTION_HOVER_MOVE:
27563                if ((mViewFlags & TOOLTIP) != TOOLTIP) {
27564                    break;
27565                }
27566                if (!mTooltipInfo.mTooltipFromLongClick && mTooltipInfo.updateAnchorPos(event)) {
27567                    if (mTooltipInfo.mTooltipPopup == null) {
27568                        // Schedule showing the tooltip after a timeout.
27569                        removeCallbacks(mTooltipInfo.mShowTooltipRunnable);
27570                        postDelayed(mTooltipInfo.mShowTooltipRunnable,
27571                                ViewConfiguration.getHoverTooltipShowTimeout());
27572                    }
27573
27574                    // Hide hover-triggered tooltip after a period of inactivity.
27575                    // Match the timeout used by NativeInputManager to hide the mouse pointer
27576                    // (depends on SYSTEM_UI_FLAG_LOW_PROFILE being set).
27577                    final int timeout;
27578                    if ((getWindowSystemUiVisibility() & SYSTEM_UI_FLAG_LOW_PROFILE)
27579                            == SYSTEM_UI_FLAG_LOW_PROFILE) {
27580                        timeout = ViewConfiguration.getHoverTooltipHideShortTimeout();
27581                    } else {
27582                        timeout = ViewConfiguration.getHoverTooltipHideTimeout();
27583                    }
27584                    removeCallbacks(mTooltipInfo.mHideTooltipRunnable);
27585                    postDelayed(mTooltipInfo.mHideTooltipRunnable, timeout);
27586                }
27587                return true;
27588
27589            case MotionEvent.ACTION_HOVER_EXIT:
27590                mTooltipInfo.clearAnchorPos();
27591                if (!mTooltipInfo.mTooltipFromLongClick) {
27592                    hideTooltip();
27593                }
27594                break;
27595        }
27596        return false;
27597    }
27598
27599    void handleTooltipKey(KeyEvent event) {
27600        switch (event.getAction()) {
27601            case KeyEvent.ACTION_DOWN:
27602                if (event.getRepeatCount() == 0) {
27603                    hideTooltip();
27604                }
27605                break;
27606
27607            case KeyEvent.ACTION_UP:
27608                handleTooltipUp();
27609                break;
27610        }
27611    }
27612
27613    private void handleTooltipUp() {
27614        if (mTooltipInfo == null || mTooltipInfo.mTooltipPopup == null) {
27615            return;
27616        }
27617        removeCallbacks(mTooltipInfo.mHideTooltipRunnable);
27618        postDelayed(mTooltipInfo.mHideTooltipRunnable,
27619                ViewConfiguration.getLongPressTooltipHideTimeout());
27620    }
27621
27622    private int getFocusableAttribute(TypedArray attributes) {
27623        TypedValue val = new TypedValue();
27624        if (attributes.getValue(com.android.internal.R.styleable.View_focusable, val)) {
27625            if (val.type == TypedValue.TYPE_INT_BOOLEAN) {
27626                return (val.data == 0 ? NOT_FOCUSABLE : FOCUSABLE);
27627            } else {
27628                return val.data;
27629            }
27630        } else {
27631            return FOCUSABLE_AUTO;
27632        }
27633    }
27634
27635    /**
27636     * @return The content view of the tooltip popup currently being shown, or null if the tooltip
27637     * is not showing.
27638     * @hide
27639     */
27640    @TestApi
27641    public View getTooltipView() {
27642        if (mTooltipInfo == null || mTooltipInfo.mTooltipPopup == null) {
27643            return null;
27644        }
27645        return mTooltipInfo.mTooltipPopup.getContentView();
27646    }
27647
27648    /**
27649     * @return {@code true} if the default focus highlight is enabled, {@code false} otherwies.
27650     * @hide
27651     */
27652    @TestApi
27653    public static boolean isDefaultFocusHighlightEnabled() {
27654        return sUseDefaultFocusHighlight;
27655    }
27656
27657    /**
27658     * Dispatch a previously unhandled {@link KeyEvent} to this view. Unlike normal key dispatch,
27659     * this dispatches to ALL child views until it is consumed. The dispatch order is z-order
27660     * (visually on-top views first).
27661     *
27662     * @param evt the previously unhandled {@link KeyEvent}.
27663     * @return the {@link View} which consumed the event or {@code null} if not consumed.
27664     */
27665    View dispatchUnhandledKeyEvent(KeyEvent evt) {
27666        if (onUnhandledKeyEvent(evt)) {
27667            return this;
27668        }
27669        return null;
27670    }
27671
27672    /**
27673     * Allows this view to handle {@link KeyEvent}s which weren't handled by normal dispatch. This
27674     * occurs after the normal view hierarchy dispatch, but before the window callback. By default,
27675     * this will dispatch into all the listeners registered via
27676     * {@link #addOnUnhandledKeyEventListener(OnUnhandledKeyEventListener)} in last-in-first-out
27677     * order (most recently added will receive events first).
27678     *
27679     * @param event An unhandled event.
27680     * @return {@code true} if the event was handled, {@code false} otherwise.
27681     * @see #addOnUnhandledKeyEventListener
27682     */
27683    boolean onUnhandledKeyEvent(@NonNull KeyEvent event) {
27684        if (mListenerInfo != null && mListenerInfo.mUnhandledKeyListeners != null) {
27685            for (int i = mListenerInfo.mUnhandledKeyListeners.size() - 1; i >= 0; --i) {
27686                if (mListenerInfo.mUnhandledKeyListeners.get(i).onUnhandledKeyEvent(this, event)) {
27687                    return true;
27688                }
27689            }
27690        }
27691        return false;
27692    }
27693
27694    boolean hasUnhandledKeyListener() {
27695        return (mListenerInfo != null && mListenerInfo.mUnhandledKeyListeners != null
27696                && !mListenerInfo.mUnhandledKeyListeners.isEmpty());
27697    }
27698
27699    /**
27700     * Adds a listener which will receive unhandled {@link KeyEvent}s. This must be called on the
27701     * UI thread.
27702     *
27703     * @param listener a receiver of unhandled {@link KeyEvent}s.
27704     * @see #removeOnUnhandledKeyEventListener
27705     */
27706    public void addOnUnhandledKeyEventListener(OnUnhandledKeyEventListener listener) {
27707        ArrayList<OnUnhandledKeyEventListener> listeners = getListenerInfo().mUnhandledKeyListeners;
27708        if (listeners == null) {
27709            listeners = new ArrayList<>();
27710            getListenerInfo().mUnhandledKeyListeners = listeners;
27711        }
27712        listeners.add(listener);
27713        if (listeners.size() == 1 && mParent instanceof ViewGroup) {
27714            ((ViewGroup) mParent).incrementChildUnhandledKeyListeners();
27715        }
27716    }
27717
27718    /**
27719     * Removes a listener which will receive unhandled {@link KeyEvent}s. This must be called on the
27720     * UI thread.
27721     *
27722     * @param listener a receiver of unhandled {@link KeyEvent}s.
27723     * @see #addOnUnhandledKeyEventListener
27724     */
27725    public void removeOnUnhandledKeyEventListener(OnUnhandledKeyEventListener listener) {
27726        if (mListenerInfo != null) {
27727            if (mListenerInfo.mUnhandledKeyListeners != null
27728                    && !mListenerInfo.mUnhandledKeyListeners.isEmpty()) {
27729                mListenerInfo.mUnhandledKeyListeners.remove(listener);
27730                if (mListenerInfo.mUnhandledKeyListeners.isEmpty()) {
27731                    mListenerInfo.mUnhandledKeyListeners = null;
27732                    if (mParent instanceof ViewGroup) {
27733                        ((ViewGroup) mParent).decrementChildUnhandledKeyListeners();
27734                    }
27735                }
27736            }
27737        }
27738    }
27739}
27740