View.java revision fb62ecb220e66fd4a772f91717fff95294432c97
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 java.lang.Math.max;
20
21import android.animation.AnimatorInflater;
22import android.animation.StateListAnimator;
23import android.annotation.CallSuper;
24import android.annotation.ColorInt;
25import android.annotation.DrawableRes;
26import android.annotation.FloatRange;
27import android.annotation.IdRes;
28import android.annotation.IntDef;
29import android.annotation.IntRange;
30import android.annotation.LayoutRes;
31import android.annotation.NonNull;
32import android.annotation.Nullable;
33import android.annotation.Size;
34import android.annotation.TestApi;
35import android.annotation.UiThread;
36import android.content.ClipData;
37import android.content.Context;
38import android.content.ContextWrapper;
39import android.content.Intent;
40import android.content.res.ColorStateList;
41import android.content.res.Configuration;
42import android.content.res.Resources;
43import android.content.res.TypedArray;
44import android.graphics.Bitmap;
45import android.graphics.Canvas;
46import android.graphics.Color;
47import android.graphics.Insets;
48import android.graphics.Interpolator;
49import android.graphics.LinearGradient;
50import android.graphics.Matrix;
51import android.graphics.Outline;
52import android.graphics.Paint;
53import android.graphics.PixelFormat;
54import android.graphics.Point;
55import android.graphics.PorterDuff;
56import android.graphics.PorterDuffXfermode;
57import android.graphics.Rect;
58import android.graphics.RectF;
59import android.graphics.Region;
60import android.graphics.Shader;
61import android.graphics.drawable.ColorDrawable;
62import android.graphics.drawable.Drawable;
63import android.hardware.display.DisplayManagerGlobal;
64import android.net.Uri;
65import android.os.Build;
66import android.os.Bundle;
67import android.os.Handler;
68import android.os.IBinder;
69import android.os.Parcel;
70import android.os.Parcelable;
71import android.os.RemoteException;
72import android.os.SystemClock;
73import android.os.SystemProperties;
74import android.os.Trace;
75import android.text.TextUtils;
76import android.util.AttributeSet;
77import android.util.FloatProperty;
78import android.util.LayoutDirection;
79import android.util.Log;
80import android.util.LongSparseLongArray;
81import android.util.Pools.SynchronizedPool;
82import android.util.Property;
83import android.util.SparseArray;
84import android.util.StateSet;
85import android.util.SuperNotCalledException;
86import android.util.TypedValue;
87import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
88import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
89import android.view.AccessibilityIterators.TextSegmentIterator;
90import android.view.AccessibilityIterators.WordTextSegmentIterator;
91import android.view.ContextMenu.ContextMenuInfo;
92import android.view.accessibility.AccessibilityEvent;
93import android.view.accessibility.AccessibilityEventSource;
94import android.view.accessibility.AccessibilityManager;
95import android.view.accessibility.AccessibilityNodeInfo;
96import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction;
97import android.view.accessibility.AccessibilityNodeProvider;
98import android.view.accessibility.AccessibilityWindowInfo;
99import android.view.animation.Animation;
100import android.view.animation.AnimationUtils;
101import android.view.animation.Transformation;
102import android.view.autofill.AutofillManager;
103import android.view.autofill.AutofillValue;
104import android.view.inputmethod.EditorInfo;
105import android.view.inputmethod.InputConnection;
106import android.view.inputmethod.InputMethodManager;
107import android.widget.Checkable;
108import android.widget.FrameLayout;
109import android.widget.ScrollBarDrawable;
110
111import com.android.internal.R;
112import com.android.internal.util.Preconditions;
113import com.android.internal.view.TooltipPopup;
114import com.android.internal.view.menu.MenuBuilder;
115import com.android.internal.widget.ScrollBarUtils;
116
117import com.google.android.collect.Lists;
118import com.google.android.collect.Maps;
119
120import java.lang.annotation.Retention;
121import java.lang.annotation.RetentionPolicy;
122import java.lang.ref.WeakReference;
123import java.lang.reflect.Field;
124import java.lang.reflect.InvocationTargetException;
125import java.lang.reflect.Method;
126import java.lang.reflect.Modifier;
127import java.util.ArrayList;
128import java.util.Arrays;
129import java.util.Collection;
130import java.util.Collections;
131import java.util.HashMap;
132import java.util.List;
133import java.util.Locale;
134import java.util.Map;
135import java.util.concurrent.CopyOnWriteArrayList;
136import java.util.concurrent.atomic.AtomicInteger;
137import java.util.function.Predicate;
138
139/**
140 * <p>
141 * This class represents the basic building block for user interface components. A View
142 * occupies a rectangular area on the screen and is responsible for drawing and
143 * event handling. View is the base class for <em>widgets</em>, which are
144 * used to create interactive UI components (buttons, text fields, etc.). The
145 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
146 * are invisible containers that hold other Views (or other ViewGroups) and define
147 * their layout properties.
148 * </p>
149 *
150 * <div class="special reference">
151 * <h3>Developer Guides</h3>
152 * <p>For information about using this class to develop your application's user interface,
153 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
154 * </div>
155 *
156 * <a name="Using"></a>
157 * <h3>Using Views</h3>
158 * <p>
159 * All of the views in a window are arranged in a single tree. You can add views
160 * either from code or by specifying a tree of views in one or more XML layout
161 * files. There are many specialized subclasses of views that act as controls or
162 * are capable of displaying text, images, or other content.
163 * </p>
164 * <p>
165 * Once you have created a tree of views, there are typically a few types of
166 * common operations you may wish to perform:
167 * <ul>
168 * <li><strong>Set properties:</strong> for example setting the text of a
169 * {@link android.widget.TextView}. The available properties and the methods
170 * that set them will vary among the different subclasses of views. Note that
171 * properties that are known at build time can be set in the XML layout
172 * files.</li>
173 * <li><strong>Set focus:</strong> The framework will handle moving focus in
174 * response to user input. To force focus to a specific view, call
175 * {@link #requestFocus}.</li>
176 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
177 * that will be notified when something interesting happens to the view. For
178 * example, all views will let you set a listener to be notified when the view
179 * gains or loses focus. You can register such a listener using
180 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
181 * Other view subclasses offer more specialized listeners. For example, a Button
182 * exposes a listener to notify clients when the button is clicked.</li>
183 * <li><strong>Set visibility:</strong> You can hide or show views using
184 * {@link #setVisibility(int)}.</li>
185 * </ul>
186 * </p>
187 * <p><em>
188 * Note: The Android framework is responsible for measuring, laying out and
189 * drawing views. You should not call methods that perform these actions on
190 * views yourself unless you are actually implementing a
191 * {@link android.view.ViewGroup}.
192 * </em></p>
193 *
194 * <a name="Lifecycle"></a>
195 * <h3>Implementing a Custom View</h3>
196 *
197 * <p>
198 * To implement a custom view, you will usually begin by providing overrides for
199 * some of the standard methods that the framework calls on all views. You do
200 * not need to override all of these methods. In fact, you can start by just
201 * overriding {@link #onDraw(android.graphics.Canvas)}.
202 * <table border="2" width="85%" align="center" cellpadding="5">
203 *     <thead>
204 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
205 *     </thead>
206 *
207 *     <tbody>
208 *     <tr>
209 *         <td rowspan="2">Creation</td>
210 *         <td>Constructors</td>
211 *         <td>There is a form of the constructor that are called when the view
212 *         is created from code and a form that is called when the view is
213 *         inflated from a layout file. The second form should parse and apply
214 *         any attributes defined in the layout file.
215 *         </td>
216 *     </tr>
217 *     <tr>
218 *         <td><code>{@link #onFinishInflate()}</code></td>
219 *         <td>Called after a view and all of its children has been inflated
220 *         from XML.</td>
221 *     </tr>
222 *
223 *     <tr>
224 *         <td rowspan="3">Layout</td>
225 *         <td><code>{@link #onMeasure(int, int)}</code></td>
226 *         <td>Called to determine the size requirements for this view and all
227 *         of its children.
228 *         </td>
229 *     </tr>
230 *     <tr>
231 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
232 *         <td>Called when this view should assign a size and position to all
233 *         of its children.
234 *         </td>
235 *     </tr>
236 *     <tr>
237 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
238 *         <td>Called when the size of this view has changed.
239 *         </td>
240 *     </tr>
241 *
242 *     <tr>
243 *         <td>Drawing</td>
244 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
245 *         <td>Called when the view should render its content.
246 *         </td>
247 *     </tr>
248 *
249 *     <tr>
250 *         <td rowspan="4">Event processing</td>
251 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
252 *         <td>Called when a new hardware key event occurs.
253 *         </td>
254 *     </tr>
255 *     <tr>
256 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
257 *         <td>Called when a hardware key up event occurs.
258 *         </td>
259 *     </tr>
260 *     <tr>
261 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
262 *         <td>Called when a trackball motion event occurs.
263 *         </td>
264 *     </tr>
265 *     <tr>
266 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
267 *         <td>Called when a touch screen motion event occurs.
268 *         </td>
269 *     </tr>
270 *
271 *     <tr>
272 *         <td rowspan="2">Focus</td>
273 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
274 *         <td>Called when the view gains or loses focus.
275 *         </td>
276 *     </tr>
277 *
278 *     <tr>
279 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
280 *         <td>Called when the window containing the view gains or loses focus.
281 *         </td>
282 *     </tr>
283 *
284 *     <tr>
285 *         <td rowspan="3">Attaching</td>
286 *         <td><code>{@link #onAttachedToWindow()}</code></td>
287 *         <td>Called when the view is attached to a window.
288 *         </td>
289 *     </tr>
290 *
291 *     <tr>
292 *         <td><code>{@link #onDetachedFromWindow}</code></td>
293 *         <td>Called when the view is detached from its window.
294 *         </td>
295 *     </tr>
296 *
297 *     <tr>
298 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
299 *         <td>Called when the visibility of the window containing the view
300 *         has changed.
301 *         </td>
302 *     </tr>
303 *     </tbody>
304 *
305 * </table>
306 * </p>
307 *
308 * <a name="IDs"></a>
309 * <h3>IDs</h3>
310 * Views may have an integer id associated with them. These ids are typically
311 * assigned in the layout XML files, and are used to find specific views within
312 * the view tree. A common pattern is to:
313 * <ul>
314 * <li>Define a Button in the layout file and assign it a unique ID.
315 * <pre>
316 * &lt;Button
317 *     android:id="@+id/my_button"
318 *     android:layout_width="wrap_content"
319 *     android:layout_height="wrap_content"
320 *     android:text="@string/my_button_text"/&gt;
321 * </pre></li>
322 * <li>From the onCreate method of an Activity, find the Button
323 * <pre class="prettyprint">
324 *      Button myButton = (Button) findViewById(R.id.my_button);
325 * </pre></li>
326 * </ul>
327 * <p>
328 * View IDs need not be unique throughout the tree, but it is good practice to
329 * ensure that they are at least unique within the part of the tree you are
330 * searching.
331 * </p>
332 *
333 * <a name="Position"></a>
334 * <h3>Position</h3>
335 * <p>
336 * The geometry of a view is that of a rectangle. A view has a location,
337 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
338 * two dimensions, expressed as a width and a height. The unit for location
339 * and dimensions is the pixel.
340 * </p>
341 *
342 * <p>
343 * It is possible to retrieve the location of a view by invoking the methods
344 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
345 * coordinate of the rectangle representing the view. The latter returns the
346 * top, or Y, coordinate of the rectangle representing the view. These methods
347 * both return the location of the view relative to its parent. For instance,
348 * when getLeft() returns 20, that means the view is located 20 pixels to the
349 * right of the left edge of its direct parent.
350 * </p>
351 *
352 * <p>
353 * In addition, several convenience methods are offered to avoid unnecessary
354 * computations, namely {@link #getRight()} and {@link #getBottom()}.
355 * These methods return the coordinates of the right and bottom edges of the
356 * rectangle representing the view. For instance, calling {@link #getRight()}
357 * is similar to the following computation: <code>getLeft() + getWidth()</code>
358 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
359 * </p>
360 *
361 * <a name="SizePaddingMargins"></a>
362 * <h3>Size, padding and margins</h3>
363 * <p>
364 * The size of a view is expressed with a width and a height. A view actually
365 * possess two pairs of width and height values.
366 * </p>
367 *
368 * <p>
369 * The first pair is known as <em>measured width</em> and
370 * <em>measured height</em>. These dimensions define how big a view wants to be
371 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
372 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
373 * and {@link #getMeasuredHeight()}.
374 * </p>
375 *
376 * <p>
377 * The second pair is simply known as <em>width</em> and <em>height</em>, or
378 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
379 * dimensions define the actual size of the view on screen, at drawing time and
380 * after layout. These values may, but do not have to, be different from the
381 * measured width and height. The width and height can be obtained by calling
382 * {@link #getWidth()} and {@link #getHeight()}.
383 * </p>
384 *
385 * <p>
386 * To measure its dimensions, a view takes into account its padding. The padding
387 * is expressed in pixels for the left, top, right and bottom parts of the view.
388 * Padding can be used to offset the content of the view by a specific amount of
389 * pixels. For instance, a left padding of 2 will push the view's content by
390 * 2 pixels to the right of the left edge. Padding can be set using the
391 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
392 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
393 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
394 * {@link #getPaddingEnd()}.
395 * </p>
396 *
397 * <p>
398 * Even though a view can define a padding, it does not provide any support for
399 * margins. However, view groups provide such a support. Refer to
400 * {@link android.view.ViewGroup} and
401 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
402 * </p>
403 *
404 * <a name="Layout"></a>
405 * <h3>Layout</h3>
406 * <p>
407 * Layout is a two pass process: a measure pass and a layout pass. The measuring
408 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
409 * of the view tree. Each view pushes dimension specifications down the tree
410 * during the recursion. At the end of the measure pass, every view has stored
411 * its measurements. The second pass happens in
412 * {@link #layout(int,int,int,int)} and is also top-down. During
413 * this pass each parent is responsible for positioning all of its children
414 * using the sizes computed in the measure pass.
415 * </p>
416 *
417 * <p>
418 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
419 * {@link #getMeasuredHeight()} values must be set, along with those for all of
420 * that view's descendants. A view's measured width and measured height values
421 * must respect the constraints imposed by the view's parents. This guarantees
422 * that at the end of the measure pass, all parents accept all of their
423 * children's measurements. A parent view may call measure() more than once on
424 * its children. For example, the parent may measure each child once with
425 * unspecified dimensions to find out how big they want to be, then call
426 * measure() on them again with actual numbers if the sum of all the children's
427 * unconstrained sizes is too big or too small.
428 * </p>
429 *
430 * <p>
431 * The measure pass uses two classes to communicate dimensions. The
432 * {@link MeasureSpec} class is used by views to tell their parents how they
433 * want to be measured and positioned. The base LayoutParams class just
434 * describes how big the view wants to be for both width and height. For each
435 * dimension, it can specify one of:
436 * <ul>
437 * <li> an exact number
438 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
439 * (minus padding)
440 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
441 * enclose its content (plus padding).
442 * </ul>
443 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
444 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
445 * an X and Y value.
446 * </p>
447 *
448 * <p>
449 * MeasureSpecs are used to push requirements down the tree from parent to
450 * child. A MeasureSpec can be in one of three modes:
451 * <ul>
452 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
453 * of a child view. For example, a LinearLayout may call measure() on its child
454 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
455 * tall the child view wants to be given a width of 240 pixels.
456 * <li>EXACTLY: This is used by the parent to impose an exact size on the
457 * child. The child must use this size, and guarantee that all of its
458 * descendants will fit within this size.
459 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
460 * child. The child must guarantee that it and all of its descendants will fit
461 * within this size.
462 * </ul>
463 * </p>
464 *
465 * <p>
466 * To initiate a layout, call {@link #requestLayout}. This method is typically
467 * called by a view on itself when it believes that is can no longer fit within
468 * its current bounds.
469 * </p>
470 *
471 * <a name="Drawing"></a>
472 * <h3>Drawing</h3>
473 * <p>
474 * Drawing is handled by walking the tree and recording the drawing commands of
475 * any View that needs to update. After this, the drawing commands of the
476 * entire tree are issued to screen, clipped to the newly damaged area.
477 * </p>
478 *
479 * <p>
480 * The tree is largely recorded and drawn in order, with parents drawn before
481 * (i.e., behind) their children, with siblings drawn in the order they appear
482 * in the tree. If you set a background drawable for a View, then the View will
483 * draw it before calling back to its <code>onDraw()</code> method. The child
484 * drawing order can be overridden with
485 * {@link ViewGroup#setChildrenDrawingOrderEnabled(boolean) custom child drawing order}
486 * in a ViewGroup, and with {@link #setZ(float)} custom Z values} set on Views.
487 * </p>
488 *
489 * <p>
490 * To force a view to draw, call {@link #invalidate()}.
491 * </p>
492 *
493 * <a name="EventHandlingThreading"></a>
494 * <h3>Event Handling and Threading</h3>
495 * <p>
496 * The basic cycle of a view is as follows:
497 * <ol>
498 * <li>An event comes in and is dispatched to the appropriate view. The view
499 * handles the event and notifies any listeners.</li>
500 * <li>If in the course of processing the event, the view's bounds may need
501 * to be changed, the view will call {@link #requestLayout()}.</li>
502 * <li>Similarly, if in the course of processing the event the view's appearance
503 * may need to be changed, the view will call {@link #invalidate()}.</li>
504 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
505 * the framework will take care of measuring, laying out, and drawing the tree
506 * as appropriate.</li>
507 * </ol>
508 * </p>
509 *
510 * <p><em>Note: The entire view tree is single threaded. You must always be on
511 * the UI thread when calling any method on any view.</em>
512 * If you are doing work on other threads and want to update the state of a view
513 * from that thread, you should use a {@link Handler}.
514 * </p>
515 *
516 * <a name="FocusHandling"></a>
517 * <h3>Focus Handling</h3>
518 * <p>
519 * The framework will handle routine focus movement in response to user input.
520 * This includes changing the focus as views are removed or hidden, or as new
521 * views become available. Views indicate their willingness to take focus
522 * through the {@link #isFocusable} method. To change whether a view can take
523 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
524 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
525 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
526 * </p>
527 * <p>
528 * Focus movement is based on an algorithm which finds the nearest neighbor in a
529 * given direction. In rare cases, the default algorithm may not match the
530 * intended behavior of the developer. In these situations, you can provide
531 * explicit overrides by using these XML attributes in the layout file:
532 * <pre>
533 * nextFocusDown
534 * nextFocusLeft
535 * nextFocusRight
536 * nextFocusUp
537 * </pre>
538 * </p>
539 *
540 *
541 * <p>
542 * To get a particular view to take focus, call {@link #requestFocus()}.
543 * </p>
544 *
545 * <a name="TouchMode"></a>
546 * <h3>Touch Mode</h3>
547 * <p>
548 * When a user is navigating a user interface via directional keys such as a D-pad, it is
549 * necessary to give focus to actionable items such as buttons so the user can see
550 * what will take input.  If the device has touch capabilities, however, and the user
551 * begins interacting with the interface by touching it, it is no longer necessary to
552 * always highlight, or give focus to, a particular view.  This motivates a mode
553 * for interaction named 'touch mode'.
554 * </p>
555 * <p>
556 * For a touch capable device, once the user touches the screen, the device
557 * will enter touch mode.  From this point onward, only views for which
558 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
559 * Other views that are touchable, like buttons, will not take focus when touched; they will
560 * only fire the on click listeners.
561 * </p>
562 * <p>
563 * Any time a user hits a directional key, such as a D-pad direction, the view device will
564 * exit touch mode, and find a view to take focus, so that the user may resume interacting
565 * with the user interface without touching the screen again.
566 * </p>
567 * <p>
568 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
569 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
570 * </p>
571 *
572 * <a name="Scrolling"></a>
573 * <h3>Scrolling</h3>
574 * <p>
575 * The framework provides basic support for views that wish to internally
576 * scroll their content. This includes keeping track of the X and Y scroll
577 * offset as well as mechanisms for drawing scrollbars. See
578 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
579 * {@link #awakenScrollBars()} for more details.
580 * </p>
581 *
582 * <a name="Tags"></a>
583 * <h3>Tags</h3>
584 * <p>
585 * Unlike IDs, tags are not used to identify views. Tags are essentially an
586 * extra piece of information that can be associated with a view. They are most
587 * often used as a convenience to store data related to views in the views
588 * themselves rather than by putting them in a separate structure.
589 * </p>
590 * <p>
591 * Tags may be specified with character sequence values in layout XML as either
592 * a single tag using the {@link android.R.styleable#View_tag android:tag}
593 * attribute or multiple tags using the {@code <tag>} child element:
594 * <pre>
595 *     &ltView ...
596 *           android:tag="@string/mytag_value" /&gt;
597 *     &ltView ...&gt;
598 *         &lttag android:id="@+id/mytag"
599 *              android:value="@string/mytag_value" /&gt;
600 *     &lt/View>
601 * </pre>
602 * </p>
603 * <p>
604 * Tags may also be specified with arbitrary objects from code using
605 * {@link #setTag(Object)} or {@link #setTag(int, Object)}.
606 * </p>
607 *
608 * <a name="Themes"></a>
609 * <h3>Themes</h3>
610 * <p>
611 * By default, Views are created using the theme of the Context object supplied
612 * to their constructor; however, a different theme may be specified by using
613 * the {@link android.R.styleable#View_theme android:theme} attribute in layout
614 * XML or by passing a {@link ContextThemeWrapper} to the constructor from
615 * code.
616 * </p>
617 * <p>
618 * When the {@link android.R.styleable#View_theme android:theme} attribute is
619 * used in XML, the specified theme is applied on top of the inflation
620 * context's theme (see {@link LayoutInflater}) and used for the view itself as
621 * well as any child elements.
622 * </p>
623 * <p>
624 * In the following example, both views will be created using the Material dark
625 * color scheme; however, because an overlay theme is used which only defines a
626 * subset of attributes, the value of
627 * {@link android.R.styleable#Theme_colorAccent android:colorAccent} defined on
628 * the inflation context's theme (e.g. the Activity theme) will be preserved.
629 * <pre>
630 *     &ltLinearLayout
631 *             ...
632 *             android:theme="@android:theme/ThemeOverlay.Material.Dark"&gt;
633 *         &ltView ...&gt;
634 *     &lt/LinearLayout&gt;
635 * </pre>
636 * </p>
637 *
638 * <a name="Properties"></a>
639 * <h3>Properties</h3>
640 * <p>
641 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
642 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
643 * available both in the {@link Property} form as well as in similarly-named setter/getter
644 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
645 * be used to set persistent state associated with these rendering-related properties on the view.
646 * The properties and methods can also be used in conjunction with
647 * {@link android.animation.Animator Animator}-based animations, described more in the
648 * <a href="#Animation">Animation</a> section.
649 * </p>
650 *
651 * <a name="Animation"></a>
652 * <h3>Animation</h3>
653 * <p>
654 * Starting with Android 3.0, the preferred way of animating views is to use the
655 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
656 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
657 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
658 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
659 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
660 * makes animating these View properties particularly easy and efficient.
661 * </p>
662 * <p>
663 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
664 * You can attach an {@link Animation} object to a view using
665 * {@link #setAnimation(Animation)} or
666 * {@link #startAnimation(Animation)}. The animation can alter the scale,
667 * rotation, translation and alpha of a view over time. If the animation is
668 * attached to a view that has children, the animation will affect the entire
669 * subtree rooted by that node. When an animation is started, the framework will
670 * take care of redrawing the appropriate views until the animation completes.
671 * </p>
672 *
673 * <a name="Security"></a>
674 * <h3>Security</h3>
675 * <p>
676 * Sometimes it is essential that an application be able to verify that an action
677 * is being performed with the full knowledge and consent of the user, such as
678 * granting a permission request, making a purchase or clicking on an advertisement.
679 * Unfortunately, a malicious application could try to spoof the user into
680 * performing these actions, unaware, by concealing the intended purpose of the view.
681 * As a remedy, the framework offers a touch filtering mechanism that can be used to
682 * improve the security of views that provide access to sensitive functionality.
683 * </p><p>
684 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
685 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
686 * will discard touches that are received whenever the view's window is obscured by
687 * another visible window.  As a result, the view will not receive touches whenever a
688 * toast, dialog or other window appears above the view's window.
689 * </p><p>
690 * For more fine-grained control over security, consider overriding the
691 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
692 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
693 * </p>
694 *
695 * @attr ref android.R.styleable#View_alpha
696 * @attr ref android.R.styleable#View_background
697 * @attr ref android.R.styleable#View_clickable
698 * @attr ref android.R.styleable#View_contentDescription
699 * @attr ref android.R.styleable#View_drawingCacheQuality
700 * @attr ref android.R.styleable#View_duplicateParentState
701 * @attr ref android.R.styleable#View_id
702 * @attr ref android.R.styleable#View_requiresFadingEdge
703 * @attr ref android.R.styleable#View_fadeScrollbars
704 * @attr ref android.R.styleable#View_fadingEdgeLength
705 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
706 * @attr ref android.R.styleable#View_fitsSystemWindows
707 * @attr ref android.R.styleable#View_isScrollContainer
708 * @attr ref android.R.styleable#View_focusable
709 * @attr ref android.R.styleable#View_focusableInTouchMode
710 * @attr ref android.R.styleable#View_focusedByDefault
711 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
712 * @attr ref android.R.styleable#View_keepScreenOn
713 * @attr ref android.R.styleable#View_keyboardNavigationCluster
714 * @attr ref android.R.styleable#View_layerType
715 * @attr ref android.R.styleable#View_layoutDirection
716 * @attr ref android.R.styleable#View_longClickable
717 * @attr ref android.R.styleable#View_minHeight
718 * @attr ref android.R.styleable#View_minWidth
719 * @attr ref android.R.styleable#View_nextClusterForward
720 * @attr ref android.R.styleable#View_nextFocusDown
721 * @attr ref android.R.styleable#View_nextFocusLeft
722 * @attr ref android.R.styleable#View_nextFocusRight
723 * @attr ref android.R.styleable#View_nextFocusUp
724 * @attr ref android.R.styleable#View_onClick
725 * @attr ref android.R.styleable#View_padding
726 * @attr ref android.R.styleable#View_paddingBottom
727 * @attr ref android.R.styleable#View_paddingLeft
728 * @attr ref android.R.styleable#View_paddingRight
729 * @attr ref android.R.styleable#View_paddingTop
730 * @attr ref android.R.styleable#View_paddingStart
731 * @attr ref android.R.styleable#View_paddingEnd
732 * @attr ref android.R.styleable#View_saveEnabled
733 * @attr ref android.R.styleable#View_rotation
734 * @attr ref android.R.styleable#View_rotationX
735 * @attr ref android.R.styleable#View_rotationY
736 * @attr ref android.R.styleable#View_scaleX
737 * @attr ref android.R.styleable#View_scaleY
738 * @attr ref android.R.styleable#View_scrollX
739 * @attr ref android.R.styleable#View_scrollY
740 * @attr ref android.R.styleable#View_scrollbarSize
741 * @attr ref android.R.styleable#View_scrollbarStyle
742 * @attr ref android.R.styleable#View_scrollbars
743 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
744 * @attr ref android.R.styleable#View_scrollbarFadeDuration
745 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
746 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
747 * @attr ref android.R.styleable#View_scrollbarThumbVertical
748 * @attr ref android.R.styleable#View_scrollbarTrackVertical
749 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
750 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
751 * @attr ref android.R.styleable#View_stateListAnimator
752 * @attr ref android.R.styleable#View_transitionName
753 * @attr ref android.R.styleable#View_soundEffectsEnabled
754 * @attr ref android.R.styleable#View_tag
755 * @attr ref android.R.styleable#View_textAlignment
756 * @attr ref android.R.styleable#View_textDirection
757 * @attr ref android.R.styleable#View_transformPivotX
758 * @attr ref android.R.styleable#View_transformPivotY
759 * @attr ref android.R.styleable#View_translationX
760 * @attr ref android.R.styleable#View_translationY
761 * @attr ref android.R.styleable#View_translationZ
762 * @attr ref android.R.styleable#View_visibility
763 * @attr ref android.R.styleable#View_theme
764 *
765 * @see android.view.ViewGroup
766 */
767@UiThread
768public class View implements Drawable.Callback, KeyEvent.Callback,
769        AccessibilityEventSource {
770    private static final boolean DBG = false;
771
772    /** @hide */
773    public static boolean DEBUG_DRAW = false;
774
775    /**
776     * The logging tag used by this class with android.util.Log.
777     */
778    protected static final String VIEW_LOG_TAG = "View";
779
780    /**
781     * When set to true, apps will draw debugging information about their layouts.
782     *
783     * @hide
784     */
785    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
786
787    /**
788     * When set to true, this view will save its attribute data.
789     *
790     * @hide
791     */
792    public static boolean mDebugViewAttributes = false;
793
794    /**
795     * Used to mark a View that has no ID.
796     */
797    public static final int NO_ID = -1;
798
799    /**
800     * Last ID that is given to Views that are no part of activities.
801     *
802     * {@hide}
803     */
804    public static final int LAST_APP_ACCESSIBILITY_ID = Integer.MAX_VALUE / 2;
805
806    /**
807     * Signals that compatibility booleans have been initialized according to
808     * target SDK versions.
809     */
810    private static boolean sCompatibilityDone = false;
811
812    /**
813     * Use the old (broken) way of building MeasureSpecs.
814     */
815    private static boolean sUseBrokenMakeMeasureSpec = false;
816
817    /**
818     * Always return a size of 0 for MeasureSpec values with a mode of UNSPECIFIED
819     */
820    static boolean sUseZeroUnspecifiedMeasureSpec = false;
821
822    /**
823     * Ignore any optimizations using the measure cache.
824     */
825    private static boolean sIgnoreMeasureCache = false;
826
827    /**
828     * Ignore an optimization that skips unnecessary EXACTLY layout passes.
829     */
830    private static boolean sAlwaysRemeasureExactly = false;
831
832    /**
833     * Relax constraints around whether setLayoutParams() must be called after
834     * modifying the layout params.
835     */
836    private static boolean sLayoutParamsAlwaysChanged = false;
837
838    /**
839     * Allow setForeground/setBackground to be called (and ignored) on a textureview,
840     * without throwing
841     */
842    static boolean sTextureViewIgnoresDrawableSetters = false;
843
844    /**
845     * Prior to N, some ViewGroups would not convert LayoutParams properly even though both extend
846     * MarginLayoutParams. For instance, converting LinearLayout.LayoutParams to
847     * RelativeLayout.LayoutParams would lose margin information. This is fixed on N but target API
848     * check is implemented for backwards compatibility.
849     *
850     * {@hide}
851     */
852    protected static boolean sPreserveMarginParamsInLayoutParamConversion;
853
854    /**
855     * Prior to N, when drag enters into child of a view that has already received an
856     * ACTION_DRAG_ENTERED event, the parent doesn't get a ACTION_DRAG_EXITED event.
857     * ACTION_DRAG_LOCATION and ACTION_DROP were delivered to the parent of a view that returned
858     * false from its event handler for these events.
859     * Starting from N, the parent will get ACTION_DRAG_EXITED event before the child gets its
860     * ACTION_DRAG_ENTERED. ACTION_DRAG_LOCATION and ACTION_DROP are never propagated to the parent.
861     * sCascadedDragDrop is true for pre-N apps for backwards compatibility implementation.
862     */
863    static boolean sCascadedDragDrop;
864
865    /**
866     * Prior to O, auto-focusable didn't exist and widgets such as ListView use hasFocusable
867     * to determine things like whether or not to permit item click events. We can't break
868     * apps that do this just because more things (clickable things) are now auto-focusable
869     * and they would get different results, so give old behavior to old apps.
870     */
871    static boolean sHasFocusableExcludeAutoFocusable;
872
873    /**
874     * Prior to O, auto-focusable didn't exist and views marked as clickable weren't implicitly
875     * made focusable by default. As a result, apps could (incorrectly) change the clickable
876     * setting of views off the UI thread. Now that clickable can effect the focusable state,
877     * changing the clickable attribute off the UI thread will cause an exception (since changing
878     * the focusable state checks). In order to prevent apps from crashing, we will handle this
879     * specific case and just not notify parents on new focusables resulting from marking views
880     * clickable from outside the UI thread.
881     */
882    private static boolean sAutoFocusableOffUIThreadWontNotifyParents;
883
884    /** @hide */
885    @IntDef({NOT_FOCUSABLE, FOCUSABLE, FOCUSABLE_AUTO})
886    @Retention(RetentionPolicy.SOURCE)
887    public @interface Focusable {}
888
889    /**
890     * This view does not want keystrokes.
891     * <p>
892     * Use with {@link #setFocusable(int)} and <a href="#attr_android:focusable">{@code
893     * android:focusable}.
894     */
895    public static final int NOT_FOCUSABLE = 0x00000000;
896
897    /**
898     * This view wants keystrokes.
899     * <p>
900     * Use with {@link #setFocusable(int)} and <a href="#attr_android:focusable">{@code
901     * android:focusable}.
902     */
903    public static final int FOCUSABLE = 0x00000001;
904
905    /**
906     * This view determines focusability automatically. This is the default.
907     * <p>
908     * Use with {@link #setFocusable(int)} and <a href="#attr_android:focusable">{@code
909     * android:focusable}.
910     */
911    public static final int FOCUSABLE_AUTO = 0x00000010;
912
913    /**
914     * Mask for use with setFlags indicating bits used for focus.
915     */
916    private static final int FOCUSABLE_MASK = 0x00000011;
917
918    /**
919     * This view will adjust its padding to fit sytem windows (e.g. status bar)
920     */
921    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
922
923    /** @hide */
924    @IntDef({VISIBLE, INVISIBLE, GONE})
925    @Retention(RetentionPolicy.SOURCE)
926    public @interface Visibility {}
927
928    /**
929     * This view is visible.
930     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
931     * android:visibility}.
932     */
933    public static final int VISIBLE = 0x00000000;
934
935    /**
936     * This view is invisible, but it still takes up space for layout purposes.
937     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
938     * android:visibility}.
939     */
940    public static final int INVISIBLE = 0x00000004;
941
942    /**
943     * This view is invisible, and it doesn't take any space for layout
944     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
945     * android:visibility}.
946     */
947    public static final int GONE = 0x00000008;
948
949    /**
950     * Mask for use with setFlags indicating bits used for visibility.
951     * {@hide}
952     */
953    static final int VISIBILITY_MASK = 0x0000000C;
954
955    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
956
957    /** @hide */
958    @IntDef({
959            AUTOFILL_MODE_INHERIT,
960            AUTOFILL_MODE_AUTO,
961            AUTOFILL_MODE_MANUAL
962    })
963    @Retention(RetentionPolicy.SOURCE)
964    public @interface AutofillMode {}
965
966    /**
967     * This view inherits the autofill state from it's parent. If there is no parent it is
968     * {@link #AUTOFILL_MODE_AUTO}.
969     * Use with {@link #setAutofillMode(int)} and <a href="#attr_android:autofillMode">
970     * {@code android:autofillMode}.
971     */
972    public static final int AUTOFILL_MODE_INHERIT = 0;
973
974    /**
975     * Allows this view to automatically trigger an autofill request when it get focus.
976     * Use with {@link #setAutofillMode(int)} and <a href="#attr_android:autofillMode">
977     * {@code android:autofillMode}.
978     */
979    public static final int AUTOFILL_MODE_AUTO = 1;
980
981    /**
982     * Do not trigger an autofill request if this view is focused. The user can still force
983     * an autofill request.
984     * <p>This does not prevent this field from being autofilled if an autofill operation is
985     * triggered from a different view.</p>
986     *
987     * Use with {@link #setAutofillMode(int)} and <a href="#attr_android:autofillMode">{@code
988     * android:autofillMode}.
989     */
990    public static final int AUTOFILL_MODE_MANUAL = 2;
991
992    /**
993     * This view contains an email address.
994     *
995     * Use with {@link #setAutofillHints(String[])}, or set "{@value #AUTOFILL_HINT_EMAIL_ADDRESS}"
996     * to <a href="#attr_android:autofillHint"> {@code android:autofillHint}.
997     */
998    public static final String AUTOFILL_HINT_EMAIL_ADDRESS = "emailAddress";
999
1000    /**
1001     * The view contains a real name.
1002     *
1003     * Use with {@link #setAutofillHints(String[])}, or set "{@value #AUTOFILL_HINT_NAME}" to
1004     * <a href="#attr_android:autofillHint"> {@code android:autofillHint}.
1005     */
1006    public static final String AUTOFILL_HINT_NAME = "name";
1007
1008    /**
1009     * The view contains a user name.
1010     *
1011     * Use with {@link #setAutofillHints(String[])}, or set "{@value #AUTOFILL_HINT_USERNAME}" to
1012     * <a href="#attr_android:autofillHint"> {@code android:autofillHint}.
1013     */
1014    public static final String AUTOFILL_HINT_USERNAME = "username";
1015
1016    /**
1017     * The view contains a password.
1018     *
1019     * Use with {@link #setAutofillHints(String[])}, or set "{@value #AUTOFILL_HINT_PASSWORD}" to
1020     * <a href="#attr_android:autofillHint"> {@code android:autofillHint}.
1021     */
1022    public static final String AUTOFILL_HINT_PASSWORD = "password";
1023
1024    /**
1025     * The view contains a phone number.
1026     *
1027     * Use with {@link #setAutofillHints(String[])}, or set "{@value #AUTOFILL_HINT_PHONE}" to
1028     * <a href="#attr_android:autofillHint"> {@code android:autofillHint}.
1029     */
1030    public static final String AUTOFILL_HINT_PHONE = "phone";
1031
1032    /**
1033     * The view contains a postal address.
1034     *
1035     * Use with {@link #setAutofillHints(String[])}, or set "{@value #AUTOFILL_HINT_POSTAL_ADDRESS}"
1036     * to <a href="#attr_android:autofillHint"> {@code android:autofillHint}.
1037     */
1038    public static final String AUTOFILL_HINT_POSTAL_ADDRESS = "postalAddress";
1039
1040    /**
1041     * The view contains a postal code.
1042     *
1043     * Use with {@link #setAutofillHints(String[])}, or set "{@value #AUTOFILL_HINT_POSTAL_CODE}" to
1044     * <a href="#attr_android:autofillHint"> {@code android:autofillHint}.
1045     */
1046    public static final String AUTOFILL_HINT_POSTAL_CODE = "postalCode";
1047
1048    /**
1049     * The view contains a credit card number.
1050     *
1051     * Use with {@link #setAutofillHints(String[])}, or set "{@value
1052     * #AUTOFILL_HINT_CREDIT_CARD_NUMBER}" to <a href="#attr_android:autofillHint"> {@code
1053     * android:autofillHint}.
1054     */
1055    public static final String AUTOFILL_HINT_CREDIT_CARD_NUMBER = "creditCardNumber";
1056
1057    /**
1058     * The view contains a credit card security code.
1059     *
1060     * Use with {@link #setAutofillHints(String[])}, or set "{@value
1061     * #AUTOFILL_HINT_CREDIT_CARD_SECURITY_CODE}" to <a href="#attr_android:autofillHint"> {@code
1062     * android:autofillHint}.
1063     */
1064    public static final String AUTOFILL_HINT_CREDIT_CARD_SECURITY_CODE = "creditCardSecurityCode";
1065
1066    /**
1067     * The view contains a credit card expiration date.
1068     *
1069     * Use with {@link #setAutofillHints(String[])}, or set "{@value
1070     * #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DATE}" to <a href="#attr_android:autofillHint"> {@code
1071     * android:autofillHint}.
1072     */
1073    public static final String AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DATE =
1074            "creditCardExpirationDate";
1075
1076    /**
1077     * The view contains the month a credit card expires.
1078     *
1079     * Use with {@link #setAutofillHints(String[])}, or set "{@value
1080     * #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_MONTH}" to <a href="#attr_android:autofillHint"> {@code
1081     * android:autofillHint}.
1082     */
1083    public static final String AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_MONTH =
1084            "creditCardExpirationMonth";
1085
1086    /**
1087     * The view contains the year a credit card expires.
1088     *
1089     * Use with {@link #setAutofillHints(String[])}, or set "{@value
1090     * #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_YEAR}" to <a href="#attr_android:autofillHint"> {@code
1091     * android:autofillHint}.
1092     */
1093    public static final String AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_YEAR =
1094            "creditCardExpirationYear";
1095
1096    /**
1097     * The view contains the day a credit card expires.
1098     *
1099     * Use with {@link #setAutofillHints(String[])}, or set "{@value
1100     * #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DAY}" to <a href="#attr_android:autofillHint"> {@code
1101     * android:autofillHint}.
1102     */
1103    public static final String AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DAY = "creditCardExpirationDay";
1104
1105    /**
1106     * Hintd for the autofill services that describes the content of the view.
1107     */
1108    private @Nullable String[] mAutofillHints;
1109
1110    /** @hide */
1111    @IntDef({
1112            AUTOFILL_TYPE_NONE,
1113            AUTOFILL_TYPE_TEXT,
1114            AUTOFILL_TYPE_TOGGLE,
1115            AUTOFILL_TYPE_LIST,
1116            AUTOFILL_TYPE_DATE
1117    })
1118    @Retention(RetentionPolicy.SOURCE)
1119    public @interface AutofillType {}
1120
1121    /**
1122     * Autofill type for views that cannot be autofilled.
1123     */
1124    public static final int AUTOFILL_TYPE_NONE = 0;
1125
1126    /**
1127     * Autofill type for a text field, which is filled by a {@link CharSequence}.
1128     *
1129     * <p>{@link AutofillValue} instances for autofilling a {@link View} can be obtained through
1130     * {@link AutofillValue#forText(CharSequence)}, and the value passed to autofill a
1131     * {@link View} can be fetched through {@link AutofillValue#getTextValue()}.
1132     */
1133    public static final int AUTOFILL_TYPE_TEXT = 1;
1134
1135    /**
1136     * Autofill type for a togglable field, which is filled by a {@code boolean}.
1137     *
1138     * <p>{@link AutofillValue} instances for autofilling a {@link View} can be obtained through
1139     * {@link AutofillValue#forToggle(boolean)}, and the value passed to autofill a
1140     * {@link View} can be fetched through {@link AutofillValue#getToggleValue()}.
1141     */
1142    public static final int AUTOFILL_TYPE_TOGGLE = 2;
1143
1144    /**
1145     * Autofill type for a selection list field, which is filled by an {@code int}
1146     * representing the element index inside the list (starting at {@code 0}).
1147     *
1148     * <p>{@link AutofillValue} instances for autofilling a {@link View} can be obtained through
1149     * {@link AutofillValue#forList(int)}, and the value passed to autofill a
1150     * {@link View} can be fetched through {@link AutofillValue#getListValue()}.
1151     *
1152     * <p>The available options in the selection list are typically provided by
1153     * {@link android.app.assist.AssistStructure.ViewNode#getAutofillOptions()}.
1154     */
1155    public static final int AUTOFILL_TYPE_LIST = 3;
1156
1157
1158    /**
1159     * Autofill type for a field that contains a date, which is represented by a long representing
1160     * the number of milliseconds since the standard base time known as "the epoch", namely
1161     * January 1, 1970, 00:00:00 GMT (see {@link java.util.Date#getTime()}.
1162     *
1163     * <p>{@link AutofillValue} instances for autofilling a {@link View} can be obtained through
1164     * {@link AutofillValue#forDate(long)}, and the values passed to
1165     * autofill a {@link View} can be fetched through {@link AutofillValue#getDateValue()}.
1166     */
1167    public static final int AUTOFILL_TYPE_DATE = 4;
1168
1169    /** @hide */
1170    @IntDef({
1171            IMPORTANT_FOR_AUTOFILL_AUTO,
1172            IMPORTANT_FOR_AUTOFILL_YES,
1173            IMPORTANT_FOR_AUTOFILL_NO
1174    })
1175    @Retention(RetentionPolicy.SOURCE)
1176    public @interface AutofillImportance {}
1177
1178    /**
1179     * Automatically determine whether a view is important for auto-fill.
1180     */
1181    public static final int IMPORTANT_FOR_AUTOFILL_AUTO = 0x0;
1182
1183    /**
1184     * The view is important for important for auto-fill.
1185     */
1186    public static final int IMPORTANT_FOR_AUTOFILL_YES = 0x1;
1187
1188    /**
1189     * The view is not important for auto-fill.
1190     */
1191    public static final int IMPORTANT_FOR_AUTOFILL_NO = 0x2;
1192
1193    /**
1194     * This view is enabled. Interpretation varies by subclass.
1195     * Use with ENABLED_MASK when calling setFlags.
1196     * {@hide}
1197     */
1198    static final int ENABLED = 0x00000000;
1199
1200    /**
1201     * This view is disabled. Interpretation varies by subclass.
1202     * Use with ENABLED_MASK when calling setFlags.
1203     * {@hide}
1204     */
1205    static final int DISABLED = 0x00000020;
1206
1207   /**
1208    * Mask for use with setFlags indicating bits used for indicating whether
1209    * this view is enabled
1210    * {@hide}
1211    */
1212    static final int ENABLED_MASK = 0x00000020;
1213
1214    /**
1215     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
1216     * called and further optimizations will be performed. It is okay to have
1217     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
1218     * {@hide}
1219     */
1220    static final int WILL_NOT_DRAW = 0x00000080;
1221
1222    /**
1223     * Mask for use with setFlags indicating bits used for indicating whether
1224     * this view is will draw
1225     * {@hide}
1226     */
1227    static final int DRAW_MASK = 0x00000080;
1228
1229    /**
1230     * <p>This view doesn't show scrollbars.</p>
1231     * {@hide}
1232     */
1233    static final int SCROLLBARS_NONE = 0x00000000;
1234
1235    /**
1236     * <p>This view shows horizontal scrollbars.</p>
1237     * {@hide}
1238     */
1239    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
1240
1241    /**
1242     * <p>This view shows vertical scrollbars.</p>
1243     * {@hide}
1244     */
1245    static final int SCROLLBARS_VERTICAL = 0x00000200;
1246
1247    /**
1248     * <p>Mask for use with setFlags indicating bits used for indicating which
1249     * scrollbars are enabled.</p>
1250     * {@hide}
1251     */
1252    static final int SCROLLBARS_MASK = 0x00000300;
1253
1254    /**
1255     * Indicates that the view should filter touches when its window is obscured.
1256     * Refer to the class comments for more information about this security feature.
1257     * {@hide}
1258     */
1259    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
1260
1261    /**
1262     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
1263     * that they are optional and should be skipped if the window has
1264     * requested system UI flags that ignore those insets for layout.
1265     */
1266    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
1267
1268    /**
1269     * <p>This view doesn't show fading edges.</p>
1270     * {@hide}
1271     */
1272    static final int FADING_EDGE_NONE = 0x00000000;
1273
1274    /**
1275     * <p>This view shows horizontal fading edges.</p>
1276     * {@hide}
1277     */
1278    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
1279
1280    /**
1281     * <p>This view shows vertical fading edges.</p>
1282     * {@hide}
1283     */
1284    static final int FADING_EDGE_VERTICAL = 0x00002000;
1285
1286    /**
1287     * <p>Mask for use with setFlags indicating bits used for indicating which
1288     * fading edges are enabled.</p>
1289     * {@hide}
1290     */
1291    static final int FADING_EDGE_MASK = 0x00003000;
1292
1293    /**
1294     * <p>Indicates this view can be clicked. When clickable, a View reacts
1295     * to clicks by notifying the OnClickListener.<p>
1296     * {@hide}
1297     */
1298    static final int CLICKABLE = 0x00004000;
1299
1300    /**
1301     * <p>Indicates this view is caching its drawing into a bitmap.</p>
1302     * {@hide}
1303     */
1304    static final int DRAWING_CACHE_ENABLED = 0x00008000;
1305
1306    /**
1307     * <p>Indicates that no icicle should be saved for this view.<p>
1308     * {@hide}
1309     */
1310    static final int SAVE_DISABLED = 0x000010000;
1311
1312    /**
1313     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
1314     * property.</p>
1315     * {@hide}
1316     */
1317    static final int SAVE_DISABLED_MASK = 0x000010000;
1318
1319    /**
1320     * <p>Indicates that no drawing cache should ever be created for this view.<p>
1321     * {@hide}
1322     */
1323    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
1324
1325    /**
1326     * <p>Indicates this view can take / keep focus when int touch mode.</p>
1327     * {@hide}
1328     */
1329    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
1330
1331    /** @hide */
1332    @Retention(RetentionPolicy.SOURCE)
1333    @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO})
1334    public @interface DrawingCacheQuality {}
1335
1336    /**
1337     * <p>Enables low quality mode for the drawing cache.</p>
1338     */
1339    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
1340
1341    /**
1342     * <p>Enables high quality mode for the drawing cache.</p>
1343     */
1344    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
1345
1346    /**
1347     * <p>Enables automatic quality mode for the drawing cache.</p>
1348     */
1349    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
1350
1351    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
1352            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
1353    };
1354
1355    /**
1356     * <p>Mask for use with setFlags indicating bits used for the cache
1357     * quality property.</p>
1358     * {@hide}
1359     */
1360    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
1361
1362    /**
1363     * <p>
1364     * Indicates this view can be long clicked. When long clickable, a View
1365     * reacts to long clicks by notifying the OnLongClickListener or showing a
1366     * context menu.
1367     * </p>
1368     * {@hide}
1369     */
1370    static final int LONG_CLICKABLE = 0x00200000;
1371
1372    /**
1373     * <p>Indicates that this view gets its drawable states from its direct parent
1374     * and ignores its original internal states.</p>
1375     *
1376     * @hide
1377     */
1378    static final int DUPLICATE_PARENT_STATE = 0x00400000;
1379
1380    /**
1381     * <p>
1382     * Indicates this view can be context clicked. When context clickable, a View reacts to a
1383     * context click (e.g. a primary stylus button press or right mouse click) by notifying the
1384     * OnContextClickListener.
1385     * </p>
1386     * {@hide}
1387     */
1388    static final int CONTEXT_CLICKABLE = 0x00800000;
1389
1390
1391    /** @hide */
1392    @IntDef({
1393        SCROLLBARS_INSIDE_OVERLAY,
1394        SCROLLBARS_INSIDE_INSET,
1395        SCROLLBARS_OUTSIDE_OVERLAY,
1396        SCROLLBARS_OUTSIDE_INSET
1397    })
1398    @Retention(RetentionPolicy.SOURCE)
1399    public @interface ScrollBarStyle {}
1400
1401    /**
1402     * The scrollbar style to display the scrollbars inside the content area,
1403     * without increasing the padding. The scrollbars will be overlaid with
1404     * translucency on the view's content.
1405     */
1406    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
1407
1408    /**
1409     * The scrollbar style to display the scrollbars inside the padded area,
1410     * increasing the padding of the view. The scrollbars will not overlap the
1411     * content area of the view.
1412     */
1413    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
1414
1415    /**
1416     * The scrollbar style to display the scrollbars at the edge of the view,
1417     * without increasing the padding. The scrollbars will be overlaid with
1418     * translucency.
1419     */
1420    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
1421
1422    /**
1423     * The scrollbar style to display the scrollbars at the edge of the view,
1424     * increasing the padding of the view. The scrollbars will only overlap the
1425     * background, if any.
1426     */
1427    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
1428
1429    /**
1430     * Mask to check if the scrollbar style is overlay or inset.
1431     * {@hide}
1432     */
1433    static final int SCROLLBARS_INSET_MASK = 0x01000000;
1434
1435    /**
1436     * Mask to check if the scrollbar style is inside or outside.
1437     * {@hide}
1438     */
1439    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
1440
1441    /**
1442     * Mask for scrollbar style.
1443     * {@hide}
1444     */
1445    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
1446
1447    /**
1448     * View flag indicating that the screen should remain on while the
1449     * window containing this view is visible to the user.  This effectively
1450     * takes care of automatically setting the WindowManager's
1451     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
1452     */
1453    public static final int KEEP_SCREEN_ON = 0x04000000;
1454
1455    /**
1456     * View flag indicating whether this view should have sound effects enabled
1457     * for events such as clicking and touching.
1458     */
1459    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
1460
1461    /**
1462     * View flag indicating whether this view should have haptic feedback
1463     * enabled for events such as long presses.
1464     */
1465    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
1466
1467    /**
1468     * <p>Indicates that the view hierarchy should stop saving state when
1469     * it reaches this view.  If state saving is initiated immediately at
1470     * the view, it will be allowed.
1471     * {@hide}
1472     */
1473    static final int PARENT_SAVE_DISABLED = 0x20000000;
1474
1475    /**
1476     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1477     * {@hide}
1478     */
1479    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1480
1481    private static Paint sDebugPaint;
1482
1483    /**
1484     * <p>Indicates this view can display a tooltip on hover or long press.</p>
1485     * {@hide}
1486     */
1487    static final int TOOLTIP = 0x40000000;
1488
1489    /** @hide */
1490    @IntDef(flag = true,
1491            value = {
1492                FOCUSABLES_ALL,
1493                FOCUSABLES_TOUCH_MODE
1494            })
1495    @Retention(RetentionPolicy.SOURCE)
1496    public @interface FocusableMode {}
1497
1498    /**
1499     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1500     * should add all focusable Views regardless if they are focusable in touch mode.
1501     */
1502    public static final int FOCUSABLES_ALL = 0x00000000;
1503
1504    /**
1505     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1506     * should add only Views focusable in touch mode.
1507     */
1508    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1509
1510    /** @hide */
1511    @IntDef({
1512            FOCUS_BACKWARD,
1513            FOCUS_FORWARD,
1514            FOCUS_LEFT,
1515            FOCUS_UP,
1516            FOCUS_RIGHT,
1517            FOCUS_DOWN
1518    })
1519    @Retention(RetentionPolicy.SOURCE)
1520    public @interface FocusDirection {}
1521
1522    /** @hide */
1523    @IntDef({
1524            FOCUS_LEFT,
1525            FOCUS_UP,
1526            FOCUS_RIGHT,
1527            FOCUS_DOWN
1528    })
1529    @Retention(RetentionPolicy.SOURCE)
1530    public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward
1531
1532    /**
1533     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1534     * item.
1535     */
1536    public static final int FOCUS_BACKWARD = 0x00000001;
1537
1538    /**
1539     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1540     * item.
1541     */
1542    public static final int FOCUS_FORWARD = 0x00000002;
1543
1544    /**
1545     * Use with {@link #focusSearch(int)}. Move focus to the left.
1546     */
1547    public static final int FOCUS_LEFT = 0x00000011;
1548
1549    /**
1550     * Use with {@link #focusSearch(int)}. Move focus up.
1551     */
1552    public static final int FOCUS_UP = 0x00000021;
1553
1554    /**
1555     * Use with {@link #focusSearch(int)}. Move focus to the right.
1556     */
1557    public static final int FOCUS_RIGHT = 0x00000042;
1558
1559    /**
1560     * Use with {@link #focusSearch(int)}. Move focus down.
1561     */
1562    public static final int FOCUS_DOWN = 0x00000082;
1563
1564    /**
1565     * Bits of {@link #getMeasuredWidthAndState()} and
1566     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1567     */
1568    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1569
1570    /**
1571     * Bits of {@link #getMeasuredWidthAndState()} and
1572     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1573     */
1574    public static final int MEASURED_STATE_MASK = 0xff000000;
1575
1576    /**
1577     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1578     * for functions that combine both width and height into a single int,
1579     * such as {@link #getMeasuredState()} and the childState argument of
1580     * {@link #resolveSizeAndState(int, int, int)}.
1581     */
1582    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1583
1584    /**
1585     * Bit of {@link #getMeasuredWidthAndState()} and
1586     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1587     * is smaller that the space the view would like to have.
1588     */
1589    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1590
1591    /**
1592     * Base View state sets
1593     */
1594    // Singles
1595    /**
1596     * Indicates the view has no states set. States are used with
1597     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1598     * view depending on its state.
1599     *
1600     * @see android.graphics.drawable.Drawable
1601     * @see #getDrawableState()
1602     */
1603    protected static final int[] EMPTY_STATE_SET;
1604    /**
1605     * Indicates the view is enabled. States are used with
1606     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1607     * view depending on its state.
1608     *
1609     * @see android.graphics.drawable.Drawable
1610     * @see #getDrawableState()
1611     */
1612    protected static final int[] ENABLED_STATE_SET;
1613    /**
1614     * Indicates the view is focused. States are used with
1615     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1616     * view depending on its state.
1617     *
1618     * @see android.graphics.drawable.Drawable
1619     * @see #getDrawableState()
1620     */
1621    protected static final int[] FOCUSED_STATE_SET;
1622    /**
1623     * Indicates the view is selected. States are used with
1624     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1625     * view depending on its state.
1626     *
1627     * @see android.graphics.drawable.Drawable
1628     * @see #getDrawableState()
1629     */
1630    protected static final int[] SELECTED_STATE_SET;
1631    /**
1632     * Indicates the view is pressed. States are used with
1633     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1634     * view depending on its state.
1635     *
1636     * @see android.graphics.drawable.Drawable
1637     * @see #getDrawableState()
1638     */
1639    protected static final int[] PRESSED_STATE_SET;
1640    /**
1641     * Indicates the view's window has focus. States are used with
1642     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1643     * view depending on its state.
1644     *
1645     * @see android.graphics.drawable.Drawable
1646     * @see #getDrawableState()
1647     */
1648    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1649    // Doubles
1650    /**
1651     * Indicates the view is enabled and has the focus.
1652     *
1653     * @see #ENABLED_STATE_SET
1654     * @see #FOCUSED_STATE_SET
1655     */
1656    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1657    /**
1658     * Indicates the view is enabled and selected.
1659     *
1660     * @see #ENABLED_STATE_SET
1661     * @see #SELECTED_STATE_SET
1662     */
1663    protected static final int[] ENABLED_SELECTED_STATE_SET;
1664    /**
1665     * Indicates the view is enabled and that its window has focus.
1666     *
1667     * @see #ENABLED_STATE_SET
1668     * @see #WINDOW_FOCUSED_STATE_SET
1669     */
1670    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1671    /**
1672     * Indicates the view is focused and selected.
1673     *
1674     * @see #FOCUSED_STATE_SET
1675     * @see #SELECTED_STATE_SET
1676     */
1677    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1678    /**
1679     * Indicates the view has the focus and that its window has the focus.
1680     *
1681     * @see #FOCUSED_STATE_SET
1682     * @see #WINDOW_FOCUSED_STATE_SET
1683     */
1684    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1685    /**
1686     * Indicates the view is selected and that its window has the focus.
1687     *
1688     * @see #SELECTED_STATE_SET
1689     * @see #WINDOW_FOCUSED_STATE_SET
1690     */
1691    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1692    // Triples
1693    /**
1694     * Indicates the view is enabled, focused and selected.
1695     *
1696     * @see #ENABLED_STATE_SET
1697     * @see #FOCUSED_STATE_SET
1698     * @see #SELECTED_STATE_SET
1699     */
1700    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1701    /**
1702     * Indicates the view is enabled, focused and its window has the focus.
1703     *
1704     * @see #ENABLED_STATE_SET
1705     * @see #FOCUSED_STATE_SET
1706     * @see #WINDOW_FOCUSED_STATE_SET
1707     */
1708    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1709    /**
1710     * Indicates the view is enabled, selected and its window has the focus.
1711     *
1712     * @see #ENABLED_STATE_SET
1713     * @see #SELECTED_STATE_SET
1714     * @see #WINDOW_FOCUSED_STATE_SET
1715     */
1716    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1717    /**
1718     * Indicates the view is focused, selected and its window has the focus.
1719     *
1720     * @see #FOCUSED_STATE_SET
1721     * @see #SELECTED_STATE_SET
1722     * @see #WINDOW_FOCUSED_STATE_SET
1723     */
1724    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1725    /**
1726     * Indicates the view is enabled, focused, selected and its window
1727     * has the focus.
1728     *
1729     * @see #ENABLED_STATE_SET
1730     * @see #FOCUSED_STATE_SET
1731     * @see #SELECTED_STATE_SET
1732     * @see #WINDOW_FOCUSED_STATE_SET
1733     */
1734    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1735    /**
1736     * Indicates the view is pressed and its window has the focus.
1737     *
1738     * @see #PRESSED_STATE_SET
1739     * @see #WINDOW_FOCUSED_STATE_SET
1740     */
1741    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1742    /**
1743     * Indicates the view is pressed and selected.
1744     *
1745     * @see #PRESSED_STATE_SET
1746     * @see #SELECTED_STATE_SET
1747     */
1748    protected static final int[] PRESSED_SELECTED_STATE_SET;
1749    /**
1750     * Indicates the view is pressed, selected and its window has the focus.
1751     *
1752     * @see #PRESSED_STATE_SET
1753     * @see #SELECTED_STATE_SET
1754     * @see #WINDOW_FOCUSED_STATE_SET
1755     */
1756    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1757    /**
1758     * Indicates the view is pressed and focused.
1759     *
1760     * @see #PRESSED_STATE_SET
1761     * @see #FOCUSED_STATE_SET
1762     */
1763    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1764    /**
1765     * Indicates the view is pressed, focused and its window has the focus.
1766     *
1767     * @see #PRESSED_STATE_SET
1768     * @see #FOCUSED_STATE_SET
1769     * @see #WINDOW_FOCUSED_STATE_SET
1770     */
1771    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1772    /**
1773     * Indicates the view is pressed, focused and selected.
1774     *
1775     * @see #PRESSED_STATE_SET
1776     * @see #SELECTED_STATE_SET
1777     * @see #FOCUSED_STATE_SET
1778     */
1779    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1780    /**
1781     * Indicates the view is pressed, focused, selected and its window has the focus.
1782     *
1783     * @see #PRESSED_STATE_SET
1784     * @see #FOCUSED_STATE_SET
1785     * @see #SELECTED_STATE_SET
1786     * @see #WINDOW_FOCUSED_STATE_SET
1787     */
1788    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1789    /**
1790     * Indicates the view is pressed and enabled.
1791     *
1792     * @see #PRESSED_STATE_SET
1793     * @see #ENABLED_STATE_SET
1794     */
1795    protected static final int[] PRESSED_ENABLED_STATE_SET;
1796    /**
1797     * Indicates the view is pressed, enabled and its window has the focus.
1798     *
1799     * @see #PRESSED_STATE_SET
1800     * @see #ENABLED_STATE_SET
1801     * @see #WINDOW_FOCUSED_STATE_SET
1802     */
1803    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1804    /**
1805     * Indicates the view is pressed, enabled and selected.
1806     *
1807     * @see #PRESSED_STATE_SET
1808     * @see #ENABLED_STATE_SET
1809     * @see #SELECTED_STATE_SET
1810     */
1811    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1812    /**
1813     * Indicates the view is pressed, enabled, selected and its window has the
1814     * focus.
1815     *
1816     * @see #PRESSED_STATE_SET
1817     * @see #ENABLED_STATE_SET
1818     * @see #SELECTED_STATE_SET
1819     * @see #WINDOW_FOCUSED_STATE_SET
1820     */
1821    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1822    /**
1823     * Indicates the view is pressed, enabled and focused.
1824     *
1825     * @see #PRESSED_STATE_SET
1826     * @see #ENABLED_STATE_SET
1827     * @see #FOCUSED_STATE_SET
1828     */
1829    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1830    /**
1831     * Indicates the view is pressed, enabled, focused and its window has the
1832     * focus.
1833     *
1834     * @see #PRESSED_STATE_SET
1835     * @see #ENABLED_STATE_SET
1836     * @see #FOCUSED_STATE_SET
1837     * @see #WINDOW_FOCUSED_STATE_SET
1838     */
1839    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1840    /**
1841     * Indicates the view is pressed, enabled, focused and selected.
1842     *
1843     * @see #PRESSED_STATE_SET
1844     * @see #ENABLED_STATE_SET
1845     * @see #SELECTED_STATE_SET
1846     * @see #FOCUSED_STATE_SET
1847     */
1848    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1849    /**
1850     * Indicates the view is pressed, enabled, focused, selected and its window
1851     * has the focus.
1852     *
1853     * @see #PRESSED_STATE_SET
1854     * @see #ENABLED_STATE_SET
1855     * @see #SELECTED_STATE_SET
1856     * @see #FOCUSED_STATE_SET
1857     * @see #WINDOW_FOCUSED_STATE_SET
1858     */
1859    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1860
1861    static {
1862        EMPTY_STATE_SET = StateSet.get(0);
1863
1864        WINDOW_FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_WINDOW_FOCUSED);
1865
1866        SELECTED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_SELECTED);
1867        SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1868                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED);
1869
1870        FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_FOCUSED);
1871        FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1872                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED);
1873        FOCUSED_SELECTED_STATE_SET = StateSet.get(
1874                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED);
1875        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1876                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1877                        | StateSet.VIEW_STATE_FOCUSED);
1878
1879        ENABLED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_ENABLED);
1880        ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1881                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED);
1882        ENABLED_SELECTED_STATE_SET = StateSet.get(
1883                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED);
1884        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1885                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1886                        | StateSet.VIEW_STATE_ENABLED);
1887        ENABLED_FOCUSED_STATE_SET = StateSet.get(
1888                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED);
1889        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1890                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1891                        | StateSet.VIEW_STATE_ENABLED);
1892        ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1893                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1894                        | StateSet.VIEW_STATE_ENABLED);
1895        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1896                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1897                        | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED);
1898
1899        PRESSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_PRESSED);
1900        PRESSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1901                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1902        PRESSED_SELECTED_STATE_SET = StateSet.get(
1903                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_PRESSED);
1904        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1905                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1906                        | StateSet.VIEW_STATE_PRESSED);
1907        PRESSED_FOCUSED_STATE_SET = StateSet.get(
1908                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1909        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1910                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1911                        | StateSet.VIEW_STATE_PRESSED);
1912        PRESSED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1913                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1914                        | StateSet.VIEW_STATE_PRESSED);
1915        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1916                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1917                        | StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1918        PRESSED_ENABLED_STATE_SET = StateSet.get(
1919                StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1920        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1921                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED
1922                        | StateSet.VIEW_STATE_PRESSED);
1923        PRESSED_ENABLED_SELECTED_STATE_SET = StateSet.get(
1924                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED
1925                        | StateSet.VIEW_STATE_PRESSED);
1926        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1927                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1928                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1929        PRESSED_ENABLED_FOCUSED_STATE_SET = StateSet.get(
1930                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED
1931                        | StateSet.VIEW_STATE_PRESSED);
1932        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1933                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1934                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1935        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1936                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1937                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1938        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1939                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1940                        | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED
1941                        | StateSet.VIEW_STATE_PRESSED);
1942    }
1943
1944    /**
1945     * Accessibility event types that are dispatched for text population.
1946     */
1947    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1948            AccessibilityEvent.TYPE_VIEW_CLICKED
1949            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1950            | AccessibilityEvent.TYPE_VIEW_SELECTED
1951            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1952            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1953            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1954            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1955            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1956            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1957            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1958            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1959
1960    static final int DEBUG_CORNERS_COLOR = Color.rgb(63, 127, 255);
1961
1962    static final int DEBUG_CORNERS_SIZE_DIP = 8;
1963
1964    /**
1965     * Temporary Rect currently for use in setBackground().  This will probably
1966     * be extended in the future to hold our own class with more than just
1967     * a Rect. :)
1968     */
1969    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1970
1971    /**
1972     * Map used to store views' tags.
1973     */
1974    private SparseArray<Object> mKeyedTags;
1975
1976    /**
1977     * The animation currently associated with this view.
1978     * @hide
1979     */
1980    protected Animation mCurrentAnimation = null;
1981
1982    /**
1983     * Width as measured during measure pass.
1984     * {@hide}
1985     */
1986    @ViewDebug.ExportedProperty(category = "measurement")
1987    int mMeasuredWidth;
1988
1989    /**
1990     * Height as measured during measure pass.
1991     * {@hide}
1992     */
1993    @ViewDebug.ExportedProperty(category = "measurement")
1994    int mMeasuredHeight;
1995
1996    /**
1997     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1998     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1999     * its display list. This flag, used only when hw accelerated, allows us to clear the
2000     * flag while retaining this information until it's needed (at getDisplayList() time and
2001     * in drawChild(), when we decide to draw a view's children's display lists into our own).
2002     *
2003     * {@hide}
2004     */
2005    boolean mRecreateDisplayList = false;
2006
2007    /**
2008     * The view's identifier.
2009     * {@hide}
2010     *
2011     * @see #setId(int)
2012     * @see #getId()
2013     */
2014    @IdRes
2015    @ViewDebug.ExportedProperty(resolveId = true)
2016    int mID = NO_ID;
2017
2018    /** The ID of this view for accessibility and autofill purposes.
2019     * <ul>
2020     *     <li>== {@link #NO_ID}: ID has not been assigned yet
2021     *     <li>&le; {@link #LAST_APP_ACCESSIBILITY_ID}: View is not part of a activity. The ID is
2022     *                                                  unique in the process. This might change
2023     *                                                  over activity lifecycle events.
2024     *     <li>&gt; {@link #LAST_APP_ACCESSIBILITY_ID}: View is part of a activity. The ID is
2025     *                                                  unique in the activity. This stays the same
2026     *                                                  over activity lifecycle events.
2027     */
2028    private int mAccessibilityViewId = NO_ID;
2029
2030    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
2031
2032    SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent;
2033
2034    /**
2035     * The view's tag.
2036     * {@hide}
2037     *
2038     * @see #setTag(Object)
2039     * @see #getTag()
2040     */
2041    protected Object mTag = null;
2042
2043    // for mPrivateFlags:
2044    /** {@hide} */
2045    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
2046    /** {@hide} */
2047    static final int PFLAG_FOCUSED                     = 0x00000002;
2048    /** {@hide} */
2049    static final int PFLAG_SELECTED                    = 0x00000004;
2050    /** {@hide} */
2051    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
2052    /** {@hide} */
2053    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
2054    /** {@hide} */
2055    static final int PFLAG_DRAWN                       = 0x00000020;
2056    /**
2057     * When this flag is set, this view is running an animation on behalf of its
2058     * children and should therefore not cancel invalidate requests, even if they
2059     * lie outside of this view's bounds.
2060     *
2061     * {@hide}
2062     */
2063    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
2064    /** {@hide} */
2065    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
2066    /** {@hide} */
2067    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
2068    /** {@hide} */
2069    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
2070    /** {@hide} */
2071    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
2072    /** {@hide} */
2073    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
2074    /** {@hide} */
2075    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
2076
2077    private static final int PFLAG_PRESSED             = 0x00004000;
2078
2079    /** {@hide} */
2080    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
2081    /**
2082     * Flag used to indicate that this view should be drawn once more (and only once
2083     * more) after its animation has completed.
2084     * {@hide}
2085     */
2086    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
2087
2088    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
2089
2090    /**
2091     * Indicates that the View returned true when onSetAlpha() was called and that
2092     * the alpha must be restored.
2093     * {@hide}
2094     */
2095    static final int PFLAG_ALPHA_SET                   = 0x00040000;
2096
2097    /**
2098     * Set by {@link #setScrollContainer(boolean)}.
2099     */
2100    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
2101
2102    /**
2103     * Set by {@link #setScrollContainer(boolean)}.
2104     */
2105    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
2106
2107    /**
2108     * View flag indicating whether this view was invalidated (fully or partially.)
2109     *
2110     * @hide
2111     */
2112    static final int PFLAG_DIRTY                       = 0x00200000;
2113
2114    /**
2115     * View flag indicating whether this view was invalidated by an opaque
2116     * invalidate request.
2117     *
2118     * @hide
2119     */
2120    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
2121
2122    /**
2123     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
2124     *
2125     * @hide
2126     */
2127    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
2128
2129    /**
2130     * Indicates whether the background is opaque.
2131     *
2132     * @hide
2133     */
2134    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
2135
2136    /**
2137     * Indicates whether the scrollbars are opaque.
2138     *
2139     * @hide
2140     */
2141    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
2142
2143    /**
2144     * Indicates whether the view is opaque.
2145     *
2146     * @hide
2147     */
2148    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
2149
2150    /**
2151     * Indicates a prepressed state;
2152     * the short time between ACTION_DOWN and recognizing
2153     * a 'real' press. Prepressed is used to recognize quick taps
2154     * even when they are shorter than ViewConfiguration.getTapTimeout().
2155     *
2156     * @hide
2157     */
2158    private static final int PFLAG_PREPRESSED          = 0x02000000;
2159
2160    /**
2161     * Indicates whether the view is temporarily detached.
2162     *
2163     * @hide
2164     */
2165    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
2166
2167    /**
2168     * Indicates that we should awaken scroll bars once attached
2169     *
2170     * PLEASE NOTE: This flag is now unused as we now send onVisibilityChanged
2171     * during window attachment and it is no longer needed. Feel free to repurpose it.
2172     *
2173     * @hide
2174     */
2175    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
2176
2177    /**
2178     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
2179     * @hide
2180     */
2181    private static final int PFLAG_HOVERED             = 0x10000000;
2182
2183    /**
2184     * no longer needed, should be reused
2185     */
2186    private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000;
2187
2188    /** {@hide} */
2189    static final int PFLAG_ACTIVATED                   = 0x40000000;
2190
2191    /**
2192     * Indicates that this view was specifically invalidated, not just dirtied because some
2193     * child view was invalidated. The flag is used to determine when we need to recreate
2194     * a view's display list (as opposed to just returning a reference to its existing
2195     * display list).
2196     *
2197     * @hide
2198     */
2199    static final int PFLAG_INVALIDATED                 = 0x80000000;
2200
2201    /**
2202     * Masks for mPrivateFlags2, as generated by dumpFlags():
2203     *
2204     * |-------|-------|-------|-------|
2205     *                                 1 PFLAG2_DRAG_CAN_ACCEPT
2206     *                                1  PFLAG2_DRAG_HOVERED
2207     *                              11   PFLAG2_LAYOUT_DIRECTION_MASK
2208     *                             1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
2209     *                            1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
2210     *                            11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
2211     *                           1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
2212     *                          1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
2213     *                          11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
2214     *                         1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
2215     *                         1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
2216     *                         11        PFLAG2_TEXT_DIRECTION_FLAGS[6]
2217     *                         111       PFLAG2_TEXT_DIRECTION_FLAGS[7]
2218     *                         111       PFLAG2_TEXT_DIRECTION_MASK
2219     *                        1          PFLAG2_TEXT_DIRECTION_RESOLVED
2220     *                       1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
2221     *                     111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
2222     *                    1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
2223     *                   1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
2224     *                   11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
2225     *                  1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
2226     *                  1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
2227     *                  11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
2228     *                  111              PFLAG2_TEXT_ALIGNMENT_MASK
2229     *                 1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
2230     *                1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
2231     *              111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
2232     *           111                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
2233     *         11                        PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK
2234     *       1                           PFLAG2_ACCESSIBILITY_FOCUSED
2235     *      1                            PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED
2236     *     1                             PFLAG2_VIEW_QUICK_REJECTED
2237     *    1                              PFLAG2_PADDING_RESOLVED
2238     *   1                               PFLAG2_DRAWABLE_RESOLVED
2239     *  1                                PFLAG2_HAS_TRANSIENT_STATE
2240     * |-------|-------|-------|-------|
2241     */
2242
2243    /**
2244     * Indicates that this view has reported that it can accept the current drag's content.
2245     * Cleared when the drag operation concludes.
2246     * @hide
2247     */
2248    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
2249
2250    /**
2251     * Indicates that this view is currently directly under the drag location in a
2252     * drag-and-drop operation involving content that it can accept.  Cleared when
2253     * the drag exits the view, or when the drag operation concludes.
2254     * @hide
2255     */
2256    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
2257
2258    /** @hide */
2259    @IntDef({
2260        LAYOUT_DIRECTION_LTR,
2261        LAYOUT_DIRECTION_RTL,
2262        LAYOUT_DIRECTION_INHERIT,
2263        LAYOUT_DIRECTION_LOCALE
2264    })
2265    @Retention(RetentionPolicy.SOURCE)
2266    // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection
2267    public @interface LayoutDir {}
2268
2269    /** @hide */
2270    @IntDef({
2271        LAYOUT_DIRECTION_LTR,
2272        LAYOUT_DIRECTION_RTL
2273    })
2274    @Retention(RetentionPolicy.SOURCE)
2275    public @interface ResolvedLayoutDir {}
2276
2277    /**
2278     * A flag to indicate that the layout direction of this view has not been defined yet.
2279     * @hide
2280     */
2281    public static final int LAYOUT_DIRECTION_UNDEFINED = LayoutDirection.UNDEFINED;
2282
2283    /**
2284     * Horizontal layout direction of this view is from Left to Right.
2285     * Use with {@link #setLayoutDirection}.
2286     */
2287    public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR;
2288
2289    /**
2290     * Horizontal layout direction of this view is from Right to Left.
2291     * Use with {@link #setLayoutDirection}.
2292     */
2293    public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL;
2294
2295    /**
2296     * Horizontal layout direction of this view is inherited from its parent.
2297     * Use with {@link #setLayoutDirection}.
2298     */
2299    public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT;
2300
2301    /**
2302     * Horizontal layout direction of this view is from deduced from the default language
2303     * script for the locale. Use with {@link #setLayoutDirection}.
2304     */
2305    public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE;
2306
2307    /**
2308     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2309     * @hide
2310     */
2311    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
2312
2313    /**
2314     * Mask for use with private flags indicating bits used for horizontal layout direction.
2315     * @hide
2316     */
2317    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2318
2319    /**
2320     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
2321     * right-to-left direction.
2322     * @hide
2323     */
2324    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2325
2326    /**
2327     * Indicates whether the view horizontal layout direction has been resolved.
2328     * @hide
2329     */
2330    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2331
2332    /**
2333     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
2334     * @hide
2335     */
2336    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
2337            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2338
2339    /*
2340     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
2341     * flag value.
2342     * @hide
2343     */
2344    private static final int[] LAYOUT_DIRECTION_FLAGS = {
2345            LAYOUT_DIRECTION_LTR,
2346            LAYOUT_DIRECTION_RTL,
2347            LAYOUT_DIRECTION_INHERIT,
2348            LAYOUT_DIRECTION_LOCALE
2349    };
2350
2351    /**
2352     * Default horizontal layout direction.
2353     */
2354    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
2355
2356    /**
2357     * Default horizontal layout direction.
2358     * @hide
2359     */
2360    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
2361
2362    /**
2363     * Text direction is inherited through {@link ViewGroup}
2364     */
2365    public static final int TEXT_DIRECTION_INHERIT = 0;
2366
2367    /**
2368     * Text direction is using "first strong algorithm". The first strong directional character
2369     * determines the paragraph direction. If there is no strong directional character, the
2370     * paragraph direction is the view's resolved layout direction.
2371     */
2372    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
2373
2374    /**
2375     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
2376     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
2377     * If there are neither, the paragraph direction is the view's resolved layout direction.
2378     */
2379    public static final int TEXT_DIRECTION_ANY_RTL = 2;
2380
2381    /**
2382     * Text direction is forced to LTR.
2383     */
2384    public static final int TEXT_DIRECTION_LTR = 3;
2385
2386    /**
2387     * Text direction is forced to RTL.
2388     */
2389    public static final int TEXT_DIRECTION_RTL = 4;
2390
2391    /**
2392     * Text direction is coming from the system Locale.
2393     */
2394    public static final int TEXT_DIRECTION_LOCALE = 5;
2395
2396    /**
2397     * Text direction is using "first strong algorithm". The first strong directional character
2398     * determines the paragraph direction. If there is no strong directional character, the
2399     * paragraph direction is LTR.
2400     */
2401    public static final int TEXT_DIRECTION_FIRST_STRONG_LTR = 6;
2402
2403    /**
2404     * Text direction is using "first strong algorithm". The first strong directional character
2405     * determines the paragraph direction. If there is no strong directional character, the
2406     * paragraph direction is RTL.
2407     */
2408    public static final int TEXT_DIRECTION_FIRST_STRONG_RTL = 7;
2409
2410    /**
2411     * Default text direction is inherited
2412     */
2413    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
2414
2415    /**
2416     * Default resolved text direction
2417     * @hide
2418     */
2419    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
2420
2421    /**
2422     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
2423     * @hide
2424     */
2425    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
2426
2427    /**
2428     * Mask for use with private flags indicating bits used for text direction.
2429     * @hide
2430     */
2431    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
2432            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2433
2434    /**
2435     * Array of text direction flags for mapping attribute "textDirection" to correct
2436     * flag value.
2437     * @hide
2438     */
2439    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
2440            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2441            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2442            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2443            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2444            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2445            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2446            TEXT_DIRECTION_FIRST_STRONG_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2447            TEXT_DIRECTION_FIRST_STRONG_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
2448    };
2449
2450    /**
2451     * Indicates whether the view text direction has been resolved.
2452     * @hide
2453     */
2454    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
2455            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2456
2457    /**
2458     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2459     * @hide
2460     */
2461    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
2462
2463    /**
2464     * Mask for use with private flags indicating bits used for resolved text direction.
2465     * @hide
2466     */
2467    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
2468            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2469
2470    /**
2471     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
2472     * @hide
2473     */
2474    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
2475            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2476
2477    /** @hide */
2478    @IntDef({
2479        TEXT_ALIGNMENT_INHERIT,
2480        TEXT_ALIGNMENT_GRAVITY,
2481        TEXT_ALIGNMENT_CENTER,
2482        TEXT_ALIGNMENT_TEXT_START,
2483        TEXT_ALIGNMENT_TEXT_END,
2484        TEXT_ALIGNMENT_VIEW_START,
2485        TEXT_ALIGNMENT_VIEW_END
2486    })
2487    @Retention(RetentionPolicy.SOURCE)
2488    public @interface TextAlignment {}
2489
2490    /**
2491     * Default text alignment. The text alignment of this View is inherited from its parent.
2492     * Use with {@link #setTextAlignment(int)}
2493     */
2494    public static final int TEXT_ALIGNMENT_INHERIT = 0;
2495
2496    /**
2497     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
2498     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
2499     *
2500     * Use with {@link #setTextAlignment(int)}
2501     */
2502    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
2503
2504    /**
2505     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2506     *
2507     * Use with {@link #setTextAlignment(int)}
2508     */
2509    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2510
2511    /**
2512     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2513     *
2514     * Use with {@link #setTextAlignment(int)}
2515     */
2516    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2517
2518    /**
2519     * Center the paragraph, e.g. ALIGN_CENTER.
2520     *
2521     * Use with {@link #setTextAlignment(int)}
2522     */
2523    public static final int TEXT_ALIGNMENT_CENTER = 4;
2524
2525    /**
2526     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2527     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2528     *
2529     * Use with {@link #setTextAlignment(int)}
2530     */
2531    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2532
2533    /**
2534     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2535     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2536     *
2537     * Use with {@link #setTextAlignment(int)}
2538     */
2539    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2540
2541    /**
2542     * Default text alignment is inherited
2543     */
2544    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2545
2546    /**
2547     * Default resolved text alignment
2548     * @hide
2549     */
2550    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2551
2552    /**
2553      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2554      * @hide
2555      */
2556    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2557
2558    /**
2559      * Mask for use with private flags indicating bits used for text alignment.
2560      * @hide
2561      */
2562    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2563
2564    /**
2565     * Array of text direction flags for mapping attribute "textAlignment" to correct
2566     * flag value.
2567     * @hide
2568     */
2569    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2570            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2571            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2572            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2573            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2574            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2575            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2576            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2577    };
2578
2579    /**
2580     * Indicates whether the view text alignment has been resolved.
2581     * @hide
2582     */
2583    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2584
2585    /**
2586     * Bit shift to get the resolved text alignment.
2587     * @hide
2588     */
2589    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2590
2591    /**
2592     * Mask for use with private flags indicating bits used for text alignment.
2593     * @hide
2594     */
2595    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2596            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2597
2598    /**
2599     * Indicates whether if the view text alignment has been resolved to gravity
2600     */
2601    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2602            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2603
2604    // Accessiblity constants for mPrivateFlags2
2605
2606    /**
2607     * Shift for the bits in {@link #mPrivateFlags2} related to the
2608     * "importantForAccessibility" attribute.
2609     */
2610    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2611
2612    /**
2613     * Automatically determine whether a view is important for accessibility.
2614     */
2615    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2616
2617    /**
2618     * The view is important for accessibility.
2619     */
2620    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2621
2622    /**
2623     * The view is not important for accessibility.
2624     */
2625    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2626
2627    /**
2628     * The view is not important for accessibility, nor are any of its
2629     * descendant views.
2630     */
2631    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004;
2632
2633    /**
2634     * The default whether the view is important for accessibility.
2635     */
2636    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2637
2638    /**
2639     * Mask for obtaining the bits which specify how to determine
2640     * whether a view is important for accessibility.
2641     */
2642    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2643        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO
2644        | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS)
2645        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2646
2647    /**
2648     * Shift for the bits in {@link #mPrivateFlags2} related to the
2649     * "accessibilityLiveRegion" attribute.
2650     */
2651    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23;
2652
2653    /**
2654     * Live region mode specifying that accessibility services should not
2655     * automatically announce changes to this view. This is the default live
2656     * region mode for most views.
2657     * <p>
2658     * Use with {@link #setAccessibilityLiveRegion(int)}.
2659     */
2660    public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000;
2661
2662    /**
2663     * Live region mode specifying that accessibility services should announce
2664     * changes to this view.
2665     * <p>
2666     * Use with {@link #setAccessibilityLiveRegion(int)}.
2667     */
2668    public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001;
2669
2670    /**
2671     * Live region mode specifying that accessibility services should interrupt
2672     * ongoing speech to immediately announce changes to this view.
2673     * <p>
2674     * Use with {@link #setAccessibilityLiveRegion(int)}.
2675     */
2676    public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002;
2677
2678    /**
2679     * The default whether the view is important for accessibility.
2680     */
2681    static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE;
2682
2683    /**
2684     * Mask for obtaining the bits which specify a view's accessibility live
2685     * region mode.
2686     */
2687    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE
2688            | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE)
2689            << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
2690
2691    /**
2692     * Flag indicating whether a view has accessibility focus.
2693     */
2694    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000;
2695
2696    /**
2697     * Flag whether the accessibility state of the subtree rooted at this view changed.
2698     */
2699    static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000;
2700
2701    /**
2702     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2703     * is used to check whether later changes to the view's transform should invalidate the
2704     * view to force the quickReject test to run again.
2705     */
2706    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2707
2708    /**
2709     * Flag indicating that start/end padding has been resolved into left/right padding
2710     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2711     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2712     * during measurement. In some special cases this is required such as when an adapter-based
2713     * view measures prospective children without attaching them to a window.
2714     */
2715    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2716
2717    /**
2718     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2719     */
2720    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2721
2722    /**
2723     * Indicates that the view is tracking some sort of transient state
2724     * that the app should not need to be aware of, but that the framework
2725     * should take special care to preserve.
2726     */
2727    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000;
2728
2729    /**
2730     * Group of bits indicating that RTL properties resolution is done.
2731     */
2732    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2733            PFLAG2_TEXT_DIRECTION_RESOLVED |
2734            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2735            PFLAG2_PADDING_RESOLVED |
2736            PFLAG2_DRAWABLE_RESOLVED;
2737
2738    // There are a couple of flags left in mPrivateFlags2
2739
2740    /* End of masks for mPrivateFlags2 */
2741
2742    /**
2743     * Masks for mPrivateFlags3, as generated by dumpFlags():
2744     *
2745     * |-------|-------|-------|-------|
2746     *                                 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM
2747     *                                1  PFLAG3_VIEW_IS_ANIMATING_ALPHA
2748     *                               1   PFLAG3_IS_LAID_OUT
2749     *                              1    PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT
2750     *                             1     PFLAG3_CALLED_SUPER
2751     *                            1      PFLAG3_APPLYING_INSETS
2752     *                           1       PFLAG3_FITTING_SYSTEM_WINDOWS
2753     *                          1        PFLAG3_NESTED_SCROLLING_ENABLED
2754     *                         1         PFLAG3_SCROLL_INDICATOR_TOP
2755     *                        1          PFLAG3_SCROLL_INDICATOR_BOTTOM
2756     *                       1           PFLAG3_SCROLL_INDICATOR_LEFT
2757     *                      1            PFLAG3_SCROLL_INDICATOR_RIGHT
2758     *                     1             PFLAG3_SCROLL_INDICATOR_START
2759     *                    1              PFLAG3_SCROLL_INDICATOR_END
2760     *                   1               PFLAG3_ASSIST_BLOCKED
2761     *                  1                PFLAG3_CLUSTER
2762     *                 1                 PFLAG3_IS_AUTOFILLED
2763     *                1                  PFLAG3_FINGER_DOWN
2764     *               1                   PFLAG3_FOCUSED_BY_DEFAULT
2765     *             11                    PFLAG3_AUTO_FILL_MODE_MASK
2766     *           11                      PFLAG3_IMPORTANT_FOR_AUTOFILL
2767     *          1                        PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE
2768     *         1                         PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED
2769     *        1                          PFLAG3_TEMPORARY_DETACH
2770     *       1                           PFLAG3_NO_REVEAL_ON_FOCUS
2771     * |-------|-------|-------|-------|
2772     */
2773
2774    /**
2775     * Flag indicating that view has a transform animation set on it. This is used to track whether
2776     * an animation is cleared between successive frames, in order to tell the associated
2777     * DisplayList to clear its animation matrix.
2778     */
2779    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2780
2781    /**
2782     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2783     * animation is cleared between successive frames, in order to tell the associated
2784     * DisplayList to restore its alpha value.
2785     */
2786    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2787
2788    /**
2789     * Flag indicating that the view has been through at least one layout since it
2790     * was last attached to a window.
2791     */
2792    static final int PFLAG3_IS_LAID_OUT = 0x4;
2793
2794    /**
2795     * Flag indicating that a call to measure() was skipped and should be done
2796     * instead when layout() is invoked.
2797     */
2798    static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8;
2799
2800    /**
2801     * Flag indicating that an overridden method correctly called down to
2802     * the superclass implementation as required by the API spec.
2803     */
2804    static final int PFLAG3_CALLED_SUPER = 0x10;
2805
2806    /**
2807     * Flag indicating that we're in the process of applying window insets.
2808     */
2809    static final int PFLAG3_APPLYING_INSETS = 0x20;
2810
2811    /**
2812     * Flag indicating that we're in the process of fitting system windows using the old method.
2813     */
2814    static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40;
2815
2816    /**
2817     * Flag indicating that nested scrolling is enabled for this view.
2818     * The view will optionally cooperate with views up its parent chain to allow for
2819     * integrated nested scrolling along the same axis.
2820     */
2821    static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80;
2822
2823    /**
2824     * Flag indicating that the bottom scroll indicator should be displayed
2825     * when this view can scroll up.
2826     */
2827    static final int PFLAG3_SCROLL_INDICATOR_TOP = 0x0100;
2828
2829    /**
2830     * Flag indicating that the bottom scroll indicator should be displayed
2831     * when this view can scroll down.
2832     */
2833    static final int PFLAG3_SCROLL_INDICATOR_BOTTOM = 0x0200;
2834
2835    /**
2836     * Flag indicating that the left scroll indicator should be displayed
2837     * when this view can scroll left.
2838     */
2839    static final int PFLAG3_SCROLL_INDICATOR_LEFT = 0x0400;
2840
2841    /**
2842     * Flag indicating that the right scroll indicator should be displayed
2843     * when this view can scroll right.
2844     */
2845    static final int PFLAG3_SCROLL_INDICATOR_RIGHT = 0x0800;
2846
2847    /**
2848     * Flag indicating that the start scroll indicator should be displayed
2849     * when this view can scroll in the start direction.
2850     */
2851    static final int PFLAG3_SCROLL_INDICATOR_START = 0x1000;
2852
2853    /**
2854     * Flag indicating that the end scroll indicator should be displayed
2855     * when this view can scroll in the end direction.
2856     */
2857    static final int PFLAG3_SCROLL_INDICATOR_END = 0x2000;
2858
2859    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2860
2861    static final int SCROLL_INDICATORS_NONE = 0x0000;
2862
2863    /**
2864     * Mask for use with setFlags indicating bits used for indicating which
2865     * scroll indicators are enabled.
2866     */
2867    static final int SCROLL_INDICATORS_PFLAG3_MASK = PFLAG3_SCROLL_INDICATOR_TOP
2868            | PFLAG3_SCROLL_INDICATOR_BOTTOM | PFLAG3_SCROLL_INDICATOR_LEFT
2869            | PFLAG3_SCROLL_INDICATOR_RIGHT | PFLAG3_SCROLL_INDICATOR_START
2870            | PFLAG3_SCROLL_INDICATOR_END;
2871
2872    /**
2873     * Left-shift required to translate between public scroll indicator flags
2874     * and internal PFLAGS3 flags. When used as a right-shift, translates
2875     * PFLAGS3 flags to public flags.
2876     */
2877    static final int SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT = 8;
2878
2879    /** @hide */
2880    @Retention(RetentionPolicy.SOURCE)
2881    @IntDef(flag = true,
2882            value = {
2883                    SCROLL_INDICATOR_TOP,
2884                    SCROLL_INDICATOR_BOTTOM,
2885                    SCROLL_INDICATOR_LEFT,
2886                    SCROLL_INDICATOR_RIGHT,
2887                    SCROLL_INDICATOR_START,
2888                    SCROLL_INDICATOR_END,
2889            })
2890    public @interface ScrollIndicators {}
2891
2892    /**
2893     * Scroll indicator direction for the top edge of the view.
2894     *
2895     * @see #setScrollIndicators(int)
2896     * @see #setScrollIndicators(int, int)
2897     * @see #getScrollIndicators()
2898     */
2899    public static final int SCROLL_INDICATOR_TOP =
2900            PFLAG3_SCROLL_INDICATOR_TOP >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2901
2902    /**
2903     * Scroll indicator direction for the bottom edge of the view.
2904     *
2905     * @see #setScrollIndicators(int)
2906     * @see #setScrollIndicators(int, int)
2907     * @see #getScrollIndicators()
2908     */
2909    public static final int SCROLL_INDICATOR_BOTTOM =
2910            PFLAG3_SCROLL_INDICATOR_BOTTOM >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2911
2912    /**
2913     * Scroll indicator direction for the left edge of the view.
2914     *
2915     * @see #setScrollIndicators(int)
2916     * @see #setScrollIndicators(int, int)
2917     * @see #getScrollIndicators()
2918     */
2919    public static final int SCROLL_INDICATOR_LEFT =
2920            PFLAG3_SCROLL_INDICATOR_LEFT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2921
2922    /**
2923     * Scroll indicator direction for the right edge of the view.
2924     *
2925     * @see #setScrollIndicators(int)
2926     * @see #setScrollIndicators(int, int)
2927     * @see #getScrollIndicators()
2928     */
2929    public static final int SCROLL_INDICATOR_RIGHT =
2930            PFLAG3_SCROLL_INDICATOR_RIGHT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2931
2932    /**
2933     * Scroll indicator direction for the starting edge of the view.
2934     * <p>
2935     * Resolved according to the view's layout direction, see
2936     * {@link #getLayoutDirection()} for more information.
2937     *
2938     * @see #setScrollIndicators(int)
2939     * @see #setScrollIndicators(int, int)
2940     * @see #getScrollIndicators()
2941     */
2942    public static final int SCROLL_INDICATOR_START =
2943            PFLAG3_SCROLL_INDICATOR_START >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2944
2945    /**
2946     * Scroll indicator direction for the ending edge of the view.
2947     * <p>
2948     * Resolved according to the view's layout direction, see
2949     * {@link #getLayoutDirection()} for more information.
2950     *
2951     * @see #setScrollIndicators(int)
2952     * @see #setScrollIndicators(int, int)
2953     * @see #getScrollIndicators()
2954     */
2955    public static final int SCROLL_INDICATOR_END =
2956            PFLAG3_SCROLL_INDICATOR_END >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2957
2958    /**
2959     * <p>Indicates that we are allowing {@link ViewStructure} to traverse
2960     * into this view.<p>
2961     */
2962    static final int PFLAG3_ASSIST_BLOCKED = 0x4000;
2963
2964    /**
2965     * Flag indicating that the view is a root of a keyboard navigation cluster.
2966     *
2967     * @see #isKeyboardNavigationCluster()
2968     * @see #setKeyboardNavigationCluster(boolean)
2969     */
2970    private static final int PFLAG3_CLUSTER = 0x8000;
2971
2972    /**
2973     * Flag indicating that the view is autofilled
2974     *
2975     * @see #isAutofilled()
2976     * @see #setAutofilled(boolean)
2977     */
2978    private static final int PFLAG3_IS_AUTOFILLED = 0x10000;
2979
2980    /**
2981     * Indicates that the user is currently touching the screen.
2982     * Currently used for the tooltip positioning only.
2983     */
2984    private static final int PFLAG3_FINGER_DOWN = 0x20000;
2985
2986    /**
2987     * Flag indicating that this view is the default-focus view.
2988     *
2989     * @see #isFocusedByDefault()
2990     * @see #setFocusedByDefault(boolean)
2991     */
2992    private static final int PFLAG3_FOCUSED_BY_DEFAULT = 0x40000;
2993
2994    /**
2995     * Shift for the place where the autofill mode is stored in the pflags
2996     *
2997     * @see #getAutofillMode()
2998     * @see #setAutofillMode(int)
2999     */
3000    private static final int PFLAG3_AUTOFILL_MODE_SHIFT = 19;
3001
3002    /**
3003     * Mask for autofill modes
3004     *
3005     * @see #getAutofillMode()
3006     * @see #setAutofillMode(int)
3007     */
3008    private static final int PFLAG3_AUTOFILL_MODE_MASK = (AUTOFILL_MODE_INHERIT
3009            | AUTOFILL_MODE_AUTO | AUTOFILL_MODE_MANUAL) << PFLAG3_AUTOFILL_MODE_SHIFT;
3010
3011    /**
3012     * Shift for the bits in {@link #mPrivateFlags3} related to the
3013     * "importantForAutofill" attribute.
3014     */
3015    static final int PFLAG3_IMPORTANT_FOR_AUTOFILL_SHIFT = 21;
3016
3017    /**
3018     * Mask for obtaining the bits which specify how to determine
3019     * whether a view is important for autofill.
3020     */
3021    static final int PFLAG3_IMPORTANT_FOR_AUTOFILL_MASK = (IMPORTANT_FOR_AUTOFILL_AUTO
3022            | IMPORTANT_FOR_AUTOFILL_YES | IMPORTANT_FOR_AUTOFILL_NO)
3023            << PFLAG3_IMPORTANT_FOR_AUTOFILL_SHIFT;
3024
3025    /**
3026     * Whether this view has rendered elements that overlap (see {@link
3027     * #hasOverlappingRendering()}, {@link #forceHasOverlappingRendering(boolean)}, and
3028     * {@link #getHasOverlappingRendering()} ). The value in this bit is only valid when
3029     * PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED has been set. Otherwise, the value is
3030     * determined by whatever {@link #hasOverlappingRendering()} returns.
3031     */
3032    private static final int PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE = 0x800000;
3033
3034    /**
3035     * Whether {@link #forceHasOverlappingRendering(boolean)} has been called. When true, value
3036     * in PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE is valid.
3037     */
3038    private static final int PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED = 0x1000000;
3039
3040    /**
3041     * Flag indicating that the view is temporarily detached from the parent view.
3042     *
3043     * @see #onStartTemporaryDetach()
3044     * @see #onFinishTemporaryDetach()
3045     */
3046    static final int PFLAG3_TEMPORARY_DETACH = 0x2000000;
3047
3048    /**
3049     * Flag indicating that the view does not wish to be revealed within its parent
3050     * hierarchy when it gains focus. Expressed in the negative since the historical
3051     * default behavior is to reveal on focus; this flag suppresses that behavior.
3052     *
3053     * @see #setRevealOnFocusHint(boolean)
3054     * @see #getRevealOnFocusHint()
3055     */
3056    private static final int PFLAG3_NO_REVEAL_ON_FOCUS = 0x4000000;
3057
3058    /* End of masks for mPrivateFlags3 */
3059
3060    /**
3061     * Always allow a user to over-scroll this view, provided it is a
3062     * view that can scroll.
3063     *
3064     * @see #getOverScrollMode()
3065     * @see #setOverScrollMode(int)
3066     */
3067    public static final int OVER_SCROLL_ALWAYS = 0;
3068
3069    /**
3070     * Allow a user to over-scroll this view only if the content is large
3071     * enough to meaningfully scroll, provided it is a view that can scroll.
3072     *
3073     * @see #getOverScrollMode()
3074     * @see #setOverScrollMode(int)
3075     */
3076    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
3077
3078    /**
3079     * Never allow a user to over-scroll this view.
3080     *
3081     * @see #getOverScrollMode()
3082     * @see #setOverScrollMode(int)
3083     */
3084    public static final int OVER_SCROLL_NEVER = 2;
3085
3086    /**
3087     * Special constant for {@link #setSystemUiVisibility(int)}: View has
3088     * requested the system UI (status bar) to be visible (the default).
3089     *
3090     * @see #setSystemUiVisibility(int)
3091     */
3092    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
3093
3094    /**
3095     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
3096     * system UI to enter an unobtrusive "low profile" mode.
3097     *
3098     * <p>This is for use in games, book readers, video players, or any other
3099     * "immersive" application where the usual system chrome is deemed too distracting.
3100     *
3101     * <p>In low profile mode, the status bar and/or navigation icons may dim.
3102     *
3103     * @see #setSystemUiVisibility(int)
3104     */
3105    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
3106
3107    /**
3108     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
3109     * system navigation be temporarily hidden.
3110     *
3111     * <p>This is an even less obtrusive state than that called for by
3112     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
3113     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
3114     * those to disappear. This is useful (in conjunction with the
3115     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
3116     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
3117     * window flags) for displaying content using every last pixel on the display.
3118     *
3119     * <p>There is a limitation: because navigation controls are so important, the least user
3120     * interaction will cause them to reappear immediately.  When this happens, both
3121     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
3122     * so that both elements reappear at the same time.
3123     *
3124     * @see #setSystemUiVisibility(int)
3125     */
3126    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
3127
3128    /**
3129     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
3130     * into the normal fullscreen mode so that its content can take over the screen
3131     * while still allowing the user to interact with the application.
3132     *
3133     * <p>This has the same visual effect as
3134     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
3135     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
3136     * meaning that non-critical screen decorations (such as the status bar) will be
3137     * hidden while the user is in the View's window, focusing the experience on
3138     * that content.  Unlike the window flag, if you are using ActionBar in
3139     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
3140     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
3141     * hide the action bar.
3142     *
3143     * <p>This approach to going fullscreen is best used over the window flag when
3144     * it is a transient state -- that is, the application does this at certain
3145     * points in its user interaction where it wants to allow the user to focus
3146     * on content, but not as a continuous state.  For situations where the application
3147     * would like to simply stay full screen the entire time (such as a game that
3148     * wants to take over the screen), the
3149     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
3150     * is usually a better approach.  The state set here will be removed by the system
3151     * in various situations (such as the user moving to another application) like
3152     * the other system UI states.
3153     *
3154     * <p>When using this flag, the application should provide some easy facility
3155     * for the user to go out of it.  A common example would be in an e-book
3156     * reader, where tapping on the screen brings back whatever screen and UI
3157     * decorations that had been hidden while the user was immersed in reading
3158     * the book.
3159     *
3160     * @see #setSystemUiVisibility(int)
3161     */
3162    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
3163
3164    /**
3165     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
3166     * flags, we would like a stable view of the content insets given to
3167     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
3168     * will always represent the worst case that the application can expect
3169     * as a continuous state.  In the stock Android UI this is the space for
3170     * the system bar, nav bar, and status bar, but not more transient elements
3171     * such as an input method.
3172     *
3173     * The stable layout your UI sees is based on the system UI modes you can
3174     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
3175     * then you will get a stable layout for changes of the
3176     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
3177     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
3178     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
3179     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
3180     * with a stable layout.  (Note that you should avoid using
3181     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
3182     *
3183     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
3184     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
3185     * then a hidden status bar will be considered a "stable" state for purposes
3186     * here.  This allows your UI to continually hide the status bar, while still
3187     * using the system UI flags to hide the action bar while still retaining
3188     * a stable layout.  Note that changing the window fullscreen flag will never
3189     * provide a stable layout for a clean transition.
3190     *
3191     * <p>If you are using ActionBar in
3192     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
3193     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
3194     * insets it adds to those given to the application.
3195     */
3196    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
3197
3198    /**
3199     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
3200     * to be laid out as if it has requested
3201     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
3202     * allows it to avoid artifacts when switching in and out of that mode, at
3203     * the expense that some of its user interface may be covered by screen
3204     * decorations when they are shown.  You can perform layout of your inner
3205     * UI elements to account for the navigation system UI through the
3206     * {@link #fitSystemWindows(Rect)} method.
3207     */
3208    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
3209
3210    /**
3211     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
3212     * to be laid out as if it has requested
3213     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
3214     * allows it to avoid artifacts when switching in and out of that mode, at
3215     * the expense that some of its user interface may be covered by screen
3216     * decorations when they are shown.  You can perform layout of your inner
3217     * UI elements to account for non-fullscreen system UI through the
3218     * {@link #fitSystemWindows(Rect)} method.
3219     */
3220    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
3221
3222    /**
3223     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
3224     * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  If this flag is
3225     * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any
3226     * user interaction.
3227     * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only
3228     * has an effect when used in combination with that flag.</p>
3229     */
3230    public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800;
3231
3232    /**
3233     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
3234     * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation
3235     * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  Use this flag to create an immersive
3236     * experience while also hiding the system bars.  If this flag is not set,
3237     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user
3238     * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system
3239     * if the user swipes from the top of the screen.
3240     * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with
3241     * system gestures, such as swiping from the top of the screen.  These transient system bars
3242     * will overlay app’s content, may have some degree of transparency, and will automatically
3243     * hide after a short timeout.
3244     * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and
3245     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination
3246     * with one or both of those flags.</p>
3247     */
3248    public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000;
3249
3250    /**
3251     * Flag for {@link #setSystemUiVisibility(int)}: Requests the status bar to draw in a mode that
3252     * is compatible with light status bar backgrounds.
3253     *
3254     * <p>For this to take effect, the window must request
3255     * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS
3256     *         FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not
3257     * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_STATUS
3258     *         FLAG_TRANSLUCENT_STATUS}.
3259     *
3260     * @see android.R.attr#windowLightStatusBar
3261     */
3262    public static final int SYSTEM_UI_FLAG_LIGHT_STATUS_BAR = 0x00002000;
3263
3264    /**
3265     * This flag was previously used for a private API. DO NOT reuse it for a public API as it might
3266     * trigger undefined behavior on older platforms with apps compiled against a new SDK.
3267     */
3268    private static final int SYSTEM_UI_RESERVED_LEGACY1 = 0x00004000;
3269
3270    /**
3271     * This flag was previously used for a private API. DO NOT reuse it for a public API as it might
3272     * trigger undefined behavior on older platforms with apps compiled against a new SDK.
3273     */
3274    private static final int SYSTEM_UI_RESERVED_LEGACY2 = 0x00010000;
3275
3276    /**
3277     * Flag for {@link #setSystemUiVisibility(int)}: Requests the navigation bar to draw in a mode
3278     * that is compatible with light navigation bar backgrounds.
3279     *
3280     * <p>For this to take effect, the window must request
3281     * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS
3282     *         FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not
3283     * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_NAVIGATION
3284     *         FLAG_TRANSLUCENT_NAVIGATION}.
3285     */
3286    public static final int SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR = 0x00000010;
3287
3288    /**
3289     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
3290     */
3291    @Deprecated
3292    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
3293
3294    /**
3295     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
3296     */
3297    @Deprecated
3298    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
3299
3300    /**
3301     * @hide
3302     *
3303     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3304     * out of the public fields to keep the undefined bits out of the developer's way.
3305     *
3306     * Flag to make the status bar not expandable.  Unless you also
3307     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
3308     */
3309    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
3310
3311    /**
3312     * @hide
3313     *
3314     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3315     * out of the public fields to keep the undefined bits out of the developer's way.
3316     *
3317     * Flag to hide notification icons and scrolling ticker text.
3318     */
3319    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
3320
3321    /**
3322     * @hide
3323     *
3324     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3325     * out of the public fields to keep the undefined bits out of the developer's way.
3326     *
3327     * Flag to disable incoming notification alerts.  This will not block
3328     * icons, but it will block sound, vibrating and other visual or aural notifications.
3329     */
3330    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
3331
3332    /**
3333     * @hide
3334     *
3335     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3336     * out of the public fields to keep the undefined bits out of the developer's way.
3337     *
3338     * Flag to hide only the scrolling ticker.  Note that
3339     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
3340     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
3341     */
3342    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
3343
3344    /**
3345     * @hide
3346     *
3347     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3348     * out of the public fields to keep the undefined bits out of the developer's way.
3349     *
3350     * Flag to hide the center system info area.
3351     */
3352    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
3353
3354    /**
3355     * @hide
3356     *
3357     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3358     * out of the public fields to keep the undefined bits out of the developer's way.
3359     *
3360     * Flag to hide only the home button.  Don't use this
3361     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3362     */
3363    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
3364
3365    /**
3366     * @hide
3367     *
3368     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3369     * out of the public fields to keep the undefined bits out of the developer's way.
3370     *
3371     * Flag to hide only the back button. Don't use this
3372     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3373     */
3374    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
3375
3376    /**
3377     * @hide
3378     *
3379     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3380     * out of the public fields to keep the undefined bits out of the developer's way.
3381     *
3382     * Flag to hide only the clock.  You might use this if your activity has
3383     * its own clock making the status bar's clock redundant.
3384     */
3385    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
3386
3387    /**
3388     * @hide
3389     *
3390     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3391     * out of the public fields to keep the undefined bits out of the developer's way.
3392     *
3393     * Flag to hide only the recent apps button. Don't use this
3394     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3395     */
3396    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
3397
3398    /**
3399     * @hide
3400     *
3401     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3402     * out of the public fields to keep the undefined bits out of the developer's way.
3403     *
3404     * Flag to disable the global search gesture. Don't use this
3405     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3406     */
3407    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
3408
3409    /**
3410     * @hide
3411     *
3412     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3413     * out of the public fields to keep the undefined bits out of the developer's way.
3414     *
3415     * Flag to specify that the status bar is displayed in transient mode.
3416     */
3417    public static final int STATUS_BAR_TRANSIENT = 0x04000000;
3418
3419    /**
3420     * @hide
3421     *
3422     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3423     * out of the public fields to keep the undefined bits out of the developer's way.
3424     *
3425     * Flag to specify that the navigation bar is displayed in transient mode.
3426     */
3427    public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000;
3428
3429    /**
3430     * @hide
3431     *
3432     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3433     * out of the public fields to keep the undefined bits out of the developer's way.
3434     *
3435     * Flag to specify that the hidden status bar would like to be shown.
3436     */
3437    public static final int STATUS_BAR_UNHIDE = 0x10000000;
3438
3439    /**
3440     * @hide
3441     *
3442     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3443     * out of the public fields to keep the undefined bits out of the developer's way.
3444     *
3445     * Flag to specify that the hidden navigation bar would like to be shown.
3446     */
3447    public static final int NAVIGATION_BAR_UNHIDE = 0x20000000;
3448
3449    /**
3450     * @hide
3451     *
3452     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3453     * out of the public fields to keep the undefined bits out of the developer's way.
3454     *
3455     * Flag to specify that the status bar is displayed in translucent mode.
3456     */
3457    public static final int STATUS_BAR_TRANSLUCENT = 0x40000000;
3458
3459    /**
3460     * @hide
3461     *
3462     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3463     * out of the public fields to keep the undefined bits out of the developer's way.
3464     *
3465     * Flag to specify that the navigation bar is displayed in translucent mode.
3466     */
3467    public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000;
3468
3469    /**
3470     * @hide
3471     *
3472     * Makes navigation bar transparent (but not the status bar).
3473     */
3474    public static final int NAVIGATION_BAR_TRANSPARENT = 0x00008000;
3475
3476    /**
3477     * @hide
3478     *
3479     * Makes status bar transparent (but not the navigation bar).
3480     */
3481    public static final int STATUS_BAR_TRANSPARENT = 0x00000008;
3482
3483    /**
3484     * @hide
3485     *
3486     * Makes both status bar and navigation bar transparent.
3487     */
3488    public static final int SYSTEM_UI_TRANSPARENT = NAVIGATION_BAR_TRANSPARENT
3489            | STATUS_BAR_TRANSPARENT;
3490
3491    /**
3492     * @hide
3493     */
3494    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FF7;
3495
3496    /**
3497     * These are the system UI flags that can be cleared by events outside
3498     * of an application.  Currently this is just the ability to tap on the
3499     * screen while hiding the navigation bar to have it return.
3500     * @hide
3501     */
3502    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
3503            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
3504            | SYSTEM_UI_FLAG_FULLSCREEN;
3505
3506    /**
3507     * Flags that can impact the layout in relation to system UI.
3508     */
3509    public static final int SYSTEM_UI_LAYOUT_FLAGS =
3510            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
3511            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
3512
3513    /** @hide */
3514    @IntDef(flag = true,
3515            value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION })
3516    @Retention(RetentionPolicy.SOURCE)
3517    public @interface FindViewFlags {}
3518
3519    /**
3520     * Find views that render the specified text.
3521     *
3522     * @see #findViewsWithText(ArrayList, CharSequence, int)
3523     */
3524    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
3525
3526    /**
3527     * Find find views that contain the specified content description.
3528     *
3529     * @see #findViewsWithText(ArrayList, CharSequence, int)
3530     */
3531    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
3532
3533    /**
3534     * Find views that contain {@link AccessibilityNodeProvider}. Such
3535     * a View is a root of virtual view hierarchy and may contain the searched
3536     * text. If this flag is set Views with providers are automatically
3537     * added and it is a responsibility of the client to call the APIs of
3538     * the provider to determine whether the virtual tree rooted at this View
3539     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
3540     * representing the virtual views with this text.
3541     *
3542     * @see #findViewsWithText(ArrayList, CharSequence, int)
3543     *
3544     * @hide
3545     */
3546    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
3547
3548    /**
3549     * The undefined cursor position.
3550     *
3551     * @hide
3552     */
3553    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
3554
3555    /**
3556     * Indicates that the screen has changed state and is now off.
3557     *
3558     * @see #onScreenStateChanged(int)
3559     */
3560    public static final int SCREEN_STATE_OFF = 0x0;
3561
3562    /**
3563     * Indicates that the screen has changed state and is now on.
3564     *
3565     * @see #onScreenStateChanged(int)
3566     */
3567    public static final int SCREEN_STATE_ON = 0x1;
3568
3569    /**
3570     * Indicates no axis of view scrolling.
3571     */
3572    public static final int SCROLL_AXIS_NONE = 0;
3573
3574    /**
3575     * Indicates scrolling along the horizontal axis.
3576     */
3577    public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0;
3578
3579    /**
3580     * Indicates scrolling along the vertical axis.
3581     */
3582    public static final int SCROLL_AXIS_VERTICAL = 1 << 1;
3583
3584    /**
3585     * Controls the over-scroll mode for this view.
3586     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
3587     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
3588     * and {@link #OVER_SCROLL_NEVER}.
3589     */
3590    private int mOverScrollMode;
3591
3592    /**
3593     * The parent this view is attached to.
3594     * {@hide}
3595     *
3596     * @see #getParent()
3597     */
3598    protected ViewParent mParent;
3599
3600    /**
3601     * {@hide}
3602     */
3603    AttachInfo mAttachInfo;
3604
3605    /**
3606     * {@hide}
3607     */
3608    @ViewDebug.ExportedProperty(flagMapping = {
3609        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
3610                name = "FORCE_LAYOUT"),
3611        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
3612                name = "LAYOUT_REQUIRED"),
3613        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
3614            name = "DRAWING_CACHE_INVALID", outputIf = false),
3615        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
3616        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
3617        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
3618        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
3619    }, formatToHexString = true)
3620
3621    /* @hide */
3622    public int mPrivateFlags;
3623    int mPrivateFlags2;
3624    int mPrivateFlags3;
3625
3626    /**
3627     * This view's request for the visibility of the status bar.
3628     * @hide
3629     */
3630    @ViewDebug.ExportedProperty(flagMapping = {
3631        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
3632                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
3633                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
3634        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
3635                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
3636                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
3637        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
3638                                equals = SYSTEM_UI_FLAG_VISIBLE,
3639                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
3640    }, formatToHexString = true)
3641    int mSystemUiVisibility;
3642
3643    /**
3644     * Reference count for transient state.
3645     * @see #setHasTransientState(boolean)
3646     */
3647    int mTransientStateCount = 0;
3648
3649    /**
3650     * Count of how many windows this view has been attached to.
3651     */
3652    int mWindowAttachCount;
3653
3654    /**
3655     * The layout parameters associated with this view and used by the parent
3656     * {@link android.view.ViewGroup} to determine how this view should be
3657     * laid out.
3658     * {@hide}
3659     */
3660    protected ViewGroup.LayoutParams mLayoutParams;
3661
3662    /**
3663     * The view flags hold various views states.
3664     * {@hide}
3665     */
3666    @ViewDebug.ExportedProperty(formatToHexString = true)
3667    int mViewFlags;
3668
3669    static class TransformationInfo {
3670        /**
3671         * The transform matrix for the View. This transform is calculated internally
3672         * based on the translation, rotation, and scale properties.
3673         *
3674         * Do *not* use this variable directly; instead call getMatrix(), which will
3675         * load the value from the View's RenderNode.
3676         */
3677        private final Matrix mMatrix = new Matrix();
3678
3679        /**
3680         * The inverse transform matrix for the View. This transform is calculated
3681         * internally based on the translation, rotation, and scale properties.
3682         *
3683         * Do *not* use this variable directly; instead call getInverseMatrix(),
3684         * which will load the value from the View's RenderNode.
3685         */
3686        private Matrix mInverseMatrix;
3687
3688        /**
3689         * The opacity of the View. This is a value from 0 to 1, where 0 means
3690         * completely transparent and 1 means completely opaque.
3691         */
3692        @ViewDebug.ExportedProperty
3693        float mAlpha = 1f;
3694
3695        /**
3696         * The opacity of the view as manipulated by the Fade transition. This is a hidden
3697         * property only used by transitions, which is composited with the other alpha
3698         * values to calculate the final visual alpha value.
3699         */
3700        float mTransitionAlpha = 1f;
3701    }
3702
3703    /** @hide */
3704    public TransformationInfo mTransformationInfo;
3705
3706    /**
3707     * Current clip bounds. to which all drawing of this view are constrained.
3708     */
3709    Rect mClipBounds = null;
3710
3711    private boolean mLastIsOpaque;
3712
3713    /**
3714     * The distance in pixels from the left edge of this view's parent
3715     * to the left edge of this view.
3716     * {@hide}
3717     */
3718    @ViewDebug.ExportedProperty(category = "layout")
3719    protected int mLeft;
3720    /**
3721     * The distance in pixels from the left edge of this view's parent
3722     * to the right edge of this view.
3723     * {@hide}
3724     */
3725    @ViewDebug.ExportedProperty(category = "layout")
3726    protected int mRight;
3727    /**
3728     * The distance in pixels from the top edge of this view's parent
3729     * to the top edge of this view.
3730     * {@hide}
3731     */
3732    @ViewDebug.ExportedProperty(category = "layout")
3733    protected int mTop;
3734    /**
3735     * The distance in pixels from the top edge of this view's parent
3736     * to the bottom edge of this view.
3737     * {@hide}
3738     */
3739    @ViewDebug.ExportedProperty(category = "layout")
3740    protected int mBottom;
3741
3742    /**
3743     * The offset, in pixels, by which the content of this view is scrolled
3744     * horizontally.
3745     * {@hide}
3746     */
3747    @ViewDebug.ExportedProperty(category = "scrolling")
3748    protected int mScrollX;
3749    /**
3750     * The offset, in pixels, by which the content of this view is scrolled
3751     * vertically.
3752     * {@hide}
3753     */
3754    @ViewDebug.ExportedProperty(category = "scrolling")
3755    protected int mScrollY;
3756
3757    /**
3758     * The left padding in pixels, that is the distance in pixels between the
3759     * left edge of this view and the left edge of its content.
3760     * {@hide}
3761     */
3762    @ViewDebug.ExportedProperty(category = "padding")
3763    protected int mPaddingLeft = 0;
3764    /**
3765     * The right padding in pixels, that is the distance in pixels between the
3766     * right edge of this view and the right edge of its content.
3767     * {@hide}
3768     */
3769    @ViewDebug.ExportedProperty(category = "padding")
3770    protected int mPaddingRight = 0;
3771    /**
3772     * The top padding in pixels, that is the distance in pixels between the
3773     * top edge of this view and the top edge of its content.
3774     * {@hide}
3775     */
3776    @ViewDebug.ExportedProperty(category = "padding")
3777    protected int mPaddingTop;
3778    /**
3779     * The bottom padding in pixels, that is the distance in pixels between the
3780     * bottom edge of this view and the bottom edge of its content.
3781     * {@hide}
3782     */
3783    @ViewDebug.ExportedProperty(category = "padding")
3784    protected int mPaddingBottom;
3785
3786    /**
3787     * The layout insets in pixels, that is the distance in pixels between the
3788     * visible edges of this view its bounds.
3789     */
3790    private Insets mLayoutInsets;
3791
3792    /**
3793     * Briefly describes the view and is primarily used for accessibility support.
3794     */
3795    private CharSequence mContentDescription;
3796
3797    /**
3798     * Specifies the id of a view for which this view serves as a label for
3799     * accessibility purposes.
3800     */
3801    private int mLabelForId = View.NO_ID;
3802
3803    /**
3804     * Predicate for matching labeled view id with its label for
3805     * accessibility purposes.
3806     */
3807    private MatchLabelForPredicate mMatchLabelForPredicate;
3808
3809    /**
3810     * Specifies a view before which this one is visited in accessibility traversal.
3811     */
3812    private int mAccessibilityTraversalBeforeId = NO_ID;
3813
3814    /**
3815     * Specifies a view after which this one is visited in accessibility traversal.
3816     */
3817    private int mAccessibilityTraversalAfterId = NO_ID;
3818
3819    /**
3820     * Predicate for matching a view by its id.
3821     */
3822    private MatchIdPredicate mMatchIdPredicate;
3823
3824    /**
3825     * Cache the paddingRight set by the user to append to the scrollbar's size.
3826     *
3827     * @hide
3828     */
3829    @ViewDebug.ExportedProperty(category = "padding")
3830    protected int mUserPaddingRight;
3831
3832    /**
3833     * Cache the paddingBottom set by the user to append to the scrollbar's size.
3834     *
3835     * @hide
3836     */
3837    @ViewDebug.ExportedProperty(category = "padding")
3838    protected int mUserPaddingBottom;
3839
3840    /**
3841     * Cache the paddingLeft set by the user to append to the scrollbar's size.
3842     *
3843     * @hide
3844     */
3845    @ViewDebug.ExportedProperty(category = "padding")
3846    protected int mUserPaddingLeft;
3847
3848    /**
3849     * Cache the paddingStart set by the user to append to the scrollbar's size.
3850     *
3851     */
3852    @ViewDebug.ExportedProperty(category = "padding")
3853    int mUserPaddingStart;
3854
3855    /**
3856     * Cache the paddingEnd set by the user to append to the scrollbar's size.
3857     *
3858     */
3859    @ViewDebug.ExportedProperty(category = "padding")
3860    int mUserPaddingEnd;
3861
3862    /**
3863     * Cache initial left padding.
3864     *
3865     * @hide
3866     */
3867    int mUserPaddingLeftInitial;
3868
3869    /**
3870     * Cache initial right padding.
3871     *
3872     * @hide
3873     */
3874    int mUserPaddingRightInitial;
3875
3876    /**
3877     * Default undefined padding
3878     */
3879    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
3880
3881    /**
3882     * Cache if a left padding has been defined
3883     */
3884    private boolean mLeftPaddingDefined = false;
3885
3886    /**
3887     * Cache if a right padding has been defined
3888     */
3889    private boolean mRightPaddingDefined = false;
3890
3891    /**
3892     * @hide
3893     */
3894    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
3895    /**
3896     * @hide
3897     */
3898    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
3899
3900    private LongSparseLongArray mMeasureCache;
3901
3902    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
3903    private Drawable mBackground;
3904    private TintInfo mBackgroundTint;
3905
3906    @ViewDebug.ExportedProperty(deepExport = true, prefix = "fg_")
3907    private ForegroundInfo mForegroundInfo;
3908
3909    private Drawable mScrollIndicatorDrawable;
3910
3911    /**
3912     * RenderNode used for backgrounds.
3913     * <p>
3914     * When non-null and valid, this is expected to contain an up-to-date copy
3915     * of the background drawable. It is cleared on temporary detach, and reset
3916     * on cleanup.
3917     */
3918    private RenderNode mBackgroundRenderNode;
3919
3920    private int mBackgroundResource;
3921    private boolean mBackgroundSizeChanged;
3922
3923    /** The default focus highlight.
3924     * @see #mDefaultFocusHighlightEnabled
3925     * @see Drawable#hasFocusStateSpecified()
3926     */
3927    private Drawable mDefaultFocusHighlight;
3928    private Drawable mDefaultFocusHighlightCache;
3929    private boolean mDefaultFocusHighlightSizeChanged;
3930
3931    private String mTransitionName;
3932
3933    static class TintInfo {
3934        ColorStateList mTintList;
3935        PorterDuff.Mode mTintMode;
3936        boolean mHasTintMode;
3937        boolean mHasTintList;
3938    }
3939
3940    private static class ForegroundInfo {
3941        private Drawable mDrawable;
3942        private TintInfo mTintInfo;
3943        private int mGravity = Gravity.FILL;
3944        private boolean mInsidePadding = true;
3945        private boolean mBoundsChanged = true;
3946        private final Rect mSelfBounds = new Rect();
3947        private final Rect mOverlayBounds = new Rect();
3948    }
3949
3950    static class ListenerInfo {
3951        /**
3952         * Listener used to dispatch focus change events.
3953         * This field should be made private, so it is hidden from the SDK.
3954         * {@hide}
3955         */
3956        protected OnFocusChangeListener mOnFocusChangeListener;
3957
3958        /**
3959         * Listeners for layout change events.
3960         */
3961        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
3962
3963        protected OnScrollChangeListener mOnScrollChangeListener;
3964
3965        /**
3966         * Listeners for attach events.
3967         */
3968        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
3969
3970        /**
3971         * Listener used to dispatch click events.
3972         * This field should be made private, so it is hidden from the SDK.
3973         * {@hide}
3974         */
3975        public OnClickListener mOnClickListener;
3976
3977        /**
3978         * Listener used to dispatch long click events.
3979         * This field should be made private, so it is hidden from the SDK.
3980         * {@hide}
3981         */
3982        protected OnLongClickListener mOnLongClickListener;
3983
3984        /**
3985         * Listener used to dispatch context click events. This field should be made private, so it
3986         * is hidden from the SDK.
3987         * {@hide}
3988         */
3989        protected OnContextClickListener mOnContextClickListener;
3990
3991        /**
3992         * Listener used to build the context menu.
3993         * This field should be made private, so it is hidden from the SDK.
3994         * {@hide}
3995         */
3996        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
3997
3998        private OnKeyListener mOnKeyListener;
3999
4000        private OnTouchListener mOnTouchListener;
4001
4002        private OnHoverListener mOnHoverListener;
4003
4004        private OnGenericMotionListener mOnGenericMotionListener;
4005
4006        private OnDragListener mOnDragListener;
4007
4008        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
4009
4010        OnApplyWindowInsetsListener mOnApplyWindowInsetsListener;
4011
4012        OnCapturedPointerListener mOnCapturedPointerListener;
4013    }
4014
4015    ListenerInfo mListenerInfo;
4016
4017    private static class TooltipInfo {
4018        /**
4019         * Text to be displayed in a tooltip popup.
4020         */
4021        @Nullable
4022        CharSequence mTooltipText;
4023
4024        /**
4025         * View-relative position of the tooltip anchor point.
4026         */
4027        int mAnchorX;
4028        int mAnchorY;
4029
4030        /**
4031         * The tooltip popup.
4032         */
4033        @Nullable
4034        TooltipPopup mTooltipPopup;
4035
4036        /**
4037         * Set to true if the tooltip was shown as a result of a long click.
4038         */
4039        boolean mTooltipFromLongClick;
4040
4041        /**
4042         * Keep these Runnables so that they can be used to reschedule.
4043         */
4044        Runnable mShowTooltipRunnable;
4045        Runnable mHideTooltipRunnable;
4046    }
4047
4048    TooltipInfo mTooltipInfo;
4049
4050    // Temporary values used to hold (x,y) coordinates when delegating from the
4051    // two-arg performLongClick() method to the legacy no-arg version.
4052    private float mLongClickX = Float.NaN;
4053    private float mLongClickY = Float.NaN;
4054
4055    /**
4056     * The application environment this view lives in.
4057     * This field should be made private, so it is hidden from the SDK.
4058     * {@hide}
4059     */
4060    @ViewDebug.ExportedProperty(deepExport = true)
4061    protected Context mContext;
4062
4063    private final Resources mResources;
4064
4065    private ScrollabilityCache mScrollCache;
4066
4067    private int[] mDrawableState = null;
4068
4069    ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND;
4070
4071    /**
4072     * Animator that automatically runs based on state changes.
4073     */
4074    private StateListAnimator mStateListAnimator;
4075
4076    /**
4077     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
4078     * the user may specify which view to go to next.
4079     */
4080    private int mNextFocusLeftId = View.NO_ID;
4081
4082    /**
4083     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
4084     * the user may specify which view to go to next.
4085     */
4086    private int mNextFocusRightId = View.NO_ID;
4087
4088    /**
4089     * When this view has focus and the next focus is {@link #FOCUS_UP},
4090     * the user may specify which view to go to next.
4091     */
4092    private int mNextFocusUpId = View.NO_ID;
4093
4094    /**
4095     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
4096     * the user may specify which view to go to next.
4097     */
4098    private int mNextFocusDownId = View.NO_ID;
4099
4100    /**
4101     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
4102     * the user may specify which view to go to next.
4103     */
4104    int mNextFocusForwardId = View.NO_ID;
4105
4106    /**
4107     * User-specified next keyboard navigation cluster in the {@link #FOCUS_FORWARD} direction.
4108     *
4109     * @see #findUserSetNextKeyboardNavigationCluster(View, int)
4110     */
4111    int mNextClusterForwardId = View.NO_ID;
4112
4113    /**
4114     * Whether this View should use a default focus highlight when it gets focused but doesn't
4115     * have {@link android.R.attr#state_focused} defined in its background.
4116     */
4117    boolean mDefaultFocusHighlightEnabled = true;
4118
4119    private CheckForLongPress mPendingCheckForLongPress;
4120    private CheckForTap mPendingCheckForTap = null;
4121    private PerformClick mPerformClick;
4122    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
4123
4124    private UnsetPressedState mUnsetPressedState;
4125
4126    /**
4127     * Whether the long press's action has been invoked.  The tap's action is invoked on the
4128     * up event while a long press is invoked as soon as the long press duration is reached, so
4129     * a long press could be performed before the tap is checked, in which case the tap's action
4130     * should not be invoked.
4131     */
4132    private boolean mHasPerformedLongPress;
4133
4134    /**
4135     * Whether a context click button is currently pressed down. This is true when the stylus is
4136     * touching the screen and the primary button has been pressed, or if a mouse's right button is
4137     * pressed. This is false once the button is released or if the stylus has been lifted.
4138     */
4139    private boolean mInContextButtonPress;
4140
4141    /**
4142     * Whether the next up event should be ignored for the purposes of gesture recognition. This is
4143     * true after a stylus button press has occured, when the next up event should not be recognized
4144     * as a tap.
4145     */
4146    private boolean mIgnoreNextUpEvent;
4147
4148    /**
4149     * The minimum height of the view. We'll try our best to have the height
4150     * of this view to at least this amount.
4151     */
4152    @ViewDebug.ExportedProperty(category = "measurement")
4153    private int mMinHeight;
4154
4155    /**
4156     * The minimum width of the view. We'll try our best to have the width
4157     * of this view to at least this amount.
4158     */
4159    @ViewDebug.ExportedProperty(category = "measurement")
4160    private int mMinWidth;
4161
4162    /**
4163     * The delegate to handle touch events that are physically in this view
4164     * but should be handled by another view.
4165     */
4166    private TouchDelegate mTouchDelegate = null;
4167
4168    /**
4169     * Solid color to use as a background when creating the drawing cache. Enables
4170     * the cache to use 16 bit bitmaps instead of 32 bit.
4171     */
4172    private int mDrawingCacheBackgroundColor = 0;
4173
4174    /**
4175     * Special tree observer used when mAttachInfo is null.
4176     */
4177    private ViewTreeObserver mFloatingTreeObserver;
4178
4179    /**
4180     * Cache the touch slop from the context that created the view.
4181     */
4182    private int mTouchSlop;
4183
4184    /**
4185     * Object that handles automatic animation of view properties.
4186     */
4187    private ViewPropertyAnimator mAnimator = null;
4188
4189    /**
4190     * List of registered FrameMetricsObservers.
4191     */
4192    private ArrayList<FrameMetricsObserver> mFrameMetricsObservers;
4193
4194    /**
4195     * Flag indicating that a drag can cross window boundaries.  When
4196     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called
4197     * with this flag set, all visible applications with targetSdkVersion >=
4198     * {@link android.os.Build.VERSION_CODES#N API 24} will be able to participate
4199     * in the drag operation and receive the dragged content.
4200     *
4201     * <p>If this is the only flag set, then the drag recipient will only have access to text data
4202     * and intents contained in the {@link ClipData} object. Access to URIs contained in the
4203     * {@link ClipData} is determined by other DRAG_FLAG_GLOBAL_* flags</p>
4204     */
4205    public static final int DRAG_FLAG_GLOBAL = 1 << 8;  // 256
4206
4207    /**
4208     * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to
4209     * request read access to the content URI(s) contained in the {@link ClipData} object.
4210     * @see android.content.Intent#FLAG_GRANT_READ_URI_PERMISSION
4211     */
4212    public static final int DRAG_FLAG_GLOBAL_URI_READ = Intent.FLAG_GRANT_READ_URI_PERMISSION;
4213
4214    /**
4215     * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to
4216     * request write access to the content URI(s) contained in the {@link ClipData} object.
4217     * @see android.content.Intent#FLAG_GRANT_WRITE_URI_PERMISSION
4218     */
4219    public static final int DRAG_FLAG_GLOBAL_URI_WRITE = Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
4220
4221    /**
4222     * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link
4223     * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant can be persisted across device
4224     * reboots until explicitly revoked with
4225     * {@link android.content.Context#revokeUriPermission(Uri, int)} Context.revokeUriPermission}.
4226     * @see android.content.Intent#FLAG_GRANT_PERSISTABLE_URI_PERMISSION
4227     */
4228    public static final int DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION =
4229            Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION;
4230
4231    /**
4232     * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link
4233     * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant applies to any URI that is a prefix
4234     * match against the original granted URI.
4235     * @see android.content.Intent#FLAG_GRANT_PREFIX_URI_PERMISSION
4236     */
4237    public static final int DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION =
4238            Intent.FLAG_GRANT_PREFIX_URI_PERMISSION;
4239
4240    /**
4241     * Flag indicating that the drag shadow will be opaque.  When
4242     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called
4243     * with this flag set, the drag shadow will be opaque, otherwise, it will be semitransparent.
4244     */
4245    public static final int DRAG_FLAG_OPAQUE = 1 << 9;
4246
4247    /**
4248     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
4249     */
4250    private float mVerticalScrollFactor;
4251
4252    /**
4253     * Position of the vertical scroll bar.
4254     */
4255    private int mVerticalScrollbarPosition;
4256
4257    /**
4258     * Position the scroll bar at the default position as determined by the system.
4259     */
4260    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
4261
4262    /**
4263     * Position the scroll bar along the left edge.
4264     */
4265    public static final int SCROLLBAR_POSITION_LEFT = 1;
4266
4267    /**
4268     * Position the scroll bar along the right edge.
4269     */
4270    public static final int SCROLLBAR_POSITION_RIGHT = 2;
4271
4272    /**
4273     * Indicates that the view does not have a layer.
4274     *
4275     * @see #getLayerType()
4276     * @see #setLayerType(int, android.graphics.Paint)
4277     * @see #LAYER_TYPE_SOFTWARE
4278     * @see #LAYER_TYPE_HARDWARE
4279     */
4280    public static final int LAYER_TYPE_NONE = 0;
4281
4282    /**
4283     * <p>Indicates that the view has a software layer. A software layer is backed
4284     * by a bitmap and causes the view to be rendered using Android's software
4285     * rendering pipeline, even if hardware acceleration is enabled.</p>
4286     *
4287     * <p>Software layers have various usages:</p>
4288     * <p>When the application is not using hardware acceleration, a software layer
4289     * is useful to apply a specific color filter and/or blending mode and/or
4290     * translucency to a view and all its children.</p>
4291     * <p>When the application is using hardware acceleration, a software layer
4292     * is useful to render drawing primitives not supported by the hardware
4293     * accelerated pipeline. It can also be used to cache a complex view tree
4294     * into a texture and reduce the complexity of drawing operations. For instance,
4295     * when animating a complex view tree with a translation, a software layer can
4296     * be used to render the view tree only once.</p>
4297     * <p>Software layers should be avoided when the affected view tree updates
4298     * often. Every update will require to re-render the software layer, which can
4299     * potentially be slow (particularly when hardware acceleration is turned on
4300     * since the layer will have to be uploaded into a hardware texture after every
4301     * update.)</p>
4302     *
4303     * @see #getLayerType()
4304     * @see #setLayerType(int, android.graphics.Paint)
4305     * @see #LAYER_TYPE_NONE
4306     * @see #LAYER_TYPE_HARDWARE
4307     */
4308    public static final int LAYER_TYPE_SOFTWARE = 1;
4309
4310    /**
4311     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
4312     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
4313     * OpenGL hardware) and causes the view to be rendered using Android's hardware
4314     * rendering pipeline, but only if hardware acceleration is turned on for the
4315     * view hierarchy. When hardware acceleration is turned off, hardware layers
4316     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
4317     *
4318     * <p>A hardware layer is useful to apply a specific color filter and/or
4319     * blending mode and/or translucency to a view and all its children.</p>
4320     * <p>A hardware layer can be used to cache a complex view tree into a
4321     * texture and reduce the complexity of drawing operations. For instance,
4322     * when animating a complex view tree with a translation, a hardware layer can
4323     * be used to render the view tree only once.</p>
4324     * <p>A hardware layer can also be used to increase the rendering quality when
4325     * rotation transformations are applied on a view. It can also be used to
4326     * prevent potential clipping issues when applying 3D transforms on a view.</p>
4327     *
4328     * @see #getLayerType()
4329     * @see #setLayerType(int, android.graphics.Paint)
4330     * @see #LAYER_TYPE_NONE
4331     * @see #LAYER_TYPE_SOFTWARE
4332     */
4333    public static final int LAYER_TYPE_HARDWARE = 2;
4334
4335    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
4336            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
4337            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
4338            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
4339    })
4340    int mLayerType = LAYER_TYPE_NONE;
4341    Paint mLayerPaint;
4342
4343    /**
4344     * Set to true when drawing cache is enabled and cannot be created.
4345     *
4346     * @hide
4347     */
4348    public boolean mCachingFailed;
4349    private Bitmap mDrawingCache;
4350    private Bitmap mUnscaledDrawingCache;
4351
4352    /**
4353     * RenderNode holding View properties, potentially holding a DisplayList of View content.
4354     * <p>
4355     * When non-null and valid, this is expected to contain an up-to-date copy
4356     * of the View content. Its DisplayList content is cleared on temporary detach and reset on
4357     * cleanup.
4358     */
4359    final RenderNode mRenderNode;
4360
4361    /**
4362     * Set to true when the view is sending hover accessibility events because it
4363     * is the innermost hovered view.
4364     */
4365    private boolean mSendingHoverAccessibilityEvents;
4366
4367    /**
4368     * Delegate for injecting accessibility functionality.
4369     */
4370    AccessibilityDelegate mAccessibilityDelegate;
4371
4372    /**
4373     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
4374     * and add/remove objects to/from the overlay directly through the Overlay methods.
4375     */
4376    ViewOverlay mOverlay;
4377
4378    /**
4379     * The currently active parent view for receiving delegated nested scrolling events.
4380     * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared
4381     * by {@link #stopNestedScroll()} at the same point where we clear
4382     * requestDisallowInterceptTouchEvent.
4383     */
4384    private ViewParent mNestedScrollingParent;
4385
4386    /**
4387     * Consistency verifier for debugging purposes.
4388     * @hide
4389     */
4390    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
4391            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
4392                    new InputEventConsistencyVerifier(this, 0) : null;
4393
4394    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
4395
4396    private int[] mTempNestedScrollConsumed;
4397
4398    /**
4399     * An overlay is going to draw this View instead of being drawn as part of this
4400     * View's parent. mGhostView is the View in the Overlay that must be invalidated
4401     * when this view is invalidated.
4402     */
4403    GhostView mGhostView;
4404
4405    /**
4406     * Holds pairs of adjacent attribute data: attribute name followed by its value.
4407     * @hide
4408     */
4409    @ViewDebug.ExportedProperty(category = "attributes", hasAdjacentMapping = true)
4410    public String[] mAttributes;
4411
4412    /**
4413     * Maps a Resource id to its name.
4414     */
4415    private static SparseArray<String> mAttributeMap;
4416
4417    /**
4418     * Queue of pending runnables. Used to postpone calls to post() until this
4419     * view is attached and has a handler.
4420     */
4421    private HandlerActionQueue mRunQueue;
4422
4423    /**
4424     * The pointer icon when the mouse hovers on this view. The default is null.
4425     */
4426    private PointerIcon mPointerIcon;
4427
4428    /**
4429     * @hide
4430     */
4431    String mStartActivityRequestWho;
4432
4433    @Nullable
4434    private RoundScrollbarRenderer mRoundScrollbarRenderer;
4435
4436    /**
4437     * Simple constructor to use when creating a view from code.
4438     *
4439     * @param context The Context the view is running in, through which it can
4440     *        access the current theme, resources, etc.
4441     */
4442    public View(Context context) {
4443        mContext = context;
4444        mResources = context != null ? context.getResources() : null;
4445        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED | FOCUSABLE_AUTO;
4446        // Set some flags defaults
4447        mPrivateFlags2 =
4448                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
4449                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
4450                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
4451                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
4452                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
4453                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
4454        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
4455        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
4456        mUserPaddingStart = UNDEFINED_PADDING;
4457        mUserPaddingEnd = UNDEFINED_PADDING;
4458        mRenderNode = RenderNode.create(getClass().getName(), this);
4459
4460        if (!sCompatibilityDone && context != null) {
4461            final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
4462
4463            // Older apps may need this compatibility hack for measurement.
4464            sUseBrokenMakeMeasureSpec = targetSdkVersion <= Build.VERSION_CODES.JELLY_BEAN_MR1;
4465
4466            // Older apps expect onMeasure() to always be called on a layout pass, regardless
4467            // of whether a layout was requested on that View.
4468            sIgnoreMeasureCache = targetSdkVersion < Build.VERSION_CODES.KITKAT;
4469
4470            Canvas.sCompatibilityRestore = targetSdkVersion < Build.VERSION_CODES.M;
4471
4472            // In M and newer, our widgets can pass a "hint" value in the size
4473            // for UNSPECIFIED MeasureSpecs. This lets child views of scrolling containers
4474            // know what the expected parent size is going to be, so e.g. list items can size
4475            // themselves at 1/3 the size of their container. It breaks older apps though,
4476            // specifically apps that use some popular open source libraries.
4477            sUseZeroUnspecifiedMeasureSpec = targetSdkVersion < Build.VERSION_CODES.M;
4478
4479            // Old versions of the platform would give different results from
4480            // LinearLayout measurement passes using EXACTLY and non-EXACTLY
4481            // modes, so we always need to run an additional EXACTLY pass.
4482            sAlwaysRemeasureExactly = targetSdkVersion <= Build.VERSION_CODES.M;
4483
4484            // Prior to N, layout params could change without requiring a
4485            // subsequent call to setLayoutParams() and they would usually
4486            // work. Partial layout breaks this assumption.
4487            sLayoutParamsAlwaysChanged = targetSdkVersion <= Build.VERSION_CODES.M;
4488
4489            // Prior to N, TextureView would silently ignore calls to setBackground/setForeground.
4490            // On N+, we throw, but that breaks compatibility with apps that use these methods.
4491            sTextureViewIgnoresDrawableSetters = targetSdkVersion <= Build.VERSION_CODES.M;
4492
4493            // Prior to N, we would drop margins in LayoutParam conversions. The fix triggers bugs
4494            // in apps so we target check it to avoid breaking existing apps.
4495            sPreserveMarginParamsInLayoutParamConversion =
4496                    targetSdkVersion >= Build.VERSION_CODES.N;
4497
4498            sCascadedDragDrop = targetSdkVersion < Build.VERSION_CODES.N;
4499
4500            sHasFocusableExcludeAutoFocusable = targetSdkVersion < Build.VERSION_CODES.O;
4501
4502            sAutoFocusableOffUIThreadWontNotifyParents = targetSdkVersion < Build.VERSION_CODES.O;
4503
4504            sCompatibilityDone = true;
4505        }
4506    }
4507
4508    /**
4509     * Constructor that is called when inflating a view from XML. This is called
4510     * when a view is being constructed from an XML file, supplying attributes
4511     * that were specified in the XML file. This version uses a default style of
4512     * 0, so the only attribute values applied are those in the Context's Theme
4513     * and the given AttributeSet.
4514     *
4515     * <p>
4516     * The method onFinishInflate() will be called after all children have been
4517     * added.
4518     *
4519     * @param context The Context the view is running in, through which it can
4520     *        access the current theme, resources, etc.
4521     * @param attrs The attributes of the XML tag that is inflating the view.
4522     * @see #View(Context, AttributeSet, int)
4523     */
4524    public View(Context context, @Nullable AttributeSet attrs) {
4525        this(context, attrs, 0);
4526    }
4527
4528    /**
4529     * Perform inflation from XML and apply a class-specific base style from a
4530     * theme attribute. This constructor of View allows subclasses to use their
4531     * own base style when they are inflating. For example, a Button class's
4532     * constructor would call this version of the super class constructor and
4533     * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this
4534     * allows the theme's button style to modify all of the base view attributes
4535     * (in particular its background) as well as the Button class's attributes.
4536     *
4537     * @param context The Context the view is running in, through which it can
4538     *        access the current theme, resources, etc.
4539     * @param attrs The attributes of the XML tag that is inflating the view.
4540     * @param defStyleAttr An attribute in the current theme that contains a
4541     *        reference to a style resource that supplies default values for
4542     *        the view. Can be 0 to not look for defaults.
4543     * @see #View(Context, AttributeSet)
4544     */
4545    public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
4546        this(context, attrs, defStyleAttr, 0);
4547    }
4548
4549    /**
4550     * Perform inflation from XML and apply a class-specific base style from a
4551     * theme attribute or style resource. This constructor of View allows
4552     * subclasses to use their own base style when they are inflating.
4553     * <p>
4554     * When determining the final value of a particular attribute, there are
4555     * four inputs that come into play:
4556     * <ol>
4557     * <li>Any attribute values in the given AttributeSet.
4558     * <li>The style resource specified in the AttributeSet (named "style").
4559     * <li>The default style specified by <var>defStyleAttr</var>.
4560     * <li>The default style specified by <var>defStyleRes</var>.
4561     * <li>The base values in this theme.
4562     * </ol>
4563     * <p>
4564     * Each of these inputs is considered in-order, with the first listed taking
4565     * precedence over the following ones. In other words, if in the
4566     * AttributeSet you have supplied <code>&lt;Button * textColor="#ff000000"&gt;</code>
4567     * , then the button's text will <em>always</em> be black, regardless of
4568     * what is specified in any of the styles.
4569     *
4570     * @param context The Context the view is running in, through which it can
4571     *        access the current theme, resources, etc.
4572     * @param attrs The attributes of the XML tag that is inflating the view.
4573     * @param defStyleAttr An attribute in the current theme that contains a
4574     *        reference to a style resource that supplies default values for
4575     *        the view. Can be 0 to not look for defaults.
4576     * @param defStyleRes A resource identifier of a style resource that
4577     *        supplies default values for the view, used only if
4578     *        defStyleAttr is 0 or can not be found in the theme. Can be 0
4579     *        to not look for defaults.
4580     * @see #View(Context, AttributeSet, int)
4581     */
4582    public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
4583        this(context);
4584
4585        final TypedArray a = context.obtainStyledAttributes(
4586                attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes);
4587
4588        if (mDebugViewAttributes) {
4589            saveAttributeData(attrs, a);
4590        }
4591
4592        Drawable background = null;
4593
4594        int leftPadding = -1;
4595        int topPadding = -1;
4596        int rightPadding = -1;
4597        int bottomPadding = -1;
4598        int startPadding = UNDEFINED_PADDING;
4599        int endPadding = UNDEFINED_PADDING;
4600
4601        int padding = -1;
4602        int paddingHorizontal = -1;
4603        int paddingVertical = -1;
4604
4605        int viewFlagValues = 0;
4606        int viewFlagMasks = 0;
4607
4608        boolean setScrollContainer = false;
4609
4610        int x = 0;
4611        int y = 0;
4612
4613        float tx = 0;
4614        float ty = 0;
4615        float tz = 0;
4616        float elevation = 0;
4617        float rotation = 0;
4618        float rotationX = 0;
4619        float rotationY = 0;
4620        float sx = 1f;
4621        float sy = 1f;
4622        boolean transformSet = false;
4623
4624        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
4625        int overScrollMode = mOverScrollMode;
4626        boolean initializeScrollbars = false;
4627        boolean initializeScrollIndicators = false;
4628
4629        boolean startPaddingDefined = false;
4630        boolean endPaddingDefined = false;
4631        boolean leftPaddingDefined = false;
4632        boolean rightPaddingDefined = false;
4633
4634        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
4635
4636        // Set default values.
4637        viewFlagValues |= FOCUSABLE_AUTO;
4638        viewFlagMasks |= FOCUSABLE_AUTO;
4639
4640        final int N = a.getIndexCount();
4641        for (int i = 0; i < N; i++) {
4642            int attr = a.getIndex(i);
4643            switch (attr) {
4644                case com.android.internal.R.styleable.View_background:
4645                    background = a.getDrawable(attr);
4646                    break;
4647                case com.android.internal.R.styleable.View_padding:
4648                    padding = a.getDimensionPixelSize(attr, -1);
4649                    mUserPaddingLeftInitial = padding;
4650                    mUserPaddingRightInitial = padding;
4651                    leftPaddingDefined = true;
4652                    rightPaddingDefined = true;
4653                    break;
4654                case com.android.internal.R.styleable.View_paddingHorizontal:
4655                    paddingHorizontal = a.getDimensionPixelSize(attr, -1);
4656                    mUserPaddingLeftInitial = paddingHorizontal;
4657                    mUserPaddingRightInitial = paddingHorizontal;
4658                    leftPaddingDefined = true;
4659                    rightPaddingDefined = true;
4660                    break;
4661                case com.android.internal.R.styleable.View_paddingVertical:
4662                    paddingVertical = a.getDimensionPixelSize(attr, -1);
4663                    break;
4664                 case com.android.internal.R.styleable.View_paddingLeft:
4665                    leftPadding = a.getDimensionPixelSize(attr, -1);
4666                    mUserPaddingLeftInitial = leftPadding;
4667                    leftPaddingDefined = true;
4668                    break;
4669                case com.android.internal.R.styleable.View_paddingTop:
4670                    topPadding = a.getDimensionPixelSize(attr, -1);
4671                    break;
4672                case com.android.internal.R.styleable.View_paddingRight:
4673                    rightPadding = a.getDimensionPixelSize(attr, -1);
4674                    mUserPaddingRightInitial = rightPadding;
4675                    rightPaddingDefined = true;
4676                    break;
4677                case com.android.internal.R.styleable.View_paddingBottom:
4678                    bottomPadding = a.getDimensionPixelSize(attr, -1);
4679                    break;
4680                case com.android.internal.R.styleable.View_paddingStart:
4681                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
4682                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
4683                    break;
4684                case com.android.internal.R.styleable.View_paddingEnd:
4685                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
4686                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
4687                    break;
4688                case com.android.internal.R.styleable.View_scrollX:
4689                    x = a.getDimensionPixelOffset(attr, 0);
4690                    break;
4691                case com.android.internal.R.styleable.View_scrollY:
4692                    y = a.getDimensionPixelOffset(attr, 0);
4693                    break;
4694                case com.android.internal.R.styleable.View_alpha:
4695                    setAlpha(a.getFloat(attr, 1f));
4696                    break;
4697                case com.android.internal.R.styleable.View_transformPivotX:
4698                    setPivotX(a.getDimension(attr, 0));
4699                    break;
4700                case com.android.internal.R.styleable.View_transformPivotY:
4701                    setPivotY(a.getDimension(attr, 0));
4702                    break;
4703                case com.android.internal.R.styleable.View_translationX:
4704                    tx = a.getDimension(attr, 0);
4705                    transformSet = true;
4706                    break;
4707                case com.android.internal.R.styleable.View_translationY:
4708                    ty = a.getDimension(attr, 0);
4709                    transformSet = true;
4710                    break;
4711                case com.android.internal.R.styleable.View_translationZ:
4712                    tz = a.getDimension(attr, 0);
4713                    transformSet = true;
4714                    break;
4715                case com.android.internal.R.styleable.View_elevation:
4716                    elevation = a.getDimension(attr, 0);
4717                    transformSet = true;
4718                    break;
4719                case com.android.internal.R.styleable.View_rotation:
4720                    rotation = a.getFloat(attr, 0);
4721                    transformSet = true;
4722                    break;
4723                case com.android.internal.R.styleable.View_rotationX:
4724                    rotationX = a.getFloat(attr, 0);
4725                    transformSet = true;
4726                    break;
4727                case com.android.internal.R.styleable.View_rotationY:
4728                    rotationY = a.getFloat(attr, 0);
4729                    transformSet = true;
4730                    break;
4731                case com.android.internal.R.styleable.View_scaleX:
4732                    sx = a.getFloat(attr, 1f);
4733                    transformSet = true;
4734                    break;
4735                case com.android.internal.R.styleable.View_scaleY:
4736                    sy = a.getFloat(attr, 1f);
4737                    transformSet = true;
4738                    break;
4739                case com.android.internal.R.styleable.View_id:
4740                    mID = a.getResourceId(attr, NO_ID);
4741                    break;
4742                case com.android.internal.R.styleable.View_tag:
4743                    mTag = a.getText(attr);
4744                    break;
4745                case com.android.internal.R.styleable.View_fitsSystemWindows:
4746                    if (a.getBoolean(attr, false)) {
4747                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
4748                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
4749                    }
4750                    break;
4751                case com.android.internal.R.styleable.View_focusable:
4752                    viewFlagValues = (viewFlagValues & ~FOCUSABLE_MASK) | getFocusableAttribute(a);
4753                    if ((viewFlagValues & FOCUSABLE_AUTO) == 0) {
4754                        viewFlagMasks |= FOCUSABLE_MASK;
4755                    }
4756                    break;
4757                case com.android.internal.R.styleable.View_focusableInTouchMode:
4758                    if (a.getBoolean(attr, false)) {
4759                        // unset auto focus since focusableInTouchMode implies explicit focusable
4760                        viewFlagValues &= ~FOCUSABLE_AUTO;
4761                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
4762                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
4763                    }
4764                    break;
4765                case com.android.internal.R.styleable.View_clickable:
4766                    if (a.getBoolean(attr, false)) {
4767                        viewFlagValues |= CLICKABLE;
4768                        viewFlagMasks |= CLICKABLE;
4769                    }
4770                    break;
4771                case com.android.internal.R.styleable.View_longClickable:
4772                    if (a.getBoolean(attr, false)) {
4773                        viewFlagValues |= LONG_CLICKABLE;
4774                        viewFlagMasks |= LONG_CLICKABLE;
4775                    }
4776                    break;
4777                case com.android.internal.R.styleable.View_contextClickable:
4778                    if (a.getBoolean(attr, false)) {
4779                        viewFlagValues |= CONTEXT_CLICKABLE;
4780                        viewFlagMasks |= CONTEXT_CLICKABLE;
4781                    }
4782                    break;
4783                case com.android.internal.R.styleable.View_saveEnabled:
4784                    if (!a.getBoolean(attr, true)) {
4785                        viewFlagValues |= SAVE_DISABLED;
4786                        viewFlagMasks |= SAVE_DISABLED_MASK;
4787                    }
4788                    break;
4789                case com.android.internal.R.styleable.View_duplicateParentState:
4790                    if (a.getBoolean(attr, false)) {
4791                        viewFlagValues |= DUPLICATE_PARENT_STATE;
4792                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
4793                    }
4794                    break;
4795                case com.android.internal.R.styleable.View_visibility:
4796                    final int visibility = a.getInt(attr, 0);
4797                    if (visibility != 0) {
4798                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
4799                        viewFlagMasks |= VISIBILITY_MASK;
4800                    }
4801                    break;
4802                case com.android.internal.R.styleable.View_layoutDirection:
4803                    // Clear any layout direction flags (included resolved bits) already set
4804                    mPrivateFlags2 &=
4805                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
4806                    // Set the layout direction flags depending on the value of the attribute
4807                    final int layoutDirection = a.getInt(attr, -1);
4808                    final int value = (layoutDirection != -1) ?
4809                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
4810                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
4811                    break;
4812                case com.android.internal.R.styleable.View_drawingCacheQuality:
4813                    final int cacheQuality = a.getInt(attr, 0);
4814                    if (cacheQuality != 0) {
4815                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
4816                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
4817                    }
4818                    break;
4819                case com.android.internal.R.styleable.View_contentDescription:
4820                    setContentDescription(a.getString(attr));
4821                    break;
4822                case com.android.internal.R.styleable.View_accessibilityTraversalBefore:
4823                    setAccessibilityTraversalBefore(a.getResourceId(attr, NO_ID));
4824                    break;
4825                case com.android.internal.R.styleable.View_accessibilityTraversalAfter:
4826                    setAccessibilityTraversalAfter(a.getResourceId(attr, NO_ID));
4827                    break;
4828                case com.android.internal.R.styleable.View_labelFor:
4829                    setLabelFor(a.getResourceId(attr, NO_ID));
4830                    break;
4831                case com.android.internal.R.styleable.View_soundEffectsEnabled:
4832                    if (!a.getBoolean(attr, true)) {
4833                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
4834                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
4835                    }
4836                    break;
4837                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
4838                    if (!a.getBoolean(attr, true)) {
4839                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
4840                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
4841                    }
4842                    break;
4843                case R.styleable.View_scrollbars:
4844                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
4845                    if (scrollbars != SCROLLBARS_NONE) {
4846                        viewFlagValues |= scrollbars;
4847                        viewFlagMasks |= SCROLLBARS_MASK;
4848                        initializeScrollbars = true;
4849                    }
4850                    break;
4851                //noinspection deprecation
4852                case R.styleable.View_fadingEdge:
4853                    if (targetSdkVersion >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
4854                        // Ignore the attribute starting with ICS
4855                        break;
4856                    }
4857                    // With builds < ICS, fall through and apply fading edges
4858                case R.styleable.View_requiresFadingEdge:
4859                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
4860                    if (fadingEdge != FADING_EDGE_NONE) {
4861                        viewFlagValues |= fadingEdge;
4862                        viewFlagMasks |= FADING_EDGE_MASK;
4863                        initializeFadingEdgeInternal(a);
4864                    }
4865                    break;
4866                case R.styleable.View_scrollbarStyle:
4867                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
4868                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4869                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
4870                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
4871                    }
4872                    break;
4873                case R.styleable.View_isScrollContainer:
4874                    setScrollContainer = true;
4875                    if (a.getBoolean(attr, false)) {
4876                        setScrollContainer(true);
4877                    }
4878                    break;
4879                case com.android.internal.R.styleable.View_keepScreenOn:
4880                    if (a.getBoolean(attr, false)) {
4881                        viewFlagValues |= KEEP_SCREEN_ON;
4882                        viewFlagMasks |= KEEP_SCREEN_ON;
4883                    }
4884                    break;
4885                case R.styleable.View_filterTouchesWhenObscured:
4886                    if (a.getBoolean(attr, false)) {
4887                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
4888                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
4889                    }
4890                    break;
4891                case R.styleable.View_nextFocusLeft:
4892                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
4893                    break;
4894                case R.styleable.View_nextFocusRight:
4895                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
4896                    break;
4897                case R.styleable.View_nextFocusUp:
4898                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
4899                    break;
4900                case R.styleable.View_nextFocusDown:
4901                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
4902                    break;
4903                case R.styleable.View_nextFocusForward:
4904                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
4905                    break;
4906                case R.styleable.View_nextClusterForward:
4907                    mNextClusterForwardId = a.getResourceId(attr, View.NO_ID);
4908                    break;
4909                case R.styleable.View_minWidth:
4910                    mMinWidth = a.getDimensionPixelSize(attr, 0);
4911                    break;
4912                case R.styleable.View_minHeight:
4913                    mMinHeight = a.getDimensionPixelSize(attr, 0);
4914                    break;
4915                case R.styleable.View_onClick:
4916                    if (context.isRestricted()) {
4917                        throw new IllegalStateException("The android:onClick attribute cannot "
4918                                + "be used within a restricted context");
4919                    }
4920
4921                    final String handlerName = a.getString(attr);
4922                    if (handlerName != null) {
4923                        setOnClickListener(new DeclaredOnClickListener(this, handlerName));
4924                    }
4925                    break;
4926                case R.styleable.View_overScrollMode:
4927                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
4928                    break;
4929                case R.styleable.View_verticalScrollbarPosition:
4930                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
4931                    break;
4932                case R.styleable.View_layerType:
4933                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
4934                    break;
4935                case R.styleable.View_textDirection:
4936                    // Clear any text direction flag already set
4937                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
4938                    // Set the text direction flags depending on the value of the attribute
4939                    final int textDirection = a.getInt(attr, -1);
4940                    if (textDirection != -1) {
4941                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
4942                    }
4943                    break;
4944                case R.styleable.View_textAlignment:
4945                    // Clear any text alignment flag already set
4946                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
4947                    // Set the text alignment flag depending on the value of the attribute
4948                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
4949                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
4950                    break;
4951                case R.styleable.View_importantForAccessibility:
4952                    setImportantForAccessibility(a.getInt(attr,
4953                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
4954                    break;
4955                case R.styleable.View_accessibilityLiveRegion:
4956                    setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT));
4957                    break;
4958                case R.styleable.View_transitionName:
4959                    setTransitionName(a.getString(attr));
4960                    break;
4961                case R.styleable.View_nestedScrollingEnabled:
4962                    setNestedScrollingEnabled(a.getBoolean(attr, false));
4963                    break;
4964                case R.styleable.View_stateListAnimator:
4965                    setStateListAnimator(AnimatorInflater.loadStateListAnimator(context,
4966                            a.getResourceId(attr, 0)));
4967                    break;
4968                case R.styleable.View_backgroundTint:
4969                    // This will get applied later during setBackground().
4970                    if (mBackgroundTint == null) {
4971                        mBackgroundTint = new TintInfo();
4972                    }
4973                    mBackgroundTint.mTintList = a.getColorStateList(
4974                            R.styleable.View_backgroundTint);
4975                    mBackgroundTint.mHasTintList = true;
4976                    break;
4977                case R.styleable.View_backgroundTintMode:
4978                    // This will get applied later during setBackground().
4979                    if (mBackgroundTint == null) {
4980                        mBackgroundTint = new TintInfo();
4981                    }
4982                    mBackgroundTint.mTintMode = Drawable.parseTintMode(a.getInt(
4983                            R.styleable.View_backgroundTintMode, -1), null);
4984                    mBackgroundTint.mHasTintMode = true;
4985                    break;
4986                case R.styleable.View_outlineProvider:
4987                    setOutlineProviderFromAttribute(a.getInt(R.styleable.View_outlineProvider,
4988                            PROVIDER_BACKGROUND));
4989                    break;
4990                case R.styleable.View_foreground:
4991                    if (targetSdkVersion >= Build.VERSION_CODES.M || this instanceof FrameLayout) {
4992                        setForeground(a.getDrawable(attr));
4993                    }
4994                    break;
4995                case R.styleable.View_foregroundGravity:
4996                    if (targetSdkVersion >= Build.VERSION_CODES.M || this instanceof FrameLayout) {
4997                        setForegroundGravity(a.getInt(attr, Gravity.NO_GRAVITY));
4998                    }
4999                    break;
5000                case R.styleable.View_foregroundTintMode:
5001                    if (targetSdkVersion >= Build.VERSION_CODES.M || this instanceof FrameLayout) {
5002                        setForegroundTintMode(Drawable.parseTintMode(a.getInt(attr, -1), null));
5003                    }
5004                    break;
5005                case R.styleable.View_foregroundTint:
5006                    if (targetSdkVersion >= Build.VERSION_CODES.M || this instanceof FrameLayout) {
5007                        setForegroundTintList(a.getColorStateList(attr));
5008                    }
5009                    break;
5010                case R.styleable.View_foregroundInsidePadding:
5011                    if (targetSdkVersion >= Build.VERSION_CODES.M || this instanceof FrameLayout) {
5012                        if (mForegroundInfo == null) {
5013                            mForegroundInfo = new ForegroundInfo();
5014                        }
5015                        mForegroundInfo.mInsidePadding = a.getBoolean(attr,
5016                                mForegroundInfo.mInsidePadding);
5017                    }
5018                    break;
5019                case R.styleable.View_scrollIndicators:
5020                    final int scrollIndicators =
5021                            (a.getInt(attr, 0) << SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT)
5022                                    & SCROLL_INDICATORS_PFLAG3_MASK;
5023                    if (scrollIndicators != 0) {
5024                        mPrivateFlags3 |= scrollIndicators;
5025                        initializeScrollIndicators = true;
5026                    }
5027                    break;
5028                case R.styleable.View_pointerIcon:
5029                    final int resourceId = a.getResourceId(attr, 0);
5030                    if (resourceId != 0) {
5031                        setPointerIcon(PointerIcon.load(
5032                                context.getResources(), resourceId));
5033                    } else {
5034                        final int pointerType = a.getInt(attr, PointerIcon.TYPE_NOT_SPECIFIED);
5035                        if (pointerType != PointerIcon.TYPE_NOT_SPECIFIED) {
5036                            setPointerIcon(PointerIcon.getSystemIcon(context, pointerType));
5037                        }
5038                    }
5039                    break;
5040                case R.styleable.View_forceHasOverlappingRendering:
5041                    if (a.peekValue(attr) != null) {
5042                        forceHasOverlappingRendering(a.getBoolean(attr, true));
5043                    }
5044                    break;
5045                case R.styleable.View_tooltipText:
5046                    setTooltipText(a.getText(attr));
5047                    break;
5048                case R.styleable.View_keyboardNavigationCluster:
5049                    if (a.peekValue(attr) != null) {
5050                        setKeyboardNavigationCluster(a.getBoolean(attr, true));
5051                    }
5052                    break;
5053                case R.styleable.View_focusedByDefault:
5054                    if (a.peekValue(attr) != null) {
5055                        setFocusedByDefault(a.getBoolean(attr, true));
5056                    }
5057                    break;
5058                case R.styleable.View_autofillMode:
5059                    if (a.peekValue(attr) != null) {
5060                        setAutofillMode(a.getInt(attr, AUTOFILL_MODE_INHERIT));
5061                    }
5062                    break;
5063                case R.styleable.View_autofillHints:
5064                    if (a.peekValue(attr) != null) {
5065                        CharSequence[] rawHints = null;
5066                        String rawString = null;
5067
5068                        if (a.getType(attr) == TypedValue.TYPE_REFERENCE) {
5069                            int resId = a.getResourceId(attr, 0);
5070
5071                            try {
5072                                rawHints = a.getTextArray(attr);
5073                            } catch (Resources.NotFoundException e) {
5074                                rawString = getResources().getString(resId);
5075                            }
5076                        } else {
5077                            rawString = a.getString(attr);
5078                        }
5079
5080                        if (rawHints == null) {
5081                            if (rawString == null) {
5082                                throw new IllegalArgumentException(
5083                                        "Could not resolve autofillHints");
5084                            } else {
5085                                rawHints = rawString.split(",");
5086                            }
5087                        }
5088
5089                        String[] hints = new String[rawHints.length];
5090
5091                        int numHints = rawHints.length;
5092                        for (int rawHintNum = 0; rawHintNum < numHints; rawHintNum++) {
5093                            hints[rawHintNum] = rawHints[rawHintNum].toString().trim();
5094                        }
5095                        setAutofillHints(hints);
5096                    }
5097                    break;
5098                case R.styleable.View_importantForAutofill:
5099                    if (a.peekValue(attr) != null) {
5100                        setImportantForAutofill(a.getInt(attr, IMPORTANT_FOR_AUTOFILL_AUTO));
5101                    }
5102                    break;
5103                case R.styleable.View_defaultFocusHighlightEnabled:
5104                    if (a.peekValue(attr) != null) {
5105                        setDefaultFocusHighlightEnabled(a.getBoolean(attr, true));
5106                    }
5107                    break;
5108            }
5109        }
5110
5111        setOverScrollMode(overScrollMode);
5112
5113        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
5114        // the resolved layout direction). Those cached values will be used later during padding
5115        // resolution.
5116        mUserPaddingStart = startPadding;
5117        mUserPaddingEnd = endPadding;
5118
5119        if (background != null) {
5120            setBackground(background);
5121        }
5122
5123        // setBackground above will record that padding is currently provided by the background.
5124        // If we have padding specified via xml, record that here instead and use it.
5125        mLeftPaddingDefined = leftPaddingDefined;
5126        mRightPaddingDefined = rightPaddingDefined;
5127
5128        if (padding >= 0) {
5129            leftPadding = padding;
5130            topPadding = padding;
5131            rightPadding = padding;
5132            bottomPadding = padding;
5133            mUserPaddingLeftInitial = padding;
5134            mUserPaddingRightInitial = padding;
5135        } else {
5136            if (paddingHorizontal >= 0) {
5137                leftPadding = paddingHorizontal;
5138                rightPadding = paddingHorizontal;
5139                mUserPaddingLeftInitial = paddingHorizontal;
5140                mUserPaddingRightInitial = paddingHorizontal;
5141            }
5142            if (paddingVertical >= 0) {
5143                topPadding = paddingVertical;
5144                bottomPadding = paddingVertical;
5145            }
5146        }
5147
5148        if (isRtlCompatibilityMode()) {
5149            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
5150            // left / right padding are used if defined (meaning here nothing to do). If they are not
5151            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
5152            // start / end and resolve them as left / right (layout direction is not taken into account).
5153            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
5154            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
5155            // defined.
5156            if (!mLeftPaddingDefined && startPaddingDefined) {
5157                leftPadding = startPadding;
5158            }
5159            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
5160            if (!mRightPaddingDefined && endPaddingDefined) {
5161                rightPadding = endPadding;
5162            }
5163            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
5164        } else {
5165            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
5166            // values defined. Otherwise, left /right values are used.
5167            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
5168            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
5169            // defined.
5170            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
5171
5172            if (mLeftPaddingDefined && !hasRelativePadding) {
5173                mUserPaddingLeftInitial = leftPadding;
5174            }
5175            if (mRightPaddingDefined && !hasRelativePadding) {
5176                mUserPaddingRightInitial = rightPadding;
5177            }
5178        }
5179
5180        internalSetPadding(
5181                mUserPaddingLeftInitial,
5182                topPadding >= 0 ? topPadding : mPaddingTop,
5183                mUserPaddingRightInitial,
5184                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
5185
5186        if (viewFlagMasks != 0) {
5187            setFlags(viewFlagValues, viewFlagMasks);
5188        }
5189
5190        if (initializeScrollbars) {
5191            initializeScrollbarsInternal(a);
5192        }
5193
5194        if (initializeScrollIndicators) {
5195            initializeScrollIndicatorsInternal();
5196        }
5197
5198        a.recycle();
5199
5200        // Needs to be called after mViewFlags is set
5201        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
5202            recomputePadding();
5203        }
5204
5205        if (x != 0 || y != 0) {
5206            scrollTo(x, y);
5207        }
5208
5209        if (transformSet) {
5210            setTranslationX(tx);
5211            setTranslationY(ty);
5212            setTranslationZ(tz);
5213            setElevation(elevation);
5214            setRotation(rotation);
5215            setRotationX(rotationX);
5216            setRotationY(rotationY);
5217            setScaleX(sx);
5218            setScaleY(sy);
5219        }
5220
5221        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
5222            setScrollContainer(true);
5223        }
5224
5225        computeOpaqueFlags();
5226    }
5227
5228    /**
5229     * An implementation of OnClickListener that attempts to lazily load a
5230     * named click handling method from a parent or ancestor context.
5231     */
5232    private static class DeclaredOnClickListener implements OnClickListener {
5233        private final View mHostView;
5234        private final String mMethodName;
5235
5236        private Method mResolvedMethod;
5237        private Context mResolvedContext;
5238
5239        public DeclaredOnClickListener(@NonNull View hostView, @NonNull String methodName) {
5240            mHostView = hostView;
5241            mMethodName = methodName;
5242        }
5243
5244        @Override
5245        public void onClick(@NonNull View v) {
5246            if (mResolvedMethod == null) {
5247                resolveMethod(mHostView.getContext(), mMethodName);
5248            }
5249
5250            try {
5251                mResolvedMethod.invoke(mResolvedContext, v);
5252            } catch (IllegalAccessException e) {
5253                throw new IllegalStateException(
5254                        "Could not execute non-public method for android:onClick", e);
5255            } catch (InvocationTargetException e) {
5256                throw new IllegalStateException(
5257                        "Could not execute method for android:onClick", e);
5258            }
5259        }
5260
5261        @NonNull
5262        private void resolveMethod(@Nullable Context context, @NonNull String name) {
5263            while (context != null) {
5264                try {
5265                    if (!context.isRestricted()) {
5266                        final Method method = context.getClass().getMethod(mMethodName, View.class);
5267                        if (method != null) {
5268                            mResolvedMethod = method;
5269                            mResolvedContext = context;
5270                            return;
5271                        }
5272                    }
5273                } catch (NoSuchMethodException e) {
5274                    // Failed to find method, keep searching up the hierarchy.
5275                }
5276
5277                if (context instanceof ContextWrapper) {
5278                    context = ((ContextWrapper) context).getBaseContext();
5279                } else {
5280                    // Can't search up the hierarchy, null out and fail.
5281                    context = null;
5282                }
5283            }
5284
5285            final int id = mHostView.getId();
5286            final String idText = id == NO_ID ? "" : " with id '"
5287                    + mHostView.getContext().getResources().getResourceEntryName(id) + "'";
5288            throw new IllegalStateException("Could not find method " + mMethodName
5289                    + "(View) in a parent or ancestor Context for android:onClick "
5290                    + "attribute defined on view " + mHostView.getClass() + idText);
5291        }
5292    }
5293
5294    /**
5295     * Non-public constructor for use in testing
5296     */
5297    View() {
5298        mResources = null;
5299        mRenderNode = RenderNode.create(getClass().getName(), this);
5300    }
5301
5302    final boolean debugDraw() {
5303        return DEBUG_DRAW || mAttachInfo != null && mAttachInfo.mDebugLayout;
5304    }
5305
5306    private static SparseArray<String> getAttributeMap() {
5307        if (mAttributeMap == null) {
5308            mAttributeMap = new SparseArray<>();
5309        }
5310        return mAttributeMap;
5311    }
5312
5313    private void saveAttributeData(@Nullable AttributeSet attrs, @NonNull TypedArray t) {
5314        final int attrsCount = attrs == null ? 0 : attrs.getAttributeCount();
5315        final int indexCount = t.getIndexCount();
5316        final String[] attributes = new String[(attrsCount + indexCount) * 2];
5317
5318        int i = 0;
5319
5320        // Store raw XML attributes.
5321        for (int j = 0; j < attrsCount; ++j) {
5322            attributes[i] = attrs.getAttributeName(j);
5323            attributes[i + 1] = attrs.getAttributeValue(j);
5324            i += 2;
5325        }
5326
5327        // Store resolved styleable attributes.
5328        final Resources res = t.getResources();
5329        final SparseArray<String> attributeMap = getAttributeMap();
5330        for (int j = 0; j < indexCount; ++j) {
5331            final int index = t.getIndex(j);
5332            if (!t.hasValueOrEmpty(index)) {
5333                // Value is undefined. Skip it.
5334                continue;
5335            }
5336
5337            final int resourceId = t.getResourceId(index, 0);
5338            if (resourceId == 0) {
5339                // Value is not a reference. Skip it.
5340                continue;
5341            }
5342
5343            String resourceName = attributeMap.get(resourceId);
5344            if (resourceName == null) {
5345                try {
5346                    resourceName = res.getResourceName(resourceId);
5347                } catch (Resources.NotFoundException e) {
5348                    resourceName = "0x" + Integer.toHexString(resourceId);
5349                }
5350                attributeMap.put(resourceId, resourceName);
5351            }
5352
5353            attributes[i] = resourceName;
5354            attributes[i + 1] = t.getString(index);
5355            i += 2;
5356        }
5357
5358        // Trim to fit contents.
5359        final String[] trimmed = new String[i];
5360        System.arraycopy(attributes, 0, trimmed, 0, i);
5361        mAttributes = trimmed;
5362    }
5363
5364    public String toString() {
5365        StringBuilder out = new StringBuilder(128);
5366        out.append(getClass().getName());
5367        out.append('{');
5368        out.append(Integer.toHexString(System.identityHashCode(this)));
5369        out.append(' ');
5370        switch (mViewFlags&VISIBILITY_MASK) {
5371            case VISIBLE: out.append('V'); break;
5372            case INVISIBLE: out.append('I'); break;
5373            case GONE: out.append('G'); break;
5374            default: out.append('.'); break;
5375        }
5376        out.append((mViewFlags & FOCUSABLE) == FOCUSABLE ? 'F' : '.');
5377        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
5378        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
5379        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
5380        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
5381        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
5382        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
5383        out.append((mViewFlags&CONTEXT_CLICKABLE) != 0 ? 'X' : '.');
5384        out.append(' ');
5385        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
5386        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
5387        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
5388        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
5389            out.append('p');
5390        } else {
5391            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
5392        }
5393        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
5394        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
5395        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
5396        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
5397        out.append(' ');
5398        out.append(mLeft);
5399        out.append(',');
5400        out.append(mTop);
5401        out.append('-');
5402        out.append(mRight);
5403        out.append(',');
5404        out.append(mBottom);
5405        final int id = getId();
5406        if (id != NO_ID) {
5407            out.append(" #");
5408            out.append(Integer.toHexString(id));
5409            final Resources r = mResources;
5410            if (id > 0 && Resources.resourceHasPackage(id) && r != null) {
5411                try {
5412                    String pkgname;
5413                    switch (id&0xff000000) {
5414                        case 0x7f000000:
5415                            pkgname="app";
5416                            break;
5417                        case 0x01000000:
5418                            pkgname="android";
5419                            break;
5420                        default:
5421                            pkgname = r.getResourcePackageName(id);
5422                            break;
5423                    }
5424                    String typename = r.getResourceTypeName(id);
5425                    String entryname = r.getResourceEntryName(id);
5426                    out.append(" ");
5427                    out.append(pkgname);
5428                    out.append(":");
5429                    out.append(typename);
5430                    out.append("/");
5431                    out.append(entryname);
5432                } catch (Resources.NotFoundException e) {
5433                }
5434            }
5435        }
5436        out.append("}");
5437        return out.toString();
5438    }
5439
5440    /**
5441     * <p>
5442     * Initializes the fading edges from a given set of styled attributes. This
5443     * method should be called by subclasses that need fading edges and when an
5444     * instance of these subclasses is created programmatically rather than
5445     * being inflated from XML. This method is automatically called when the XML
5446     * is inflated.
5447     * </p>
5448     *
5449     * @param a the styled attributes set to initialize the fading edges from
5450     *
5451     * @removed
5452     */
5453    protected void initializeFadingEdge(TypedArray a) {
5454        // This method probably shouldn't have been included in the SDK to begin with.
5455        // It relies on 'a' having been initialized using an attribute filter array that is
5456        // not publicly available to the SDK. The old method has been renamed
5457        // to initializeFadingEdgeInternal and hidden for framework use only;
5458        // this one initializes using defaults to make it safe to call for apps.
5459
5460        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
5461
5462        initializeFadingEdgeInternal(arr);
5463
5464        arr.recycle();
5465    }
5466
5467    /**
5468     * <p>
5469     * Initializes the fading edges from a given set of styled attributes. This
5470     * method should be called by subclasses that need fading edges and when an
5471     * instance of these subclasses is created programmatically rather than
5472     * being inflated from XML. This method is automatically called when the XML
5473     * is inflated.
5474     * </p>
5475     *
5476     * @param a the styled attributes set to initialize the fading edges from
5477     * @hide This is the real method; the public one is shimmed to be safe to call from apps.
5478     */
5479    protected void initializeFadingEdgeInternal(TypedArray a) {
5480        initScrollCache();
5481
5482        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
5483                R.styleable.View_fadingEdgeLength,
5484                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
5485    }
5486
5487    /**
5488     * Returns the size of the vertical faded edges used to indicate that more
5489     * content in this view is visible.
5490     *
5491     * @return The size in pixels of the vertical faded edge or 0 if vertical
5492     *         faded edges are not enabled for this view.
5493     * @attr ref android.R.styleable#View_fadingEdgeLength
5494     */
5495    public int getVerticalFadingEdgeLength() {
5496        if (isVerticalFadingEdgeEnabled()) {
5497            ScrollabilityCache cache = mScrollCache;
5498            if (cache != null) {
5499                return cache.fadingEdgeLength;
5500            }
5501        }
5502        return 0;
5503    }
5504
5505    /**
5506     * Set the size of the faded edge used to indicate that more content in this
5507     * view is available.  Will not change whether the fading edge is enabled; use
5508     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
5509     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
5510     * for the vertical or horizontal fading edges.
5511     *
5512     * @param length The size in pixels of the faded edge used to indicate that more
5513     *        content in this view is visible.
5514     */
5515    public void setFadingEdgeLength(int length) {
5516        initScrollCache();
5517        mScrollCache.fadingEdgeLength = length;
5518    }
5519
5520    /**
5521     * Returns the size of the horizontal faded edges used to indicate that more
5522     * content in this view is visible.
5523     *
5524     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
5525     *         faded edges are not enabled for this view.
5526     * @attr ref android.R.styleable#View_fadingEdgeLength
5527     */
5528    public int getHorizontalFadingEdgeLength() {
5529        if (isHorizontalFadingEdgeEnabled()) {
5530            ScrollabilityCache cache = mScrollCache;
5531            if (cache != null) {
5532                return cache.fadingEdgeLength;
5533            }
5534        }
5535        return 0;
5536    }
5537
5538    /**
5539     * Returns the width of the vertical scrollbar.
5540     *
5541     * @return The width in pixels of the vertical scrollbar or 0 if there
5542     *         is no vertical scrollbar.
5543     */
5544    public int getVerticalScrollbarWidth() {
5545        ScrollabilityCache cache = mScrollCache;
5546        if (cache != null) {
5547            ScrollBarDrawable scrollBar = cache.scrollBar;
5548            if (scrollBar != null) {
5549                int size = scrollBar.getSize(true);
5550                if (size <= 0) {
5551                    size = cache.scrollBarSize;
5552                }
5553                return size;
5554            }
5555            return 0;
5556        }
5557        return 0;
5558    }
5559
5560    /**
5561     * Returns the height of the horizontal scrollbar.
5562     *
5563     * @return The height in pixels of the horizontal scrollbar or 0 if
5564     *         there is no horizontal scrollbar.
5565     */
5566    protected int getHorizontalScrollbarHeight() {
5567        ScrollabilityCache cache = mScrollCache;
5568        if (cache != null) {
5569            ScrollBarDrawable scrollBar = cache.scrollBar;
5570            if (scrollBar != null) {
5571                int size = scrollBar.getSize(false);
5572                if (size <= 0) {
5573                    size = cache.scrollBarSize;
5574                }
5575                return size;
5576            }
5577            return 0;
5578        }
5579        return 0;
5580    }
5581
5582    /**
5583     * <p>
5584     * Initializes the scrollbars from a given set of styled attributes. This
5585     * method should be called by subclasses that need scrollbars and when an
5586     * instance of these subclasses is created programmatically rather than
5587     * being inflated from XML. This method is automatically called when the XML
5588     * is inflated.
5589     * </p>
5590     *
5591     * @param a the styled attributes set to initialize the scrollbars from
5592     *
5593     * @removed
5594     */
5595    protected void initializeScrollbars(TypedArray a) {
5596        // It's not safe to use this method from apps. The parameter 'a' must have been obtained
5597        // using the View filter array which is not available to the SDK. As such, internal
5598        // framework usage now uses initializeScrollbarsInternal and we grab a default
5599        // TypedArray with the right filter instead here.
5600        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
5601
5602        initializeScrollbarsInternal(arr);
5603
5604        // We ignored the method parameter. Recycle the one we actually did use.
5605        arr.recycle();
5606    }
5607
5608    /**
5609     * <p>
5610     * Initializes the scrollbars from a given set of styled attributes. This
5611     * method should be called by subclasses that need scrollbars and when an
5612     * instance of these subclasses is created programmatically rather than
5613     * being inflated from XML. This method is automatically called when the XML
5614     * is inflated.
5615     * </p>
5616     *
5617     * @param a the styled attributes set to initialize the scrollbars from
5618     * @hide
5619     */
5620    protected void initializeScrollbarsInternal(TypedArray a) {
5621        initScrollCache();
5622
5623        final ScrollabilityCache scrollabilityCache = mScrollCache;
5624
5625        if (scrollabilityCache.scrollBar == null) {
5626            scrollabilityCache.scrollBar = new ScrollBarDrawable();
5627            scrollabilityCache.scrollBar.setState(getDrawableState());
5628            scrollabilityCache.scrollBar.setCallback(this);
5629        }
5630
5631        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
5632
5633        if (!fadeScrollbars) {
5634            scrollabilityCache.state = ScrollabilityCache.ON;
5635        }
5636        scrollabilityCache.fadeScrollBars = fadeScrollbars;
5637
5638
5639        scrollabilityCache.scrollBarFadeDuration = a.getInt(
5640                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
5641                        .getScrollBarFadeDuration());
5642        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
5643                R.styleable.View_scrollbarDefaultDelayBeforeFade,
5644                ViewConfiguration.getScrollDefaultDelay());
5645
5646
5647        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
5648                com.android.internal.R.styleable.View_scrollbarSize,
5649                ViewConfiguration.get(mContext).getScaledScrollBarSize());
5650
5651        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
5652        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
5653
5654        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
5655        if (thumb != null) {
5656            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
5657        }
5658
5659        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
5660                false);
5661        if (alwaysDraw) {
5662            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
5663        }
5664
5665        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
5666        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
5667
5668        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
5669        if (thumb != null) {
5670            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
5671        }
5672
5673        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
5674                false);
5675        if (alwaysDraw) {
5676            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
5677        }
5678
5679        // Apply layout direction to the new Drawables if needed
5680        final int layoutDirection = getLayoutDirection();
5681        if (track != null) {
5682            track.setLayoutDirection(layoutDirection);
5683        }
5684        if (thumb != null) {
5685            thumb.setLayoutDirection(layoutDirection);
5686        }
5687
5688        // Re-apply user/background padding so that scrollbar(s) get added
5689        resolvePadding();
5690    }
5691
5692    private void initializeScrollIndicatorsInternal() {
5693        // Some day maybe we'll break this into top/left/start/etc. and let the
5694        // client control it. Until then, you can have any scroll indicator you
5695        // want as long as it's a 1dp foreground-colored rectangle.
5696        if (mScrollIndicatorDrawable == null) {
5697            mScrollIndicatorDrawable = mContext.getDrawable(R.drawable.scroll_indicator_material);
5698        }
5699    }
5700
5701    /**
5702     * <p>
5703     * Initalizes the scrollability cache if necessary.
5704     * </p>
5705     */
5706    private void initScrollCache() {
5707        if (mScrollCache == null) {
5708            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
5709        }
5710    }
5711
5712    private ScrollabilityCache getScrollCache() {
5713        initScrollCache();
5714        return mScrollCache;
5715    }
5716
5717    /**
5718     * Set the position of the vertical scroll bar. Should be one of
5719     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
5720     * {@link #SCROLLBAR_POSITION_RIGHT}.
5721     *
5722     * @param position Where the vertical scroll bar should be positioned.
5723     */
5724    public void setVerticalScrollbarPosition(int position) {
5725        if (mVerticalScrollbarPosition != position) {
5726            mVerticalScrollbarPosition = position;
5727            computeOpaqueFlags();
5728            resolvePadding();
5729        }
5730    }
5731
5732    /**
5733     * @return The position where the vertical scroll bar will show, if applicable.
5734     * @see #setVerticalScrollbarPosition(int)
5735     */
5736    public int getVerticalScrollbarPosition() {
5737        return mVerticalScrollbarPosition;
5738    }
5739
5740    boolean isOnScrollbar(float x, float y) {
5741        if (mScrollCache == null) {
5742            return false;
5743        }
5744        x += getScrollX();
5745        y += getScrollY();
5746        if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) {
5747            final Rect touchBounds = mScrollCache.mScrollBarTouchBounds;
5748            getVerticalScrollBarBounds(null, touchBounds);
5749            if (touchBounds.contains((int) x, (int) y)) {
5750                return true;
5751            }
5752        }
5753        if (isHorizontalScrollBarEnabled()) {
5754            final Rect touchBounds = mScrollCache.mScrollBarTouchBounds;
5755            getHorizontalScrollBarBounds(null, touchBounds);
5756            if (touchBounds.contains((int) x, (int) y)) {
5757                return true;
5758            }
5759        }
5760        return false;
5761    }
5762
5763    boolean isOnScrollbarThumb(float x, float y) {
5764        return isOnVerticalScrollbarThumb(x, y) || isOnHorizontalScrollbarThumb(x, y);
5765    }
5766
5767    private boolean isOnVerticalScrollbarThumb(float x, float y) {
5768        if (mScrollCache == null) {
5769            return false;
5770        }
5771        if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) {
5772            x += getScrollX();
5773            y += getScrollY();
5774            final Rect bounds = mScrollCache.mScrollBarBounds;
5775            final Rect touchBounds = mScrollCache.mScrollBarTouchBounds;
5776            getVerticalScrollBarBounds(bounds, touchBounds);
5777            final int range = computeVerticalScrollRange();
5778            final int offset = computeVerticalScrollOffset();
5779            final int extent = computeVerticalScrollExtent();
5780            final int thumbLength = ScrollBarUtils.getThumbLength(bounds.height(), bounds.width(),
5781                    extent, range);
5782            final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.height(), thumbLength,
5783                    extent, range, offset);
5784            final int thumbTop = bounds.top + thumbOffset;
5785            final int adjust = Math.max(mScrollCache.scrollBarMinTouchTarget - thumbLength, 0) / 2;
5786            if (x >= touchBounds.left && x <= touchBounds.right
5787                    && y >= thumbTop - adjust && y <= thumbTop + thumbLength + adjust) {
5788                return true;
5789            }
5790        }
5791        return false;
5792    }
5793
5794    private boolean isOnHorizontalScrollbarThumb(float x, float y) {
5795        if (mScrollCache == null) {
5796            return false;
5797        }
5798        if (isHorizontalScrollBarEnabled()) {
5799            x += getScrollX();
5800            y += getScrollY();
5801            final Rect bounds = mScrollCache.mScrollBarBounds;
5802            final Rect touchBounds = mScrollCache.mScrollBarTouchBounds;
5803            getHorizontalScrollBarBounds(bounds, touchBounds);
5804            final int range = computeHorizontalScrollRange();
5805            final int offset = computeHorizontalScrollOffset();
5806            final int extent = computeHorizontalScrollExtent();
5807            final int thumbLength = ScrollBarUtils.getThumbLength(bounds.width(), bounds.height(),
5808                    extent, range);
5809            final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.width(), thumbLength,
5810                    extent, range, offset);
5811            final int thumbLeft = bounds.left + thumbOffset;
5812            final int adjust = Math.max(mScrollCache.scrollBarMinTouchTarget - thumbLength, 0) / 2;
5813            if (x >= thumbLeft - adjust && x <= thumbLeft + thumbLength + adjust
5814                    && y >= touchBounds.top && y <= touchBounds.bottom) {
5815                return true;
5816            }
5817        }
5818        return false;
5819    }
5820
5821    boolean isDraggingScrollBar() {
5822        return mScrollCache != null
5823                && mScrollCache.mScrollBarDraggingState != ScrollabilityCache.NOT_DRAGGING;
5824    }
5825
5826    /**
5827     * Sets the state of all scroll indicators.
5828     * <p>
5829     * See {@link #setScrollIndicators(int, int)} for usage information.
5830     *
5831     * @param indicators a bitmask of indicators that should be enabled, or
5832     *                   {@code 0} to disable all indicators
5833     * @see #setScrollIndicators(int, int)
5834     * @see #getScrollIndicators()
5835     * @attr ref android.R.styleable#View_scrollIndicators
5836     */
5837    public void setScrollIndicators(@ScrollIndicators int indicators) {
5838        setScrollIndicators(indicators,
5839                SCROLL_INDICATORS_PFLAG3_MASK >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT);
5840    }
5841
5842    /**
5843     * Sets the state of the scroll indicators specified by the mask. To change
5844     * all scroll indicators at once, see {@link #setScrollIndicators(int)}.
5845     * <p>
5846     * When a scroll indicator is enabled, it will be displayed if the view
5847     * can scroll in the direction of the indicator.
5848     * <p>
5849     * Multiple indicator types may be enabled or disabled by passing the
5850     * logical OR of the desired types. If multiple types are specified, they
5851     * will all be set to the same enabled state.
5852     * <p>
5853     * For example, to enable the top scroll indicatorExample: {@code setScrollIndicators
5854     *
5855     * @param indicators the indicator direction, or the logical OR of multiple
5856     *             indicator directions. One or more of:
5857     *             <ul>
5858     *               <li>{@link #SCROLL_INDICATOR_TOP}</li>
5859     *               <li>{@link #SCROLL_INDICATOR_BOTTOM}</li>
5860     *               <li>{@link #SCROLL_INDICATOR_LEFT}</li>
5861     *               <li>{@link #SCROLL_INDICATOR_RIGHT}</li>
5862     *               <li>{@link #SCROLL_INDICATOR_START}</li>
5863     *               <li>{@link #SCROLL_INDICATOR_END}</li>
5864     *             </ul>
5865     * @see #setScrollIndicators(int)
5866     * @see #getScrollIndicators()
5867     * @attr ref android.R.styleable#View_scrollIndicators
5868     */
5869    public void setScrollIndicators(@ScrollIndicators int indicators, @ScrollIndicators int mask) {
5870        // Shift and sanitize mask.
5871        mask <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5872        mask &= SCROLL_INDICATORS_PFLAG3_MASK;
5873
5874        // Shift and mask indicators.
5875        indicators <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5876        indicators &= mask;
5877
5878        // Merge with non-masked flags.
5879        final int updatedFlags = indicators | (mPrivateFlags3 & ~mask);
5880
5881        if (mPrivateFlags3 != updatedFlags) {
5882            mPrivateFlags3 = updatedFlags;
5883
5884            if (indicators != 0) {
5885                initializeScrollIndicatorsInternal();
5886            }
5887            invalidate();
5888        }
5889    }
5890
5891    /**
5892     * Returns a bitmask representing the enabled scroll indicators.
5893     * <p>
5894     * For example, if the top and left scroll indicators are enabled and all
5895     * other indicators are disabled, the return value will be
5896     * {@code View.SCROLL_INDICATOR_TOP | View.SCROLL_INDICATOR_LEFT}.
5897     * <p>
5898     * To check whether the bottom scroll indicator is enabled, use the value
5899     * of {@code (getScrollIndicators() & View.SCROLL_INDICATOR_BOTTOM) != 0}.
5900     *
5901     * @return a bitmask representing the enabled scroll indicators
5902     */
5903    @ScrollIndicators
5904    public int getScrollIndicators() {
5905        return (mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK)
5906                >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5907    }
5908
5909    ListenerInfo getListenerInfo() {
5910        if (mListenerInfo != null) {
5911            return mListenerInfo;
5912        }
5913        mListenerInfo = new ListenerInfo();
5914        return mListenerInfo;
5915    }
5916
5917    /**
5918     * Register a callback to be invoked when the scroll X or Y positions of
5919     * this view change.
5920     * <p>
5921     * <b>Note:</b> Some views handle scrolling independently from View and may
5922     * have their own separate listeners for scroll-type events. For example,
5923     * {@link android.widget.ListView ListView} allows clients to register an
5924     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
5925     * to listen for changes in list scroll position.
5926     *
5927     * @param l The listener to notify when the scroll X or Y position changes.
5928     * @see android.view.View#getScrollX()
5929     * @see android.view.View#getScrollY()
5930     */
5931    public void setOnScrollChangeListener(OnScrollChangeListener l) {
5932        getListenerInfo().mOnScrollChangeListener = l;
5933    }
5934
5935    /**
5936     * Register a callback to be invoked when focus of this view changed.
5937     *
5938     * @param l The callback that will run.
5939     */
5940    public void setOnFocusChangeListener(OnFocusChangeListener l) {
5941        getListenerInfo().mOnFocusChangeListener = l;
5942    }
5943
5944    /**
5945     * Add a listener that will be called when the bounds of the view change due to
5946     * layout processing.
5947     *
5948     * @param listener The listener that will be called when layout bounds change.
5949     */
5950    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
5951        ListenerInfo li = getListenerInfo();
5952        if (li.mOnLayoutChangeListeners == null) {
5953            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
5954        }
5955        if (!li.mOnLayoutChangeListeners.contains(listener)) {
5956            li.mOnLayoutChangeListeners.add(listener);
5957        }
5958    }
5959
5960    /**
5961     * Remove a listener for layout changes.
5962     *
5963     * @param listener The listener for layout bounds change.
5964     */
5965    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
5966        ListenerInfo li = mListenerInfo;
5967        if (li == null || li.mOnLayoutChangeListeners == null) {
5968            return;
5969        }
5970        li.mOnLayoutChangeListeners.remove(listener);
5971    }
5972
5973    /**
5974     * Add a listener for attach state changes.
5975     *
5976     * This listener will be called whenever this view is attached or detached
5977     * from a window. Remove the listener using
5978     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
5979     *
5980     * @param listener Listener to attach
5981     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
5982     */
5983    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
5984        ListenerInfo li = getListenerInfo();
5985        if (li.mOnAttachStateChangeListeners == null) {
5986            li.mOnAttachStateChangeListeners
5987                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
5988        }
5989        li.mOnAttachStateChangeListeners.add(listener);
5990    }
5991
5992    /**
5993     * Remove a listener for attach state changes. The listener will receive no further
5994     * notification of window attach/detach events.
5995     *
5996     * @param listener Listener to remove
5997     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
5998     */
5999    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
6000        ListenerInfo li = mListenerInfo;
6001        if (li == null || li.mOnAttachStateChangeListeners == null) {
6002            return;
6003        }
6004        li.mOnAttachStateChangeListeners.remove(listener);
6005    }
6006
6007    /**
6008     * Returns the focus-change callback registered for this view.
6009     *
6010     * @return The callback, or null if one is not registered.
6011     */
6012    public OnFocusChangeListener getOnFocusChangeListener() {
6013        ListenerInfo li = mListenerInfo;
6014        return li != null ? li.mOnFocusChangeListener : null;
6015    }
6016
6017    /**
6018     * Register a callback to be invoked when this view is clicked. If this view is not
6019     * clickable, it becomes clickable.
6020     *
6021     * @param l The callback that will run
6022     *
6023     * @see #setClickable(boolean)
6024     */
6025    public void setOnClickListener(@Nullable OnClickListener l) {
6026        if (!isClickable()) {
6027            setClickable(true);
6028        }
6029        getListenerInfo().mOnClickListener = l;
6030    }
6031
6032    /**
6033     * Return whether this view has an attached OnClickListener.  Returns
6034     * true if there is a listener, false if there is none.
6035     */
6036    public boolean hasOnClickListeners() {
6037        ListenerInfo li = mListenerInfo;
6038        return (li != null && li.mOnClickListener != null);
6039    }
6040
6041    /**
6042     * Register a callback to be invoked when this view is clicked and held. If this view is not
6043     * long clickable, it becomes long clickable.
6044     *
6045     * @param l The callback that will run
6046     *
6047     * @see #setLongClickable(boolean)
6048     */
6049    public void setOnLongClickListener(@Nullable OnLongClickListener l) {
6050        if (!isLongClickable()) {
6051            setLongClickable(true);
6052        }
6053        getListenerInfo().mOnLongClickListener = l;
6054    }
6055
6056    /**
6057     * Register a callback to be invoked when this view is context clicked. If the view is not
6058     * context clickable, it becomes context clickable.
6059     *
6060     * @param l The callback that will run
6061     * @see #setContextClickable(boolean)
6062     */
6063    public void setOnContextClickListener(@Nullable OnContextClickListener l) {
6064        if (!isContextClickable()) {
6065            setContextClickable(true);
6066        }
6067        getListenerInfo().mOnContextClickListener = l;
6068    }
6069
6070    /**
6071     * Register a callback to be invoked when the context menu for this view is
6072     * being built. If this view is not long clickable, it becomes long clickable.
6073     *
6074     * @param l The callback that will run
6075     *
6076     */
6077    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
6078        if (!isLongClickable()) {
6079            setLongClickable(true);
6080        }
6081        getListenerInfo().mOnCreateContextMenuListener = l;
6082    }
6083
6084    /**
6085     * Set an observer to collect stats for each frame rendered for this view.
6086     *
6087     * @hide
6088     */
6089    public void addFrameMetricsListener(Window window,
6090            Window.OnFrameMetricsAvailableListener listener,
6091            Handler handler) {
6092        if (mAttachInfo != null) {
6093            if (mAttachInfo.mThreadedRenderer != null) {
6094                if (mFrameMetricsObservers == null) {
6095                    mFrameMetricsObservers = new ArrayList<>();
6096                }
6097
6098                FrameMetricsObserver fmo = new FrameMetricsObserver(window,
6099                        handler.getLooper(), listener);
6100                mFrameMetricsObservers.add(fmo);
6101                mAttachInfo.mThreadedRenderer.addFrameMetricsObserver(fmo);
6102            } else {
6103                Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats");
6104            }
6105        } else {
6106            if (mFrameMetricsObservers == null) {
6107                mFrameMetricsObservers = new ArrayList<>();
6108            }
6109
6110            FrameMetricsObserver fmo = new FrameMetricsObserver(window,
6111                    handler.getLooper(), listener);
6112            mFrameMetricsObservers.add(fmo);
6113        }
6114    }
6115
6116    /**
6117     * Remove observer configured to collect frame stats for this view.
6118     *
6119     * @hide
6120     */
6121    public void removeFrameMetricsListener(
6122            Window.OnFrameMetricsAvailableListener listener) {
6123        ThreadedRenderer renderer = getThreadedRenderer();
6124        FrameMetricsObserver fmo = findFrameMetricsObserver(listener);
6125        if (fmo == null) {
6126            throw new IllegalArgumentException(
6127                    "attempt to remove OnFrameMetricsAvailableListener that was never added");
6128        }
6129
6130        if (mFrameMetricsObservers != null) {
6131            mFrameMetricsObservers.remove(fmo);
6132            if (renderer != null) {
6133                renderer.removeFrameMetricsObserver(fmo);
6134            }
6135        }
6136    }
6137
6138    private void registerPendingFrameMetricsObservers() {
6139        if (mFrameMetricsObservers != null) {
6140            ThreadedRenderer renderer = getThreadedRenderer();
6141            if (renderer != null) {
6142                for (FrameMetricsObserver fmo : mFrameMetricsObservers) {
6143                    renderer.addFrameMetricsObserver(fmo);
6144                }
6145            } else {
6146                Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats");
6147            }
6148        }
6149    }
6150
6151    private FrameMetricsObserver findFrameMetricsObserver(
6152            Window.OnFrameMetricsAvailableListener listener) {
6153        for (int i = 0; i < mFrameMetricsObservers.size(); i++) {
6154            FrameMetricsObserver observer = mFrameMetricsObservers.get(i);
6155            if (observer.mListener == listener) {
6156                return observer;
6157            }
6158        }
6159
6160        return null;
6161    }
6162
6163    /**
6164     * Call this view's OnClickListener, if it is defined.  Performs all normal
6165     * actions associated with clicking: reporting accessibility event, playing
6166     * a sound, etc.
6167     *
6168     * @return True there was an assigned OnClickListener that was called, false
6169     *         otherwise is returned.
6170     */
6171    public boolean performClick() {
6172        final boolean result;
6173        final ListenerInfo li = mListenerInfo;
6174        if (li != null && li.mOnClickListener != null) {
6175            playSoundEffect(SoundEffectConstants.CLICK);
6176            li.mOnClickListener.onClick(this);
6177            result = true;
6178        } else {
6179            result = false;
6180        }
6181
6182        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
6183
6184        notifyEnterOrExitForAutoFillIfNeeded(true);
6185
6186        return result;
6187    }
6188
6189    /**
6190     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
6191     * this only calls the listener, and does not do any associated clicking
6192     * actions like reporting an accessibility event.
6193     *
6194     * @return True there was an assigned OnClickListener that was called, false
6195     *         otherwise is returned.
6196     */
6197    public boolean callOnClick() {
6198        ListenerInfo li = mListenerInfo;
6199        if (li != null && li.mOnClickListener != null) {
6200            li.mOnClickListener.onClick(this);
6201            return true;
6202        }
6203        return false;
6204    }
6205
6206    /**
6207     * Calls this view's OnLongClickListener, if it is defined. Invokes the
6208     * context menu if the OnLongClickListener did not consume the event.
6209     *
6210     * @return {@code true} if one of the above receivers consumed the event,
6211     *         {@code false} otherwise
6212     */
6213    public boolean performLongClick() {
6214        return performLongClickInternal(mLongClickX, mLongClickY);
6215    }
6216
6217    /**
6218     * Calls this view's OnLongClickListener, if it is defined. Invokes the
6219     * context menu if the OnLongClickListener did not consume the event,
6220     * anchoring it to an (x,y) coordinate.
6221     *
6222     * @param x x coordinate of the anchoring touch event, or {@link Float#NaN}
6223     *          to disable anchoring
6224     * @param y y coordinate of the anchoring touch event, or {@link Float#NaN}
6225     *          to disable anchoring
6226     * @return {@code true} if one of the above receivers consumed the event,
6227     *         {@code false} otherwise
6228     */
6229    public boolean performLongClick(float x, float y) {
6230        mLongClickX = x;
6231        mLongClickY = y;
6232        final boolean handled = performLongClick();
6233        mLongClickX = Float.NaN;
6234        mLongClickY = Float.NaN;
6235        return handled;
6236    }
6237
6238    /**
6239     * Calls this view's OnLongClickListener, if it is defined. Invokes the
6240     * context menu if the OnLongClickListener did not consume the event,
6241     * optionally anchoring it to an (x,y) coordinate.
6242     *
6243     * @param x x coordinate of the anchoring touch event, or {@link Float#NaN}
6244     *          to disable anchoring
6245     * @param y y coordinate of the anchoring touch event, or {@link Float#NaN}
6246     *          to disable anchoring
6247     * @return {@code true} if one of the above receivers consumed the event,
6248     *         {@code false} otherwise
6249     */
6250    private boolean performLongClickInternal(float x, float y) {
6251        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
6252
6253        boolean handled = false;
6254        final ListenerInfo li = mListenerInfo;
6255        if (li != null && li.mOnLongClickListener != null) {
6256            handled = li.mOnLongClickListener.onLongClick(View.this);
6257        }
6258        if (!handled) {
6259            final boolean isAnchored = !Float.isNaN(x) && !Float.isNaN(y);
6260            handled = isAnchored ? showContextMenu(x, y) : showContextMenu();
6261        }
6262        if ((mViewFlags & TOOLTIP) == TOOLTIP) {
6263            if (!handled) {
6264                handled = showLongClickTooltip((int) x, (int) y);
6265            }
6266        }
6267        if (handled) {
6268            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
6269        }
6270        return handled;
6271    }
6272
6273    /**
6274     * Call this view's OnContextClickListener, if it is defined.
6275     *
6276     * @param x the x coordinate of the context click
6277     * @param y the y coordinate of the context click
6278     * @return True if there was an assigned OnContextClickListener that consumed the event, false
6279     *         otherwise.
6280     */
6281    public boolean performContextClick(float x, float y) {
6282        return performContextClick();
6283    }
6284
6285    /**
6286     * Call this view's OnContextClickListener, if it is defined.
6287     *
6288     * @return True if there was an assigned OnContextClickListener that consumed the event, false
6289     *         otherwise.
6290     */
6291    public boolean performContextClick() {
6292        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CONTEXT_CLICKED);
6293
6294        boolean handled = false;
6295        ListenerInfo li = mListenerInfo;
6296        if (li != null && li.mOnContextClickListener != null) {
6297            handled = li.mOnContextClickListener.onContextClick(View.this);
6298        }
6299        if (handled) {
6300            performHapticFeedback(HapticFeedbackConstants.CONTEXT_CLICK);
6301        }
6302        return handled;
6303    }
6304
6305    /**
6306     * Performs button-related actions during a touch down event.
6307     *
6308     * @param event The event.
6309     * @return True if the down was consumed.
6310     *
6311     * @hide
6312     */
6313    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
6314        if (event.isFromSource(InputDevice.SOURCE_MOUSE) &&
6315            (event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
6316            showContextMenu(event.getX(), event.getY());
6317            mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
6318            return true;
6319        }
6320        return false;
6321    }
6322
6323    /**
6324     * Shows the context menu for this view.
6325     *
6326     * @return {@code true} if the context menu was shown, {@code false}
6327     *         otherwise
6328     * @see #showContextMenu(float, float)
6329     */
6330    public boolean showContextMenu() {
6331        return getParent().showContextMenuForChild(this);
6332    }
6333
6334    /**
6335     * Shows the context menu for this view anchored to the specified
6336     * view-relative coordinate.
6337     *
6338     * @param x the X coordinate in pixels relative to the view to which the
6339     *          menu should be anchored, or {@link Float#NaN} to disable anchoring
6340     * @param y the Y coordinate in pixels relative to the view to which the
6341     *          menu should be anchored, or {@link Float#NaN} to disable anchoring
6342     * @return {@code true} if the context menu was shown, {@code false}
6343     *         otherwise
6344     */
6345    public boolean showContextMenu(float x, float y) {
6346        return getParent().showContextMenuForChild(this, x, y);
6347    }
6348
6349    /**
6350     * Start an action mode with the default type {@link ActionMode#TYPE_PRIMARY}.
6351     *
6352     * @param callback Callback that will control the lifecycle of the action mode
6353     * @return The new action mode if it is started, null otherwise
6354     *
6355     * @see ActionMode
6356     * @see #startActionMode(android.view.ActionMode.Callback, int)
6357     */
6358    public ActionMode startActionMode(ActionMode.Callback callback) {
6359        return startActionMode(callback, ActionMode.TYPE_PRIMARY);
6360    }
6361
6362    /**
6363     * Start an action mode with the given type.
6364     *
6365     * @param callback Callback that will control the lifecycle of the action mode
6366     * @param type One of {@link ActionMode#TYPE_PRIMARY} or {@link ActionMode#TYPE_FLOATING}.
6367     * @return The new action mode if it is started, null otherwise
6368     *
6369     * @see ActionMode
6370     */
6371    public ActionMode startActionMode(ActionMode.Callback callback, int type) {
6372        ViewParent parent = getParent();
6373        if (parent == null) return null;
6374        try {
6375            return parent.startActionModeForChild(this, callback, type);
6376        } catch (AbstractMethodError ame) {
6377            // Older implementations of custom views might not implement this.
6378            return parent.startActionModeForChild(this, callback);
6379        }
6380    }
6381
6382    /**
6383     * Call {@link Context#startActivityForResult(String, Intent, int, Bundle)} for the View's
6384     * Context, creating a unique View identifier to retrieve the result.
6385     *
6386     * @param intent The Intent to be started.
6387     * @param requestCode The request code to use.
6388     * @hide
6389     */
6390    public void startActivityForResult(Intent intent, int requestCode) {
6391        mStartActivityRequestWho = "@android:view:" + System.identityHashCode(this);
6392        getContext().startActivityForResult(mStartActivityRequestWho, intent, requestCode, null);
6393    }
6394
6395    /**
6396     * If this View corresponds to the calling who, dispatches the activity result.
6397     * @param who The identifier for the targeted View to receive the result.
6398     * @param requestCode The integer request code originally supplied to
6399     *                    startActivityForResult(), allowing you to identify who this
6400     *                    result came from.
6401     * @param resultCode The integer result code returned by the child activity
6402     *                   through its setResult().
6403     * @param data An Intent, which can return result data to the caller
6404     *               (various data can be attached to Intent "extras").
6405     * @return {@code true} if the activity result was dispatched.
6406     * @hide
6407     */
6408    public boolean dispatchActivityResult(
6409            String who, int requestCode, int resultCode, Intent data) {
6410        if (mStartActivityRequestWho != null && mStartActivityRequestWho.equals(who)) {
6411            onActivityResult(requestCode, resultCode, data);
6412            mStartActivityRequestWho = null;
6413            return true;
6414        }
6415        return false;
6416    }
6417
6418    /**
6419     * Receive the result from a previous call to {@link #startActivityForResult(Intent, int)}.
6420     *
6421     * @param requestCode The integer request code originally supplied to
6422     *                    startActivityForResult(), allowing you to identify who this
6423     *                    result came from.
6424     * @param resultCode The integer result code returned by the child activity
6425     *                   through its setResult().
6426     * @param data An Intent, which can return result data to the caller
6427     *               (various data can be attached to Intent "extras").
6428     * @hide
6429     */
6430    public void onActivityResult(int requestCode, int resultCode, Intent data) {
6431        // Do nothing.
6432    }
6433
6434    /**
6435     * Register a callback to be invoked when a hardware key is pressed in this view.
6436     * Key presses in software input methods will generally not trigger the methods of
6437     * this listener.
6438     * @param l the key listener to attach to this view
6439     */
6440    public void setOnKeyListener(OnKeyListener l) {
6441        getListenerInfo().mOnKeyListener = l;
6442    }
6443
6444    /**
6445     * Register a callback to be invoked when a touch event is sent to this view.
6446     * @param l the touch listener to attach to this view
6447     */
6448    public void setOnTouchListener(OnTouchListener l) {
6449        getListenerInfo().mOnTouchListener = l;
6450    }
6451
6452    /**
6453     * Register a callback to be invoked when a generic motion event is sent to this view.
6454     * @param l the generic motion listener to attach to this view
6455     */
6456    public void setOnGenericMotionListener(OnGenericMotionListener l) {
6457        getListenerInfo().mOnGenericMotionListener = l;
6458    }
6459
6460    /**
6461     * Register a callback to be invoked when a hover event is sent to this view.
6462     * @param l the hover listener to attach to this view
6463     */
6464    public void setOnHoverListener(OnHoverListener l) {
6465        getListenerInfo().mOnHoverListener = l;
6466    }
6467
6468    /**
6469     * Register a drag event listener callback object for this View. The parameter is
6470     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
6471     * View, the system calls the
6472     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
6473     * @param l An implementation of {@link android.view.View.OnDragListener}.
6474     */
6475    public void setOnDragListener(OnDragListener l) {
6476        getListenerInfo().mOnDragListener = l;
6477    }
6478
6479    /**
6480     * Give this view focus. This will cause
6481     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
6482     *
6483     * Note: this does not check whether this {@link View} should get focus, it just
6484     * gives it focus no matter what.  It should only be called internally by framework
6485     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
6486     *
6487     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
6488     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
6489     *        focus moved when requestFocus() is called. It may not always
6490     *        apply, in which case use the default View.FOCUS_DOWN.
6491     * @param previouslyFocusedRect The rectangle of the view that had focus
6492     *        prior in this View's coordinate system.
6493     */
6494    void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) {
6495        if (DBG) {
6496            System.out.println(this + " requestFocus()");
6497        }
6498
6499        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
6500            mPrivateFlags |= PFLAG_FOCUSED;
6501
6502            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
6503
6504            if (mParent != null) {
6505                mParent.requestChildFocus(this, this);
6506                setFocusedInCluster();
6507            }
6508
6509            if (mAttachInfo != null) {
6510                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
6511            }
6512
6513            onFocusChanged(true, direction, previouslyFocusedRect);
6514            refreshDrawableState();
6515        }
6516    }
6517
6518    /**
6519     * Sets this view's preference for reveal behavior when it gains focus.
6520     *
6521     * <p>When set to true, this is a signal to ancestor views in the hierarchy that
6522     * this view would prefer to be brought fully into view when it gains focus.
6523     * For example, a text field that a user is meant to type into. Other views such
6524     * as scrolling containers may prefer to opt-out of this behavior.</p>
6525     *
6526     * <p>The default value for views is true, though subclasses may change this
6527     * based on their preferred behavior.</p>
6528     *
6529     * @param revealOnFocus true to request reveal on focus in ancestors, false otherwise
6530     *
6531     * @see #getRevealOnFocusHint()
6532     */
6533    public final void setRevealOnFocusHint(boolean revealOnFocus) {
6534        if (revealOnFocus) {
6535            mPrivateFlags3 &= ~PFLAG3_NO_REVEAL_ON_FOCUS;
6536        } else {
6537            mPrivateFlags3 |= PFLAG3_NO_REVEAL_ON_FOCUS;
6538        }
6539    }
6540
6541    /**
6542     * Returns this view's preference for reveal behavior when it gains focus.
6543     *
6544     * <p>When this method returns true for a child view requesting focus, ancestor
6545     * views responding to a focus change in {@link ViewParent#requestChildFocus(View, View)}
6546     * should make a best effort to make the newly focused child fully visible to the user.
6547     * When it returns false, ancestor views should preferably not disrupt scroll positioning or
6548     * other properties affecting visibility to the user as part of the focus change.</p>
6549     *
6550     * @return true if this view would prefer to become fully visible when it gains focus,
6551     *         false if it would prefer not to disrupt scroll positioning
6552     *
6553     * @see #setRevealOnFocusHint(boolean)
6554     */
6555    public final boolean getRevealOnFocusHint() {
6556        return (mPrivateFlags3 & PFLAG3_NO_REVEAL_ON_FOCUS) == 0;
6557    }
6558
6559    /**
6560     * Populates <code>outRect</code> with the hotspot bounds. By default,
6561     * the hotspot bounds are identical to the screen bounds.
6562     *
6563     * @param outRect rect to populate with hotspot bounds
6564     * @hide Only for internal use by views and widgets.
6565     */
6566    public void getHotspotBounds(Rect outRect) {
6567        final Drawable background = getBackground();
6568        if (background != null) {
6569            background.getHotspotBounds(outRect);
6570        } else {
6571            getBoundsOnScreen(outRect);
6572        }
6573    }
6574
6575    /**
6576     * Request that a rectangle of this view be visible on the screen,
6577     * scrolling if necessary just enough.
6578     *
6579     * <p>A View should call this if it maintains some notion of which part
6580     * of its content is interesting.  For example, a text editing view
6581     * should call this when its cursor moves.
6582     * <p>The Rectangle passed into this method should be in the View's content coordinate space.
6583     * It should not be affected by which part of the View is currently visible or its scroll
6584     * position.
6585     *
6586     * @param rectangle The rectangle in the View's content coordinate space
6587     * @return Whether any parent scrolled.
6588     */
6589    public boolean requestRectangleOnScreen(Rect rectangle) {
6590        return requestRectangleOnScreen(rectangle, false);
6591    }
6592
6593    /**
6594     * Request that a rectangle of this view be visible on the screen,
6595     * scrolling if necessary just enough.
6596     *
6597     * <p>A View should call this if it maintains some notion of which part
6598     * of its content is interesting.  For example, a text editing view
6599     * should call this when its cursor moves.
6600     * <p>The Rectangle passed into this method should be in the View's content coordinate space.
6601     * It should not be affected by which part of the View is currently visible or its scroll
6602     * position.
6603     * <p>When <code>immediate</code> is set to true, scrolling will not be
6604     * animated.
6605     *
6606     * @param rectangle The rectangle in the View's content coordinate space
6607     * @param immediate True to forbid animated scrolling, false otherwise
6608     * @return Whether any parent scrolled.
6609     */
6610    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
6611        if (mParent == null) {
6612            return false;
6613        }
6614
6615        View child = this;
6616
6617        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
6618        position.set(rectangle);
6619
6620        ViewParent parent = mParent;
6621        boolean scrolled = false;
6622        while (parent != null) {
6623            rectangle.set((int) position.left, (int) position.top,
6624                    (int) position.right, (int) position.bottom);
6625
6626            scrolled |= parent.requestChildRectangleOnScreen(child, rectangle, immediate);
6627
6628            if (!(parent instanceof View)) {
6629                break;
6630            }
6631
6632            // move it from child's content coordinate space to parent's content coordinate space
6633            position.offset(child.mLeft - child.getScrollX(), child.mTop -child.getScrollY());
6634
6635            child = (View) parent;
6636            parent = child.getParent();
6637        }
6638
6639        return scrolled;
6640    }
6641
6642    /**
6643     * Called when this view wants to give up focus. If focus is cleared
6644     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
6645     * <p>
6646     * <strong>Note:</strong> When a View clears focus the framework is trying
6647     * to give focus to the first focusable View from the top. Hence, if this
6648     * View is the first from the top that can take focus, then all callbacks
6649     * related to clearing focus will be invoked after which the framework will
6650     * give focus to this view.
6651     * </p>
6652     */
6653    public void clearFocus() {
6654        if (DBG) {
6655            System.out.println(this + " clearFocus()");
6656        }
6657
6658        clearFocusInternal(null, true, true);
6659    }
6660
6661    /**
6662     * Clears focus from the view, optionally propagating the change up through
6663     * the parent hierarchy and requesting that the root view place new focus.
6664     *
6665     * @param propagate whether to propagate the change up through the parent
6666     *            hierarchy
6667     * @param refocus when propagate is true, specifies whether to request the
6668     *            root view place new focus
6669     */
6670    void clearFocusInternal(View focused, boolean propagate, boolean refocus) {
6671        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
6672            mPrivateFlags &= ~PFLAG_FOCUSED;
6673
6674            if (propagate && mParent != null) {
6675                mParent.clearChildFocus(this);
6676            }
6677
6678            onFocusChanged(false, 0, null);
6679            refreshDrawableState();
6680
6681            if (propagate && (!refocus || !rootViewRequestFocus())) {
6682                notifyGlobalFocusCleared(this);
6683            }
6684        }
6685    }
6686
6687    void notifyGlobalFocusCleared(View oldFocus) {
6688        if (oldFocus != null && mAttachInfo != null) {
6689            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
6690        }
6691    }
6692
6693    boolean rootViewRequestFocus() {
6694        final View root = getRootView();
6695        return root != null && root.requestFocus();
6696    }
6697
6698    /**
6699     * Called internally by the view system when a new view is getting focus.
6700     * This is what clears the old focus.
6701     * <p>
6702     * <b>NOTE:</b> The parent view's focused child must be updated manually
6703     * after calling this method. Otherwise, the view hierarchy may be left in
6704     * an inconstent state.
6705     */
6706    void unFocus(View focused) {
6707        if (DBG) {
6708            System.out.println(this + " unFocus()");
6709        }
6710
6711        clearFocusInternal(focused, false, false);
6712    }
6713
6714    /**
6715     * Returns true if this view has focus itself, or is the ancestor of the
6716     * view that has focus.
6717     *
6718     * @return True if this view has or contains focus, false otherwise.
6719     */
6720    @ViewDebug.ExportedProperty(category = "focus")
6721    public boolean hasFocus() {
6722        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
6723    }
6724
6725    /**
6726     * Returns true if this view is focusable or if it contains a reachable View
6727     * for which {@link #hasFocusable()} returns {@code true}. A "reachable hasFocusable()"
6728     * is a view whose parents do not block descendants focus.
6729     * Only {@link #VISIBLE} views are considered focusable.
6730     *
6731     * <p>As of {@link Build.VERSION_CODES#O} views that are determined to be focusable
6732     * through {@link #FOCUSABLE_AUTO} will also cause this method to return {@code true}.
6733     * Apps that declare a {@link android.content.pm.ApplicationInfo#targetSdkVersion} of
6734     * earlier than {@link Build.VERSION_CODES#O} will continue to see this method return
6735     * {@code false} for views not explicitly marked as focusable.
6736     * Use {@link #hasExplicitFocusable()} if you require the pre-{@link Build.VERSION_CODES#O}
6737     * behavior.</p>
6738     *
6739     * @return {@code true} if the view is focusable or if the view contains a focusable
6740     *         view, {@code false} otherwise
6741     *
6742     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
6743     * @see ViewGroup#getTouchscreenBlocksFocus()
6744     * @see #hasExplicitFocusable()
6745     */
6746    public boolean hasFocusable() {
6747        return hasFocusable(!sHasFocusableExcludeAutoFocusable, false);
6748    }
6749
6750    /**
6751     * Returns true if this view is focusable or if it contains a reachable View
6752     * for which {@link #hasExplicitFocusable()} returns {@code true}.
6753     * A "reachable hasExplicitFocusable()" is a view whose parents do not block descendants focus.
6754     * Only {@link #VISIBLE} views for which {@link #getFocusable()} would return
6755     * {@link #FOCUSABLE} are considered focusable.
6756     *
6757     * <p>This method preserves the pre-{@link Build.VERSION_CODES#O} behavior of
6758     * {@link #hasFocusable()} in that only views explicitly set focusable will cause
6759     * this method to return true. A view set to {@link #FOCUSABLE_AUTO} that resolves
6760     * to focusable will not.</p>
6761     *
6762     * @return {@code true} if the view is focusable or if the view contains a focusable
6763     *         view, {@code false} otherwise
6764     *
6765     * @see #hasFocusable()
6766     */
6767    public boolean hasExplicitFocusable() {
6768        return hasFocusable(false, true);
6769    }
6770
6771    boolean hasFocusable(boolean allowAutoFocus, boolean dispatchExplicit) {
6772        if (!isFocusableInTouchMode()) {
6773            for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) {
6774                final ViewGroup g = (ViewGroup) p;
6775                if (g.shouldBlockFocusForTouchscreen()) {
6776                    return false;
6777                }
6778            }
6779        }
6780
6781        // Invisible and gone views are never focusable.
6782        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6783            return false;
6784        }
6785
6786        // Only use effective focusable value when allowed.
6787        if ((allowAutoFocus || getFocusable() != FOCUSABLE_AUTO) && isFocusable()) {
6788            return true;
6789        }
6790
6791        return false;
6792    }
6793
6794    /**
6795     * Called by the view system when the focus state of this view changes.
6796     * When the focus change event is caused by directional navigation, direction
6797     * and previouslyFocusedRect provide insight into where the focus is coming from.
6798     * When overriding, be sure to call up through to the super class so that
6799     * the standard focus handling will occur.
6800     *
6801     * @param gainFocus True if the View has focus; false otherwise.
6802     * @param direction The direction focus has moved when requestFocus()
6803     *                  is called to give this view focus. Values are
6804     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
6805     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
6806     *                  It may not always apply, in which case use the default.
6807     * @param previouslyFocusedRect The rectangle, in this view's coordinate
6808     *        system, of the previously focused view.  If applicable, this will be
6809     *        passed in as finer grained information about where the focus is coming
6810     *        from (in addition to direction).  Will be <code>null</code> otherwise.
6811     */
6812    @CallSuper
6813    protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction,
6814            @Nullable Rect previouslyFocusedRect) {
6815        if (gainFocus) {
6816            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
6817        } else {
6818            notifyViewAccessibilityStateChangedIfNeeded(
6819                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
6820        }
6821
6822        // Here we check whether we still need the default focus highlight, and switch it on/off.
6823        switchDefaultFocusHighlight();
6824
6825        InputMethodManager imm = InputMethodManager.peekInstance();
6826        if (!gainFocus) {
6827            if (isPressed()) {
6828                setPressed(false);
6829            }
6830            if (imm != null && mAttachInfo != null && mAttachInfo.mHasWindowFocus) {
6831                imm.focusOut(this);
6832            }
6833            onFocusLost();
6834        } else if (imm != null && mAttachInfo != null && mAttachInfo.mHasWindowFocus) {
6835            imm.focusIn(this);
6836        }
6837
6838        invalidate(true);
6839        ListenerInfo li = mListenerInfo;
6840        if (li != null && li.mOnFocusChangeListener != null) {
6841            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
6842        }
6843
6844        if (mAttachInfo != null) {
6845            mAttachInfo.mKeyDispatchState.reset(this);
6846        }
6847
6848        notifyEnterOrExitForAutoFillIfNeeded(gainFocus);
6849    }
6850
6851    private void notifyEnterOrExitForAutoFillIfNeeded(boolean enter) {
6852        if (isAutofillable() && isAttachedToWindow()
6853                && getResolvedAutofillMode() == AUTOFILL_MODE_AUTO) {
6854            AutofillManager afm = getAutofillManager();
6855            if (afm != null) {
6856                if (enter && hasWindowFocus() && isFocused()) {
6857                    afm.notifyViewEntered(this);
6858                } else if (!hasWindowFocus() || !isFocused()) {
6859                    afm.notifyViewExited(this);
6860                }
6861            }
6862        }
6863    }
6864
6865    /**
6866     * Sends an accessibility event of the given type. If accessibility is
6867     * not enabled this method has no effect. The default implementation calls
6868     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
6869     * to populate information about the event source (this View), then calls
6870     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
6871     * populate the text content of the event source including its descendants,
6872     * and last calls
6873     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
6874     * on its parent to request sending of the event to interested parties.
6875     * <p>
6876     * If an {@link AccessibilityDelegate} has been specified via calling
6877     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6878     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
6879     * responsible for handling this call.
6880     * </p>
6881     *
6882     * @param eventType The type of the event to send, as defined by several types from
6883     * {@link android.view.accessibility.AccessibilityEvent}, such as
6884     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
6885     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
6886     *
6887     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
6888     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6889     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
6890     * @see AccessibilityDelegate
6891     */
6892    public void sendAccessibilityEvent(int eventType) {
6893        if (mAccessibilityDelegate != null) {
6894            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
6895        } else {
6896            sendAccessibilityEventInternal(eventType);
6897        }
6898    }
6899
6900    /**
6901     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
6902     * {@link AccessibilityEvent} to make an announcement which is related to some
6903     * sort of a context change for which none of the events representing UI transitions
6904     * is a good fit. For example, announcing a new page in a book. If accessibility
6905     * is not enabled this method does nothing.
6906     *
6907     * @param text The announcement text.
6908     */
6909    public void announceForAccessibility(CharSequence text) {
6910        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
6911            AccessibilityEvent event = AccessibilityEvent.obtain(
6912                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
6913            onInitializeAccessibilityEvent(event);
6914            event.getText().add(text);
6915            event.setContentDescription(null);
6916            mParent.requestSendAccessibilityEvent(this, event);
6917        }
6918    }
6919
6920    /**
6921     * @see #sendAccessibilityEvent(int)
6922     *
6923     * Note: Called from the default {@link AccessibilityDelegate}.
6924     *
6925     * @hide
6926     */
6927    public void sendAccessibilityEventInternal(int eventType) {
6928        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
6929            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
6930        }
6931    }
6932
6933    /**
6934     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
6935     * takes as an argument an empty {@link AccessibilityEvent} and does not
6936     * perform a check whether accessibility is enabled.
6937     * <p>
6938     * If an {@link AccessibilityDelegate} has been specified via calling
6939     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6940     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
6941     * is responsible for handling this call.
6942     * </p>
6943     *
6944     * @param event The event to send.
6945     *
6946     * @see #sendAccessibilityEvent(int)
6947     */
6948    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
6949        if (mAccessibilityDelegate != null) {
6950            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
6951        } else {
6952            sendAccessibilityEventUncheckedInternal(event);
6953        }
6954    }
6955
6956    /**
6957     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
6958     *
6959     * Note: Called from the default {@link AccessibilityDelegate}.
6960     *
6961     * @hide
6962     */
6963    public void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
6964        if (!isShown()) {
6965            return;
6966        }
6967        onInitializeAccessibilityEvent(event);
6968        // Only a subset of accessibility events populates text content.
6969        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
6970            dispatchPopulateAccessibilityEvent(event);
6971        }
6972        // In the beginning we called #isShown(), so we know that getParent() is not null.
6973        getParent().requestSendAccessibilityEvent(this, event);
6974    }
6975
6976    /**
6977     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
6978     * to its children for adding their text content to the event. Note that the
6979     * event text is populated in a separate dispatch path since we add to the
6980     * event not only the text of the source but also the text of all its descendants.
6981     * A typical implementation will call
6982     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
6983     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
6984     * on each child. Override this method if custom population of the event text
6985     * content is required.
6986     * <p>
6987     * If an {@link AccessibilityDelegate} has been specified via calling
6988     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6989     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
6990     * is responsible for handling this call.
6991     * </p>
6992     * <p>
6993     * <em>Note:</em> Accessibility events of certain types are not dispatched for
6994     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
6995     * </p>
6996     *
6997     * @param event The event.
6998     *
6999     * @return True if the event population was completed.
7000     */
7001    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
7002        if (mAccessibilityDelegate != null) {
7003            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
7004        } else {
7005            return dispatchPopulateAccessibilityEventInternal(event);
7006        }
7007    }
7008
7009    /**
7010     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
7011     *
7012     * Note: Called from the default {@link AccessibilityDelegate}.
7013     *
7014     * @hide
7015     */
7016    public boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
7017        onPopulateAccessibilityEvent(event);
7018        return false;
7019    }
7020
7021    /**
7022     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
7023     * giving a chance to this View to populate the accessibility event with its
7024     * text content. While this method is free to modify event
7025     * attributes other than text content, doing so should normally be performed in
7026     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
7027     * <p>
7028     * Example: Adding formatted date string to an accessibility event in addition
7029     *          to the text added by the super implementation:
7030     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
7031     *     super.onPopulateAccessibilityEvent(event);
7032     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
7033     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
7034     *         mCurrentDate.getTimeInMillis(), flags);
7035     *     event.getText().add(selectedDateUtterance);
7036     * }</pre>
7037     * <p>
7038     * If an {@link AccessibilityDelegate} has been specified via calling
7039     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7040     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
7041     * is responsible for handling this call.
7042     * </p>
7043     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
7044     * information to the event, in case the default implementation has basic information to add.
7045     * </p>
7046     *
7047     * @param event The accessibility event which to populate.
7048     *
7049     * @see #sendAccessibilityEvent(int)
7050     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
7051     */
7052    @CallSuper
7053    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
7054        if (mAccessibilityDelegate != null) {
7055            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
7056        } else {
7057            onPopulateAccessibilityEventInternal(event);
7058        }
7059    }
7060
7061    /**
7062     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
7063     *
7064     * Note: Called from the default {@link AccessibilityDelegate}.
7065     *
7066     * @hide
7067     */
7068    public void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
7069    }
7070
7071    /**
7072     * Initializes an {@link AccessibilityEvent} with information about
7073     * this View which is the event source. In other words, the source of
7074     * an accessibility event is the view whose state change triggered firing
7075     * the event.
7076     * <p>
7077     * Example: Setting the password property of an event in addition
7078     *          to properties set by the super implementation:
7079     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
7080     *     super.onInitializeAccessibilityEvent(event);
7081     *     event.setPassword(true);
7082     * }</pre>
7083     * <p>
7084     * If an {@link AccessibilityDelegate} has been specified via calling
7085     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7086     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
7087     * is responsible for handling this call.
7088     * </p>
7089     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
7090     * information to the event, in case the default implementation has basic information to add.
7091     * </p>
7092     * @param event The event to initialize.
7093     *
7094     * @see #sendAccessibilityEvent(int)
7095     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
7096     */
7097    @CallSuper
7098    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
7099        if (mAccessibilityDelegate != null) {
7100            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
7101        } else {
7102            onInitializeAccessibilityEventInternal(event);
7103        }
7104    }
7105
7106    /**
7107     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
7108     *
7109     * Note: Called from the default {@link AccessibilityDelegate}.
7110     *
7111     * @hide
7112     */
7113    public void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
7114        event.setSource(this);
7115        event.setClassName(getAccessibilityClassName());
7116        event.setPackageName(getContext().getPackageName());
7117        event.setEnabled(isEnabled());
7118        event.setContentDescription(mContentDescription);
7119
7120        switch (event.getEventType()) {
7121            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
7122                ArrayList<View> focusablesTempList = (mAttachInfo != null)
7123                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
7124                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
7125                event.setItemCount(focusablesTempList.size());
7126                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
7127                if (mAttachInfo != null) {
7128                    focusablesTempList.clear();
7129                }
7130            } break;
7131            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
7132                CharSequence text = getIterableTextForAccessibility();
7133                if (text != null && text.length() > 0) {
7134                    event.setFromIndex(getAccessibilitySelectionStart());
7135                    event.setToIndex(getAccessibilitySelectionEnd());
7136                    event.setItemCount(text.length());
7137                }
7138            } break;
7139        }
7140    }
7141
7142    /**
7143     * Returns an {@link AccessibilityNodeInfo} representing this view from the
7144     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
7145     * This method is responsible for obtaining an accessibility node info from a
7146     * pool of reusable instances and calling
7147     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
7148     * initialize the former.
7149     * <p>
7150     * Note: The client is responsible for recycling the obtained instance by calling
7151     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
7152     * </p>
7153     *
7154     * @return A populated {@link AccessibilityNodeInfo}.
7155     *
7156     * @see AccessibilityNodeInfo
7157     */
7158    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
7159        if (mAccessibilityDelegate != null) {
7160            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
7161        } else {
7162            return createAccessibilityNodeInfoInternal();
7163        }
7164    }
7165
7166    /**
7167     * @see #createAccessibilityNodeInfo()
7168     *
7169     * @hide
7170     */
7171    public AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
7172        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
7173        if (provider != null) {
7174            return provider.createAccessibilityNodeInfo(AccessibilityNodeProvider.HOST_VIEW_ID);
7175        } else {
7176            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
7177            onInitializeAccessibilityNodeInfo(info);
7178            return info;
7179        }
7180    }
7181
7182    /**
7183     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
7184     * The base implementation sets:
7185     * <ul>
7186     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
7187     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
7188     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
7189     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
7190     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
7191     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
7192     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
7193     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
7194     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
7195     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
7196     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
7197     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
7198     *   <li>{@link AccessibilityNodeInfo#setContextClickable(boolean)}</li>
7199     * </ul>
7200     * <p>
7201     * Subclasses should override this method, call the super implementation,
7202     * and set additional attributes.
7203     * </p>
7204     * <p>
7205     * If an {@link AccessibilityDelegate} has been specified via calling
7206     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7207     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
7208     * is responsible for handling this call.
7209     * </p>
7210     *
7211     * @param info The instance to initialize.
7212     */
7213    @CallSuper
7214    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
7215        if (mAccessibilityDelegate != null) {
7216            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
7217        } else {
7218            onInitializeAccessibilityNodeInfoInternal(info);
7219        }
7220    }
7221
7222    /**
7223     * Gets the location of this view in screen coordinates.
7224     *
7225     * @param outRect The output location
7226     * @hide
7227     */
7228    public void getBoundsOnScreen(Rect outRect) {
7229        getBoundsOnScreen(outRect, false);
7230    }
7231
7232    /**
7233     * Gets the location of this view in screen coordinates.
7234     *
7235     * @param outRect The output location
7236     * @param clipToParent Whether to clip child bounds to the parent ones.
7237     * @hide
7238     */
7239    public void getBoundsOnScreen(Rect outRect, boolean clipToParent) {
7240        if (mAttachInfo == null) {
7241            return;
7242        }
7243
7244        RectF position = mAttachInfo.mTmpTransformRect;
7245        position.set(0, 0, mRight - mLeft, mBottom - mTop);
7246
7247        if (!hasIdentityMatrix()) {
7248            getMatrix().mapRect(position);
7249        }
7250
7251        position.offset(mLeft, mTop);
7252
7253        ViewParent parent = mParent;
7254        while (parent instanceof View) {
7255            View parentView = (View) parent;
7256
7257            position.offset(-parentView.mScrollX, -parentView.mScrollY);
7258
7259            if (clipToParent) {
7260                position.left = Math.max(position.left, 0);
7261                position.top = Math.max(position.top, 0);
7262                position.right = Math.min(position.right, parentView.getWidth());
7263                position.bottom = Math.min(position.bottom, parentView.getHeight());
7264            }
7265
7266            if (!parentView.hasIdentityMatrix()) {
7267                parentView.getMatrix().mapRect(position);
7268            }
7269
7270            position.offset(parentView.mLeft, parentView.mTop);
7271
7272            parent = parentView.mParent;
7273        }
7274
7275        if (parent instanceof ViewRootImpl) {
7276            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
7277            position.offset(0, -viewRootImpl.mCurScrollY);
7278        }
7279
7280        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
7281
7282        outRect.set(Math.round(position.left), Math.round(position.top),
7283                Math.round(position.right), Math.round(position.bottom));
7284    }
7285
7286    /**
7287     * Return the class name of this object to be used for accessibility purposes.
7288     * Subclasses should only override this if they are implementing something that
7289     * should be seen as a completely new class of view when used by accessibility,
7290     * unrelated to the class it is deriving from.  This is used to fill in
7291     * {@link AccessibilityNodeInfo#setClassName AccessibilityNodeInfo.setClassName}.
7292     */
7293    public CharSequence getAccessibilityClassName() {
7294        return View.class.getName();
7295    }
7296
7297    /**
7298     * Called when assist structure is being retrieved from a view as part of
7299     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData}.
7300     * @param structure Fill in with structured view data.  The default implementation
7301     * fills in all data that can be inferred from the view itself.
7302     */
7303    public void onProvideStructure(ViewStructure structure) {
7304        onProvideStructureForAssistOrAutofill(structure, false);
7305    }
7306
7307    /**
7308     * Called when assist structure is being retrieved from a view as part of an autofill request.
7309     *
7310     * <p>This method already provides most of what's needed for autofill, but should be overridden
7311     * when:
7312     * <ol>
7313     * <li>The view contents does not include PII (Personally Identifiable Information), so it
7314     * can call {@link ViewStructure#setDataIsSensitive(boolean)} passing {@code false}.
7315     * <li>It must set fields such {@link ViewStructure#setText(CharSequence)},
7316     * {@link ViewStructure#setAutofillOptions(String[])}, or {@link ViewStructure#setUrl(String)}.
7317     * </ol>
7318     *
7319     * @param structure Fill in with structured view data. The default implementation
7320     * fills in all data that can be inferred from the view itself.
7321     * @param flags optional flags (currently {@code 0}).
7322     */
7323    public void onProvideAutofillStructure(ViewStructure structure, int flags) {
7324        onProvideStructureForAssistOrAutofill(structure, true);
7325    }
7326
7327    private void setAutofillId(ViewStructure structure) {
7328        // The autofill id needs to be unique, but its value doesn't matter,
7329        // so it's better to reuse the accessibility id to save space.
7330        structure.setAutofillId(getAccessibilityViewId());
7331    }
7332
7333    private void onProvideStructureForAssistOrAutofill(ViewStructure structure,
7334            boolean forAutofill) {
7335        final int id = mID;
7336        if (id != NO_ID && !isViewIdGenerated(id)) {
7337            String pkg, type, entry;
7338            try {
7339                final Resources res = getResources();
7340                entry = res.getResourceEntryName(id);
7341                type = res.getResourceTypeName(id);
7342                pkg = res.getResourcePackageName(id);
7343            } catch (Resources.NotFoundException e) {
7344                entry = type = pkg = null;
7345            }
7346            structure.setId(id, pkg, type, entry);
7347        } else {
7348            structure.setId(id, null, null, null);
7349        }
7350
7351        if (forAutofill) {
7352            setAutofillId(structure);
7353            final @AutofillType int autofillType = getAutofillType();
7354            // Don't need to fill autofill info if view does not support it.
7355            // For example, only TextViews that are editable support autofill
7356            if (autofillType != AUTOFILL_TYPE_NONE) {
7357                structure.setAutofillType(autofillType);
7358                structure.setAutofillHints(getAutofillHints());
7359                structure.setAutofillValue(getAutofillValue());
7360            }
7361        }
7362
7363        structure.setDimens(mLeft, mTop, mScrollX, mScrollY, mRight - mLeft, mBottom - mTop);
7364        if (!hasIdentityMatrix()) {
7365            structure.setTransformation(getMatrix());
7366        }
7367        structure.setElevation(getZ());
7368        structure.setVisibility(getVisibility());
7369        structure.setEnabled(isEnabled());
7370        if (isClickable()) {
7371            structure.setClickable(true);
7372        }
7373        if (isFocusable()) {
7374            structure.setFocusable(true);
7375        }
7376        if (isFocused()) {
7377            structure.setFocused(true);
7378        }
7379        if (isAccessibilityFocused()) {
7380            structure.setAccessibilityFocused(true);
7381        }
7382        if (isSelected()) {
7383            structure.setSelected(true);
7384        }
7385        if (isActivated()) {
7386            structure.setActivated(true);
7387        }
7388        if (isLongClickable()) {
7389            structure.setLongClickable(true);
7390        }
7391        if (this instanceof Checkable) {
7392            structure.setCheckable(true);
7393            if (((Checkable)this).isChecked()) {
7394                structure.setChecked(true);
7395            }
7396        }
7397        if (isOpaque()) {
7398            structure.setOpaque(true);
7399        }
7400        if (isContextClickable()) {
7401            structure.setContextClickable(true);
7402        }
7403        structure.setClassName(getAccessibilityClassName().toString());
7404        structure.setContentDescription(getContentDescription());
7405    }
7406
7407    /**
7408     * Called when assist structure is being retrieved from a view as part of
7409     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData} to
7410     * generate additional virtual structure under this view.  The defaullt implementation
7411     * uses {@link #getAccessibilityNodeProvider()} to try to generate this from the
7412     * view's virtual accessibility nodes, if any.  You can override this for a more
7413     * optimal implementation providing this data.
7414     */
7415    public void onProvideVirtualStructure(ViewStructure structure) {
7416        onProvideVirtualStructureForAssistOrAutofill(structure, false);
7417    }
7418
7419    /**
7420     * Called when assist structure is being retrieved from a view as part of an autofill request
7421     * to generate additional virtual structure under this view.
7422     *
7423     * <p>The default implementation uses {@link #getAccessibilityNodeProvider()} to try to
7424     * generate this from the view's virtual accessibility nodes, if any. You can override this
7425     * for a more optimal implementation providing this data.
7426     *
7427     * <p>When implementing this method, subclasses must follow the rules below:
7428     *
7429     * <ol>
7430     * <li>Also implement {@link #autofill(SparseArray)} to autofill the virtual
7431     * children.
7432     * <li>Call
7433     * {@link android.view.autofill.AutofillManager#notifyViewEntered} and
7434     * {@link android.view.autofill.AutofillManager#notifyViewExited(View, int)}
7435     * when the focus inside the view changed.
7436     * <li>Call {@link android.view.autofill.AutofillManager#notifyValueChanged(View, int,
7437     * AutofillValue)} when the value of a child changed.
7438     * <li>Call {@link AutofillManager#commit()} when the autofill context
7439     * of the view structure changed and you want the current autofill interaction if such
7440     * to be commited.
7441     * <li>Call {@link AutofillManager#cancel()} ()} when the autofill context
7442     * of the view structure changed and you want the current autofill interaction if such
7443     * to be cancelled.
7444     * </ol>
7445     *
7446     * @param structure Fill in with structured view data.
7447     * @param flags optional flags (currently {@code 0}).
7448     */
7449    public void onProvideAutofillVirtualStructure(ViewStructure structure, int flags) {
7450        onProvideVirtualStructureForAssistOrAutofill(structure, true);
7451    }
7452
7453    private void onProvideVirtualStructureForAssistOrAutofill(ViewStructure structure,
7454            boolean forAutofill) {
7455        if (forAutofill) {
7456            setAutofillId(structure);
7457        }
7458        // NOTE: currently flags are only used for AutoFill; if they're used for Assist as well,
7459        // this method should take a boolean with the type of request.
7460        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
7461        if (provider != null) {
7462            AccessibilityNodeInfo info = createAccessibilityNodeInfo();
7463            structure.setChildCount(1);
7464            ViewStructure root = structure.newChild(0);
7465            if (forAutofill) {
7466                setAutofillId(root);
7467            }
7468            populateVirtualStructure(root, provider, info, forAutofill);
7469            info.recycle();
7470        }
7471    }
7472
7473    /**
7474     * Automatically fills the content of this view with the {@code value}.
7475     *
7476     * <p>By default does nothing, but views should override it (and {@link #getAutofillType()},
7477     * {@link #getAutofillValue()}, and {@link #onProvideAutofillStructure(ViewStructure, int)}
7478     * to support the Autofill Framework.
7479     *
7480     * <p>Typically, it is implemented by:
7481     *
7482     * <ol>
7483     * <li>Calling the proper getter method on {@link AutofillValue} to fetch the actual value.
7484     * <li>Passing the actual value to the equivalent setter in the view.
7485     * </ol>
7486     *
7487     * <p>For example, a text-field view would call:
7488     * <pre class="prettyprint">
7489     * CharSequence text = value.getTextValue();
7490     * if (text != null) {
7491     *     setText(text);
7492     * }
7493     * </pre>
7494     *
7495     * <p>If the value is updated asyncronously the next call to
7496     * {@link AutofillManager#notifyValueChanged(View)} must happen <u>after</u> the value was
7497     * changed to the autofilled value. If not, the view will not be considered autofilled.
7498     *
7499     * @param value value to be autofilled.
7500     */
7501    public void autofill(@SuppressWarnings("unused") AutofillValue value) {
7502    }
7503
7504    /**
7505     * Automatically fills the content of a virtual views.
7506     *
7507     * <p>See {@link #autofill(AutofillValue)} and
7508     * {@link #onProvideAutofillVirtualStructure(ViewStructure, int)} for more info.
7509     * <p>To indicate that a virtual view was autofilled
7510     * <code>@android:drawable/autofilled_highlight</code> should be drawn over it until the data
7511     * changes.
7512     *
7513     * @param values map of values to be autofilled, keyed by virtual child id.
7514     */
7515    public void autofill(@NonNull @SuppressWarnings("unused") SparseArray<AutofillValue> values) {
7516    }
7517
7518    /**
7519     * Describes the autofill type that should be used on calls to
7520     * {@link #autofill(AutofillValue)} and {@link #autofill(SparseArray)}.
7521     *
7522     * <p>By default returns {@link #AUTOFILL_TYPE_NONE}, but views should override it (and
7523     * {@link #autofill(AutofillValue)} to support the Autofill Framework.
7524     */
7525    public @AutofillType int getAutofillType() {
7526        return AUTOFILL_TYPE_NONE;
7527    }
7528
7529    /**
7530     * Describes the content of a view so that a autofill service can fill in the appropriate data.
7531     *
7532     * @return The hints set via the attribute or {@code null} if no hint it set.
7533     *
7534     * @attr ref android.R.styleable#View_autofillHints
7535     */
7536    @ViewDebug.ExportedProperty()
7537    @Nullable public String[] getAutofillHints() {
7538        return mAutofillHints;
7539    }
7540
7541    /**
7542     * @hide
7543     */
7544    public boolean isAutofilled() {
7545        return (mPrivateFlags3 & PFLAG3_IS_AUTOFILLED) != 0;
7546    }
7547
7548    /**
7549     * Gets the {@link View}'s current autofill value.
7550     *
7551     * <p>By default returns {@code null}, but views should override it (and
7552     * {@link #autofill(AutofillValue)}, and {@link #getAutofillType()} to support the Autofill
7553     * Framework.
7554     */
7555    @Nullable
7556    public AutofillValue getAutofillValue() {
7557        return null;
7558    }
7559
7560    /**
7561     * Gets the mode for determining whether this View is important for autofill.
7562     *
7563     * <p>See {@link #setImportantForAutofill(int)} for more info about this mode.
7564     *
7565     * @return {@link #IMPORTANT_FOR_AUTOFILL_AUTO} by default, or value passed to
7566     * {@link #setImportantForAutofill(int)}.
7567     *
7568     * @attr ref android.R.styleable#View_importantForAutofill
7569     */
7570    @ViewDebug.ExportedProperty(mapping = {
7571            @ViewDebug.IntToString(from = IMPORTANT_FOR_AUTOFILL_AUTO, to = "auto"),
7572            @ViewDebug.IntToString(from = IMPORTANT_FOR_AUTOFILL_YES, to = "yes"),
7573            @ViewDebug.IntToString(from = IMPORTANT_FOR_AUTOFILL_NO, to = "no")})
7574    public @AutofillImportance int getImportantForAutofill() {
7575        return (mPrivateFlags3
7576                & PFLAG3_IMPORTANT_FOR_AUTOFILL_MASK) >> PFLAG3_IMPORTANT_FOR_AUTOFILL_SHIFT;
7577    }
7578
7579    /**
7580     * Sets the mode for determining whether this View is important for autofill.
7581     *
7582     * <p>See {@link #setImportantForAutofill(int)} for more info about this mode.
7583     *
7584     * @param mode {@link #IMPORTANT_FOR_AUTOFILL_AUTO}, {@link #IMPORTANT_FOR_AUTOFILL_YES},
7585     * or {@link #IMPORTANT_FOR_AUTOFILL_NO}.
7586     *
7587     * @attr ref android.R.styleable#View_importantForAutofill
7588     */
7589    public void setImportantForAutofill(@AutofillImportance int mode) {
7590        mPrivateFlags3 &= ~PFLAG3_IMPORTANT_FOR_AUTOFILL_MASK;
7591        mPrivateFlags3 |= (mode << PFLAG3_IMPORTANT_FOR_AUTOFILL_SHIFT)
7592                & PFLAG3_IMPORTANT_FOR_AUTOFILL_MASK;
7593    }
7594
7595    /**
7596     * Hints the Android System whether the {@link android.app.assist.AssistStructure.ViewNode}
7597     * associated with this View should be included in a {@link ViewStructure} used for
7598     * autofill purposes.
7599     *
7600     * <p>Generally speaking, a view is important for autofill if:
7601     * <ol>
7602     * <li>The view can-be autofilled by an {@link android.service.autofill.AutofillService}.
7603     * <li>The view contents can help an {@link android.service.autofill.AutofillService} to
7604     * autofill other views.
7605     * <ol>
7606     *
7607     * <p>For example, view containers should typically return {@code false} for performance reasons
7608     * (since the important info is provided by their children), but if the container is actually
7609     * whose children are part of a compound view, it should return {@code true} (and then override
7610     * {@link #dispatchProvideAutofillStructure(ViewStructure, int)} to simply call
7611     * {@link #onProvideAutofillStructure(ViewStructure, int)} so its children are not included in
7612     * the structure). On the other hand, views representing labels or editable fields should
7613     * typically return {@code true}, but in some cases they could return {@code false} (for
7614     * example, if they're part of a "Captcha" mechanism).
7615     *
7616     * <p>By default, this method returns {@code true} if {@link #getImportantForAutofill()} returns
7617     * {@link #IMPORTANT_FOR_AUTOFILL_YES}, {@code false } if it returns
7618     * {@link #IMPORTANT_FOR_AUTOFILL_NO}, and use some heuristics to define the importance when it
7619     * returns {@link #IMPORTANT_FOR_AUTOFILL_AUTO}. Hence, it should rarely be overridden - Views
7620     * should use {@link #setImportantForAutofill(int)} instead.
7621     *
7622     * <p><strong>Note:</strong> returning {@code false} does not guarantee the view will be
7623     * excluded from the structure; for example, if the user explicitly requested auto-fill, the
7624     * View might be always included.
7625     *
7626     * <p>This decision applies just for the view, not its children - if the view children are not
7627     * important for autofill, the view should override
7628     * {@link #dispatchProvideAutofillStructure(ViewStructure, int)} to simply call
7629     * {@link #onProvideAutofillStructure(ViewStructure, int)} (instead of calling
7630     * {@link #dispatchProvideAutofillStructure(ViewStructure, int)} for each child).
7631     *
7632     * @return whether the view is considered important for autofill.
7633     *
7634     * @see #IMPORTANT_FOR_AUTOFILL_AUTO
7635     * @see #IMPORTANT_FOR_AUTOFILL_YES
7636     * @see #IMPORTANT_FOR_AUTOFILL_NO
7637     */
7638    public final boolean isImportantForAutofill() {
7639        final int flag = getImportantForAutofill();
7640
7641        // First, check if view explicity set it to YES or NO
7642        if ((flag & IMPORTANT_FOR_AUTOFILL_YES) != 0) {
7643            return true;
7644        }
7645        if ((flag & IMPORTANT_FOR_AUTOFILL_NO) != 0) {
7646            return false;
7647        }
7648
7649        // Then use some heuristics to handle AUTO.
7650
7651        // Always include views that have a explicity resource id.
7652        final int id = mID;
7653        if (id != NO_ID && !isViewIdGenerated(id)) {
7654            final Resources res = getResources();
7655            String entry = null;
7656            String pkg = null;
7657            try {
7658                entry = res.getResourceEntryName(id);
7659                pkg = res.getResourcePackageName(id);
7660            } catch (Resources.NotFoundException e) {
7661                // ignore
7662            }
7663            if (entry != null && pkg != null && pkg.equals(mContext.getPackageName())) {
7664                return true;
7665            }
7666        }
7667
7668        // Otherwise, assume it's not important...
7669        return false;
7670    }
7671
7672    @Nullable
7673    private AutofillManager getAutofillManager() {
7674        return mContext.getSystemService(AutofillManager.class);
7675    }
7676
7677    private boolean isAutofillable() {
7678        return getAutofillType() != AUTOFILL_TYPE_NONE && !isAutofillBlocked();
7679    }
7680
7681    private void populateVirtualStructure(ViewStructure structure,
7682            AccessibilityNodeProvider provider, AccessibilityNodeInfo info, boolean forAutofill) {
7683        structure.setId(AccessibilityNodeInfo.getVirtualDescendantId(info.getSourceNodeId()),
7684                null, null, null);
7685        Rect rect = structure.getTempRect();
7686        info.getBoundsInParent(rect);
7687        structure.setDimens(rect.left, rect.top, 0, 0, rect.width(), rect.height());
7688        structure.setVisibility(VISIBLE);
7689        structure.setEnabled(info.isEnabled());
7690        if (info.isClickable()) {
7691            structure.setClickable(true);
7692        }
7693        if (info.isFocusable()) {
7694            structure.setFocusable(true);
7695        }
7696        if (info.isFocused()) {
7697            structure.setFocused(true);
7698        }
7699        if (info.isAccessibilityFocused()) {
7700            structure.setAccessibilityFocused(true);
7701        }
7702        if (info.isSelected()) {
7703            structure.setSelected(true);
7704        }
7705        if (info.isLongClickable()) {
7706            structure.setLongClickable(true);
7707        }
7708        if (info.isCheckable()) {
7709            structure.setCheckable(true);
7710            if (info.isChecked()) {
7711                structure.setChecked(true);
7712            }
7713        }
7714        if (info.isContextClickable()) {
7715            structure.setContextClickable(true);
7716        }
7717        CharSequence cname = info.getClassName();
7718        structure.setClassName(cname != null ? cname.toString() : null);
7719        structure.setContentDescription(info.getContentDescription());
7720        if (!forAutofill && (info.getText() != null || info.getError() != null)) {
7721            // TODO(b/33197203) (b/33269702): when sanitized, try to use the Accessibility API to
7722            // just set sanitized values (like text coming from resource files), rather than not
7723            // setting it at all.
7724            structure.setText(info.getText(), info.getTextSelectionStart(),
7725                    info.getTextSelectionEnd());
7726        }
7727        final int NCHILDREN = info.getChildCount();
7728        if (NCHILDREN > 0) {
7729            structure.setChildCount(NCHILDREN);
7730            for (int i=0; i<NCHILDREN; i++) {
7731                AccessibilityNodeInfo cinfo = provider.createAccessibilityNodeInfo(
7732                        AccessibilityNodeInfo.getVirtualDescendantId(info.getChildId(i)));
7733                ViewStructure child = structure.newChild(i);
7734                if (forAutofill) {
7735                    // TODO(b/33197203): add CTS test to autofill virtual children based on
7736                    // Accessibility API.
7737                    child.setAutofillId(structure, i);
7738                }
7739                populateVirtualStructure(child, provider, cinfo, forAutofill);
7740                cinfo.recycle();
7741            }
7742        }
7743    }
7744
7745    /**
7746     * Dispatch creation of {@link ViewStructure} down the hierarchy.  The default
7747     * implementation calls {@link #onProvideStructure} and
7748     * {@link #onProvideVirtualStructure}.
7749     */
7750    public void dispatchProvideStructure(ViewStructure structure) {
7751        dispatchProvideStructureForAssistOrAutofill(structure, false);
7752    }
7753
7754    /**
7755     * Dispatch creation of {@link ViewStructure} down the hierarchy.
7756     *
7757     * <p>The structure must be filled according to the request type, which is set in the
7758     * {@code flags} parameter - see the documentation on each flag for more details.
7759     *
7760     * <p>The default implementation calls {@link #onProvideAutofillStructure(ViewStructure, int)}
7761     * and {@link #onProvideAutofillVirtualStructure(ViewStructure, int)}.
7762     *
7763     * @param structure Fill in with structured view data.
7764     * @param flags optional flags (currently {@code 0}).
7765     */
7766    public void dispatchProvideAutofillStructure(ViewStructure structure, int flags) {
7767        dispatchProvideStructureForAssistOrAutofill(structure, true);
7768    }
7769
7770    private void dispatchProvideStructureForAssistOrAutofill(ViewStructure structure,
7771            boolean forAutofill) {
7772        boolean blocked = forAutofill ? isAutofillBlocked() : isAssistBlocked();
7773        if (!blocked) {
7774            if (forAutofill) {
7775                setAutofillId(structure);
7776                // NOTE: flags are not currently supported, hence 0
7777                onProvideAutofillStructure(structure, 0);
7778                onProvideAutofillVirtualStructure(structure, 0);
7779            } else {
7780                onProvideStructure(structure);
7781                onProvideVirtualStructure(structure);
7782            }
7783        } else {
7784            structure.setClassName(getAccessibilityClassName().toString());
7785            structure.setAssistBlocked(true);
7786        }
7787    }
7788
7789    /**
7790     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
7791     *
7792     * Note: Called from the default {@link AccessibilityDelegate}.
7793     *
7794     * @hide
7795     */
7796    public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
7797        if (mAttachInfo == null) {
7798            return;
7799        }
7800
7801        Rect bounds = mAttachInfo.mTmpInvalRect;
7802
7803        getDrawingRect(bounds);
7804        info.setBoundsInParent(bounds);
7805
7806        getBoundsOnScreen(bounds, true);
7807        info.setBoundsInScreen(bounds);
7808
7809        ViewParent parent = getParentForAccessibility();
7810        if (parent instanceof View) {
7811            info.setParent((View) parent);
7812        }
7813
7814        if (mID != View.NO_ID) {
7815            View rootView = getRootView();
7816            if (rootView == null) {
7817                rootView = this;
7818            }
7819
7820            View label = rootView.findLabelForView(this, mID);
7821            if (label != null) {
7822                info.setLabeledBy(label);
7823            }
7824
7825            if ((mAttachInfo.mAccessibilityFetchFlags
7826                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
7827                    && Resources.resourceHasPackage(mID)) {
7828                try {
7829                    String viewId = getResources().getResourceName(mID);
7830                    info.setViewIdResourceName(viewId);
7831                } catch (Resources.NotFoundException nfe) {
7832                    /* ignore */
7833                }
7834            }
7835        }
7836
7837        if (mLabelForId != View.NO_ID) {
7838            View rootView = getRootView();
7839            if (rootView == null) {
7840                rootView = this;
7841            }
7842            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
7843            if (labeled != null) {
7844                info.setLabelFor(labeled);
7845            }
7846        }
7847
7848        if (mAccessibilityTraversalBeforeId != View.NO_ID) {
7849            View rootView = getRootView();
7850            if (rootView == null) {
7851                rootView = this;
7852            }
7853            View next = rootView.findViewInsideOutShouldExist(this,
7854                    mAccessibilityTraversalBeforeId);
7855            if (next != null && next.includeForAccessibility()) {
7856                info.setTraversalBefore(next);
7857            }
7858        }
7859
7860        if (mAccessibilityTraversalAfterId != View.NO_ID) {
7861            View rootView = getRootView();
7862            if (rootView == null) {
7863                rootView = this;
7864            }
7865            View next = rootView.findViewInsideOutShouldExist(this,
7866                    mAccessibilityTraversalAfterId);
7867            if (next != null && next.includeForAccessibility()) {
7868                info.setTraversalAfter(next);
7869            }
7870        }
7871
7872        info.setVisibleToUser(isVisibleToUser());
7873
7874        info.setImportantForAccessibility(isImportantForAccessibility());
7875        info.setPackageName(mContext.getPackageName());
7876        info.setClassName(getAccessibilityClassName());
7877        info.setContentDescription(getContentDescription());
7878
7879        info.setEnabled(isEnabled());
7880        info.setClickable(isClickable());
7881        info.setFocusable(isFocusable());
7882        info.setFocused(isFocused());
7883        info.setAccessibilityFocused(isAccessibilityFocused());
7884        info.setSelected(isSelected());
7885        info.setLongClickable(isLongClickable());
7886        info.setContextClickable(isContextClickable());
7887        info.setLiveRegion(getAccessibilityLiveRegion());
7888
7889        // TODO: These make sense only if we are in an AdapterView but all
7890        // views can be selected. Maybe from accessibility perspective
7891        // we should report as selectable view in an AdapterView.
7892        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
7893        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
7894
7895        if (isFocusable()) {
7896            if (isFocused()) {
7897                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
7898            } else {
7899                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
7900            }
7901        }
7902
7903        if (!isAccessibilityFocused()) {
7904            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
7905        } else {
7906            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
7907        }
7908
7909        if (isClickable() && isEnabled()) {
7910            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
7911        }
7912
7913        if (isLongClickable() && isEnabled()) {
7914            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
7915        }
7916
7917        if (isContextClickable() && isEnabled()) {
7918            info.addAction(AccessibilityAction.ACTION_CONTEXT_CLICK);
7919        }
7920
7921        CharSequence text = getIterableTextForAccessibility();
7922        if (text != null && text.length() > 0) {
7923            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
7924
7925            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
7926            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
7927            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
7928            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
7929                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
7930                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
7931        }
7932
7933        info.addAction(AccessibilityAction.ACTION_SHOW_ON_SCREEN);
7934        populateAccessibilityNodeInfoDrawingOrderInParent(info);
7935    }
7936
7937    /**
7938     * Adds extra data to an {@link AccessibilityNodeInfo} based on an explicit request for the
7939     * additional data.
7940     * <p>
7941     * This method only needs overloading if the node is marked as having extra data available.
7942     * </p>
7943     *
7944     * @param info The info to which to add the extra data. Never {@code null}.
7945     * @param extraDataKey A key specifying the type of extra data to add to the info. The
7946     *                     extra data should be added to the {@link Bundle} returned by
7947     *                     the info's {@link AccessibilityNodeInfo#getExtras} method. Never
7948     *                     {@code null}.
7949     * @param arguments A {@link Bundle} holding any arguments relevant for this request. May be
7950     *                  {@code null} if the service provided no arguments.
7951     *
7952     * @see AccessibilityNodeInfo#setAvailableExtraData(List)
7953     */
7954    public void addExtraDataToAccessibilityNodeInfo(
7955            @NonNull AccessibilityNodeInfo info, @NonNull String extraDataKey,
7956            @Nullable Bundle arguments) {
7957    }
7958
7959    /**
7960     * Determine the order in which this view will be drawn relative to its siblings for a11y
7961     *
7962     * @param info The info whose drawing order should be populated
7963     */
7964    private void populateAccessibilityNodeInfoDrawingOrderInParent(AccessibilityNodeInfo info) {
7965        /*
7966         * If the view's bounds haven't been set yet, layout has not completed. In that situation,
7967         * drawing order may not be well-defined, and some Views with custom drawing order may
7968         * not be initialized sufficiently to respond properly getChildDrawingOrder.
7969         */
7970        if ((mPrivateFlags & PFLAG_HAS_BOUNDS) == 0) {
7971            info.setDrawingOrder(0);
7972            return;
7973        }
7974        int drawingOrderInParent = 1;
7975        // Iterate up the hierarchy if parents are not important for a11y
7976        View viewAtDrawingLevel = this;
7977        final ViewParent parent = getParentForAccessibility();
7978        while (viewAtDrawingLevel != parent) {
7979            final ViewParent currentParent = viewAtDrawingLevel.getParent();
7980            if (!(currentParent instanceof ViewGroup)) {
7981                // Should only happen for the Decor
7982                drawingOrderInParent = 0;
7983                break;
7984            } else {
7985                final ViewGroup parentGroup = (ViewGroup) currentParent;
7986                final int childCount = parentGroup.getChildCount();
7987                if (childCount > 1) {
7988                    List<View> preorderedList = parentGroup.buildOrderedChildList();
7989                    if (preorderedList != null) {
7990                        final int childDrawIndex = preorderedList.indexOf(viewAtDrawingLevel);
7991                        for (int i = 0; i < childDrawIndex; i++) {
7992                            drawingOrderInParent += numViewsForAccessibility(preorderedList.get(i));
7993                        }
7994                    } else {
7995                        final int childIndex = parentGroup.indexOfChild(viewAtDrawingLevel);
7996                        final boolean customOrder = parentGroup.isChildrenDrawingOrderEnabled();
7997                        final int childDrawIndex = ((childIndex >= 0) && customOrder) ? parentGroup
7998                                .getChildDrawingOrder(childCount, childIndex) : childIndex;
7999                        final int numChildrenToIterate = customOrder ? childCount : childDrawIndex;
8000                        if (childDrawIndex != 0) {
8001                            for (int i = 0; i < numChildrenToIterate; i++) {
8002                                final int otherDrawIndex = (customOrder ?
8003                                        parentGroup.getChildDrawingOrder(childCount, i) : i);
8004                                if (otherDrawIndex < childDrawIndex) {
8005                                    drawingOrderInParent +=
8006                                            numViewsForAccessibility(parentGroup.getChildAt(i));
8007                                }
8008                            }
8009                        }
8010                    }
8011                }
8012            }
8013            viewAtDrawingLevel = (View) currentParent;
8014        }
8015        info.setDrawingOrder(drawingOrderInParent);
8016    }
8017
8018    private static int numViewsForAccessibility(View view) {
8019        if (view != null) {
8020            if (view.includeForAccessibility()) {
8021                return 1;
8022            } else if (view instanceof ViewGroup) {
8023                return ((ViewGroup) view).getNumChildrenForAccessibility();
8024            }
8025        }
8026        return 0;
8027    }
8028
8029    private View findLabelForView(View view, int labeledId) {
8030        if (mMatchLabelForPredicate == null) {
8031            mMatchLabelForPredicate = new MatchLabelForPredicate();
8032        }
8033        mMatchLabelForPredicate.mLabeledId = labeledId;
8034        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
8035    }
8036
8037    /**
8038     * Computes whether this view is visible to the user. Such a view is
8039     * attached, visible, all its predecessors are visible, it is not clipped
8040     * entirely by its predecessors, and has an alpha greater than zero.
8041     *
8042     * @return Whether the view is visible on the screen.
8043     *
8044     * @hide
8045     */
8046    protected boolean isVisibleToUser() {
8047        return isVisibleToUser(null);
8048    }
8049
8050    /**
8051     * Computes whether the given portion of this view is visible to the user.
8052     * Such a view is attached, visible, all its predecessors are visible,
8053     * has an alpha greater than zero, and the specified portion is not
8054     * clipped entirely by its predecessors.
8055     *
8056     * @param boundInView the portion of the view to test; coordinates should be relative; may be
8057     *                    <code>null</code>, and the entire view will be tested in this case.
8058     *                    When <code>true</code> is returned by the function, the actual visible
8059     *                    region will be stored in this parameter; that is, if boundInView is fully
8060     *                    contained within the view, no modification will be made, otherwise regions
8061     *                    outside of the visible area of the view will be clipped.
8062     *
8063     * @return Whether the specified portion of the view is visible on the screen.
8064     *
8065     * @hide
8066     */
8067    protected boolean isVisibleToUser(Rect boundInView) {
8068        if (mAttachInfo != null) {
8069            // Attached to invisible window means this view is not visible.
8070            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
8071                return false;
8072            }
8073            // An invisible predecessor or one with alpha zero means
8074            // that this view is not visible to the user.
8075            Object current = this;
8076            while (current instanceof View) {
8077                View view = (View) current;
8078                // We have attach info so this view is attached and there is no
8079                // need to check whether we reach to ViewRootImpl on the way up.
8080                if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
8081                        view.getVisibility() != VISIBLE) {
8082                    return false;
8083                }
8084                current = view.mParent;
8085            }
8086            // Check if the view is entirely covered by its predecessors.
8087            Rect visibleRect = mAttachInfo.mTmpInvalRect;
8088            Point offset = mAttachInfo.mPoint;
8089            if (!getGlobalVisibleRect(visibleRect, offset)) {
8090                return false;
8091            }
8092            // Check if the visible portion intersects the rectangle of interest.
8093            if (boundInView != null) {
8094                visibleRect.offset(-offset.x, -offset.y);
8095                return boundInView.intersect(visibleRect);
8096            }
8097            return true;
8098        }
8099        return false;
8100    }
8101
8102    /**
8103     * Returns the delegate for implementing accessibility support via
8104     * composition. For more details see {@link AccessibilityDelegate}.
8105     *
8106     * @return The delegate, or null if none set.
8107     *
8108     * @hide
8109     */
8110    public AccessibilityDelegate getAccessibilityDelegate() {
8111        return mAccessibilityDelegate;
8112    }
8113
8114    /**
8115     * Sets a delegate for implementing accessibility support via composition
8116     * (as opposed to inheritance). For more details, see
8117     * {@link AccessibilityDelegate}.
8118     * <p>
8119     * <strong>Note:</strong> On platform versions prior to
8120     * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on
8121     * views in the {@code android.widget.*} package are called <i>before</i>
8122     * host methods. This prevents certain properties such as class name from
8123     * being modified by overriding
8124     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)},
8125     * as any changes will be overwritten by the host class.
8126     * <p>
8127     * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate
8128     * methods are called <i>after</i> host methods, which all properties to be
8129     * modified without being overwritten by the host class.
8130     *
8131     * @param delegate the object to which accessibility method calls should be
8132     *                 delegated
8133     * @see AccessibilityDelegate
8134     */
8135    public void setAccessibilityDelegate(@Nullable AccessibilityDelegate delegate) {
8136        mAccessibilityDelegate = delegate;
8137    }
8138
8139    /**
8140     * Gets the provider for managing a virtual view hierarchy rooted at this View
8141     * and reported to {@link android.accessibilityservice.AccessibilityService}s
8142     * that explore the window content.
8143     * <p>
8144     * If this method returns an instance, this instance is responsible for managing
8145     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
8146     * View including the one representing the View itself. Similarly the returned
8147     * instance is responsible for performing accessibility actions on any virtual
8148     * view or the root view itself.
8149     * </p>
8150     * <p>
8151     * If an {@link AccessibilityDelegate} has been specified via calling
8152     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
8153     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
8154     * is responsible for handling this call.
8155     * </p>
8156     *
8157     * @return The provider.
8158     *
8159     * @see AccessibilityNodeProvider
8160     */
8161    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
8162        if (mAccessibilityDelegate != null) {
8163            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
8164        } else {
8165            return null;
8166        }
8167    }
8168
8169    /**
8170     * Gets the unique identifier of this view on the screen for accessibility purposes.
8171     *
8172     * @return The view accessibility id.
8173     *
8174     * @hide
8175     */
8176    public int getAccessibilityViewId() {
8177        if (mAccessibilityViewId == NO_ID) {
8178            mAccessibilityViewId = mContext.getNextAccessibilityId();
8179        }
8180        return mAccessibilityViewId;
8181    }
8182
8183    /**
8184     * Gets the unique identifier of the window in which this View reseides.
8185     *
8186     * @return The window accessibility id.
8187     *
8188     * @hide
8189     */
8190    public int getAccessibilityWindowId() {
8191        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId
8192                : AccessibilityWindowInfo.UNDEFINED_WINDOW_ID;
8193    }
8194
8195    /**
8196     * Returns the {@link View}'s content description.
8197     * <p>
8198     * <strong>Note:</strong> Do not override this method, as it will have no
8199     * effect on the content description presented to accessibility services.
8200     * You must call {@link #setContentDescription(CharSequence)} to modify the
8201     * content description.
8202     *
8203     * @return the content description
8204     * @see #setContentDescription(CharSequence)
8205     * @attr ref android.R.styleable#View_contentDescription
8206     */
8207    @ViewDebug.ExportedProperty(category = "accessibility")
8208    public CharSequence getContentDescription() {
8209        return mContentDescription;
8210    }
8211
8212    /**
8213     * Sets the {@link View}'s content description.
8214     * <p>
8215     * A content description briefly describes the view and is primarily used
8216     * for accessibility support to determine how a view should be presented to
8217     * the user. In the case of a view with no textual representation, such as
8218     * {@link android.widget.ImageButton}, a useful content description
8219     * explains what the view does. For example, an image button with a phone
8220     * icon that is used to place a call may use "Call" as its content
8221     * description. An image of a floppy disk that is used to save a file may
8222     * use "Save".
8223     *
8224     * @param contentDescription The content description.
8225     * @see #getContentDescription()
8226     * @attr ref android.R.styleable#View_contentDescription
8227     */
8228    @RemotableViewMethod
8229    public void setContentDescription(CharSequence contentDescription) {
8230        if (mContentDescription == null) {
8231            if (contentDescription == null) {
8232                return;
8233            }
8234        } else if (mContentDescription.equals(contentDescription)) {
8235            return;
8236        }
8237        mContentDescription = contentDescription;
8238        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
8239        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
8240            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
8241            notifySubtreeAccessibilityStateChangedIfNeeded();
8242        } else {
8243            notifyViewAccessibilityStateChangedIfNeeded(
8244                    AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
8245        }
8246    }
8247
8248    /**
8249     * Sets the id of a view before which this one is visited in accessibility traversal.
8250     * A screen-reader must visit the content of this view before the content of the one
8251     * it precedes. For example, if view B is set to be before view A, then a screen-reader
8252     * will traverse the entire content of B before traversing the entire content of A,
8253     * regardles of what traversal strategy it is using.
8254     * <p>
8255     * Views that do not have specified before/after relationships are traversed in order
8256     * determined by the screen-reader.
8257     * </p>
8258     * <p>
8259     * Setting that this view is before a view that is not important for accessibility
8260     * or if this view is not important for accessibility will have no effect as the
8261     * screen-reader is not aware of unimportant views.
8262     * </p>
8263     *
8264     * @param beforeId The id of a view this one precedes in accessibility traversal.
8265     *
8266     * @attr ref android.R.styleable#View_accessibilityTraversalBefore
8267     *
8268     * @see #setImportantForAccessibility(int)
8269     */
8270    @RemotableViewMethod
8271    public void setAccessibilityTraversalBefore(int beforeId) {
8272        if (mAccessibilityTraversalBeforeId == beforeId) {
8273            return;
8274        }
8275        mAccessibilityTraversalBeforeId = beforeId;
8276        notifyViewAccessibilityStateChangedIfNeeded(
8277                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
8278    }
8279
8280    /**
8281     * Gets the id of a view before which this one is visited in accessibility traversal.
8282     *
8283     * @return The id of a view this one precedes in accessibility traversal if
8284     *         specified, otherwise {@link #NO_ID}.
8285     *
8286     * @see #setAccessibilityTraversalBefore(int)
8287     */
8288    public int getAccessibilityTraversalBefore() {
8289        return mAccessibilityTraversalBeforeId;
8290    }
8291
8292    /**
8293     * Sets the id of a view after which this one is visited in accessibility traversal.
8294     * A screen-reader must visit the content of the other view before the content of this
8295     * one. For example, if view B is set to be after view A, then a screen-reader
8296     * will traverse the entire content of A before traversing the entire content of B,
8297     * regardles of what traversal strategy it is using.
8298     * <p>
8299     * Views that do not have specified before/after relationships are traversed in order
8300     * determined by the screen-reader.
8301     * </p>
8302     * <p>
8303     * Setting that this view is after a view that is not important for accessibility
8304     * or if this view is not important for accessibility will have no effect as the
8305     * screen-reader is not aware of unimportant views.
8306     * </p>
8307     *
8308     * @param afterId The id of a view this one succedees in accessibility traversal.
8309     *
8310     * @attr ref android.R.styleable#View_accessibilityTraversalAfter
8311     *
8312     * @see #setImportantForAccessibility(int)
8313     */
8314    @RemotableViewMethod
8315    public void setAccessibilityTraversalAfter(int afterId) {
8316        if (mAccessibilityTraversalAfterId == afterId) {
8317            return;
8318        }
8319        mAccessibilityTraversalAfterId = afterId;
8320        notifyViewAccessibilityStateChangedIfNeeded(
8321                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
8322    }
8323
8324    /**
8325     * Gets the id of a view after which this one is visited in accessibility traversal.
8326     *
8327     * @return The id of a view this one succeedes in accessibility traversal if
8328     *         specified, otherwise {@link #NO_ID}.
8329     *
8330     * @see #setAccessibilityTraversalAfter(int)
8331     */
8332    public int getAccessibilityTraversalAfter() {
8333        return mAccessibilityTraversalAfterId;
8334    }
8335
8336    /**
8337     * Gets the id of a view for which this view serves as a label for
8338     * accessibility purposes.
8339     *
8340     * @return The labeled view id.
8341     */
8342    @ViewDebug.ExportedProperty(category = "accessibility")
8343    public int getLabelFor() {
8344        return mLabelForId;
8345    }
8346
8347    /**
8348     * Sets the id of a view for which this view serves as a label for
8349     * accessibility purposes.
8350     *
8351     * @param id The labeled view id.
8352     */
8353    @RemotableViewMethod
8354    public void setLabelFor(@IdRes int id) {
8355        if (mLabelForId == id) {
8356            return;
8357        }
8358        mLabelForId = id;
8359        if (mLabelForId != View.NO_ID
8360                && mID == View.NO_ID) {
8361            mID = generateViewId();
8362        }
8363        notifyViewAccessibilityStateChangedIfNeeded(
8364                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
8365    }
8366
8367    /**
8368     * Invoked whenever this view loses focus, either by losing window focus or by losing
8369     * focus within its window. This method can be used to clear any state tied to the
8370     * focus. For instance, if a button is held pressed with the trackball and the window
8371     * loses focus, this method can be used to cancel the press.
8372     *
8373     * Subclasses of View overriding this method should always call super.onFocusLost().
8374     *
8375     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
8376     * @see #onWindowFocusChanged(boolean)
8377     *
8378     * @hide pending API council approval
8379     */
8380    @CallSuper
8381    protected void onFocusLost() {
8382        resetPressedState();
8383    }
8384
8385    private void resetPressedState() {
8386        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8387            return;
8388        }
8389
8390        if (isPressed()) {
8391            setPressed(false);
8392
8393            if (!mHasPerformedLongPress) {
8394                removeLongPressCallback();
8395            }
8396        }
8397    }
8398
8399    /**
8400     * Returns true if this view has focus
8401     *
8402     * @return True if this view has focus, false otherwise.
8403     */
8404    @ViewDebug.ExportedProperty(category = "focus")
8405    public boolean isFocused() {
8406        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
8407    }
8408
8409    /**
8410     * Find the view in the hierarchy rooted at this view that currently has
8411     * focus.
8412     *
8413     * @return The view that currently has focus, or null if no focused view can
8414     *         be found.
8415     */
8416    public View findFocus() {
8417        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
8418    }
8419
8420    /**
8421     * Indicates whether this view is one of the set of scrollable containers in
8422     * its window.
8423     *
8424     * @return whether this view is one of the set of scrollable containers in
8425     * its window
8426     *
8427     * @attr ref android.R.styleable#View_isScrollContainer
8428     */
8429    public boolean isScrollContainer() {
8430        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
8431    }
8432
8433    /**
8434     * Change whether this view is one of the set of scrollable containers in
8435     * its window.  This will be used to determine whether the window can
8436     * resize or must pan when a soft input area is open -- scrollable
8437     * containers allow the window to use resize mode since the container
8438     * will appropriately shrink.
8439     *
8440     * @attr ref android.R.styleable#View_isScrollContainer
8441     */
8442    public void setScrollContainer(boolean isScrollContainer) {
8443        if (isScrollContainer) {
8444            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
8445                mAttachInfo.mScrollContainers.add(this);
8446                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
8447            }
8448            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
8449        } else {
8450            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
8451                mAttachInfo.mScrollContainers.remove(this);
8452            }
8453            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
8454        }
8455    }
8456
8457    /**
8458     * Returns the quality of the drawing cache.
8459     *
8460     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
8461     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
8462     *
8463     * @see #setDrawingCacheQuality(int)
8464     * @see #setDrawingCacheEnabled(boolean)
8465     * @see #isDrawingCacheEnabled()
8466     *
8467     * @attr ref android.R.styleable#View_drawingCacheQuality
8468     */
8469    @DrawingCacheQuality
8470    public int getDrawingCacheQuality() {
8471        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
8472    }
8473
8474    /**
8475     * Set the drawing cache quality of this view. This value is used only when the
8476     * drawing cache is enabled
8477     *
8478     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
8479     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
8480     *
8481     * @see #getDrawingCacheQuality()
8482     * @see #setDrawingCacheEnabled(boolean)
8483     * @see #isDrawingCacheEnabled()
8484     *
8485     * @attr ref android.R.styleable#View_drawingCacheQuality
8486     */
8487    public void setDrawingCacheQuality(@DrawingCacheQuality int quality) {
8488        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
8489    }
8490
8491    /**
8492     * Returns whether the screen should remain on, corresponding to the current
8493     * value of {@link #KEEP_SCREEN_ON}.
8494     *
8495     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
8496     *
8497     * @see #setKeepScreenOn(boolean)
8498     *
8499     * @attr ref android.R.styleable#View_keepScreenOn
8500     */
8501    public boolean getKeepScreenOn() {
8502        return (mViewFlags & KEEP_SCREEN_ON) != 0;
8503    }
8504
8505    /**
8506     * Controls whether the screen should remain on, modifying the
8507     * value of {@link #KEEP_SCREEN_ON}.
8508     *
8509     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
8510     *
8511     * @see #getKeepScreenOn()
8512     *
8513     * @attr ref android.R.styleable#View_keepScreenOn
8514     */
8515    public void setKeepScreenOn(boolean keepScreenOn) {
8516        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
8517    }
8518
8519    /**
8520     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
8521     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
8522     *
8523     * @attr ref android.R.styleable#View_nextFocusLeft
8524     */
8525    public int getNextFocusLeftId() {
8526        return mNextFocusLeftId;
8527    }
8528
8529    /**
8530     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
8531     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
8532     * decide automatically.
8533     *
8534     * @attr ref android.R.styleable#View_nextFocusLeft
8535     */
8536    public void setNextFocusLeftId(int nextFocusLeftId) {
8537        mNextFocusLeftId = nextFocusLeftId;
8538    }
8539
8540    /**
8541     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
8542     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
8543     *
8544     * @attr ref android.R.styleable#View_nextFocusRight
8545     */
8546    public int getNextFocusRightId() {
8547        return mNextFocusRightId;
8548    }
8549
8550    /**
8551     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
8552     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
8553     * decide automatically.
8554     *
8555     * @attr ref android.R.styleable#View_nextFocusRight
8556     */
8557    public void setNextFocusRightId(int nextFocusRightId) {
8558        mNextFocusRightId = nextFocusRightId;
8559    }
8560
8561    /**
8562     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
8563     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
8564     *
8565     * @attr ref android.R.styleable#View_nextFocusUp
8566     */
8567    public int getNextFocusUpId() {
8568        return mNextFocusUpId;
8569    }
8570
8571    /**
8572     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
8573     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
8574     * decide automatically.
8575     *
8576     * @attr ref android.R.styleable#View_nextFocusUp
8577     */
8578    public void setNextFocusUpId(int nextFocusUpId) {
8579        mNextFocusUpId = nextFocusUpId;
8580    }
8581
8582    /**
8583     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
8584     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
8585     *
8586     * @attr ref android.R.styleable#View_nextFocusDown
8587     */
8588    public int getNextFocusDownId() {
8589        return mNextFocusDownId;
8590    }
8591
8592    /**
8593     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
8594     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
8595     * decide automatically.
8596     *
8597     * @attr ref android.R.styleable#View_nextFocusDown
8598     */
8599    public void setNextFocusDownId(int nextFocusDownId) {
8600        mNextFocusDownId = nextFocusDownId;
8601    }
8602
8603    /**
8604     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
8605     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
8606     *
8607     * @attr ref android.R.styleable#View_nextFocusForward
8608     */
8609    public int getNextFocusForwardId() {
8610        return mNextFocusForwardId;
8611    }
8612
8613    /**
8614     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
8615     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
8616     * decide automatically.
8617     *
8618     * @attr ref android.R.styleable#View_nextFocusForward
8619     */
8620    public void setNextFocusForwardId(int nextFocusForwardId) {
8621        mNextFocusForwardId = nextFocusForwardId;
8622    }
8623
8624    /**
8625     * Gets the id of the root of the next keyboard navigation cluster.
8626     * @return The next keyboard navigation cluster ID, or {@link #NO_ID} if the framework should
8627     * decide automatically.
8628     *
8629     * @attr ref android.R.styleable#View_nextClusterForward
8630     */
8631    public int getNextClusterForwardId() {
8632        return mNextClusterForwardId;
8633    }
8634
8635    /**
8636     * Sets the id of the view to use as the root of the next keyboard navigation cluster.
8637     * @param nextClusterForwardId The next cluster ID, or {@link #NO_ID} if the framework should
8638     * decide automatically.
8639     *
8640     * @attr ref android.R.styleable#View_nextClusterForward
8641     */
8642    public void setNextClusterForwardId(int nextClusterForwardId) {
8643        mNextClusterForwardId = nextClusterForwardId;
8644    }
8645
8646    /**
8647     * Returns the visibility of this view and all of its ancestors
8648     *
8649     * @return True if this view and all of its ancestors are {@link #VISIBLE}
8650     */
8651    public boolean isShown() {
8652        View current = this;
8653        //noinspection ConstantConditions
8654        do {
8655            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
8656                return false;
8657            }
8658            ViewParent parent = current.mParent;
8659            if (parent == null) {
8660                return false; // We are not attached to the view root
8661            }
8662            if (!(parent instanceof View)) {
8663                return true;
8664            }
8665            current = (View) parent;
8666        } while (current != null);
8667
8668        return false;
8669    }
8670
8671    /**
8672     * Called by the view hierarchy when the content insets for a window have
8673     * changed, to allow it to adjust its content to fit within those windows.
8674     * The content insets tell you the space that the status bar, input method,
8675     * and other system windows infringe on the application's window.
8676     *
8677     * <p>You do not normally need to deal with this function, since the default
8678     * window decoration given to applications takes care of applying it to the
8679     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
8680     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
8681     * and your content can be placed under those system elements.  You can then
8682     * use this method within your view hierarchy if you have parts of your UI
8683     * which you would like to ensure are not being covered.
8684     *
8685     * <p>The default implementation of this method simply applies the content
8686     * insets to the view's padding, consuming that content (modifying the
8687     * insets to be 0), and returning true.  This behavior is off by default, but can
8688     * be enabled through {@link #setFitsSystemWindows(boolean)}.
8689     *
8690     * <p>This function's traversal down the hierarchy is depth-first.  The same content
8691     * insets object is propagated down the hierarchy, so any changes made to it will
8692     * be seen by all following views (including potentially ones above in
8693     * the hierarchy since this is a depth-first traversal).  The first view
8694     * that returns true will abort the entire traversal.
8695     *
8696     * <p>The default implementation works well for a situation where it is
8697     * used with a container that covers the entire window, allowing it to
8698     * apply the appropriate insets to its content on all edges.  If you need
8699     * a more complicated layout (such as two different views fitting system
8700     * windows, one on the top of the window, and one on the bottom),
8701     * you can override the method and handle the insets however you would like.
8702     * Note that the insets provided by the framework are always relative to the
8703     * far edges of the window, not accounting for the location of the called view
8704     * within that window.  (In fact when this method is called you do not yet know
8705     * where the layout will place the view, as it is done before layout happens.)
8706     *
8707     * <p>Note: unlike many View methods, there is no dispatch phase to this
8708     * call.  If you are overriding it in a ViewGroup and want to allow the
8709     * call to continue to your children, you must be sure to call the super
8710     * implementation.
8711     *
8712     * <p>Here is a sample layout that makes use of fitting system windows
8713     * to have controls for a video view placed inside of the window decorations
8714     * that it hides and shows.  This can be used with code like the second
8715     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
8716     *
8717     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
8718     *
8719     * @param insets Current content insets of the window.  Prior to
8720     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
8721     * the insets or else you and Android will be unhappy.
8722     *
8723     * @return {@code true} if this view applied the insets and it should not
8724     * continue propagating further down the hierarchy, {@code false} otherwise.
8725     * @see #getFitsSystemWindows()
8726     * @see #setFitsSystemWindows(boolean)
8727     * @see #setSystemUiVisibility(int)
8728     *
8729     * @deprecated As of API 20 use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply
8730     * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use
8731     * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)}
8732     * to implement handling their own insets.
8733     */
8734    @Deprecated
8735    protected boolean fitSystemWindows(Rect insets) {
8736        if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) {
8737            if (insets == null) {
8738                // Null insets by definition have already been consumed.
8739                // This call cannot apply insets since there are none to apply,
8740                // so return false.
8741                return false;
8742            }
8743            // If we're not in the process of dispatching the newer apply insets call,
8744            // that means we're not in the compatibility path. Dispatch into the newer
8745            // apply insets path and take things from there.
8746            try {
8747                mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS;
8748                return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed();
8749            } finally {
8750                mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS;
8751            }
8752        } else {
8753            // We're being called from the newer apply insets path.
8754            // Perform the standard fallback behavior.
8755            return fitSystemWindowsInt(insets);
8756        }
8757    }
8758
8759    private boolean fitSystemWindowsInt(Rect insets) {
8760        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
8761            mUserPaddingStart = UNDEFINED_PADDING;
8762            mUserPaddingEnd = UNDEFINED_PADDING;
8763            Rect localInsets = sThreadLocal.get();
8764            if (localInsets == null) {
8765                localInsets = new Rect();
8766                sThreadLocal.set(localInsets);
8767            }
8768            boolean res = computeFitSystemWindows(insets, localInsets);
8769            mUserPaddingLeftInitial = localInsets.left;
8770            mUserPaddingRightInitial = localInsets.right;
8771            internalSetPadding(localInsets.left, localInsets.top,
8772                    localInsets.right, localInsets.bottom);
8773            return res;
8774        }
8775        return false;
8776    }
8777
8778    /**
8779     * Called when the view should apply {@link WindowInsets} according to its internal policy.
8780     *
8781     * <p>This method should be overridden by views that wish to apply a policy different from or
8782     * in addition to the default behavior. Clients that wish to force a view subtree
8783     * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p>
8784     *
8785     * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set
8786     * it will be called during dispatch instead of this method. The listener may optionally
8787     * call this method from its own implementation if it wishes to apply the view's default
8788     * insets policy in addition to its own.</p>
8789     *
8790     * <p>Implementations of this method should either return the insets parameter unchanged
8791     * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed
8792     * that this view applied itself. This allows new inset types added in future platform
8793     * versions to pass through existing implementations unchanged without being erroneously
8794     * consumed.</p>
8795     *
8796     * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows}
8797     * property is set then the view will consume the system window insets and apply them
8798     * as padding for the view.</p>
8799     *
8800     * @param insets Insets to apply
8801     * @return The supplied insets with any applied insets consumed
8802     */
8803    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
8804        if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) {
8805            // We weren't called from within a direct call to fitSystemWindows,
8806            // call into it as a fallback in case we're in a class that overrides it
8807            // and has logic to perform.
8808            if (fitSystemWindows(insets.getSystemWindowInsets())) {
8809                return insets.consumeSystemWindowInsets();
8810            }
8811        } else {
8812            // We were called from within a direct call to fitSystemWindows.
8813            if (fitSystemWindowsInt(insets.getSystemWindowInsets())) {
8814                return insets.consumeSystemWindowInsets();
8815            }
8816        }
8817        return insets;
8818    }
8819
8820    /**
8821     * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying
8822     * window insets to this view. The listener's
8823     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
8824     * method will be called instead of the view's
8825     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
8826     *
8827     * @param listener Listener to set
8828     *
8829     * @see #onApplyWindowInsets(WindowInsets)
8830     */
8831    public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {
8832        getListenerInfo().mOnApplyWindowInsetsListener = listener;
8833    }
8834
8835    /**
8836     * Request to apply the given window insets to this view or another view in its subtree.
8837     *
8838     * <p>This method should be called by clients wishing to apply insets corresponding to areas
8839     * obscured by window decorations or overlays. This can include the status and navigation bars,
8840     * action bars, input methods and more. New inset categories may be added in the future.
8841     * The method returns the insets provided minus any that were applied by this view or its
8842     * children.</p>
8843     *
8844     * <p>Clients wishing to provide custom behavior should override the
8845     * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a
8846     * {@link OnApplyWindowInsetsListener} via the
8847     * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener}
8848     * method.</p>
8849     *
8850     * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method.
8851     * </p>
8852     *
8853     * @param insets Insets to apply
8854     * @return The provided insets minus the insets that were consumed
8855     */
8856    public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
8857        try {
8858            mPrivateFlags3 |= PFLAG3_APPLYING_INSETS;
8859            if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
8860                return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);
8861            } else {
8862                return onApplyWindowInsets(insets);
8863            }
8864        } finally {
8865            mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS;
8866        }
8867    }
8868
8869    /**
8870     * Compute the view's coordinate within the surface.
8871     *
8872     * <p>Computes the coordinates of this view in its surface. The argument
8873     * must be an array of two integers. After the method returns, the array
8874     * contains the x and y location in that order.</p>
8875     * @hide
8876     * @param location an array of two integers in which to hold the coordinates
8877     */
8878    public void getLocationInSurface(@Size(2) int[] location) {
8879        getLocationInWindow(location);
8880        if (mAttachInfo != null && mAttachInfo.mViewRootImpl != null) {
8881            location[0] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.left;
8882            location[1] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.top;
8883        }
8884    }
8885
8886    /**
8887     * Provide original WindowInsets that are dispatched to the view hierarchy. The insets are
8888     * only available if the view is attached.
8889     *
8890     * @return WindowInsets from the top of the view hierarchy or null if View is detached
8891     */
8892    public WindowInsets getRootWindowInsets() {
8893        if (mAttachInfo != null) {
8894            return mAttachInfo.mViewRootImpl.getWindowInsets(false /* forceConstruct */);
8895        }
8896        return null;
8897    }
8898
8899    /**
8900     * @hide Compute the insets that should be consumed by this view and the ones
8901     * that should propagate to those under it.
8902     */
8903    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
8904        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
8905                || mAttachInfo == null
8906                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
8907                        && !mAttachInfo.mOverscanRequested)) {
8908            outLocalInsets.set(inoutInsets);
8909            inoutInsets.set(0, 0, 0, 0);
8910            return true;
8911        } else {
8912            // The application wants to take care of fitting system window for
8913            // the content...  however we still need to take care of any overscan here.
8914            final Rect overscan = mAttachInfo.mOverscanInsets;
8915            outLocalInsets.set(overscan);
8916            inoutInsets.left -= overscan.left;
8917            inoutInsets.top -= overscan.top;
8918            inoutInsets.right -= overscan.right;
8919            inoutInsets.bottom -= overscan.bottom;
8920            return false;
8921        }
8922    }
8923
8924    /**
8925     * Compute insets that should be consumed by this view and the ones that should propagate
8926     * to those under it.
8927     *
8928     * @param in Insets currently being processed by this View, likely received as a parameter
8929     *           to {@link #onApplyWindowInsets(WindowInsets)}.
8930     * @param outLocalInsets A Rect that will receive the insets that should be consumed
8931     *                       by this view
8932     * @return Insets that should be passed along to views under this one
8933     */
8934    public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) {
8935        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
8936                || mAttachInfo == null
8937                || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
8938            outLocalInsets.set(in.getSystemWindowInsets());
8939            return in.consumeSystemWindowInsets();
8940        } else {
8941            outLocalInsets.set(0, 0, 0, 0);
8942            return in;
8943        }
8944    }
8945
8946    /**
8947     * Sets whether or not this view should account for system screen decorations
8948     * such as the status bar and inset its content; that is, controlling whether
8949     * the default implementation of {@link #fitSystemWindows(Rect)} will be
8950     * executed.  See that method for more details.
8951     *
8952     * <p>Note that if you are providing your own implementation of
8953     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
8954     * flag to true -- your implementation will be overriding the default
8955     * implementation that checks this flag.
8956     *
8957     * @param fitSystemWindows If true, then the default implementation of
8958     * {@link #fitSystemWindows(Rect)} will be executed.
8959     *
8960     * @attr ref android.R.styleable#View_fitsSystemWindows
8961     * @see #getFitsSystemWindows()
8962     * @see #fitSystemWindows(Rect)
8963     * @see #setSystemUiVisibility(int)
8964     */
8965    public void setFitsSystemWindows(boolean fitSystemWindows) {
8966        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
8967    }
8968
8969    /**
8970     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
8971     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
8972     * will be executed.
8973     *
8974     * @return {@code true} if the default implementation of
8975     * {@link #fitSystemWindows(Rect)} will be executed.
8976     *
8977     * @attr ref android.R.styleable#View_fitsSystemWindows
8978     * @see #setFitsSystemWindows(boolean)
8979     * @see #fitSystemWindows(Rect)
8980     * @see #setSystemUiVisibility(int)
8981     */
8982    @ViewDebug.ExportedProperty
8983    public boolean getFitsSystemWindows() {
8984        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
8985    }
8986
8987    /** @hide */
8988    public boolean fitsSystemWindows() {
8989        return getFitsSystemWindows();
8990    }
8991
8992    /**
8993     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
8994     * @deprecated Use {@link #requestApplyInsets()} for newer platform versions.
8995     */
8996    @Deprecated
8997    public void requestFitSystemWindows() {
8998        if (mParent != null) {
8999            mParent.requestFitSystemWindows();
9000        }
9001    }
9002
9003    /**
9004     * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed.
9005     */
9006    public void requestApplyInsets() {
9007        requestFitSystemWindows();
9008    }
9009
9010    /**
9011     * For use by PhoneWindow to make its own system window fitting optional.
9012     * @hide
9013     */
9014    public void makeOptionalFitsSystemWindows() {
9015        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
9016    }
9017
9018    /**
9019     * Returns the outsets, which areas of the device that aren't a surface, but we would like to
9020     * treat them as such.
9021     * @hide
9022     */
9023    public void getOutsets(Rect outOutsetRect) {
9024        if (mAttachInfo != null) {
9025            outOutsetRect.set(mAttachInfo.mOutsets);
9026        } else {
9027            outOutsetRect.setEmpty();
9028        }
9029    }
9030
9031    /**
9032     * Returns the visibility status for this view.
9033     *
9034     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
9035     * @attr ref android.R.styleable#View_visibility
9036     */
9037    @ViewDebug.ExportedProperty(mapping = {
9038        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
9039        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
9040        @ViewDebug.IntToString(from = GONE,      to = "GONE")
9041    })
9042    @Visibility
9043    public int getVisibility() {
9044        return mViewFlags & VISIBILITY_MASK;
9045    }
9046
9047    /**
9048     * Set the visibility state of this view.
9049     *
9050     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
9051     * @attr ref android.R.styleable#View_visibility
9052     */
9053    @RemotableViewMethod
9054    public void setVisibility(@Visibility int visibility) {
9055        setFlags(visibility, VISIBILITY_MASK);
9056    }
9057
9058    /**
9059     * Returns the enabled status for this view. The interpretation of the
9060     * enabled state varies by subclass.
9061     *
9062     * @return True if this view is enabled, false otherwise.
9063     */
9064    @ViewDebug.ExportedProperty
9065    public boolean isEnabled() {
9066        return (mViewFlags & ENABLED_MASK) == ENABLED;
9067    }
9068
9069    /**
9070     * Set the enabled state of this view. The interpretation of the enabled
9071     * state varies by subclass.
9072     *
9073     * @param enabled True if this view is enabled, false otherwise.
9074     */
9075    @RemotableViewMethod
9076    public void setEnabled(boolean enabled) {
9077        if (enabled == isEnabled()) return;
9078
9079        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
9080
9081        /*
9082         * The View most likely has to change its appearance, so refresh
9083         * the drawable state.
9084         */
9085        refreshDrawableState();
9086
9087        // Invalidate too, since the default behavior for views is to be
9088        // be drawn at 50% alpha rather than to change the drawable.
9089        invalidate(true);
9090
9091        if (!enabled) {
9092            cancelPendingInputEvents();
9093        }
9094    }
9095
9096    /**
9097     * Set whether this view can receive the focus.
9098     * <p>
9099     * Setting this to false will also ensure that this view is not focusable
9100     * in touch mode.
9101     *
9102     * @param focusable If true, this view can receive the focus.
9103     *
9104     * @see #setFocusableInTouchMode(boolean)
9105     * @see #setFocusable(int)
9106     * @attr ref android.R.styleable#View_focusable
9107     */
9108    public void setFocusable(boolean focusable) {
9109        setFocusable(focusable ? FOCUSABLE : NOT_FOCUSABLE);
9110    }
9111
9112    /**
9113     * Sets whether this view can receive focus.
9114     * <p>
9115     * Setting this to {@link #FOCUSABLE_AUTO} tells the framework to determine focusability
9116     * automatically based on the view's interactivity. This is the default.
9117     * <p>
9118     * Setting this to NOT_FOCUSABLE will ensure that this view is also not focusable
9119     * in touch mode.
9120     *
9121     * @param focusable One of {@link #NOT_FOCUSABLE}, {@link #FOCUSABLE},
9122     *                  or {@link #FOCUSABLE_AUTO}.
9123     * @see #setFocusableInTouchMode(boolean)
9124     * @attr ref android.R.styleable#View_focusable
9125     */
9126    public void setFocusable(@Focusable int focusable) {
9127        if ((focusable & (FOCUSABLE_AUTO | FOCUSABLE)) == 0) {
9128            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
9129        }
9130        setFlags(focusable, FOCUSABLE_MASK);
9131    }
9132
9133    /**
9134     * Set whether this view can receive focus while in touch mode.
9135     *
9136     * Setting this to true will also ensure that this view is focusable.
9137     *
9138     * @param focusableInTouchMode If true, this view can receive the focus while
9139     *   in touch mode.
9140     *
9141     * @see #setFocusable(boolean)
9142     * @attr ref android.R.styleable#View_focusableInTouchMode
9143     */
9144    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
9145        // Focusable in touch mode should always be set before the focusable flag
9146        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
9147        // which, in touch mode, will not successfully request focus on this view
9148        // because the focusable in touch mode flag is not set
9149        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
9150
9151        // Clear FOCUSABLE_AUTO if set.
9152        if (focusableInTouchMode) {
9153            // Clears FOCUSABLE_AUTO if set.
9154            setFlags(FOCUSABLE, FOCUSABLE_MASK);
9155        }
9156    }
9157
9158    /**
9159     * Set autofill mode for the view.
9160     *
9161     * @param autofillMode One of {@link #AUTOFILL_MODE_INHERIT}, {@link #AUTOFILL_MODE_AUTO},
9162     *                     or {@link #AUTOFILL_MODE_MANUAL}.
9163     * @attr ref android.R.styleable#View_autofillMode
9164     */
9165    public void setAutofillMode(@AutofillMode int autofillMode) {
9166        Preconditions.checkArgumentInRange(autofillMode, AUTOFILL_MODE_INHERIT,
9167                AUTOFILL_MODE_MANUAL, "autofillMode");
9168
9169        mPrivateFlags3 &= ~PFLAG3_AUTOFILL_MODE_MASK;
9170        mPrivateFlags3 |= autofillMode << PFLAG3_AUTOFILL_MODE_SHIFT;
9171    }
9172
9173    /**
9174     * Sets the hints that helps the autofill service to select the appropriate data to fill the
9175     * view.
9176     *
9177     * @param autofillHints The autofill hints to set. If the array is emtpy, {@code null} is set.
9178     * @attr ref android.R.styleable#View_autofillHints
9179     */
9180    public void setAutofillHints(@Nullable String... autofillHints) {
9181        if (autofillHints == null || autofillHints.length == 0) {
9182            mAutofillHints = null;
9183        } else {
9184            mAutofillHints = autofillHints;
9185        }
9186    }
9187
9188    /**
9189     * @hide
9190     */
9191    @TestApi
9192    public void setAutofilled(boolean isAutofilled) {
9193        boolean wasChanged = isAutofilled != isAutofilled();
9194
9195        if (wasChanged) {
9196            if (isAutofilled) {
9197                mPrivateFlags3 |= PFLAG3_IS_AUTOFILLED;
9198            } else {
9199                mPrivateFlags3 &= ~PFLAG3_IS_AUTOFILLED;
9200            }
9201
9202            invalidate();
9203        }
9204    }
9205
9206    /**
9207     * Set whether this view should have sound effects enabled for events such as
9208     * clicking and touching.
9209     *
9210     * <p>You may wish to disable sound effects for a view if you already play sounds,
9211     * for instance, a dial key that plays dtmf tones.
9212     *
9213     * @param soundEffectsEnabled whether sound effects are enabled for this view.
9214     * @see #isSoundEffectsEnabled()
9215     * @see #playSoundEffect(int)
9216     * @attr ref android.R.styleable#View_soundEffectsEnabled
9217     */
9218    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
9219        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
9220    }
9221
9222    /**
9223     * @return whether this view should have sound effects enabled for events such as
9224     *     clicking and touching.
9225     *
9226     * @see #setSoundEffectsEnabled(boolean)
9227     * @see #playSoundEffect(int)
9228     * @attr ref android.R.styleable#View_soundEffectsEnabled
9229     */
9230    @ViewDebug.ExportedProperty
9231    public boolean isSoundEffectsEnabled() {
9232        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
9233    }
9234
9235    /**
9236     * Set whether this view should have haptic feedback for events such as
9237     * long presses.
9238     *
9239     * <p>You may wish to disable haptic feedback if your view already controls
9240     * its own haptic feedback.
9241     *
9242     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
9243     * @see #isHapticFeedbackEnabled()
9244     * @see #performHapticFeedback(int)
9245     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
9246     */
9247    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
9248        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
9249    }
9250
9251    /**
9252     * @return whether this view should have haptic feedback enabled for events
9253     * long presses.
9254     *
9255     * @see #setHapticFeedbackEnabled(boolean)
9256     * @see #performHapticFeedback(int)
9257     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
9258     */
9259    @ViewDebug.ExportedProperty
9260    public boolean isHapticFeedbackEnabled() {
9261        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
9262    }
9263
9264    /**
9265     * Returns the layout direction for this view.
9266     *
9267     * @return One of {@link #LAYOUT_DIRECTION_LTR},
9268     *   {@link #LAYOUT_DIRECTION_RTL},
9269     *   {@link #LAYOUT_DIRECTION_INHERIT} or
9270     *   {@link #LAYOUT_DIRECTION_LOCALE}.
9271     *
9272     * @attr ref android.R.styleable#View_layoutDirection
9273     *
9274     * @hide
9275     */
9276    @ViewDebug.ExportedProperty(category = "layout", mapping = {
9277        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
9278        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
9279        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
9280        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
9281    })
9282    @LayoutDir
9283    public int getRawLayoutDirection() {
9284        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
9285    }
9286
9287    /**
9288     * Set the layout direction for this view. This will propagate a reset of layout direction
9289     * resolution to the view's children and resolve layout direction for this view.
9290     *
9291     * @param layoutDirection the layout direction to set. Should be one of:
9292     *
9293     * {@link #LAYOUT_DIRECTION_LTR},
9294     * {@link #LAYOUT_DIRECTION_RTL},
9295     * {@link #LAYOUT_DIRECTION_INHERIT},
9296     * {@link #LAYOUT_DIRECTION_LOCALE}.
9297     *
9298     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
9299     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
9300     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
9301     *
9302     * @attr ref android.R.styleable#View_layoutDirection
9303     */
9304    @RemotableViewMethod
9305    public void setLayoutDirection(@LayoutDir int layoutDirection) {
9306        if (getRawLayoutDirection() != layoutDirection) {
9307            // Reset the current layout direction and the resolved one
9308            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
9309            resetRtlProperties();
9310            // Set the new layout direction (filtered)
9311            mPrivateFlags2 |=
9312                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
9313            // We need to resolve all RTL properties as they all depend on layout direction
9314            resolveRtlPropertiesIfNeeded();
9315            requestLayout();
9316            invalidate(true);
9317        }
9318    }
9319
9320    /**
9321     * Returns the resolved layout direction for this view.
9322     *
9323     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
9324     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
9325     *
9326     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
9327     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
9328     *
9329     * @attr ref android.R.styleable#View_layoutDirection
9330     */
9331    @ViewDebug.ExportedProperty(category = "layout", mapping = {
9332        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
9333        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
9334    })
9335    @ResolvedLayoutDir
9336    public int getLayoutDirection() {
9337        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
9338        if (targetSdkVersion < Build.VERSION_CODES.JELLY_BEAN_MR1) {
9339            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
9340            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
9341        }
9342        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
9343                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
9344    }
9345
9346    /**
9347     * Indicates whether or not this view's layout is right-to-left. This is resolved from
9348     * layout attribute and/or the inherited value from the parent
9349     *
9350     * @return true if the layout is right-to-left.
9351     *
9352     * @hide
9353     */
9354    @ViewDebug.ExportedProperty(category = "layout")
9355    public boolean isLayoutRtl() {
9356        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
9357    }
9358
9359    /**
9360     * Indicates whether the view is currently tracking transient state that the
9361     * app should not need to concern itself with saving and restoring, but that
9362     * the framework should take special note to preserve when possible.
9363     *
9364     * <p>A view with transient state cannot be trivially rebound from an external
9365     * data source, such as an adapter binding item views in a list. This may be
9366     * because the view is performing an animation, tracking user selection
9367     * of content, or similar.</p>
9368     *
9369     * @return true if the view has transient state
9370     */
9371    @ViewDebug.ExportedProperty(category = "layout")
9372    public boolean hasTransientState() {
9373        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
9374    }
9375
9376    /**
9377     * Set whether this view is currently tracking transient state that the
9378     * framework should attempt to preserve when possible. This flag is reference counted,
9379     * so every call to setHasTransientState(true) should be paired with a later call
9380     * to setHasTransientState(false).
9381     *
9382     * <p>A view with transient state cannot be trivially rebound from an external
9383     * data source, such as an adapter binding item views in a list. This may be
9384     * because the view is performing an animation, tracking user selection
9385     * of content, or similar.</p>
9386     *
9387     * @param hasTransientState true if this view has transient state
9388     */
9389    public void setHasTransientState(boolean hasTransientState) {
9390        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
9391                mTransientStateCount - 1;
9392        if (mTransientStateCount < 0) {
9393            mTransientStateCount = 0;
9394            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
9395                    "unmatched pair of setHasTransientState calls");
9396        } else if ((hasTransientState && mTransientStateCount == 1) ||
9397                (!hasTransientState && mTransientStateCount == 0)) {
9398            // update flag if we've just incremented up from 0 or decremented down to 0
9399            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
9400                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
9401            if (mParent != null) {
9402                try {
9403                    mParent.childHasTransientStateChanged(this, hasTransientState);
9404                } catch (AbstractMethodError e) {
9405                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
9406                            " does not fully implement ViewParent", e);
9407                }
9408            }
9409        }
9410    }
9411
9412    /**
9413     * Returns true if this view is currently attached to a window.
9414     */
9415    public boolean isAttachedToWindow() {
9416        return mAttachInfo != null;
9417    }
9418
9419    /**
9420     * Returns true if this view has been through at least one layout since it
9421     * was last attached to or detached from a window.
9422     */
9423    public boolean isLaidOut() {
9424        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
9425    }
9426
9427    /**
9428     * If this view doesn't do any drawing on its own, set this flag to
9429     * allow further optimizations. By default, this flag is not set on
9430     * View, but could be set on some View subclasses such as ViewGroup.
9431     *
9432     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
9433     * you should clear this flag.
9434     *
9435     * @param willNotDraw whether or not this View draw on its own
9436     */
9437    public void setWillNotDraw(boolean willNotDraw) {
9438        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
9439    }
9440
9441    /**
9442     * Returns whether or not this View draws on its own.
9443     *
9444     * @return true if this view has nothing to draw, false otherwise
9445     */
9446    @ViewDebug.ExportedProperty(category = "drawing")
9447    public boolean willNotDraw() {
9448        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
9449    }
9450
9451    /**
9452     * When a View's drawing cache is enabled, drawing is redirected to an
9453     * offscreen bitmap. Some views, like an ImageView, must be able to
9454     * bypass this mechanism if they already draw a single bitmap, to avoid
9455     * unnecessary usage of the memory.
9456     *
9457     * @param willNotCacheDrawing true if this view does not cache its
9458     *        drawing, false otherwise
9459     */
9460    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
9461        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
9462    }
9463
9464    /**
9465     * Returns whether or not this View can cache its drawing or not.
9466     *
9467     * @return true if this view does not cache its drawing, false otherwise
9468     */
9469    @ViewDebug.ExportedProperty(category = "drawing")
9470    public boolean willNotCacheDrawing() {
9471        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
9472    }
9473
9474    /**
9475     * Indicates whether this view reacts to click events or not.
9476     *
9477     * @return true if the view is clickable, false otherwise
9478     *
9479     * @see #setClickable(boolean)
9480     * @attr ref android.R.styleable#View_clickable
9481     */
9482    @ViewDebug.ExportedProperty
9483    public boolean isClickable() {
9484        return (mViewFlags & CLICKABLE) == CLICKABLE;
9485    }
9486
9487    /**
9488     * Enables or disables click events for this view. When a view
9489     * is clickable it will change its state to "pressed" on every click.
9490     * Subclasses should set the view clickable to visually react to
9491     * user's clicks.
9492     *
9493     * @param clickable true to make the view clickable, false otherwise
9494     *
9495     * @see #isClickable()
9496     * @attr ref android.R.styleable#View_clickable
9497     */
9498    public void setClickable(boolean clickable) {
9499        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
9500    }
9501
9502    /**
9503     * Indicates whether this view reacts to long click events or not.
9504     *
9505     * @return true if the view is long clickable, false otherwise
9506     *
9507     * @see #setLongClickable(boolean)
9508     * @attr ref android.R.styleable#View_longClickable
9509     */
9510    public boolean isLongClickable() {
9511        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
9512    }
9513
9514    /**
9515     * Enables or disables long click events for this view. When a view is long
9516     * clickable it reacts to the user holding down the button for a longer
9517     * duration than a tap. This event can either launch the listener or a
9518     * context menu.
9519     *
9520     * @param longClickable true to make the view long clickable, false otherwise
9521     * @see #isLongClickable()
9522     * @attr ref android.R.styleable#View_longClickable
9523     */
9524    public void setLongClickable(boolean longClickable) {
9525        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
9526    }
9527
9528    /**
9529     * Indicates whether this view reacts to context clicks or not.
9530     *
9531     * @return true if the view is context clickable, false otherwise
9532     * @see #setContextClickable(boolean)
9533     * @attr ref android.R.styleable#View_contextClickable
9534     */
9535    public boolean isContextClickable() {
9536        return (mViewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
9537    }
9538
9539    /**
9540     * Enables or disables context clicking for this view. This event can launch the listener.
9541     *
9542     * @param contextClickable true to make the view react to a context click, false otherwise
9543     * @see #isContextClickable()
9544     * @attr ref android.R.styleable#View_contextClickable
9545     */
9546    public void setContextClickable(boolean contextClickable) {
9547        setFlags(contextClickable ? CONTEXT_CLICKABLE : 0, CONTEXT_CLICKABLE);
9548    }
9549
9550    /**
9551     * Sets the pressed state for this view and provides a touch coordinate for
9552     * animation hinting.
9553     *
9554     * @param pressed Pass true to set the View's internal state to "pressed",
9555     *            or false to reverts the View's internal state from a
9556     *            previously set "pressed" state.
9557     * @param x The x coordinate of the touch that caused the press
9558     * @param y The y coordinate of the touch that caused the press
9559     */
9560    private void setPressed(boolean pressed, float x, float y) {
9561        if (pressed) {
9562            drawableHotspotChanged(x, y);
9563        }
9564
9565        setPressed(pressed);
9566    }
9567
9568    /**
9569     * Sets the pressed state for this view.
9570     *
9571     * @see #isClickable()
9572     * @see #setClickable(boolean)
9573     *
9574     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
9575     *        the View's internal state from a previously set "pressed" state.
9576     */
9577    public void setPressed(boolean pressed) {
9578        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
9579
9580        if (pressed) {
9581            mPrivateFlags |= PFLAG_PRESSED;
9582        } else {
9583            mPrivateFlags &= ~PFLAG_PRESSED;
9584        }
9585
9586        if (needsRefresh) {
9587            refreshDrawableState();
9588        }
9589        dispatchSetPressed(pressed);
9590    }
9591
9592    /**
9593     * Dispatch setPressed to all of this View's children.
9594     *
9595     * @see #setPressed(boolean)
9596     *
9597     * @param pressed The new pressed state
9598     */
9599    protected void dispatchSetPressed(boolean pressed) {
9600    }
9601
9602    /**
9603     * Indicates whether the view is currently in pressed state. Unless
9604     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
9605     * the pressed state.
9606     *
9607     * @see #setPressed(boolean)
9608     * @see #isClickable()
9609     * @see #setClickable(boolean)
9610     *
9611     * @return true if the view is currently pressed, false otherwise
9612     */
9613    @ViewDebug.ExportedProperty
9614    public boolean isPressed() {
9615        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
9616    }
9617
9618    /**
9619     * @hide
9620     * Indicates whether this view will participate in data collection through
9621     * {@link ViewStructure}.  If true, it will not provide any data
9622     * for itself or its children.  If false, the normal data collection will be allowed.
9623     *
9624     * @return Returns false if assist data collection is not blocked, else true.
9625     *
9626     * @see #setAssistBlocked(boolean)
9627     * @attr ref android.R.styleable#View_assistBlocked
9628     */
9629    public boolean isAssistBlocked() {
9630        return (mPrivateFlags3 & PFLAG3_ASSIST_BLOCKED) != 0;
9631    }
9632
9633    /**
9634     * @hide
9635     * Indicates whether this view will participate in data collection through
9636     * {@link ViewStructure} for autofill purposes.
9637     *
9638     * <p>If {@code true}, it will not provide any data for itself or its children.
9639     * <p>If {@code false}, the normal data collection will be allowed.
9640     *
9641     * @return Returns {@code false} if assist data collection for autofill is not blocked,
9642     * else {@code true}.
9643     *
9644     * TODO(b/33197203): update / remove javadoc tags below
9645     * @see #setAssistBlocked(boolean)
9646     * @attr ref android.R.styleable#View_assistBlocked
9647     */
9648    public boolean isAutofillBlocked() {
9649        return false; // TODO(b/33197203): properly implement it
9650    }
9651
9652    /**
9653     * @hide
9654     * Controls whether assist data collection from this view and its children is enabled
9655     * (that is, whether {@link #onProvideStructure} and
9656     * {@link #onProvideVirtualStructure} will be called).  The default value is false,
9657     * allowing normal assist collection.  Setting this to false will disable assist collection.
9658     *
9659     * @param enabled Set to true to <em>disable</em> assist data collection, or false
9660     * (the default) to allow it.
9661     *
9662     * @see #isAssistBlocked()
9663     * @see #onProvideStructure
9664     * @see #onProvideVirtualStructure
9665     * @attr ref android.R.styleable#View_assistBlocked
9666     */
9667    public void setAssistBlocked(boolean enabled) {
9668        if (enabled) {
9669            mPrivateFlags3 |= PFLAG3_ASSIST_BLOCKED;
9670        } else {
9671            mPrivateFlags3 &= ~PFLAG3_ASSIST_BLOCKED;
9672        }
9673    }
9674
9675    /**
9676     * Indicates whether this view will save its state (that is,
9677     * whether its {@link #onSaveInstanceState} method will be called).
9678     *
9679     * @return Returns true if the view state saving is enabled, else false.
9680     *
9681     * @see #setSaveEnabled(boolean)
9682     * @attr ref android.R.styleable#View_saveEnabled
9683     */
9684    public boolean isSaveEnabled() {
9685        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
9686    }
9687
9688    /**
9689     * Controls whether the saving of this view's state is
9690     * enabled (that is, whether its {@link #onSaveInstanceState} method
9691     * will be called).  Note that even if freezing is enabled, the
9692     * view still must have an id assigned to it (via {@link #setId(int)})
9693     * for its state to be saved.  This flag can only disable the
9694     * saving of this view; any child views may still have their state saved.
9695     *
9696     * @param enabled Set to false to <em>disable</em> state saving, or true
9697     * (the default) to allow it.
9698     *
9699     * @see #isSaveEnabled()
9700     * @see #setId(int)
9701     * @see #onSaveInstanceState()
9702     * @attr ref android.R.styleable#View_saveEnabled
9703     */
9704    public void setSaveEnabled(boolean enabled) {
9705        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
9706    }
9707
9708    /**
9709     * Gets whether the framework should discard touches when the view's
9710     * window is obscured by another visible window.
9711     * Refer to the {@link View} security documentation for more details.
9712     *
9713     * @return True if touch filtering is enabled.
9714     *
9715     * @see #setFilterTouchesWhenObscured(boolean)
9716     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
9717     */
9718    @ViewDebug.ExportedProperty
9719    public boolean getFilterTouchesWhenObscured() {
9720        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
9721    }
9722
9723    /**
9724     * Sets whether the framework should discard touches when the view's
9725     * window is obscured by another visible window.
9726     * Refer to the {@link View} security documentation for more details.
9727     *
9728     * @param enabled True if touch filtering should be enabled.
9729     *
9730     * @see #getFilterTouchesWhenObscured
9731     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
9732     */
9733    public void setFilterTouchesWhenObscured(boolean enabled) {
9734        setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0,
9735                FILTER_TOUCHES_WHEN_OBSCURED);
9736    }
9737
9738    /**
9739     * Indicates whether the entire hierarchy under this view will save its
9740     * state when a state saving traversal occurs from its parent.  The default
9741     * is true; if false, these views will not be saved unless
9742     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
9743     *
9744     * @return Returns true if the view state saving from parent is enabled, else false.
9745     *
9746     * @see #setSaveFromParentEnabled(boolean)
9747     */
9748    public boolean isSaveFromParentEnabled() {
9749        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
9750    }
9751
9752    /**
9753     * Controls whether the entire hierarchy under this view will save its
9754     * state when a state saving traversal occurs from its parent.  The default
9755     * is true; if false, these views will not be saved unless
9756     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
9757     *
9758     * @param enabled Set to false to <em>disable</em> state saving, or true
9759     * (the default) to allow it.
9760     *
9761     * @see #isSaveFromParentEnabled()
9762     * @see #setId(int)
9763     * @see #onSaveInstanceState()
9764     */
9765    public void setSaveFromParentEnabled(boolean enabled) {
9766        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
9767    }
9768
9769
9770    /**
9771     * Returns whether this View is currently able to take focus.
9772     *
9773     * @return True if this view can take focus, or false otherwise.
9774     */
9775    @ViewDebug.ExportedProperty(category = "focus")
9776    public final boolean isFocusable() {
9777        return FOCUSABLE == (mViewFlags & FOCUSABLE);
9778    }
9779
9780    /**
9781     * Returns the focusable setting for this view.
9782     *
9783     * @return One of {@link #NOT_FOCUSABLE}, {@link #FOCUSABLE}, or {@link #FOCUSABLE_AUTO}.
9784     * @attr ref android.R.styleable#View_focusable
9785     */
9786    @ViewDebug.ExportedProperty(mapping = {
9787            @ViewDebug.IntToString(from = NOT_FOCUSABLE, to = "NOT_FOCUSABLE"),
9788            @ViewDebug.IntToString(from = FOCUSABLE, to = "FOCUSABLE"),
9789            @ViewDebug.IntToString(from = FOCUSABLE_AUTO, to = "FOCUSABLE_AUTO")
9790            })
9791    @Focusable
9792    public int getFocusable() {
9793        return (mViewFlags & FOCUSABLE_AUTO) > 0 ? FOCUSABLE_AUTO : mViewFlags & FOCUSABLE;
9794    }
9795
9796    /**
9797     * When a view is focusable, it may not want to take focus when in touch mode.
9798     * For example, a button would like focus when the user is navigating via a D-pad
9799     * so that the user can click on it, but once the user starts touching the screen,
9800     * the button shouldn't take focus
9801     * @return Whether the view is focusable in touch mode.
9802     * @attr ref android.R.styleable#View_focusableInTouchMode
9803     */
9804    @ViewDebug.ExportedProperty
9805    public final boolean isFocusableInTouchMode() {
9806        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
9807    }
9808
9809    /**
9810     * Returns the autofill mode for this view.
9811     *
9812     * @return One of {@link #AUTOFILL_MODE_INHERIT}, {@link #AUTOFILL_MODE_AUTO}, or
9813     * {@link #AUTOFILL_MODE_MANUAL}.
9814     * @attr ref android.R.styleable#View_autofillMode
9815     */
9816    @ViewDebug.ExportedProperty(mapping = {
9817            @ViewDebug.IntToString(from = AUTOFILL_MODE_INHERIT, to = "AUTOFILL_MODE_INHERIT"),
9818            @ViewDebug.IntToString(from = AUTOFILL_MODE_AUTO, to = "AUTOFILL_MODE_AUTO"),
9819            @ViewDebug.IntToString(from = AUTOFILL_MODE_MANUAL, to = "AUTOFILL_MODE_MANUAL")
9820            })
9821    @AutofillMode
9822    public int getAutofillMode() {
9823        return (mPrivateFlags3 & PFLAG3_AUTOFILL_MODE_MASK) >> PFLAG3_AUTOFILL_MODE_SHIFT;
9824    }
9825
9826    /**
9827     * Returns the resolved autofill mode for this view.
9828     *
9829     * This is the same as {@link #getAutofillMode()} but if the mode is
9830     * {@link #AUTOFILL_MODE_INHERIT} the parents autofill mode will be returned.
9831     *
9832     * @return One of {@link #AUTOFILL_MODE_AUTO}, or {@link #AUTOFILL_MODE_MANUAL}. If the auto-
9833     *         fill mode can not be resolved e.g. {@link #getAutofillMode()} is
9834     *         {@link #AUTOFILL_MODE_INHERIT} and the {@link View} is detached
9835     *         {@link #AUTOFILL_MODE_AUTO} is returned.
9836     */
9837    public @AutofillMode int getResolvedAutofillMode() {
9838        @AutofillMode int autofillMode = getAutofillMode();
9839
9840        if (autofillMode == AUTOFILL_MODE_INHERIT) {
9841            if (mParent == null) {
9842                return AUTOFILL_MODE_AUTO;
9843            } else {
9844                return mParent.getResolvedAutofillMode();
9845            }
9846        } else {
9847            return autofillMode;
9848        }
9849    }
9850
9851    /**
9852     * Find the nearest view in the specified direction that can take focus.
9853     * This does not actually give focus to that view.
9854     *
9855     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
9856     *
9857     * @return The nearest focusable in the specified direction, or null if none
9858     *         can be found.
9859     */
9860    public View focusSearch(@FocusRealDirection int direction) {
9861        if (mParent != null) {
9862            return mParent.focusSearch(this, direction);
9863        } else {
9864            return null;
9865        }
9866    }
9867
9868    /**
9869     * Returns whether this View is a root of a keyboard navigation cluster.
9870     *
9871     * @return True if this view is a root of a cluster, or false otherwise.
9872     * @attr ref android.R.styleable#View_keyboardNavigationCluster
9873     */
9874    @ViewDebug.ExportedProperty(category = "keyboardNavigationCluster")
9875    public final boolean isKeyboardNavigationCluster() {
9876        return (mPrivateFlags3 & PFLAG3_CLUSTER) != 0;
9877    }
9878
9879    /**
9880     * Set whether this view is a root of a keyboard navigation cluster.
9881     *
9882     * @param isCluster If true, this view is a root of a cluster.
9883     *
9884     * @attr ref android.R.styleable#View_keyboardNavigationCluster
9885     */
9886    public void setKeyboardNavigationCluster(boolean isCluster) {
9887        if (isCluster) {
9888            mPrivateFlags3 |= PFLAG3_CLUSTER;
9889        } else {
9890            mPrivateFlags3 &= ~PFLAG3_CLUSTER;
9891        }
9892    }
9893
9894    /**
9895     * Sets this View as the one which receives focus the next time cluster navigation jumps
9896     * to the cluster containing this View. This does NOT change focus even if the cluster
9897     * containing this view is current.
9898     *
9899     * @hide
9900     */
9901    public void setFocusedInCluster() {
9902        if (mParent instanceof ViewGroup) {
9903            ((ViewGroup) mParent).setFocusInCluster(this);
9904        }
9905    }
9906
9907    /**
9908     * Returns whether this View should receive focus when the focus is restored for the view
9909     * hierarchy containing this view.
9910     * <p>
9911     * Focus gets restored for a view hierarchy when the root of the hierarchy gets added to a
9912     * window or serves as a target of cluster navigation.
9913     *
9914     * @see #restoreDefaultFocus()
9915     *
9916     * @return {@code true} if this view is the default-focus view, {@code false} otherwise
9917     * @attr ref android.R.styleable#View_focusedByDefault
9918     */
9919    @ViewDebug.ExportedProperty(category = "focusedByDefault")
9920    public final boolean isFocusedByDefault() {
9921        return (mPrivateFlags3 & PFLAG3_FOCUSED_BY_DEFAULT) != 0;
9922    }
9923
9924    /**
9925     * Sets whether this View should receive focus when the focus is restored for the view
9926     * hierarchy containing this view.
9927     * <p>
9928     * Focus gets restored for a view hierarchy when the root of the hierarchy gets added to a
9929     * window or serves as a target of cluster navigation.
9930     *
9931     * @param isFocusedByDefault {@code true} to set this view as the default-focus view,
9932     *                           {@code false} otherwise.
9933     *
9934     * @see #restoreDefaultFocus()
9935     *
9936     * @attr ref android.R.styleable#View_focusedByDefault
9937     */
9938    public void setFocusedByDefault(boolean isFocusedByDefault) {
9939        if (isFocusedByDefault == ((mPrivateFlags3 & PFLAG3_FOCUSED_BY_DEFAULT) != 0)) {
9940            return;
9941        }
9942
9943        if (isFocusedByDefault) {
9944            mPrivateFlags3 |= PFLAG3_FOCUSED_BY_DEFAULT;
9945        } else {
9946            mPrivateFlags3 &= ~PFLAG3_FOCUSED_BY_DEFAULT;
9947        }
9948
9949        if (mParent instanceof ViewGroup) {
9950            if (isFocusedByDefault) {
9951                ((ViewGroup) mParent).setDefaultFocus(this);
9952            } else {
9953                ((ViewGroup) mParent).clearDefaultFocus(this);
9954            }
9955        }
9956    }
9957
9958    /**
9959     * Returns whether the view hierarchy with this view as a root contain a default-focus view.
9960     *
9961     * @return {@code true} if this view has default focus, {@code false} otherwise
9962     */
9963    boolean hasDefaultFocus() {
9964        return isFocusedByDefault();
9965    }
9966
9967    /**
9968     * Find the nearest keyboard navigation cluster in the specified direction.
9969     * This does not actually give focus to that cluster.
9970     *
9971     * @param currentCluster The starting point of the search. Null means the current cluster is not
9972     *                       found yet
9973     * @param direction Direction to look
9974     *
9975     * @return The nearest keyboard navigation cluster in the specified direction, or null if none
9976     *         can be found
9977     */
9978    public View keyboardNavigationClusterSearch(View currentCluster,
9979            @FocusDirection int direction) {
9980        if (isKeyboardNavigationCluster()) {
9981            currentCluster = this;
9982        }
9983        if (isRootNamespace()) {
9984            // Root namespace means we should consider ourselves the top of the
9985            // tree for group searching; otherwise we could be group searching
9986            // into other tabs.  see LocalActivityManager and TabHost for more info.
9987            return FocusFinder.getInstance().findNextKeyboardNavigationCluster(
9988                    this, currentCluster, direction);
9989        } else if (mParent != null) {
9990            return mParent.keyboardNavigationClusterSearch(currentCluster, direction);
9991        }
9992        return null;
9993    }
9994
9995    /**
9996     * This method is the last chance for the focused view and its ancestors to
9997     * respond to an arrow key. This is called when the focused view did not
9998     * consume the key internally, nor could the view system find a new view in
9999     * the requested direction to give focus to.
10000     *
10001     * @param focused The currently focused view.
10002     * @param direction The direction focus wants to move. One of FOCUS_UP,
10003     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
10004     * @return True if the this view consumed this unhandled move.
10005     */
10006    public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) {
10007        return false;
10008    }
10009
10010    /**
10011     * Sets whether this View should use a default focus highlight when it gets focused but doesn't
10012     * have {@link android.R.attr#state_focused} defined in its background.
10013     *
10014     * @param defaultFocusHighlightEnabled {@code true} to set this view to use a default focus
10015     *                                      highlight, {@code false} otherwise.
10016     *
10017     * @attr ref android.R.styleable#View_defaultFocusHighlightEnabled
10018     */
10019    public void setDefaultFocusHighlightEnabled(boolean defaultFocusHighlightEnabled) {
10020        mDefaultFocusHighlightEnabled = defaultFocusHighlightEnabled;
10021    }
10022
10023    /**
10024
10025    /**
10026     * Returns whether this View should use a default focus highlight when it gets focused but
10027     * doesn't have {@link android.R.attr#state_focused} defined in its background.
10028     *
10029     * @return True if this View should use a default focus highlight.
10030     * @attr ref android.R.styleable#View_defaultFocusHighlightEnabled
10031     */
10032    @ViewDebug.ExportedProperty(category = "defaultFocusHighlightEnabled")
10033    public final boolean getDefaultFocusHighlightEnabled() {
10034        return mDefaultFocusHighlightEnabled;
10035    }
10036
10037    /**
10038     * If a user manually specified the next view id for a particular direction,
10039     * use the root to look up the view.
10040     * @param root The root view of the hierarchy containing this view.
10041     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
10042     * or FOCUS_BACKWARD.
10043     * @return The user specified next view, or null if there is none.
10044     */
10045    View findUserSetNextFocus(View root, @FocusDirection int direction) {
10046        switch (direction) {
10047            case FOCUS_LEFT:
10048                if (mNextFocusLeftId == View.NO_ID) return null;
10049                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
10050            case FOCUS_RIGHT:
10051                if (mNextFocusRightId == View.NO_ID) return null;
10052                return findViewInsideOutShouldExist(root, mNextFocusRightId);
10053            case FOCUS_UP:
10054                if (mNextFocusUpId == View.NO_ID) return null;
10055                return findViewInsideOutShouldExist(root, mNextFocusUpId);
10056            case FOCUS_DOWN:
10057                if (mNextFocusDownId == View.NO_ID) return null;
10058                return findViewInsideOutShouldExist(root, mNextFocusDownId);
10059            case FOCUS_FORWARD:
10060                if (mNextFocusForwardId == View.NO_ID) return null;
10061                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
10062            case FOCUS_BACKWARD: {
10063                if (mID == View.NO_ID) return null;
10064                final int id = mID;
10065                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
10066                    @Override
10067                    public boolean test(View t) {
10068                        return t.mNextFocusForwardId == id;
10069                    }
10070                });
10071            }
10072        }
10073        return null;
10074    }
10075
10076    /**
10077     * If a user manually specified the next keyboard-navigation cluster for a particular direction,
10078     * use the root to look up the view.
10079     *
10080     * @param root the root view of the hierarchy containing this view
10081     * @param direction {@link #FOCUS_FORWARD} or {@link #FOCUS_BACKWARD}
10082     * @return the user-specified next cluster, or {@code null} if there is none
10083     */
10084    View findUserSetNextKeyboardNavigationCluster(View root, @FocusDirection int direction) {
10085        switch (direction) {
10086            case FOCUS_FORWARD:
10087                if (mNextClusterForwardId == View.NO_ID) return null;
10088                return findViewInsideOutShouldExist(root, mNextClusterForwardId);
10089            case FOCUS_BACKWARD: {
10090                if (mID == View.NO_ID) return null;
10091                final int id = mID;
10092                return root.findViewByPredicateInsideOut(this,
10093                        (Predicate<View>) t -> t.mNextClusterForwardId == id);
10094            }
10095        }
10096        return null;
10097    }
10098
10099    private View findViewInsideOutShouldExist(View root, int id) {
10100        if (mMatchIdPredicate == null) {
10101            mMatchIdPredicate = new MatchIdPredicate();
10102        }
10103        mMatchIdPredicate.mId = id;
10104        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
10105        if (result == null) {
10106            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
10107        }
10108        return result;
10109    }
10110
10111    /**
10112     * Find and return all focusable views that are descendants of this view,
10113     * possibly including this view if it is focusable itself.
10114     *
10115     * @param direction The direction of the focus
10116     * @return A list of focusable views
10117     */
10118    public ArrayList<View> getFocusables(@FocusDirection int direction) {
10119        ArrayList<View> result = new ArrayList<View>(24);
10120        addFocusables(result, direction);
10121        return result;
10122    }
10123
10124    /**
10125     * Add any focusable views that are descendants of this view (possibly
10126     * including this view if it is focusable itself) to views.  If we are in touch mode,
10127     * only add views that are also focusable in touch mode.
10128     *
10129     * @param views Focusable views found so far
10130     * @param direction The direction of the focus
10131     */
10132    public void addFocusables(ArrayList<View> views, @FocusDirection int direction) {
10133        addFocusables(views, direction, isInTouchMode() ? FOCUSABLES_TOUCH_MODE : FOCUSABLES_ALL);
10134    }
10135
10136    /**
10137     * Adds any focusable views that are descendants of this view (possibly
10138     * including this view if it is focusable itself) to views. This method
10139     * adds all focusable views regardless if we are in touch mode or
10140     * only views focusable in touch mode if we are in touch mode or
10141     * only views that can take accessibility focus if accessibility is enabled
10142     * depending on the focusable mode parameter.
10143     *
10144     * @param views Focusable views found so far or null if all we are interested is
10145     *        the number of focusables.
10146     * @param direction The direction of the focus.
10147     * @param focusableMode The type of focusables to be added.
10148     *
10149     * @see #FOCUSABLES_ALL
10150     * @see #FOCUSABLES_TOUCH_MODE
10151     */
10152    public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
10153            @FocusableMode int focusableMode) {
10154        if (views == null) {
10155            return;
10156        }
10157        if (!isFocusable()) {
10158            return;
10159        }
10160        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
10161                && !isFocusableInTouchMode()) {
10162            return;
10163        }
10164        views.add(this);
10165    }
10166
10167    /**
10168     * Adds any keyboard navigation cluster roots that are descendants of this view (possibly
10169     * including this view if it is a cluster root itself) to views.
10170     *
10171     * @param views Keyboard navigation cluster roots found so far
10172     * @param direction Direction to look
10173     */
10174    public void addKeyboardNavigationClusters(
10175            @NonNull Collection<View> views,
10176            int direction) {
10177        if (!isKeyboardNavigationCluster()) {
10178            return;
10179        }
10180        if (!hasFocusable()) {
10181            return;
10182        }
10183        views.add(this);
10184    }
10185
10186    /**
10187     * Finds the Views that contain given text. The containment is case insensitive.
10188     * The search is performed by either the text that the View renders or the content
10189     * description that describes the view for accessibility purposes and the view does
10190     * not render or both. Clients can specify how the search is to be performed via
10191     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
10192     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
10193     *
10194     * @param outViews The output list of matching Views.
10195     * @param searched The text to match against.
10196     *
10197     * @see #FIND_VIEWS_WITH_TEXT
10198     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
10199     * @see #setContentDescription(CharSequence)
10200     */
10201    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched,
10202            @FindViewFlags int flags) {
10203        if (getAccessibilityNodeProvider() != null) {
10204            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
10205                outViews.add(this);
10206            }
10207        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
10208                && (searched != null && searched.length() > 0)
10209                && (mContentDescription != null && mContentDescription.length() > 0)) {
10210            String searchedLowerCase = searched.toString().toLowerCase();
10211            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
10212            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
10213                outViews.add(this);
10214            }
10215        }
10216    }
10217
10218    /**
10219     * Find and return all touchable views that are descendants of this view,
10220     * possibly including this view if it is touchable itself.
10221     *
10222     * @return A list of touchable views
10223     */
10224    public ArrayList<View> getTouchables() {
10225        ArrayList<View> result = new ArrayList<View>();
10226        addTouchables(result);
10227        return result;
10228    }
10229
10230    /**
10231     * Add any touchable views that are descendants of this view (possibly
10232     * including this view if it is touchable itself) to views.
10233     *
10234     * @param views Touchable views found so far
10235     */
10236    public void addTouchables(ArrayList<View> views) {
10237        final int viewFlags = mViewFlags;
10238
10239        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE
10240                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE)
10241                && (viewFlags & ENABLED_MASK) == ENABLED) {
10242            views.add(this);
10243        }
10244    }
10245
10246    /**
10247     * Returns whether this View is accessibility focused.
10248     *
10249     * @return True if this View is accessibility focused.
10250     */
10251    public boolean isAccessibilityFocused() {
10252        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
10253    }
10254
10255    /**
10256     * Call this to try to give accessibility focus to this view.
10257     *
10258     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
10259     * returns false or the view is no visible or the view already has accessibility
10260     * focus.
10261     *
10262     * See also {@link #focusSearch(int)}, which is what you call to say that you
10263     * have focus, and you want your parent to look for the next one.
10264     *
10265     * @return Whether this view actually took accessibility focus.
10266     *
10267     * @hide
10268     */
10269    public boolean requestAccessibilityFocus() {
10270        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
10271        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
10272            return false;
10273        }
10274        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
10275            return false;
10276        }
10277        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
10278            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
10279            ViewRootImpl viewRootImpl = getViewRootImpl();
10280            if (viewRootImpl != null) {
10281                viewRootImpl.setAccessibilityFocus(this, null);
10282            }
10283            invalidate();
10284            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
10285            return true;
10286        }
10287        return false;
10288    }
10289
10290    /**
10291     * Call this to try to clear accessibility focus of this view.
10292     *
10293     * See also {@link #focusSearch(int)}, which is what you call to say that you
10294     * have focus, and you want your parent to look for the next one.
10295     *
10296     * @hide
10297     */
10298    public void clearAccessibilityFocus() {
10299        clearAccessibilityFocusNoCallbacks(0);
10300
10301        // Clear the global reference of accessibility focus if this view or
10302        // any of its descendants had accessibility focus. This will NOT send
10303        // an event or update internal state if focus is cleared from a
10304        // descendant view, which may leave views in inconsistent states.
10305        final ViewRootImpl viewRootImpl = getViewRootImpl();
10306        if (viewRootImpl != null) {
10307            final View focusHost = viewRootImpl.getAccessibilityFocusedHost();
10308            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
10309                viewRootImpl.setAccessibilityFocus(null, null);
10310            }
10311        }
10312    }
10313
10314    private void sendAccessibilityHoverEvent(int eventType) {
10315        // Since we are not delivering to a client accessibility events from not
10316        // important views (unless the clinet request that) we need to fire the
10317        // event from the deepest view exposed to the client. As a consequence if
10318        // the user crosses a not exposed view the client will see enter and exit
10319        // of the exposed predecessor followed by and enter and exit of that same
10320        // predecessor when entering and exiting the not exposed descendant. This
10321        // is fine since the client has a clear idea which view is hovered at the
10322        // price of a couple more events being sent. This is a simple and
10323        // working solution.
10324        View source = this;
10325        while (true) {
10326            if (source.includeForAccessibility()) {
10327                source.sendAccessibilityEvent(eventType);
10328                return;
10329            }
10330            ViewParent parent = source.getParent();
10331            if (parent instanceof View) {
10332                source = (View) parent;
10333            } else {
10334                return;
10335            }
10336        }
10337    }
10338
10339    /**
10340     * Clears accessibility focus without calling any callback methods
10341     * normally invoked in {@link #clearAccessibilityFocus()}. This method
10342     * is used separately from that one for clearing accessibility focus when
10343     * giving this focus to another view.
10344     *
10345     * @param action The action, if any, that led to focus being cleared. Set to
10346     * AccessibilityNodeInfo#ACTION_ACCESSIBILITY_FOCUS to specify that focus is moving within
10347     * the window.
10348     */
10349    void clearAccessibilityFocusNoCallbacks(int action) {
10350        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
10351            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
10352            invalidate();
10353            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
10354                AccessibilityEvent event = AccessibilityEvent.obtain(
10355                        AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
10356                event.setAction(action);
10357                if (mAccessibilityDelegate != null) {
10358                    mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
10359                } else {
10360                    sendAccessibilityEventUnchecked(event);
10361                }
10362            }
10363        }
10364    }
10365
10366    /**
10367     * Call this to try to give focus to a specific view or to one of its
10368     * descendants.
10369     *
10370     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
10371     * false), or if it is focusable and it is not focusable in touch mode
10372     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
10373     *
10374     * See also {@link #focusSearch(int)}, which is what you call to say that you
10375     * have focus, and you want your parent to look for the next one.
10376     *
10377     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
10378     * {@link #FOCUS_DOWN} and <code>null</code>.
10379     *
10380     * @return Whether this view or one of its descendants actually took focus.
10381     */
10382    public final boolean requestFocus() {
10383        return requestFocus(View.FOCUS_DOWN);
10384    }
10385
10386    /**
10387     * This will request focus for whichever View was last focused within this
10388     * cluster before a focus-jump out of it.
10389     *
10390     * @hide
10391     */
10392    @TestApi
10393    public boolean restoreFocusInCluster(@FocusRealDirection int direction) {
10394        // Prioritize focusableByDefault over algorithmic focus selection.
10395        if (restoreDefaultFocus()) {
10396            return true;
10397        }
10398        return requestFocus(direction);
10399    }
10400
10401    /**
10402     * This will request focus for whichever View not in a cluster was last focused before a
10403     * focus-jump to a cluster. If no non-cluster View has previously had focus, this will focus
10404     * the "first" focusable view it finds.
10405     *
10406     * @hide
10407     */
10408    @TestApi
10409    public boolean restoreFocusNotInCluster() {
10410        return requestFocus(View.FOCUS_DOWN);
10411    }
10412
10413    /**
10414     * Gives focus to the default-focus view in the view hierarchy that has this view as a root.
10415     * If the default-focus view cannot be found, falls back to calling {@link #requestFocus(int)}.
10416     *
10417     * @return Whether this view or one of its descendants actually took focus
10418     */
10419    public boolean restoreDefaultFocus() {
10420        return requestFocus(View.FOCUS_DOWN);
10421    }
10422
10423    /**
10424     * Call this to try to give focus to a specific view or to one of its
10425     * descendants and give it a hint about what direction focus is heading.
10426     *
10427     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
10428     * false), or if it is focusable and it is not focusable in touch mode
10429     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
10430     *
10431     * See also {@link #focusSearch(int)}, which is what you call to say that you
10432     * have focus, and you want your parent to look for the next one.
10433     *
10434     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
10435     * <code>null</code> set for the previously focused rectangle.
10436     *
10437     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
10438     * @return Whether this view or one of its descendants actually took focus.
10439     */
10440    public final boolean requestFocus(int direction) {
10441        return requestFocus(direction, null);
10442    }
10443
10444    /**
10445     * Call this to try to give focus to a specific view or to one of its descendants
10446     * and give it hints about the direction and a specific rectangle that the focus
10447     * is coming from.  The rectangle can help give larger views a finer grained hint
10448     * about where focus is coming from, and therefore, where to show selection, or
10449     * forward focus change internally.
10450     *
10451     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
10452     * false), or if it is focusable and it is not focusable in touch mode
10453     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
10454     *
10455     * A View will not take focus if it is not visible.
10456     *
10457     * A View will not take focus if one of its parents has
10458     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
10459     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
10460     *
10461     * See also {@link #focusSearch(int)}, which is what you call to say that you
10462     * have focus, and you want your parent to look for the next one.
10463     *
10464     * You may wish to override this method if your custom {@link View} has an internal
10465     * {@link View} that it wishes to forward the request to.
10466     *
10467     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
10468     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
10469     *        to give a finer grained hint about where focus is coming from.  May be null
10470     *        if there is no hint.
10471     * @return Whether this view or one of its descendants actually took focus.
10472     */
10473    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
10474        return requestFocusNoSearch(direction, previouslyFocusedRect);
10475    }
10476
10477    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
10478        // need to be focusable
10479        if ((mViewFlags & FOCUSABLE) != FOCUSABLE
10480                || (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
10481            return false;
10482        }
10483
10484        // need to be focusable in touch mode if in touch mode
10485        if (isInTouchMode() &&
10486            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
10487               return false;
10488        }
10489
10490        // need to not have any parents blocking us
10491        if (hasAncestorThatBlocksDescendantFocus()) {
10492            return false;
10493        }
10494
10495        handleFocusGainInternal(direction, previouslyFocusedRect);
10496        return true;
10497    }
10498
10499    /**
10500     * Call this to try to give focus to a specific view or to one of its descendants. This is a
10501     * special variant of {@link #requestFocus() } that will allow views that are not focusable in
10502     * touch mode to request focus when they are touched.
10503     *
10504     * @return Whether this view or one of its descendants actually took focus.
10505     *
10506     * @see #isInTouchMode()
10507     *
10508     */
10509    public final boolean requestFocusFromTouch() {
10510        // Leave touch mode if we need to
10511        if (isInTouchMode()) {
10512            ViewRootImpl viewRoot = getViewRootImpl();
10513            if (viewRoot != null) {
10514                viewRoot.ensureTouchMode(false);
10515            }
10516        }
10517        return requestFocus(View.FOCUS_DOWN);
10518    }
10519
10520    /**
10521     * @return Whether any ancestor of this view blocks descendant focus.
10522     */
10523    private boolean hasAncestorThatBlocksDescendantFocus() {
10524        final boolean focusableInTouchMode = isFocusableInTouchMode();
10525        ViewParent ancestor = mParent;
10526        while (ancestor instanceof ViewGroup) {
10527            final ViewGroup vgAncestor = (ViewGroup) ancestor;
10528            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS
10529                    || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) {
10530                return true;
10531            } else {
10532                ancestor = vgAncestor.getParent();
10533            }
10534        }
10535        return false;
10536    }
10537
10538    /**
10539     * Gets the mode for determining whether this View is important for accessibility.
10540     * A view is important for accessibility if it fires accessibility events and if it
10541     * is reported to accessibility services that query the screen.
10542     *
10543     * @return The mode for determining whether a view is important for accessibility, one
10544     * of {@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, {@link #IMPORTANT_FOR_ACCESSIBILITY_YES},
10545     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO}, or
10546     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}.
10547     *
10548     * @attr ref android.R.styleable#View_importantForAccessibility
10549     *
10550     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
10551     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
10552     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
10553     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
10554     */
10555    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
10556            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
10557            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
10558            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"),
10559            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
10560                    to = "noHideDescendants")
10561        })
10562    public int getImportantForAccessibility() {
10563        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
10564                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
10565    }
10566
10567    /**
10568     * Sets the live region mode for this view. This indicates to accessibility
10569     * services whether they should automatically notify the user about changes
10570     * to the view's content description or text, or to the content descriptions
10571     * or text of the view's children (where applicable).
10572     * <p>
10573     * For example, in a login screen with a TextView that displays an "incorrect
10574     * password" notification, that view should be marked as a live region with
10575     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
10576     * <p>
10577     * To disable change notifications for this view, use
10578     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
10579     * mode for most views.
10580     * <p>
10581     * To indicate that the user should be notified of changes, use
10582     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
10583     * <p>
10584     * If the view's changes should interrupt ongoing speech and notify the user
10585     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
10586     *
10587     * @param mode The live region mode for this view, one of:
10588     *        <ul>
10589     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
10590     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
10591     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
10592     *        </ul>
10593     * @attr ref android.R.styleable#View_accessibilityLiveRegion
10594     */
10595    public void setAccessibilityLiveRegion(int mode) {
10596        if (mode != getAccessibilityLiveRegion()) {
10597            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
10598            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
10599                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
10600            notifyViewAccessibilityStateChangedIfNeeded(
10601                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10602        }
10603    }
10604
10605    /**
10606     * Gets the live region mode for this View.
10607     *
10608     * @return The live region mode for the view.
10609     *
10610     * @attr ref android.R.styleable#View_accessibilityLiveRegion
10611     *
10612     * @see #setAccessibilityLiveRegion(int)
10613     */
10614    public int getAccessibilityLiveRegion() {
10615        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
10616                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
10617    }
10618
10619    /**
10620     * Sets how to determine whether this view is important for accessibility
10621     * which is if it fires accessibility events and if it is reported to
10622     * accessibility services that query the screen.
10623     *
10624     * @param mode How to determine whether this view is important for accessibility.
10625     *
10626     * @attr ref android.R.styleable#View_importantForAccessibility
10627     *
10628     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
10629     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
10630     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
10631     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
10632     */
10633    public void setImportantForAccessibility(int mode) {
10634        final int oldMode = getImportantForAccessibility();
10635        if (mode != oldMode) {
10636            final boolean hideDescendants =
10637                    mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS;
10638
10639            // If this node or its descendants are no longer important, try to
10640            // clear accessibility focus.
10641            if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO || hideDescendants) {
10642                final View focusHost = findAccessibilityFocusHost(hideDescendants);
10643                if (focusHost != null) {
10644                    focusHost.clearAccessibilityFocus();
10645                }
10646            }
10647
10648            // If we're moving between AUTO and another state, we might not need
10649            // to send a subtree changed notification. We'll store the computed
10650            // importance, since we'll need to check it later to make sure.
10651            final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO
10652                    || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO;
10653            final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility();
10654            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
10655            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
10656                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
10657            if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) {
10658                notifySubtreeAccessibilityStateChangedIfNeeded();
10659            } else {
10660                notifyViewAccessibilityStateChangedIfNeeded(
10661                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10662            }
10663        }
10664    }
10665
10666    /**
10667     * Returns the view within this view's hierarchy that is hosting
10668     * accessibility focus.
10669     *
10670     * @param searchDescendants whether to search for focus in descendant views
10671     * @return the view hosting accessibility focus, or {@code null}
10672     */
10673    private View findAccessibilityFocusHost(boolean searchDescendants) {
10674        if (isAccessibilityFocusedViewOrHost()) {
10675            return this;
10676        }
10677
10678        if (searchDescendants) {
10679            final ViewRootImpl viewRoot = getViewRootImpl();
10680            if (viewRoot != null) {
10681                final View focusHost = viewRoot.getAccessibilityFocusedHost();
10682                if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
10683                    return focusHost;
10684                }
10685            }
10686        }
10687
10688        return null;
10689    }
10690
10691    /**
10692     * Computes whether this view should be exposed for accessibility. In
10693     * general, views that are interactive or provide information are exposed
10694     * while views that serve only as containers are hidden.
10695     * <p>
10696     * If an ancestor of this view has importance
10697     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method
10698     * returns <code>false</code>.
10699     * <p>
10700     * Otherwise, the value is computed according to the view's
10701     * {@link #getImportantForAccessibility()} value:
10702     * <ol>
10703     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or
10704     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false
10705     * </code>
10706     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code>
10707     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if
10708     * view satisfies any of the following:
10709     * <ul>
10710     * <li>Is actionable, e.g. {@link #isClickable()},
10711     * {@link #isLongClickable()}, or {@link #isFocusable()}
10712     * <li>Has an {@link AccessibilityDelegate}
10713     * <li>Has an interaction listener, e.g. {@link OnTouchListener},
10714     * {@link OnKeyListener}, etc.
10715     * <li>Is an accessibility live region, e.g.
10716     * {@link #getAccessibilityLiveRegion()} is not
10717     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}.
10718     * </ul>
10719     * </ol>
10720     *
10721     * @return Whether the view is exposed for accessibility.
10722     * @see #setImportantForAccessibility(int)
10723     * @see #getImportantForAccessibility()
10724     */
10725    public boolean isImportantForAccessibility() {
10726        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
10727                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
10728        if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO
10729                || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
10730            return false;
10731        }
10732
10733        // Check parent mode to ensure we're not hidden.
10734        ViewParent parent = mParent;
10735        while (parent instanceof View) {
10736            if (((View) parent).getImportantForAccessibility()
10737                    == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
10738                return false;
10739            }
10740            parent = parent.getParent();
10741        }
10742
10743        return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
10744                || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
10745                || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE;
10746    }
10747
10748    /**
10749     * Gets the parent for accessibility purposes. Note that the parent for
10750     * accessibility is not necessary the immediate parent. It is the first
10751     * predecessor that is important for accessibility.
10752     *
10753     * @return The parent for accessibility purposes.
10754     */
10755    public ViewParent getParentForAccessibility() {
10756        if (mParent instanceof View) {
10757            View parentView = (View) mParent;
10758            if (parentView.includeForAccessibility()) {
10759                return mParent;
10760            } else {
10761                return mParent.getParentForAccessibility();
10762            }
10763        }
10764        return null;
10765    }
10766
10767    /**
10768     * Adds the children of this View relevant for accessibility to the given list
10769     * as output. Since some Views are not important for accessibility the added
10770     * child views are not necessarily direct children of this view, rather they are
10771     * the first level of descendants important for accessibility.
10772     *
10773     * @param outChildren The output list that will receive children for accessibility.
10774     */
10775    public void addChildrenForAccessibility(ArrayList<View> outChildren) {
10776
10777    }
10778
10779    /**
10780     * Whether to regard this view for accessibility. A view is regarded for
10781     * accessibility if it is important for accessibility or the querying
10782     * accessibility service has explicitly requested that view not
10783     * important for accessibility are regarded.
10784     *
10785     * @return Whether to regard the view for accessibility.
10786     *
10787     * @hide
10788     */
10789    public boolean includeForAccessibility() {
10790        if (mAttachInfo != null) {
10791            return (mAttachInfo.mAccessibilityFetchFlags
10792                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
10793                    || isImportantForAccessibility();
10794        }
10795        return false;
10796    }
10797
10798    /**
10799     * Returns whether the View is considered actionable from
10800     * accessibility perspective. Such view are important for
10801     * accessibility.
10802     *
10803     * @return True if the view is actionable for accessibility.
10804     *
10805     * @hide
10806     */
10807    public boolean isActionableForAccessibility() {
10808        return (isClickable() || isLongClickable() || isFocusable());
10809    }
10810
10811    /**
10812     * Returns whether the View has registered callbacks which makes it
10813     * important for accessibility.
10814     *
10815     * @return True if the view is actionable for accessibility.
10816     */
10817    private boolean hasListenersForAccessibility() {
10818        ListenerInfo info = getListenerInfo();
10819        return mTouchDelegate != null || info.mOnKeyListener != null
10820                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
10821                || info.mOnHoverListener != null || info.mOnDragListener != null;
10822    }
10823
10824    /**
10825     * Notifies that the accessibility state of this view changed. The change
10826     * is local to this view and does not represent structural changes such
10827     * as children and parent. For example, the view became focusable. The
10828     * notification is at at most once every
10829     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
10830     * to avoid unnecessary load to the system. Also once a view has a pending
10831     * notification this method is a NOP until the notification has been sent.
10832     *
10833     * @hide
10834     */
10835    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
10836        if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) {
10837            return;
10838        }
10839        if (mSendViewStateChangedAccessibilityEvent == null) {
10840            mSendViewStateChangedAccessibilityEvent =
10841                    new SendViewStateChangedAccessibilityEvent();
10842        }
10843        mSendViewStateChangedAccessibilityEvent.runOrPost(changeType);
10844    }
10845
10846    /**
10847     * Notifies that the accessibility state of this view changed. The change
10848     * is *not* local to this view and does represent structural changes such
10849     * as children and parent. For example, the view size changed. The
10850     * notification is at at most once every
10851     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
10852     * to avoid unnecessary load to the system. Also once a view has a pending
10853     * notification this method is a NOP until the notification has been sent.
10854     *
10855     * @hide
10856     */
10857    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
10858        if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) {
10859            return;
10860        }
10861        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
10862            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
10863            if (mParent != null) {
10864                try {
10865                    mParent.notifySubtreeAccessibilityStateChanged(
10866                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
10867                } catch (AbstractMethodError e) {
10868                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
10869                            " does not fully implement ViewParent", e);
10870                }
10871            }
10872        }
10873    }
10874
10875    /**
10876     * Change the visibility of the View without triggering any other changes. This is
10877     * important for transitions, where visibility changes should not adjust focus or
10878     * trigger a new layout. This is only used when the visibility has already been changed
10879     * and we need a transient value during an animation. When the animation completes,
10880     * the original visibility value is always restored.
10881     *
10882     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
10883     * @hide
10884     */
10885    public void setTransitionVisibility(@Visibility int visibility) {
10886        mViewFlags = (mViewFlags & ~View.VISIBILITY_MASK) | visibility;
10887    }
10888
10889    /**
10890     * Reset the flag indicating the accessibility state of the subtree rooted
10891     * at this view changed.
10892     */
10893    void resetSubtreeAccessibilityStateChanged() {
10894        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
10895    }
10896
10897    /**
10898     * Report an accessibility action to this view's parents for delegated processing.
10899     *
10900     * <p>Implementations of {@link #performAccessibilityAction(int, Bundle)} may internally
10901     * call this method to delegate an accessibility action to a supporting parent. If the parent
10902     * returns true from its
10903     * {@link ViewParent#onNestedPrePerformAccessibilityAction(View, int, android.os.Bundle)}
10904     * method this method will return true to signify that the action was consumed.</p>
10905     *
10906     * <p>This method is useful for implementing nested scrolling child views. If
10907     * {@link #isNestedScrollingEnabled()} returns true and the action is a scrolling action
10908     * a custom view implementation may invoke this method to allow a parent to consume the
10909     * scroll first. If this method returns true the custom view should skip its own scrolling
10910     * behavior.</p>
10911     *
10912     * @param action Accessibility action to delegate
10913     * @param arguments Optional action arguments
10914     * @return true if the action was consumed by a parent
10915     */
10916    public boolean dispatchNestedPrePerformAccessibilityAction(int action, Bundle arguments) {
10917        for (ViewParent p = getParent(); p != null; p = p.getParent()) {
10918            if (p.onNestedPrePerformAccessibilityAction(this, action, arguments)) {
10919                return true;
10920            }
10921        }
10922        return false;
10923    }
10924
10925    /**
10926     * Performs the specified accessibility action on the view. For
10927     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
10928     * <p>
10929     * If an {@link AccessibilityDelegate} has been specified via calling
10930     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
10931     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
10932     * is responsible for handling this call.
10933     * </p>
10934     *
10935     * <p>The default implementation will delegate
10936     * {@link AccessibilityNodeInfo#ACTION_SCROLL_BACKWARD} and
10937     * {@link AccessibilityNodeInfo#ACTION_SCROLL_FORWARD} to nested scrolling parents if
10938     * {@link #isNestedScrollingEnabled() nested scrolling is enabled} on this view.</p>
10939     *
10940     * @param action The action to perform.
10941     * @param arguments Optional action arguments.
10942     * @return Whether the action was performed.
10943     */
10944    public boolean performAccessibilityAction(int action, Bundle arguments) {
10945      if (mAccessibilityDelegate != null) {
10946          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
10947      } else {
10948          return performAccessibilityActionInternal(action, arguments);
10949      }
10950    }
10951
10952   /**
10953    * @see #performAccessibilityAction(int, Bundle)
10954    *
10955    * Note: Called from the default {@link AccessibilityDelegate}.
10956    *
10957    * @hide
10958    */
10959    public boolean performAccessibilityActionInternal(int action, Bundle arguments) {
10960        if (isNestedScrollingEnabled()
10961                && (action == AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD
10962                || action == AccessibilityNodeInfo.ACTION_SCROLL_FORWARD
10963                || action == R.id.accessibilityActionScrollUp
10964                || action == R.id.accessibilityActionScrollLeft
10965                || action == R.id.accessibilityActionScrollDown
10966                || action == R.id.accessibilityActionScrollRight)) {
10967            if (dispatchNestedPrePerformAccessibilityAction(action, arguments)) {
10968                return true;
10969            }
10970        }
10971
10972        switch (action) {
10973            case AccessibilityNodeInfo.ACTION_CLICK: {
10974                if (isClickable()) {
10975                    performClick();
10976                    return true;
10977                }
10978            } break;
10979            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
10980                if (isLongClickable()) {
10981                    performLongClick();
10982                    return true;
10983                }
10984            } break;
10985            case AccessibilityNodeInfo.ACTION_FOCUS: {
10986                if (!hasFocus()) {
10987                    // Get out of touch mode since accessibility
10988                    // wants to move focus around.
10989                    getViewRootImpl().ensureTouchMode(false);
10990                    return requestFocus();
10991                }
10992            } break;
10993            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
10994                if (hasFocus()) {
10995                    clearFocus();
10996                    return !isFocused();
10997                }
10998            } break;
10999            case AccessibilityNodeInfo.ACTION_SELECT: {
11000                if (!isSelected()) {
11001                    setSelected(true);
11002                    return isSelected();
11003                }
11004            } break;
11005            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
11006                if (isSelected()) {
11007                    setSelected(false);
11008                    return !isSelected();
11009                }
11010            } break;
11011            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
11012                if (!isAccessibilityFocused()) {
11013                    return requestAccessibilityFocus();
11014                }
11015            } break;
11016            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
11017                if (isAccessibilityFocused()) {
11018                    clearAccessibilityFocus();
11019                    return true;
11020                }
11021            } break;
11022            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
11023                if (arguments != null) {
11024                    final int granularity = arguments.getInt(
11025                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
11026                    final boolean extendSelection = arguments.getBoolean(
11027                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
11028                    return traverseAtGranularity(granularity, true, extendSelection);
11029                }
11030            } break;
11031            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
11032                if (arguments != null) {
11033                    final int granularity = arguments.getInt(
11034                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
11035                    final boolean extendSelection = arguments.getBoolean(
11036                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
11037                    return traverseAtGranularity(granularity, false, extendSelection);
11038                }
11039            } break;
11040            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
11041                CharSequence text = getIterableTextForAccessibility();
11042                if (text == null) {
11043                    return false;
11044                }
11045                final int start = (arguments != null) ? arguments.getInt(
11046                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
11047                final int end = (arguments != null) ? arguments.getInt(
11048                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
11049                // Only cursor position can be specified (selection length == 0)
11050                if ((getAccessibilitySelectionStart() != start
11051                        || getAccessibilitySelectionEnd() != end)
11052                        && (start == end)) {
11053                    setAccessibilitySelection(start, end);
11054                    notifyViewAccessibilityStateChangedIfNeeded(
11055                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
11056                    return true;
11057                }
11058            } break;
11059            case R.id.accessibilityActionShowOnScreen: {
11060                if (mAttachInfo != null) {
11061                    final Rect r = mAttachInfo.mTmpInvalRect;
11062                    getDrawingRect(r);
11063                    return requestRectangleOnScreen(r, true);
11064                }
11065            } break;
11066            case R.id.accessibilityActionContextClick: {
11067                if (isContextClickable()) {
11068                    performContextClick();
11069                    return true;
11070                }
11071            } break;
11072        }
11073        return false;
11074    }
11075
11076    private boolean traverseAtGranularity(int granularity, boolean forward,
11077            boolean extendSelection) {
11078        CharSequence text = getIterableTextForAccessibility();
11079        if (text == null || text.length() == 0) {
11080            return false;
11081        }
11082        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
11083        if (iterator == null) {
11084            return false;
11085        }
11086        int current = getAccessibilitySelectionEnd();
11087        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
11088            current = forward ? 0 : text.length();
11089        }
11090        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
11091        if (range == null) {
11092            return false;
11093        }
11094        final int segmentStart = range[0];
11095        final int segmentEnd = range[1];
11096        int selectionStart;
11097        int selectionEnd;
11098        if (extendSelection && isAccessibilitySelectionExtendable()) {
11099            selectionStart = getAccessibilitySelectionStart();
11100            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
11101                selectionStart = forward ? segmentStart : segmentEnd;
11102            }
11103            selectionEnd = forward ? segmentEnd : segmentStart;
11104        } else {
11105            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
11106        }
11107        setAccessibilitySelection(selectionStart, selectionEnd);
11108        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
11109                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
11110        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
11111        return true;
11112    }
11113
11114    /**
11115     * Gets the text reported for accessibility purposes.
11116     *
11117     * @return The accessibility text.
11118     *
11119     * @hide
11120     */
11121    public CharSequence getIterableTextForAccessibility() {
11122        return getContentDescription();
11123    }
11124
11125    /**
11126     * Gets whether accessibility selection can be extended.
11127     *
11128     * @return If selection is extensible.
11129     *
11130     * @hide
11131     */
11132    public boolean isAccessibilitySelectionExtendable() {
11133        return false;
11134    }
11135
11136    /**
11137     * @hide
11138     */
11139    public int getAccessibilitySelectionStart() {
11140        return mAccessibilityCursorPosition;
11141    }
11142
11143    /**
11144     * @hide
11145     */
11146    public int getAccessibilitySelectionEnd() {
11147        return getAccessibilitySelectionStart();
11148    }
11149
11150    /**
11151     * @hide
11152     */
11153    public void setAccessibilitySelection(int start, int end) {
11154        if (start ==  end && end == mAccessibilityCursorPosition) {
11155            return;
11156        }
11157        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
11158            mAccessibilityCursorPosition = start;
11159        } else {
11160            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
11161        }
11162        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
11163    }
11164
11165    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
11166            int fromIndex, int toIndex) {
11167        if (mParent == null) {
11168            return;
11169        }
11170        AccessibilityEvent event = AccessibilityEvent.obtain(
11171                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
11172        onInitializeAccessibilityEvent(event);
11173        onPopulateAccessibilityEvent(event);
11174        event.setFromIndex(fromIndex);
11175        event.setToIndex(toIndex);
11176        event.setAction(action);
11177        event.setMovementGranularity(granularity);
11178        mParent.requestSendAccessibilityEvent(this, event);
11179    }
11180
11181    /**
11182     * @hide
11183     */
11184    public TextSegmentIterator getIteratorForGranularity(int granularity) {
11185        switch (granularity) {
11186            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
11187                CharSequence text = getIterableTextForAccessibility();
11188                if (text != null && text.length() > 0) {
11189                    CharacterTextSegmentIterator iterator =
11190                        CharacterTextSegmentIterator.getInstance(
11191                                mContext.getResources().getConfiguration().locale);
11192                    iterator.initialize(text.toString());
11193                    return iterator;
11194                }
11195            } break;
11196            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
11197                CharSequence text = getIterableTextForAccessibility();
11198                if (text != null && text.length() > 0) {
11199                    WordTextSegmentIterator iterator =
11200                        WordTextSegmentIterator.getInstance(
11201                                mContext.getResources().getConfiguration().locale);
11202                    iterator.initialize(text.toString());
11203                    return iterator;
11204                }
11205            } break;
11206            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
11207                CharSequence text = getIterableTextForAccessibility();
11208                if (text != null && text.length() > 0) {
11209                    ParagraphTextSegmentIterator iterator =
11210                        ParagraphTextSegmentIterator.getInstance();
11211                    iterator.initialize(text.toString());
11212                    return iterator;
11213                }
11214            } break;
11215        }
11216        return null;
11217    }
11218
11219    /**
11220     * Tells whether the {@link View} is in the state between {@link #onStartTemporaryDetach()}
11221     * and {@link #onFinishTemporaryDetach()}.
11222     *
11223     * <p>This method always returns {@code true} when called directly or indirectly from
11224     * {@link #onStartTemporaryDetach()}. The return value when called directly or indirectly from
11225     * {@link #onFinishTemporaryDetach()}, however, depends on the OS version.
11226     * <ul>
11227     *     <li>{@code true} on {@link android.os.Build.VERSION_CODES#N API 24}</li>
11228     *     <li>{@code false} on {@link android.os.Build.VERSION_CODES#N_MR1 API 25}} and later</li>
11229     * </ul>
11230     * </p>
11231     *
11232     * @return {@code true} when the View is in the state between {@link #onStartTemporaryDetach()}
11233     * and {@link #onFinishTemporaryDetach()}.
11234     */
11235    public final boolean isTemporarilyDetached() {
11236        return (mPrivateFlags3 & PFLAG3_TEMPORARY_DETACH) != 0;
11237    }
11238
11239    /**
11240     * Dispatch {@link #onStartTemporaryDetach()} to this View and its direct children if this is
11241     * a container View.
11242     */
11243    @CallSuper
11244    public void dispatchStartTemporaryDetach() {
11245        mPrivateFlags3 |= PFLAG3_TEMPORARY_DETACH;
11246        notifyEnterOrExitForAutoFillIfNeeded(false);
11247        onStartTemporaryDetach();
11248    }
11249
11250    /**
11251     * This is called when a container is going to temporarily detach a child, with
11252     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
11253     * It will either be followed by {@link #onFinishTemporaryDetach()} or
11254     * {@link #onDetachedFromWindow()} when the container is done.
11255     */
11256    public void onStartTemporaryDetach() {
11257        removeUnsetPressCallback();
11258        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
11259    }
11260
11261    /**
11262     * Dispatch {@link #onFinishTemporaryDetach()} to this View and its direct children if this is
11263     * a container View.
11264     */
11265    @CallSuper
11266    public void dispatchFinishTemporaryDetach() {
11267        mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH;
11268        onFinishTemporaryDetach();
11269        if (hasWindowFocus() && hasFocus()) {
11270            InputMethodManager.getInstance().focusIn(this);
11271        }
11272        notifyEnterOrExitForAutoFillIfNeeded(true);
11273    }
11274
11275    /**
11276     * Called after {@link #onStartTemporaryDetach} when the container is done
11277     * changing the view.
11278     */
11279    public void onFinishTemporaryDetach() {
11280    }
11281
11282    /**
11283     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
11284     * for this view's window.  Returns null if the view is not currently attached
11285     * to the window.  Normally you will not need to use this directly, but
11286     * just use the standard high-level event callbacks like
11287     * {@link #onKeyDown(int, KeyEvent)}.
11288     */
11289    public KeyEvent.DispatcherState getKeyDispatcherState() {
11290        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
11291    }
11292
11293    /**
11294     * Dispatch a key event before it is processed by any input method
11295     * associated with the view hierarchy.  This can be used to intercept
11296     * key events in special situations before the IME consumes them; a
11297     * typical example would be handling the BACK key to update the application's
11298     * UI instead of allowing the IME to see it and close itself.
11299     *
11300     * @param event The key event to be dispatched.
11301     * @return True if the event was handled, false otherwise.
11302     */
11303    public boolean dispatchKeyEventPreIme(KeyEvent event) {
11304        return onKeyPreIme(event.getKeyCode(), event);
11305    }
11306
11307    /**
11308     * Dispatch a key event to the next view on the focus path. This path runs
11309     * from the top of the view tree down to the currently focused view. If this
11310     * view has focus, it will dispatch to itself. Otherwise it will dispatch
11311     * the next node down the focus path. This method also fires any key
11312     * listeners.
11313     *
11314     * @param event The key event to be dispatched.
11315     * @return True if the event was handled, false otherwise.
11316     */
11317    public boolean dispatchKeyEvent(KeyEvent event) {
11318        if (mInputEventConsistencyVerifier != null) {
11319            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
11320        }
11321
11322        // Give any attached key listener a first crack at the event.
11323        //noinspection SimplifiableIfStatement
11324        ListenerInfo li = mListenerInfo;
11325        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
11326                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
11327            return true;
11328        }
11329
11330        if (event.dispatch(this, mAttachInfo != null
11331                ? mAttachInfo.mKeyDispatchState : null, this)) {
11332            return true;
11333        }
11334
11335        if (mInputEventConsistencyVerifier != null) {
11336            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
11337        }
11338        return false;
11339    }
11340
11341    /**
11342     * Dispatches a key shortcut event.
11343     *
11344     * @param event The key event to be dispatched.
11345     * @return True if the event was handled by the view, false otherwise.
11346     */
11347    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
11348        return onKeyShortcut(event.getKeyCode(), event);
11349    }
11350
11351    /**
11352     * Pass the touch screen motion event down to the target view, or this
11353     * view if it is the target.
11354     *
11355     * @param event The motion event to be dispatched.
11356     * @return True if the event was handled by the view, false otherwise.
11357     */
11358    public boolean dispatchTouchEvent(MotionEvent event) {
11359        // If the event should be handled by accessibility focus first.
11360        if (event.isTargetAccessibilityFocus()) {
11361            // We don't have focus or no virtual descendant has it, do not handle the event.
11362            if (!isAccessibilityFocusedViewOrHost()) {
11363                return false;
11364            }
11365            // We have focus and got the event, then use normal event dispatch.
11366            event.setTargetAccessibilityFocus(false);
11367        }
11368
11369        boolean result = false;
11370
11371        if (mInputEventConsistencyVerifier != null) {
11372            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
11373        }
11374
11375        final int actionMasked = event.getActionMasked();
11376        if (actionMasked == MotionEvent.ACTION_DOWN) {
11377            // Defensive cleanup for new gesture
11378            stopNestedScroll();
11379        }
11380
11381        if (onFilterTouchEventForSecurity(event)) {
11382            if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
11383                result = true;
11384            }
11385            //noinspection SimplifiableIfStatement
11386            ListenerInfo li = mListenerInfo;
11387            if (li != null && li.mOnTouchListener != null
11388                    && (mViewFlags & ENABLED_MASK) == ENABLED
11389                    && li.mOnTouchListener.onTouch(this, event)) {
11390                result = true;
11391            }
11392
11393            if (!result && onTouchEvent(event)) {
11394                result = true;
11395            }
11396        }
11397
11398        if (!result && mInputEventConsistencyVerifier != null) {
11399            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
11400        }
11401
11402        // Clean up after nested scrolls if this is the end of a gesture;
11403        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
11404        // of the gesture.
11405        if (actionMasked == MotionEvent.ACTION_UP ||
11406                actionMasked == MotionEvent.ACTION_CANCEL ||
11407                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
11408            stopNestedScroll();
11409        }
11410
11411        return result;
11412    }
11413
11414    boolean isAccessibilityFocusedViewOrHost() {
11415        return isAccessibilityFocused() || (getViewRootImpl() != null && getViewRootImpl()
11416                .getAccessibilityFocusedHost() == this);
11417    }
11418
11419    /**
11420     * Filter the touch event to apply security policies.
11421     *
11422     * @param event The motion event to be filtered.
11423     * @return True if the event should be dispatched, false if the event should be dropped.
11424     *
11425     * @see #getFilterTouchesWhenObscured
11426     */
11427    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
11428        //noinspection RedundantIfStatement
11429        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
11430                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
11431            // Window is obscured, drop this touch.
11432            return false;
11433        }
11434        return true;
11435    }
11436
11437    /**
11438     * Pass a trackball motion event down to the focused view.
11439     *
11440     * @param event The motion event to be dispatched.
11441     * @return True if the event was handled by the view, false otherwise.
11442     */
11443    public boolean dispatchTrackballEvent(MotionEvent event) {
11444        if (mInputEventConsistencyVerifier != null) {
11445            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
11446        }
11447
11448        return onTrackballEvent(event);
11449    }
11450
11451    /**
11452     * Pass a captured pointer event down to the focused view.
11453     *
11454     * @param event The motion event to be dispatched.
11455     * @return True if the event was handled by the view, false otherwise.
11456     */
11457    public boolean dispatchCapturedPointerEvent(MotionEvent event) {
11458        if (!hasPointerCapture()) {
11459            return false;
11460        }
11461        //noinspection SimplifiableIfStatement
11462        ListenerInfo li = mListenerInfo;
11463        if (li != null && li.mOnCapturedPointerListener != null
11464                && li.mOnCapturedPointerListener.onCapturedPointer(this, event)) {
11465            return true;
11466        }
11467        return onCapturedPointerEvent(event);
11468    }
11469
11470    /**
11471     * Dispatch a generic motion event.
11472     * <p>
11473     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
11474     * are delivered to the view under the pointer.  All other generic motion events are
11475     * delivered to the focused view.  Hover events are handled specially and are delivered
11476     * to {@link #onHoverEvent(MotionEvent)}.
11477     * </p>
11478     *
11479     * @param event The motion event to be dispatched.
11480     * @return True if the event was handled by the view, false otherwise.
11481     */
11482    public boolean dispatchGenericMotionEvent(MotionEvent event) {
11483        if (mInputEventConsistencyVerifier != null) {
11484            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
11485        }
11486
11487        final int source = event.getSource();
11488        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
11489            final int action = event.getAction();
11490            if (action == MotionEvent.ACTION_HOVER_ENTER
11491                    || action == MotionEvent.ACTION_HOVER_MOVE
11492                    || action == MotionEvent.ACTION_HOVER_EXIT) {
11493                if (dispatchHoverEvent(event)) {
11494                    return true;
11495                }
11496            } else if (dispatchGenericPointerEvent(event)) {
11497                return true;
11498            }
11499        } else if (dispatchGenericFocusedEvent(event)) {
11500            return true;
11501        }
11502
11503        if (dispatchGenericMotionEventInternal(event)) {
11504            return true;
11505        }
11506
11507        if (mInputEventConsistencyVerifier != null) {
11508            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
11509        }
11510        return false;
11511    }
11512
11513    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
11514        //noinspection SimplifiableIfStatement
11515        ListenerInfo li = mListenerInfo;
11516        if (li != null && li.mOnGenericMotionListener != null
11517                && (mViewFlags & ENABLED_MASK) == ENABLED
11518                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
11519            return true;
11520        }
11521
11522        if (onGenericMotionEvent(event)) {
11523            return true;
11524        }
11525
11526        final int actionButton = event.getActionButton();
11527        switch (event.getActionMasked()) {
11528            case MotionEvent.ACTION_BUTTON_PRESS:
11529                if (isContextClickable() && !mInContextButtonPress && !mHasPerformedLongPress
11530                        && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY
11531                        || actionButton == MotionEvent.BUTTON_SECONDARY)) {
11532                    if (performContextClick(event.getX(), event.getY())) {
11533                        mInContextButtonPress = true;
11534                        setPressed(true, event.getX(), event.getY());
11535                        removeTapCallback();
11536                        removeLongPressCallback();
11537                        return true;
11538                    }
11539                }
11540                break;
11541
11542            case MotionEvent.ACTION_BUTTON_RELEASE:
11543                if (mInContextButtonPress && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY
11544                        || actionButton == MotionEvent.BUTTON_SECONDARY)) {
11545                    mInContextButtonPress = false;
11546                    mIgnoreNextUpEvent = true;
11547                }
11548                break;
11549        }
11550
11551        if (mInputEventConsistencyVerifier != null) {
11552            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
11553        }
11554        return false;
11555    }
11556
11557    /**
11558     * Dispatch a hover event.
11559     * <p>
11560     * Do not call this method directly.
11561     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
11562     * </p>
11563     *
11564     * @param event The motion event to be dispatched.
11565     * @return True if the event was handled by the view, false otherwise.
11566     */
11567    protected boolean dispatchHoverEvent(MotionEvent event) {
11568        ListenerInfo li = mListenerInfo;
11569        //noinspection SimplifiableIfStatement
11570        if (li != null && li.mOnHoverListener != null
11571                && (mViewFlags & ENABLED_MASK) == ENABLED
11572                && li.mOnHoverListener.onHover(this, event)) {
11573            return true;
11574        }
11575
11576        return onHoverEvent(event);
11577    }
11578
11579    /**
11580     * Returns true if the view has a child to which it has recently sent
11581     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
11582     * it does not have a hovered child, then it must be the innermost hovered view.
11583     * @hide
11584     */
11585    protected boolean hasHoveredChild() {
11586        return false;
11587    }
11588
11589    /**
11590     * Dispatch a generic motion event to the view under the first pointer.
11591     * <p>
11592     * Do not call this method directly.
11593     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
11594     * </p>
11595     *
11596     * @param event The motion event to be dispatched.
11597     * @return True if the event was handled by the view, false otherwise.
11598     */
11599    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
11600        return false;
11601    }
11602
11603    /**
11604     * Dispatch a generic motion event to the currently focused view.
11605     * <p>
11606     * Do not call this method directly.
11607     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
11608     * </p>
11609     *
11610     * @param event The motion event to be dispatched.
11611     * @return True if the event was handled by the view, false otherwise.
11612     */
11613    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
11614        return false;
11615    }
11616
11617    /**
11618     * Dispatch a pointer event.
11619     * <p>
11620     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
11621     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
11622     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
11623     * and should not be expected to handle other pointing device features.
11624     * </p>
11625     *
11626     * @param event The motion event to be dispatched.
11627     * @return True if the event was handled by the view, false otherwise.
11628     * @hide
11629     */
11630    public final boolean dispatchPointerEvent(MotionEvent event) {
11631        if (event.isTouchEvent()) {
11632            return dispatchTouchEvent(event);
11633        } else {
11634            return dispatchGenericMotionEvent(event);
11635        }
11636    }
11637
11638    /**
11639     * Called when the window containing this view gains or loses window focus.
11640     * ViewGroups should override to route to their children.
11641     *
11642     * @param hasFocus True if the window containing this view now has focus,
11643     *        false otherwise.
11644     */
11645    public void dispatchWindowFocusChanged(boolean hasFocus) {
11646        onWindowFocusChanged(hasFocus);
11647    }
11648
11649    /**
11650     * Called when the window containing this view gains or loses focus.  Note
11651     * that this is separate from view focus: to receive key events, both
11652     * your view and its window must have focus.  If a window is displayed
11653     * on top of yours that takes input focus, then your own window will lose
11654     * focus but the view focus will remain unchanged.
11655     *
11656     * @param hasWindowFocus True if the window containing this view now has
11657     *        focus, false otherwise.
11658     */
11659    public void onWindowFocusChanged(boolean hasWindowFocus) {
11660        InputMethodManager imm = InputMethodManager.peekInstance();
11661        if (!hasWindowFocus) {
11662            if (isPressed()) {
11663                setPressed(false);
11664            }
11665            mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
11666            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
11667                imm.focusOut(this);
11668            }
11669            removeLongPressCallback();
11670            removeTapCallback();
11671            onFocusLost();
11672        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
11673            imm.focusIn(this);
11674        }
11675
11676        notifyEnterOrExitForAutoFillIfNeeded(hasWindowFocus);
11677
11678        refreshDrawableState();
11679    }
11680
11681    /**
11682     * Returns true if this view is in a window that currently has window focus.
11683     * Note that this is not the same as the view itself having focus.
11684     *
11685     * @return True if this view is in a window that currently has window focus.
11686     */
11687    public boolean hasWindowFocus() {
11688        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
11689    }
11690
11691    /**
11692     * Dispatch a view visibility change down the view hierarchy.
11693     * ViewGroups should override to route to their children.
11694     * @param changedView The view whose visibility changed. Could be 'this' or
11695     * an ancestor view.
11696     * @param visibility The new visibility of changedView: {@link #VISIBLE},
11697     * {@link #INVISIBLE} or {@link #GONE}.
11698     */
11699    protected void dispatchVisibilityChanged(@NonNull View changedView,
11700            @Visibility int visibility) {
11701        onVisibilityChanged(changedView, visibility);
11702    }
11703
11704    /**
11705     * Called when the visibility of the view or an ancestor of the view has
11706     * changed.
11707     *
11708     * @param changedView The view whose visibility changed. May be
11709     *                    {@code this} or an ancestor view.
11710     * @param visibility The new visibility, one of {@link #VISIBLE},
11711     *                   {@link #INVISIBLE} or {@link #GONE}.
11712     */
11713    protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) {
11714    }
11715
11716    /**
11717     * Dispatch a hint about whether this view is displayed. For instance, when
11718     * a View moves out of the screen, it might receives a display hint indicating
11719     * the view is not displayed. Applications should not <em>rely</em> on this hint
11720     * as there is no guarantee that they will receive one.
11721     *
11722     * @param hint A hint about whether or not this view is displayed:
11723     * {@link #VISIBLE} or {@link #INVISIBLE}.
11724     */
11725    public void dispatchDisplayHint(@Visibility int hint) {
11726        onDisplayHint(hint);
11727    }
11728
11729    /**
11730     * Gives this view a hint about whether is displayed or not. For instance, when
11731     * a View moves out of the screen, it might receives a display hint indicating
11732     * the view is not displayed. Applications should not <em>rely</em> on this hint
11733     * as there is no guarantee that they will receive one.
11734     *
11735     * @param hint A hint about whether or not this view is displayed:
11736     * {@link #VISIBLE} or {@link #INVISIBLE}.
11737     */
11738    protected void onDisplayHint(@Visibility int hint) {
11739    }
11740
11741    /**
11742     * Dispatch a window visibility change down the view hierarchy.
11743     * ViewGroups should override to route to their children.
11744     *
11745     * @param visibility The new visibility of the window.
11746     *
11747     * @see #onWindowVisibilityChanged(int)
11748     */
11749    public void dispatchWindowVisibilityChanged(@Visibility int visibility) {
11750        onWindowVisibilityChanged(visibility);
11751    }
11752
11753    /**
11754     * Called when the window containing has change its visibility
11755     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
11756     * that this tells you whether or not your window is being made visible
11757     * to the window manager; this does <em>not</em> tell you whether or not
11758     * your window is obscured by other windows on the screen, even if it
11759     * is itself visible.
11760     *
11761     * @param visibility The new visibility of the window.
11762     */
11763    protected void onWindowVisibilityChanged(@Visibility int visibility) {
11764        if (visibility == VISIBLE) {
11765            initialAwakenScrollBars();
11766        }
11767    }
11768
11769    /**
11770     * Internal dispatching method for {@link #onVisibilityAggregated}. Overridden by
11771     * ViewGroup. Intended to only be called when {@link #isAttachedToWindow()},
11772     * {@link #getWindowVisibility()} is {@link #VISIBLE} and this view's parent {@link #isShown()}.
11773     *
11774     * @param isVisible true if this view's visibility to the user is uninterrupted by its
11775     *                  ancestors or by window visibility
11776     * @return true if this view is visible to the user, not counting clipping or overlapping
11777     */
11778    boolean dispatchVisibilityAggregated(boolean isVisible) {
11779        final boolean thisVisible = getVisibility() == VISIBLE;
11780        // If we're not visible but something is telling us we are, ignore it.
11781        if (thisVisible || !isVisible) {
11782            onVisibilityAggregated(isVisible);
11783        }
11784        return thisVisible && isVisible;
11785    }
11786
11787    /**
11788     * Called when the user-visibility of this View is potentially affected by a change
11789     * to this view itself, an ancestor view or the window this view is attached to.
11790     *
11791     * @param isVisible true if this view and all of its ancestors are {@link #VISIBLE}
11792     *                  and this view's window is also visible
11793     */
11794    @CallSuper
11795    public void onVisibilityAggregated(boolean isVisible) {
11796        if (isVisible && mAttachInfo != null) {
11797            initialAwakenScrollBars();
11798        }
11799
11800        final Drawable dr = mBackground;
11801        if (dr != null && isVisible != dr.isVisible()) {
11802            dr.setVisible(isVisible, false);
11803        }
11804        final Drawable hl = mDefaultFocusHighlight;
11805        if (hl != null && isVisible != hl.isVisible()) {
11806            hl.setVisible(isVisible, false);
11807        }
11808        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
11809        if (fg != null && isVisible != fg.isVisible()) {
11810            fg.setVisible(isVisible, false);
11811        }
11812    }
11813
11814    /**
11815     * Returns the current visibility of the window this view is attached to
11816     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
11817     *
11818     * @return Returns the current visibility of the view's window.
11819     */
11820    @Visibility
11821    public int getWindowVisibility() {
11822        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
11823    }
11824
11825    /**
11826     * Retrieve the overall visible display size in which the window this view is
11827     * attached to has been positioned in.  This takes into account screen
11828     * decorations above the window, for both cases where the window itself
11829     * is being position inside of them or the window is being placed under
11830     * then and covered insets are used for the window to position its content
11831     * inside.  In effect, this tells you the available area where content can
11832     * be placed and remain visible to users.
11833     *
11834     * <p>This function requires an IPC back to the window manager to retrieve
11835     * the requested information, so should not be used in performance critical
11836     * code like drawing.
11837     *
11838     * @param outRect Filled in with the visible display frame.  If the view
11839     * is not attached to a window, this is simply the raw display size.
11840     */
11841    public void getWindowVisibleDisplayFrame(Rect outRect) {
11842        if (mAttachInfo != null) {
11843            try {
11844                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
11845            } catch (RemoteException e) {
11846                return;
11847            }
11848            // XXX This is really broken, and probably all needs to be done
11849            // in the window manager, and we need to know more about whether
11850            // we want the area behind or in front of the IME.
11851            final Rect insets = mAttachInfo.mVisibleInsets;
11852            outRect.left += insets.left;
11853            outRect.top += insets.top;
11854            outRect.right -= insets.right;
11855            outRect.bottom -= insets.bottom;
11856            return;
11857        }
11858        // The view is not attached to a display so we don't have a context.
11859        // Make a best guess about the display size.
11860        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
11861        d.getRectSize(outRect);
11862    }
11863
11864    /**
11865     * Like {@link #getWindowVisibleDisplayFrame}, but returns the "full" display frame this window
11866     * is currently in without any insets.
11867     *
11868     * @hide
11869     */
11870    public void getWindowDisplayFrame(Rect outRect) {
11871        if (mAttachInfo != null) {
11872            try {
11873                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
11874            } catch (RemoteException e) {
11875                return;
11876            }
11877            return;
11878        }
11879        // The view is not attached to a display so we don't have a context.
11880        // Make a best guess about the display size.
11881        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
11882        d.getRectSize(outRect);
11883    }
11884
11885    /**
11886     * Dispatch a notification about a resource configuration change down
11887     * the view hierarchy.
11888     * ViewGroups should override to route to their children.
11889     *
11890     * @param newConfig The new resource configuration.
11891     *
11892     * @see #onConfigurationChanged(android.content.res.Configuration)
11893     */
11894    public void dispatchConfigurationChanged(Configuration newConfig) {
11895        onConfigurationChanged(newConfig);
11896    }
11897
11898    /**
11899     * Called when the current configuration of the resources being used
11900     * by the application have changed.  You can use this to decide when
11901     * to reload resources that can changed based on orientation and other
11902     * configuration characteristics.  You only need to use this if you are
11903     * not relying on the normal {@link android.app.Activity} mechanism of
11904     * recreating the activity instance upon a configuration change.
11905     *
11906     * @param newConfig The new resource configuration.
11907     */
11908    protected void onConfigurationChanged(Configuration newConfig) {
11909    }
11910
11911    /**
11912     * Private function to aggregate all per-view attributes in to the view
11913     * root.
11914     */
11915    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
11916        performCollectViewAttributes(attachInfo, visibility);
11917    }
11918
11919    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
11920        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
11921            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
11922                attachInfo.mKeepScreenOn = true;
11923            }
11924            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
11925            ListenerInfo li = mListenerInfo;
11926            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
11927                attachInfo.mHasSystemUiListeners = true;
11928            }
11929        }
11930    }
11931
11932    void needGlobalAttributesUpdate(boolean force) {
11933        final AttachInfo ai = mAttachInfo;
11934        if (ai != null && !ai.mRecomputeGlobalAttributes) {
11935            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
11936                    || ai.mHasSystemUiListeners) {
11937                ai.mRecomputeGlobalAttributes = true;
11938            }
11939        }
11940    }
11941
11942    /**
11943     * Returns whether the device is currently in touch mode.  Touch mode is entered
11944     * once the user begins interacting with the device by touch, and affects various
11945     * things like whether focus is always visible to the user.
11946     *
11947     * @return Whether the device is in touch mode.
11948     */
11949    @ViewDebug.ExportedProperty
11950    public boolean isInTouchMode() {
11951        if (mAttachInfo != null) {
11952            return mAttachInfo.mInTouchMode;
11953        } else {
11954            return ViewRootImpl.isInTouchMode();
11955        }
11956    }
11957
11958    /**
11959     * Returns the context the view is running in, through which it can
11960     * access the current theme, resources, etc.
11961     *
11962     * @return The view's Context.
11963     */
11964    @ViewDebug.CapturedViewProperty
11965    public final Context getContext() {
11966        return mContext;
11967    }
11968
11969    /**
11970     * Handle a key event before it is processed by any input method
11971     * associated with the view hierarchy.  This can be used to intercept
11972     * key events in special situations before the IME consumes them; a
11973     * typical example would be handling the BACK key to update the application's
11974     * UI instead of allowing the IME to see it and close itself.
11975     *
11976     * @param keyCode The value in event.getKeyCode().
11977     * @param event Description of the key event.
11978     * @return If you handled the event, return true. If you want to allow the
11979     *         event to be handled by the next receiver, return false.
11980     */
11981    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
11982        return false;
11983    }
11984
11985    /**
11986     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
11987     * KeyEvent.Callback.onKeyDown()}: perform press of the view
11988     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
11989     * is released, if the view is enabled and clickable.
11990     * <p>
11991     * Key presses in software keyboards will generally NOT trigger this
11992     * listener, although some may elect to do so in some situations. Do not
11993     * rely on this to catch software key presses.
11994     *
11995     * @param keyCode a key code that represents the button pressed, from
11996     *                {@link android.view.KeyEvent}
11997     * @param event the KeyEvent object that defines the button action
11998     */
11999    public boolean onKeyDown(int keyCode, KeyEvent event) {
12000        if (KeyEvent.isConfirmKey(keyCode)) {
12001            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
12002                return true;
12003            }
12004
12005            if (event.getRepeatCount() == 0) {
12006                // Long clickable items don't necessarily have to be clickable.
12007                final boolean clickable = (mViewFlags & CLICKABLE) == CLICKABLE
12008                        || (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
12009                if (clickable || (mViewFlags & TOOLTIP) == TOOLTIP) {
12010                    // For the purposes of menu anchoring and drawable hotspots,
12011                    // key events are considered to be at the center of the view.
12012                    final float x = getWidth() / 2f;
12013                    final float y = getHeight() / 2f;
12014                    if (clickable) {
12015                        setPressed(true, x, y);
12016                    }
12017                    checkForLongClick(0, x, y);
12018                    return true;
12019                }
12020            }
12021        }
12022
12023        return false;
12024    }
12025
12026    /**
12027     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
12028     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
12029     * the event).
12030     * <p>Key presses in software keyboards will generally NOT trigger this listener,
12031     * although some may elect to do so in some situations. Do not rely on this to
12032     * catch software key presses.
12033     */
12034    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
12035        return false;
12036    }
12037
12038    /**
12039     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
12040     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
12041     * when {@link KeyEvent#KEYCODE_DPAD_CENTER}, {@link KeyEvent#KEYCODE_ENTER}
12042     * or {@link KeyEvent#KEYCODE_SPACE} is released.
12043     * <p>Key presses in software keyboards will generally NOT trigger this listener,
12044     * although some may elect to do so in some situations. Do not rely on this to
12045     * catch software key presses.
12046     *
12047     * @param keyCode A key code that represents the button pressed, from
12048     *                {@link android.view.KeyEvent}.
12049     * @param event   The KeyEvent object that defines the button action.
12050     */
12051    public boolean onKeyUp(int keyCode, KeyEvent event) {
12052        if (KeyEvent.isConfirmKey(keyCode)) {
12053            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
12054                return true;
12055            }
12056            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
12057                setPressed(false);
12058
12059                if (!mHasPerformedLongPress) {
12060                    // This is a tap, so remove the longpress check
12061                    removeLongPressCallback();
12062                    if (!event.isCanceled()) {
12063                        return performClick();
12064                    }
12065                }
12066            }
12067        }
12068        return false;
12069    }
12070
12071    /**
12072     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
12073     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
12074     * the event).
12075     * <p>Key presses in software keyboards will generally NOT trigger this listener,
12076     * although some may elect to do so in some situations. Do not rely on this to
12077     * catch software key presses.
12078     *
12079     * @param keyCode     A key code that represents the button pressed, from
12080     *                    {@link android.view.KeyEvent}.
12081     * @param repeatCount The number of times the action was made.
12082     * @param event       The KeyEvent object that defines the button action.
12083     */
12084    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
12085        return false;
12086    }
12087
12088    /**
12089     * Called on the focused view when a key shortcut event is not handled.
12090     * Override this method to implement local key shortcuts for the View.
12091     * Key shortcuts can also be implemented by setting the
12092     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
12093     *
12094     * @param keyCode The value in event.getKeyCode().
12095     * @param event Description of the key event.
12096     * @return If you handled the event, return true. If you want to allow the
12097     *         event to be handled by the next receiver, return false.
12098     */
12099    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
12100        return false;
12101    }
12102
12103    /**
12104     * Check whether the called view is a text editor, in which case it
12105     * would make sense to automatically display a soft input window for
12106     * it.  Subclasses should override this if they implement
12107     * {@link #onCreateInputConnection(EditorInfo)} to return true if
12108     * a call on that method would return a non-null InputConnection, and
12109     * they are really a first-class editor that the user would normally
12110     * start typing on when the go into a window containing your view.
12111     *
12112     * <p>The default implementation always returns false.  This does
12113     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
12114     * will not be called or the user can not otherwise perform edits on your
12115     * view; it is just a hint to the system that this is not the primary
12116     * purpose of this view.
12117     *
12118     * @return Returns true if this view is a text editor, else false.
12119     */
12120    public boolean onCheckIsTextEditor() {
12121        return false;
12122    }
12123
12124    /**
12125     * Create a new InputConnection for an InputMethod to interact
12126     * with the view.  The default implementation returns null, since it doesn't
12127     * support input methods.  You can override this to implement such support.
12128     * This is only needed for views that take focus and text input.
12129     *
12130     * <p>When implementing this, you probably also want to implement
12131     * {@link #onCheckIsTextEditor()} to indicate you will return a
12132     * non-null InputConnection.</p>
12133     *
12134     * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo}
12135     * object correctly and in its entirety, so that the connected IME can rely
12136     * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart}
12137     * and  {@link android.view.inputmethod.EditorInfo#initialSelEnd} members
12138     * must be filled in with the correct cursor position for IMEs to work correctly
12139     * with your application.</p>
12140     *
12141     * @param outAttrs Fill in with attribute information about the connection.
12142     */
12143    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
12144        return null;
12145    }
12146
12147    /**
12148     * Called by the {@link android.view.inputmethod.InputMethodManager}
12149     * when a view who is not the current
12150     * input connection target is trying to make a call on the manager.  The
12151     * default implementation returns false; you can override this to return
12152     * true for certain views if you are performing InputConnection proxying
12153     * to them.
12154     * @param view The View that is making the InputMethodManager call.
12155     * @return Return true to allow the call, false to reject.
12156     */
12157    public boolean checkInputConnectionProxy(View view) {
12158        return false;
12159    }
12160
12161    /**
12162     * Show the context menu for this view. It is not safe to hold on to the
12163     * menu after returning from this method.
12164     *
12165     * You should normally not overload this method. Overload
12166     * {@link #onCreateContextMenu(ContextMenu)} or define an
12167     * {@link OnCreateContextMenuListener} to add items to the context menu.
12168     *
12169     * @param menu The context menu to populate
12170     */
12171    public void createContextMenu(ContextMenu menu) {
12172        ContextMenuInfo menuInfo = getContextMenuInfo();
12173
12174        // Sets the current menu info so all items added to menu will have
12175        // my extra info set.
12176        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
12177
12178        onCreateContextMenu(menu);
12179        ListenerInfo li = mListenerInfo;
12180        if (li != null && li.mOnCreateContextMenuListener != null) {
12181            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
12182        }
12183
12184        // Clear the extra information so subsequent items that aren't mine don't
12185        // have my extra info.
12186        ((MenuBuilder)menu).setCurrentMenuInfo(null);
12187
12188        if (mParent != null) {
12189            mParent.createContextMenu(menu);
12190        }
12191    }
12192
12193    /**
12194     * Views should implement this if they have extra information to associate
12195     * with the context menu. The return result is supplied as a parameter to
12196     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
12197     * callback.
12198     *
12199     * @return Extra information about the item for which the context menu
12200     *         should be shown. This information will vary across different
12201     *         subclasses of View.
12202     */
12203    protected ContextMenuInfo getContextMenuInfo() {
12204        return null;
12205    }
12206
12207    /**
12208     * Views should implement this if the view itself is going to add items to
12209     * the context menu.
12210     *
12211     * @param menu the context menu to populate
12212     */
12213    protected void onCreateContextMenu(ContextMenu menu) {
12214    }
12215
12216    /**
12217     * Implement this method to handle trackball motion events.  The
12218     * <em>relative</em> movement of the trackball since the last event
12219     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
12220     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
12221     * that a movement of 1 corresponds to the user pressing one DPAD key (so
12222     * they will often be fractional values, representing the more fine-grained
12223     * movement information available from a trackball).
12224     *
12225     * @param event The motion event.
12226     * @return True if the event was handled, false otherwise.
12227     */
12228    public boolean onTrackballEvent(MotionEvent event) {
12229        return false;
12230    }
12231
12232    /**
12233     * Implement this method to handle generic motion events.
12234     * <p>
12235     * Generic motion events describe joystick movements, mouse hovers, track pad
12236     * touches, scroll wheel movements and other input events.  The
12237     * {@link MotionEvent#getSource() source} of the motion event specifies
12238     * the class of input that was received.  Implementations of this method
12239     * must examine the bits in the source before processing the event.
12240     * The following code example shows how this is done.
12241     * </p><p>
12242     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
12243     * are delivered to the view under the pointer.  All other generic motion events are
12244     * delivered to the focused view.
12245     * </p>
12246     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
12247     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
12248     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
12249     *             // process the joystick movement...
12250     *             return true;
12251     *         }
12252     *     }
12253     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
12254     *         switch (event.getAction()) {
12255     *             case MotionEvent.ACTION_HOVER_MOVE:
12256     *                 // process the mouse hover movement...
12257     *                 return true;
12258     *             case MotionEvent.ACTION_SCROLL:
12259     *                 // process the scroll wheel movement...
12260     *                 return true;
12261     *         }
12262     *     }
12263     *     return super.onGenericMotionEvent(event);
12264     * }</pre>
12265     *
12266     * @param event The generic motion event being processed.
12267     * @return True if the event was handled, false otherwise.
12268     */
12269    public boolean onGenericMotionEvent(MotionEvent event) {
12270        return false;
12271    }
12272
12273    /**
12274     * Implement this method to handle hover events.
12275     * <p>
12276     * This method is called whenever a pointer is hovering into, over, or out of the
12277     * bounds of a view and the view is not currently being touched.
12278     * Hover events are represented as pointer events with action
12279     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
12280     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
12281     * </p>
12282     * <ul>
12283     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
12284     * when the pointer enters the bounds of the view.</li>
12285     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
12286     * when the pointer has already entered the bounds of the view and has moved.</li>
12287     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
12288     * when the pointer has exited the bounds of the view or when the pointer is
12289     * about to go down due to a button click, tap, or similar user action that
12290     * causes the view to be touched.</li>
12291     * </ul>
12292     * <p>
12293     * The view should implement this method to return true to indicate that it is
12294     * handling the hover event, such as by changing its drawable state.
12295     * </p><p>
12296     * The default implementation calls {@link #setHovered} to update the hovered state
12297     * of the view when a hover enter or hover exit event is received, if the view
12298     * is enabled and is clickable.  The default implementation also sends hover
12299     * accessibility events.
12300     * </p>
12301     *
12302     * @param event The motion event that describes the hover.
12303     * @return True if the view handled the hover event.
12304     *
12305     * @see #isHovered
12306     * @see #setHovered
12307     * @see #onHoverChanged
12308     */
12309    public boolean onHoverEvent(MotionEvent event) {
12310        // The root view may receive hover (or touch) events that are outside the bounds of
12311        // the window.  This code ensures that we only send accessibility events for
12312        // hovers that are actually within the bounds of the root view.
12313        final int action = event.getActionMasked();
12314        if (!mSendingHoverAccessibilityEvents) {
12315            if ((action == MotionEvent.ACTION_HOVER_ENTER
12316                    || action == MotionEvent.ACTION_HOVER_MOVE)
12317                    && !hasHoveredChild()
12318                    && pointInView(event.getX(), event.getY())) {
12319                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
12320                mSendingHoverAccessibilityEvents = true;
12321            }
12322        } else {
12323            if (action == MotionEvent.ACTION_HOVER_EXIT
12324                    || (action == MotionEvent.ACTION_MOVE
12325                            && !pointInView(event.getX(), event.getY()))) {
12326                mSendingHoverAccessibilityEvents = false;
12327                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
12328            }
12329        }
12330
12331        if ((action == MotionEvent.ACTION_HOVER_ENTER || action == MotionEvent.ACTION_HOVER_MOVE)
12332                && event.isFromSource(InputDevice.SOURCE_MOUSE)
12333                && isOnScrollbar(event.getX(), event.getY())) {
12334            awakenScrollBars();
12335        }
12336
12337        // If we consider ourself hoverable, or if we we're already hovered,
12338        // handle changing state in response to ENTER and EXIT events.
12339        if (isHoverable() || isHovered()) {
12340            switch (action) {
12341                case MotionEvent.ACTION_HOVER_ENTER:
12342                    setHovered(true);
12343                    break;
12344                case MotionEvent.ACTION_HOVER_EXIT:
12345                    setHovered(false);
12346                    break;
12347            }
12348
12349            // Dispatch the event to onGenericMotionEvent before returning true.
12350            // This is to provide compatibility with existing applications that
12351            // handled HOVER_MOVE events in onGenericMotionEvent and that would
12352            // break because of the new default handling for hoverable views
12353            // in onHoverEvent.
12354            // Note that onGenericMotionEvent will be called by default when
12355            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
12356            dispatchGenericMotionEventInternal(event);
12357            // The event was already handled by calling setHovered(), so always
12358            // return true.
12359            return true;
12360        }
12361
12362        return false;
12363    }
12364
12365    /**
12366     * Returns true if the view should handle {@link #onHoverEvent}
12367     * by calling {@link #setHovered} to change its hovered state.
12368     *
12369     * @return True if the view is hoverable.
12370     */
12371    private boolean isHoverable() {
12372        final int viewFlags = mViewFlags;
12373        if ((viewFlags & ENABLED_MASK) == DISABLED) {
12374            return false;
12375        }
12376
12377        return (viewFlags & CLICKABLE) == CLICKABLE
12378                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE
12379                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
12380    }
12381
12382    /**
12383     * Returns true if the view is currently hovered.
12384     *
12385     * @return True if the view is currently hovered.
12386     *
12387     * @see #setHovered
12388     * @see #onHoverChanged
12389     */
12390    @ViewDebug.ExportedProperty
12391    public boolean isHovered() {
12392        return (mPrivateFlags & PFLAG_HOVERED) != 0;
12393    }
12394
12395    /**
12396     * Sets whether the view is currently hovered.
12397     * <p>
12398     * Calling this method also changes the drawable state of the view.  This
12399     * enables the view to react to hover by using different drawable resources
12400     * to change its appearance.
12401     * </p><p>
12402     * The {@link #onHoverChanged} method is called when the hovered state changes.
12403     * </p>
12404     *
12405     * @param hovered True if the view is hovered.
12406     *
12407     * @see #isHovered
12408     * @see #onHoverChanged
12409     */
12410    public void setHovered(boolean hovered) {
12411        if (hovered) {
12412            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
12413                mPrivateFlags |= PFLAG_HOVERED;
12414                refreshDrawableState();
12415                onHoverChanged(true);
12416            }
12417        } else {
12418            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
12419                mPrivateFlags &= ~PFLAG_HOVERED;
12420                refreshDrawableState();
12421                onHoverChanged(false);
12422            }
12423        }
12424    }
12425
12426    /**
12427     * Implement this method to handle hover state changes.
12428     * <p>
12429     * This method is called whenever the hover state changes as a result of a
12430     * call to {@link #setHovered}.
12431     * </p>
12432     *
12433     * @param hovered The current hover state, as returned by {@link #isHovered}.
12434     *
12435     * @see #isHovered
12436     * @see #setHovered
12437     */
12438    public void onHoverChanged(boolean hovered) {
12439    }
12440
12441    /**
12442     * Handles scroll bar dragging by mouse input.
12443     *
12444     * @hide
12445     * @param event The motion event.
12446     *
12447     * @return true if the event was handled as a scroll bar dragging, false otherwise.
12448     */
12449    protected boolean handleScrollBarDragging(MotionEvent event) {
12450        if (mScrollCache == null) {
12451            return false;
12452        }
12453        final float x = event.getX();
12454        final float y = event.getY();
12455        final int action = event.getAction();
12456        if ((mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING
12457                && action != MotionEvent.ACTION_DOWN)
12458                    || !event.isFromSource(InputDevice.SOURCE_MOUSE)
12459                    || !event.isButtonPressed(MotionEvent.BUTTON_PRIMARY)) {
12460            mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING;
12461            return false;
12462        }
12463
12464        switch (action) {
12465            case MotionEvent.ACTION_MOVE:
12466                if (mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING) {
12467                    return false;
12468                }
12469                if (mScrollCache.mScrollBarDraggingState
12470                        == ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR) {
12471                    final Rect bounds = mScrollCache.mScrollBarBounds;
12472                    getVerticalScrollBarBounds(bounds, null);
12473                    final int range = computeVerticalScrollRange();
12474                    final int offset = computeVerticalScrollOffset();
12475                    final int extent = computeVerticalScrollExtent();
12476
12477                    final int thumbLength = ScrollBarUtils.getThumbLength(
12478                            bounds.height(), bounds.width(), extent, range);
12479                    final int thumbOffset = ScrollBarUtils.getThumbOffset(
12480                            bounds.height(), thumbLength, extent, range, offset);
12481
12482                    final float diff = y - mScrollCache.mScrollBarDraggingPos;
12483                    final float maxThumbOffset = bounds.height() - thumbLength;
12484                    final float newThumbOffset =
12485                            Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset);
12486                    final int height = getHeight();
12487                    if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0
12488                            && height > 0 && extent > 0) {
12489                        final int newY = Math.round((range - extent)
12490                                / ((float)extent / height) * (newThumbOffset / maxThumbOffset));
12491                        if (newY != getScrollY()) {
12492                            mScrollCache.mScrollBarDraggingPos = y;
12493                            setScrollY(newY);
12494                        }
12495                    }
12496                    return true;
12497                }
12498                if (mScrollCache.mScrollBarDraggingState
12499                        == ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR) {
12500                    final Rect bounds = mScrollCache.mScrollBarBounds;
12501                    getHorizontalScrollBarBounds(bounds, null);
12502                    final int range = computeHorizontalScrollRange();
12503                    final int offset = computeHorizontalScrollOffset();
12504                    final int extent = computeHorizontalScrollExtent();
12505
12506                    final int thumbLength = ScrollBarUtils.getThumbLength(
12507                            bounds.width(), bounds.height(), extent, range);
12508                    final int thumbOffset = ScrollBarUtils.getThumbOffset(
12509                            bounds.width(), thumbLength, extent, range, offset);
12510
12511                    final float diff = x - mScrollCache.mScrollBarDraggingPos;
12512                    final float maxThumbOffset = bounds.width() - thumbLength;
12513                    final float newThumbOffset =
12514                            Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset);
12515                    final int width = getWidth();
12516                    if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0
12517                            && width > 0 && extent > 0) {
12518                        final int newX = Math.round((range - extent)
12519                                / ((float)extent / width) * (newThumbOffset / maxThumbOffset));
12520                        if (newX != getScrollX()) {
12521                            mScrollCache.mScrollBarDraggingPos = x;
12522                            setScrollX(newX);
12523                        }
12524                    }
12525                    return true;
12526                }
12527            case MotionEvent.ACTION_DOWN:
12528                if (mScrollCache.state == ScrollabilityCache.OFF) {
12529                    return false;
12530                }
12531                if (isOnVerticalScrollbarThumb(x, y)) {
12532                    mScrollCache.mScrollBarDraggingState =
12533                            ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR;
12534                    mScrollCache.mScrollBarDraggingPos = y;
12535                    return true;
12536                }
12537                if (isOnHorizontalScrollbarThumb(x, y)) {
12538                    mScrollCache.mScrollBarDraggingState =
12539                            ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR;
12540                    mScrollCache.mScrollBarDraggingPos = x;
12541                    return true;
12542                }
12543        }
12544        mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING;
12545        return false;
12546    }
12547
12548    /**
12549     * Implement this method to handle touch screen motion events.
12550     * <p>
12551     * If this method is used to detect click actions, it is recommended that
12552     * the actions be performed by implementing and calling
12553     * {@link #performClick()}. This will ensure consistent system behavior,
12554     * including:
12555     * <ul>
12556     * <li>obeying click sound preferences
12557     * <li>dispatching OnClickListener calls
12558     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
12559     * accessibility features are enabled
12560     * </ul>
12561     *
12562     * @param event The motion event.
12563     * @return True if the event was handled, false otherwise.
12564     */
12565    public boolean onTouchEvent(MotionEvent event) {
12566        final float x = event.getX();
12567        final float y = event.getY();
12568        final int viewFlags = mViewFlags;
12569        final int action = event.getAction();
12570
12571        final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE
12572                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
12573                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
12574
12575        if ((viewFlags & ENABLED_MASK) == DISABLED) {
12576            if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
12577                setPressed(false);
12578            }
12579            mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
12580            // A disabled view that is clickable still consumes the touch
12581            // events, it just doesn't respond to them.
12582            return clickable;
12583        }
12584        if (mTouchDelegate != null) {
12585            if (mTouchDelegate.onTouchEvent(event)) {
12586                return true;
12587            }
12588        }
12589
12590        if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
12591            switch (action) {
12592                case MotionEvent.ACTION_UP:
12593                    mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
12594                    if ((viewFlags & TOOLTIP) == TOOLTIP) {
12595                        handleTooltipUp();
12596                    }
12597                    if (!clickable) {
12598                        removeTapCallback();
12599                        removeLongPressCallback();
12600                        mInContextButtonPress = false;
12601                        mHasPerformedLongPress = false;
12602                        mIgnoreNextUpEvent = false;
12603                        break;
12604                    }
12605                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
12606                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
12607                        // take focus if we don't have it already and we should in
12608                        // touch mode.
12609                        boolean focusTaken = false;
12610                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
12611                            focusTaken = requestFocus();
12612                        }
12613
12614                        if (prepressed) {
12615                            // The button is being released before we actually
12616                            // showed it as pressed.  Make it show the pressed
12617                            // state now (before scheduling the click) to ensure
12618                            // the user sees it.
12619                            setPressed(true, x, y);
12620                        }
12621
12622                        if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
12623                            // This is a tap, so remove the longpress check
12624                            removeLongPressCallback();
12625
12626                            // Only perform take click actions if we were in the pressed state
12627                            if (!focusTaken) {
12628                                // Use a Runnable and post this rather than calling
12629                                // performClick directly. This lets other visual state
12630                                // of the view update before click actions start.
12631                                if (mPerformClick == null) {
12632                                    mPerformClick = new PerformClick();
12633                                }
12634                                if (!post(mPerformClick)) {
12635                                    performClick();
12636                                }
12637                            }
12638                        }
12639
12640                        if (mUnsetPressedState == null) {
12641                            mUnsetPressedState = new UnsetPressedState();
12642                        }
12643
12644                        if (prepressed) {
12645                            postDelayed(mUnsetPressedState,
12646                                    ViewConfiguration.getPressedStateDuration());
12647                        } else if (!post(mUnsetPressedState)) {
12648                            // If the post failed, unpress right now
12649                            mUnsetPressedState.run();
12650                        }
12651
12652                        removeTapCallback();
12653                    }
12654                    mIgnoreNextUpEvent = false;
12655                    break;
12656
12657                case MotionEvent.ACTION_DOWN:
12658                    if (event.getSource() == InputDevice.SOURCE_TOUCHSCREEN) {
12659                        mPrivateFlags3 |= PFLAG3_FINGER_DOWN;
12660                    }
12661                    mHasPerformedLongPress = false;
12662
12663                    if (!clickable) {
12664                        checkForLongClick(0, x, y);
12665                        break;
12666                    }
12667
12668                    if (performButtonActionOnTouchDown(event)) {
12669                        break;
12670                    }
12671
12672                    // Walk up the hierarchy to determine if we're inside a scrolling container.
12673                    boolean isInScrollingContainer = isInScrollingContainer();
12674
12675                    // For views inside a scrolling container, delay the pressed feedback for
12676                    // a short period in case this is a scroll.
12677                    if (isInScrollingContainer) {
12678                        mPrivateFlags |= PFLAG_PREPRESSED;
12679                        if (mPendingCheckForTap == null) {
12680                            mPendingCheckForTap = new CheckForTap();
12681                        }
12682                        mPendingCheckForTap.x = event.getX();
12683                        mPendingCheckForTap.y = event.getY();
12684                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
12685                    } else {
12686                        // Not inside a scrolling container, so show the feedback right away
12687                        setPressed(true, x, y);
12688                        checkForLongClick(0, x, y);
12689                    }
12690                    break;
12691
12692                case MotionEvent.ACTION_CANCEL:
12693                    if (clickable) {
12694                        setPressed(false);
12695                    }
12696                    removeTapCallback();
12697                    removeLongPressCallback();
12698                    mInContextButtonPress = false;
12699                    mHasPerformedLongPress = false;
12700                    mIgnoreNextUpEvent = false;
12701                    mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
12702                    break;
12703
12704                case MotionEvent.ACTION_MOVE:
12705                    if (clickable) {
12706                        drawableHotspotChanged(x, y);
12707                    }
12708
12709                    // Be lenient about moving outside of buttons
12710                    if (!pointInView(x, y, mTouchSlop)) {
12711                        // Outside button
12712                        // Remove any future long press/tap checks
12713                        removeTapCallback();
12714                        removeLongPressCallback();
12715                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
12716                            setPressed(false);
12717                        }
12718                        mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
12719                    }
12720                    break;
12721            }
12722
12723            return true;
12724        }
12725
12726        return false;
12727    }
12728
12729    /**
12730     * @hide
12731     */
12732    public boolean isInScrollingContainer() {
12733        ViewParent p = getParent();
12734        while (p != null && p instanceof ViewGroup) {
12735            if (((ViewGroup) p).shouldDelayChildPressedState()) {
12736                return true;
12737            }
12738            p = p.getParent();
12739        }
12740        return false;
12741    }
12742
12743    /**
12744     * Remove the longpress detection timer.
12745     */
12746    private void removeLongPressCallback() {
12747        if (mPendingCheckForLongPress != null) {
12748            removeCallbacks(mPendingCheckForLongPress);
12749        }
12750    }
12751
12752    /**
12753     * Remove the pending click action
12754     */
12755    private void removePerformClickCallback() {
12756        if (mPerformClick != null) {
12757            removeCallbacks(mPerformClick);
12758        }
12759    }
12760
12761    /**
12762     * Remove the prepress detection timer.
12763     */
12764    private void removeUnsetPressCallback() {
12765        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
12766            setPressed(false);
12767            removeCallbacks(mUnsetPressedState);
12768        }
12769    }
12770
12771    /**
12772     * Remove the tap detection timer.
12773     */
12774    private void removeTapCallback() {
12775        if (mPendingCheckForTap != null) {
12776            mPrivateFlags &= ~PFLAG_PREPRESSED;
12777            removeCallbacks(mPendingCheckForTap);
12778        }
12779    }
12780
12781    /**
12782     * Cancels a pending long press.  Your subclass can use this if you
12783     * want the context menu to come up if the user presses and holds
12784     * at the same place, but you don't want it to come up if they press
12785     * and then move around enough to cause scrolling.
12786     */
12787    public void cancelLongPress() {
12788        removeLongPressCallback();
12789
12790        /*
12791         * The prepressed state handled by the tap callback is a display
12792         * construct, but the tap callback will post a long press callback
12793         * less its own timeout. Remove it here.
12794         */
12795        removeTapCallback();
12796    }
12797
12798    /**
12799     * Remove the pending callback for sending a
12800     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
12801     */
12802    private void removeSendViewScrolledAccessibilityEventCallback() {
12803        if (mSendViewScrolledAccessibilityEvent != null) {
12804            removeCallbacks(mSendViewScrolledAccessibilityEvent);
12805            mSendViewScrolledAccessibilityEvent.mIsPending = false;
12806        }
12807    }
12808
12809    /**
12810     * Sets the TouchDelegate for this View.
12811     */
12812    public void setTouchDelegate(TouchDelegate delegate) {
12813        mTouchDelegate = delegate;
12814    }
12815
12816    /**
12817     * Gets the TouchDelegate for this View.
12818     */
12819    public TouchDelegate getTouchDelegate() {
12820        return mTouchDelegate;
12821    }
12822
12823    /**
12824     * Request unbuffered dispatch of the given stream of MotionEvents to this View.
12825     *
12826     * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input
12827     * system not batch {@link MotionEvent}s but instead deliver them as soon as they're
12828     * available. This method should only be called for touch events.
12829     *
12830     * <p class="note">This api is not intended for most applications. Buffered dispatch
12831     * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent
12832     * streams will not improve your input latency. Side effects include: increased latency,
12833     * jittery scrolls and inability to take advantage of system resampling. Talk to your input
12834     * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for
12835     * you.</p>
12836     */
12837    public final void requestUnbufferedDispatch(MotionEvent event) {
12838        final int action = event.getAction();
12839        if (mAttachInfo == null
12840                || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE
12841                || !event.isTouchEvent()) {
12842            return;
12843        }
12844        mAttachInfo.mUnbufferedDispatchRequested = true;
12845    }
12846
12847    /**
12848     * Set flags controlling behavior of this view.
12849     *
12850     * @param flags Constant indicating the value which should be set
12851     * @param mask Constant indicating the bit range that should be changed
12852     */
12853    void setFlags(int flags, int mask) {
12854        final boolean accessibilityEnabled =
12855                AccessibilityManager.getInstance(mContext).isEnabled();
12856        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
12857
12858        int old = mViewFlags;
12859        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
12860
12861        int changed = mViewFlags ^ old;
12862        if (changed == 0) {
12863            return;
12864        }
12865        int privateFlags = mPrivateFlags;
12866
12867        // If focusable is auto, update the FOCUSABLE bit.
12868        int focusableChangedByAuto = 0;
12869        if (((mViewFlags & FOCUSABLE_AUTO) != 0)
12870                && (changed & (FOCUSABLE_MASK | CLICKABLE)) != 0) {
12871            // Heuristic only takes into account whether view is clickable.
12872            final int newFocus;
12873            if ((mViewFlags & CLICKABLE) != 0) {
12874                newFocus = FOCUSABLE;
12875            } else {
12876                newFocus = NOT_FOCUSABLE;
12877            }
12878            mViewFlags = (mViewFlags & ~FOCUSABLE) | newFocus;
12879            focusableChangedByAuto = (old & FOCUSABLE) ^ (newFocus & FOCUSABLE);
12880            changed = (changed & ~FOCUSABLE) | focusableChangedByAuto;
12881        }
12882
12883        /* Check if the FOCUSABLE bit has changed */
12884        if (((changed & FOCUSABLE) != 0) && ((privateFlags & PFLAG_HAS_BOUNDS) != 0)) {
12885            if (((old & FOCUSABLE) == FOCUSABLE)
12886                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
12887                /* Give up focus if we are no longer focusable */
12888                clearFocus();
12889            } else if (((old & FOCUSABLE) == NOT_FOCUSABLE)
12890                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
12891                /*
12892                 * Tell the view system that we are now available to take focus
12893                 * if no one else already has it.
12894                 */
12895                if (mParent != null) {
12896                    ViewRootImpl viewRootImpl = getViewRootImpl();
12897                    if (!sAutoFocusableOffUIThreadWontNotifyParents
12898                            || focusableChangedByAuto == 0
12899                            || viewRootImpl == null
12900                            || viewRootImpl.mThread == Thread.currentThread()) {
12901                        mParent.focusableViewAvailable(this);
12902                    }
12903                }
12904            }
12905        }
12906
12907        final int newVisibility = flags & VISIBILITY_MASK;
12908        if (newVisibility == VISIBLE) {
12909            if ((changed & VISIBILITY_MASK) != 0) {
12910                /*
12911                 * If this view is becoming visible, invalidate it in case it changed while
12912                 * it was not visible. Marking it drawn ensures that the invalidation will
12913                 * go through.
12914                 */
12915                mPrivateFlags |= PFLAG_DRAWN;
12916                invalidate(true);
12917
12918                needGlobalAttributesUpdate(true);
12919
12920                // a view becoming visible is worth notifying the parent
12921                // about in case nothing has focus.  even if this specific view
12922                // isn't focusable, it may contain something that is, so let
12923                // the root view try to give this focus if nothing else does.
12924                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
12925                    mParent.focusableViewAvailable(this);
12926                }
12927            }
12928        }
12929
12930        /* Check if the GONE bit has changed */
12931        if ((changed & GONE) != 0) {
12932            needGlobalAttributesUpdate(false);
12933            requestLayout();
12934
12935            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
12936                if (hasFocus()) clearFocus();
12937                clearAccessibilityFocus();
12938                destroyDrawingCache();
12939                if (mParent instanceof View) {
12940                    // GONE views noop invalidation, so invalidate the parent
12941                    ((View) mParent).invalidate(true);
12942                }
12943                // Mark the view drawn to ensure that it gets invalidated properly the next
12944                // time it is visible and gets invalidated
12945                mPrivateFlags |= PFLAG_DRAWN;
12946            }
12947            if (mAttachInfo != null) {
12948                mAttachInfo.mViewVisibilityChanged = true;
12949            }
12950        }
12951
12952        /* Check if the VISIBLE bit has changed */
12953        if ((changed & INVISIBLE) != 0) {
12954            needGlobalAttributesUpdate(false);
12955            /*
12956             * If this view is becoming invisible, set the DRAWN flag so that
12957             * the next invalidate() will not be skipped.
12958             */
12959            mPrivateFlags |= PFLAG_DRAWN;
12960
12961            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
12962                // root view becoming invisible shouldn't clear focus and accessibility focus
12963                if (getRootView() != this) {
12964                    if (hasFocus()) clearFocus();
12965                    clearAccessibilityFocus();
12966                }
12967            }
12968            if (mAttachInfo != null) {
12969                mAttachInfo.mViewVisibilityChanged = true;
12970            }
12971        }
12972
12973        if ((changed & VISIBILITY_MASK) != 0) {
12974            // If the view is invisible, cleanup its display list to free up resources
12975            if (newVisibility != VISIBLE && mAttachInfo != null) {
12976                cleanupDraw();
12977            }
12978
12979            if (mParent instanceof ViewGroup) {
12980                ((ViewGroup) mParent).onChildVisibilityChanged(this,
12981                        (changed & VISIBILITY_MASK), newVisibility);
12982                ((View) mParent).invalidate(true);
12983            } else if (mParent != null) {
12984                mParent.invalidateChild(this, null);
12985            }
12986
12987            if (mAttachInfo != null) {
12988                dispatchVisibilityChanged(this, newVisibility);
12989
12990                // Aggregated visibility changes are dispatched to attached views
12991                // in visible windows where the parent is currently shown/drawn
12992                // or the parent is not a ViewGroup (and therefore assumed to be a ViewRoot),
12993                // discounting clipping or overlapping. This makes it a good place
12994                // to change animation states.
12995                if (mParent != null && getWindowVisibility() == VISIBLE &&
12996                        ((!(mParent instanceof ViewGroup)) || ((ViewGroup) mParent).isShown())) {
12997                    dispatchVisibilityAggregated(newVisibility == VISIBLE);
12998                }
12999                notifySubtreeAccessibilityStateChangedIfNeeded();
13000            }
13001        }
13002
13003        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
13004            destroyDrawingCache();
13005        }
13006
13007        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
13008            destroyDrawingCache();
13009            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
13010            invalidateParentCaches();
13011        }
13012
13013        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
13014            destroyDrawingCache();
13015            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
13016        }
13017
13018        if ((changed & DRAW_MASK) != 0) {
13019            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
13020                if (mBackground != null
13021                        || mDefaultFocusHighlight != null
13022                        || (mForegroundInfo != null && mForegroundInfo.mDrawable != null)) {
13023                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
13024                } else {
13025                    mPrivateFlags |= PFLAG_SKIP_DRAW;
13026                }
13027            } else {
13028                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
13029            }
13030            requestLayout();
13031            invalidate(true);
13032        }
13033
13034        if ((changed & KEEP_SCREEN_ON) != 0) {
13035            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
13036                mParent.recomputeViewAttributes(this);
13037            }
13038        }
13039
13040        if (accessibilityEnabled) {
13041            if ((changed & FOCUSABLE) != 0 || (changed & VISIBILITY_MASK) != 0
13042                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0
13043                    || (changed & CONTEXT_CLICKABLE) != 0) {
13044                if (oldIncludeForAccessibility != includeForAccessibility()) {
13045                    notifySubtreeAccessibilityStateChangedIfNeeded();
13046                } else {
13047                    notifyViewAccessibilityStateChangedIfNeeded(
13048                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
13049                }
13050            } else if ((changed & ENABLED_MASK) != 0) {
13051                notifyViewAccessibilityStateChangedIfNeeded(
13052                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
13053            }
13054        }
13055    }
13056
13057    /**
13058     * Change the view's z order in the tree, so it's on top of other sibling
13059     * views. This ordering change may affect layout, if the parent container
13060     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
13061     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
13062     * method should be followed by calls to {@link #requestLayout()} and
13063     * {@link View#invalidate()} on the view's parent to force the parent to redraw
13064     * with the new child ordering.
13065     *
13066     * @see ViewGroup#bringChildToFront(View)
13067     */
13068    public void bringToFront() {
13069        if (mParent != null) {
13070            mParent.bringChildToFront(this);
13071        }
13072    }
13073
13074    /**
13075     * This is called in response to an internal scroll in this view (i.e., the
13076     * view scrolled its own contents). This is typically as a result of
13077     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
13078     * called.
13079     *
13080     * @param l Current horizontal scroll origin.
13081     * @param t Current vertical scroll origin.
13082     * @param oldl Previous horizontal scroll origin.
13083     * @param oldt Previous vertical scroll origin.
13084     */
13085    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
13086        notifySubtreeAccessibilityStateChangedIfNeeded();
13087
13088        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
13089            postSendViewScrolledAccessibilityEventCallback();
13090        }
13091
13092        mBackgroundSizeChanged = true;
13093        mDefaultFocusHighlightSizeChanged = true;
13094        if (mForegroundInfo != null) {
13095            mForegroundInfo.mBoundsChanged = true;
13096        }
13097
13098        final AttachInfo ai = mAttachInfo;
13099        if (ai != null) {
13100            ai.mViewScrollChanged = true;
13101        }
13102
13103        if (mListenerInfo != null && mListenerInfo.mOnScrollChangeListener != null) {
13104            mListenerInfo.mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt);
13105        }
13106    }
13107
13108    /**
13109     * Interface definition for a callback to be invoked when the scroll
13110     * X or Y positions of a view change.
13111     * <p>
13112     * <b>Note:</b> Some views handle scrolling independently from View and may
13113     * have their own separate listeners for scroll-type events. For example,
13114     * {@link android.widget.ListView ListView} allows clients to register an
13115     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
13116     * to listen for changes in list scroll position.
13117     *
13118     * @see #setOnScrollChangeListener(View.OnScrollChangeListener)
13119     */
13120    public interface OnScrollChangeListener {
13121        /**
13122         * Called when the scroll position of a view changes.
13123         *
13124         * @param v The view whose scroll position has changed.
13125         * @param scrollX Current horizontal scroll origin.
13126         * @param scrollY Current vertical scroll origin.
13127         * @param oldScrollX Previous horizontal scroll origin.
13128         * @param oldScrollY Previous vertical scroll origin.
13129         */
13130        void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY);
13131    }
13132
13133    /**
13134     * Interface definition for a callback to be invoked when the layout bounds of a view
13135     * changes due to layout processing.
13136     */
13137    public interface OnLayoutChangeListener {
13138        /**
13139         * Called when the layout bounds of a view changes due to layout processing.
13140         *
13141         * @param v The view whose bounds have changed.
13142         * @param left The new value of the view's left property.
13143         * @param top The new value of the view's top property.
13144         * @param right The new value of the view's right property.
13145         * @param bottom The new value of the view's bottom property.
13146         * @param oldLeft The previous value of the view's left property.
13147         * @param oldTop The previous value of the view's top property.
13148         * @param oldRight The previous value of the view's right property.
13149         * @param oldBottom The previous value of the view's bottom property.
13150         */
13151        void onLayoutChange(View v, int left, int top, int right, int bottom,
13152            int oldLeft, int oldTop, int oldRight, int oldBottom);
13153    }
13154
13155    /**
13156     * This is called during layout when the size of this view has changed. If
13157     * you were just added to the view hierarchy, you're called with the old
13158     * values of 0.
13159     *
13160     * @param w Current width of this view.
13161     * @param h Current height of this view.
13162     * @param oldw Old width of this view.
13163     * @param oldh Old height of this view.
13164     */
13165    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
13166    }
13167
13168    /**
13169     * Called by draw to draw the child views. This may be overridden
13170     * by derived classes to gain control just before its children are drawn
13171     * (but after its own view has been drawn).
13172     * @param canvas the canvas on which to draw the view
13173     */
13174    protected void dispatchDraw(Canvas canvas) {
13175
13176    }
13177
13178    /**
13179     * Gets the parent of this view. Note that the parent is a
13180     * ViewParent and not necessarily a View.
13181     *
13182     * @return Parent of this view.
13183     */
13184    public final ViewParent getParent() {
13185        return mParent;
13186    }
13187
13188    /**
13189     * Set the horizontal scrolled position of your view. This will cause a call to
13190     * {@link #onScrollChanged(int, int, int, int)} and the view will be
13191     * invalidated.
13192     * @param value the x position to scroll to
13193     */
13194    public void setScrollX(int value) {
13195        scrollTo(value, mScrollY);
13196    }
13197
13198    /**
13199     * Set the vertical scrolled position of your view. This will cause a call to
13200     * {@link #onScrollChanged(int, int, int, int)} and the view will be
13201     * invalidated.
13202     * @param value the y position to scroll to
13203     */
13204    public void setScrollY(int value) {
13205        scrollTo(mScrollX, value);
13206    }
13207
13208    /**
13209     * Return the scrolled left position of this view. This is the left edge of
13210     * the displayed part of your view. You do not need to draw any pixels
13211     * farther left, since those are outside of the frame of your view on
13212     * screen.
13213     *
13214     * @return The left edge of the displayed part of your view, in pixels.
13215     */
13216    public final int getScrollX() {
13217        return mScrollX;
13218    }
13219
13220    /**
13221     * Return the scrolled top position of this view. This is the top edge of
13222     * the displayed part of your view. You do not need to draw any pixels above
13223     * it, since those are outside of the frame of your view on screen.
13224     *
13225     * @return The top edge of the displayed part of your view, in pixels.
13226     */
13227    public final int getScrollY() {
13228        return mScrollY;
13229    }
13230
13231    /**
13232     * Return the width of the your view.
13233     *
13234     * @return The width of your view, in pixels.
13235     */
13236    @ViewDebug.ExportedProperty(category = "layout")
13237    public final int getWidth() {
13238        return mRight - mLeft;
13239    }
13240
13241    /**
13242     * Return the height of your view.
13243     *
13244     * @return The height of your view, in pixels.
13245     */
13246    @ViewDebug.ExportedProperty(category = "layout")
13247    public final int getHeight() {
13248        return mBottom - mTop;
13249    }
13250
13251    /**
13252     * Return the visible drawing bounds of your view. Fills in the output
13253     * rectangle with the values from getScrollX(), getScrollY(),
13254     * getWidth(), and getHeight(). These bounds do not account for any
13255     * transformation properties currently set on the view, such as
13256     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
13257     *
13258     * @param outRect The (scrolled) drawing bounds of the view.
13259     */
13260    public void getDrawingRect(Rect outRect) {
13261        outRect.left = mScrollX;
13262        outRect.top = mScrollY;
13263        outRect.right = mScrollX + (mRight - mLeft);
13264        outRect.bottom = mScrollY + (mBottom - mTop);
13265    }
13266
13267    /**
13268     * Like {@link #getMeasuredWidthAndState()}, but only returns the
13269     * raw width component (that is the result is masked by
13270     * {@link #MEASURED_SIZE_MASK}).
13271     *
13272     * @return The raw measured width of this view.
13273     */
13274    public final int getMeasuredWidth() {
13275        return mMeasuredWidth & MEASURED_SIZE_MASK;
13276    }
13277
13278    /**
13279     * Return the full width measurement information for this view as computed
13280     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
13281     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
13282     * This should be used during measurement and layout calculations only. Use
13283     * {@link #getWidth()} to see how wide a view is after layout.
13284     *
13285     * @return The measured width of this view as a bit mask.
13286     */
13287    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
13288            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
13289                    name = "MEASURED_STATE_TOO_SMALL"),
13290    })
13291    public final int getMeasuredWidthAndState() {
13292        return mMeasuredWidth;
13293    }
13294
13295    /**
13296     * Like {@link #getMeasuredHeightAndState()}, but only returns the
13297     * raw height component (that is the result is masked by
13298     * {@link #MEASURED_SIZE_MASK}).
13299     *
13300     * @return The raw measured height of this view.
13301     */
13302    public final int getMeasuredHeight() {
13303        return mMeasuredHeight & MEASURED_SIZE_MASK;
13304    }
13305
13306    /**
13307     * Return the full height measurement information for this view as computed
13308     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
13309     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
13310     * This should be used during measurement and layout calculations only. Use
13311     * {@link #getHeight()} to see how wide a view is after layout.
13312     *
13313     * @return The measured height of this view as a bit mask.
13314     */
13315    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
13316            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
13317                    name = "MEASURED_STATE_TOO_SMALL"),
13318    })
13319    public final int getMeasuredHeightAndState() {
13320        return mMeasuredHeight;
13321    }
13322
13323    /**
13324     * Return only the state bits of {@link #getMeasuredWidthAndState()}
13325     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
13326     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
13327     * and the height component is at the shifted bits
13328     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
13329     */
13330    public final int getMeasuredState() {
13331        return (mMeasuredWidth&MEASURED_STATE_MASK)
13332                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
13333                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
13334    }
13335
13336    /**
13337     * The transform matrix of this view, which is calculated based on the current
13338     * rotation, scale, and pivot properties.
13339     *
13340     * @see #getRotation()
13341     * @see #getScaleX()
13342     * @see #getScaleY()
13343     * @see #getPivotX()
13344     * @see #getPivotY()
13345     * @return The current transform matrix for the view
13346     */
13347    public Matrix getMatrix() {
13348        ensureTransformationInfo();
13349        final Matrix matrix = mTransformationInfo.mMatrix;
13350        mRenderNode.getMatrix(matrix);
13351        return matrix;
13352    }
13353
13354    /**
13355     * Returns true if the transform matrix is the identity matrix.
13356     * Recomputes the matrix if necessary.
13357     *
13358     * @return True if the transform matrix is the identity matrix, false otherwise.
13359     */
13360    final boolean hasIdentityMatrix() {
13361        return mRenderNode.hasIdentityMatrix();
13362    }
13363
13364    void ensureTransformationInfo() {
13365        if (mTransformationInfo == null) {
13366            mTransformationInfo = new TransformationInfo();
13367        }
13368    }
13369
13370    /**
13371     * Utility method to retrieve the inverse of the current mMatrix property.
13372     * We cache the matrix to avoid recalculating it when transform properties
13373     * have not changed.
13374     *
13375     * @return The inverse of the current matrix of this view.
13376     * @hide
13377     */
13378    public final Matrix getInverseMatrix() {
13379        ensureTransformationInfo();
13380        if (mTransformationInfo.mInverseMatrix == null) {
13381            mTransformationInfo.mInverseMatrix = new Matrix();
13382        }
13383        final Matrix matrix = mTransformationInfo.mInverseMatrix;
13384        mRenderNode.getInverseMatrix(matrix);
13385        return matrix;
13386    }
13387
13388    /**
13389     * Gets the distance along the Z axis from the camera to this view.
13390     *
13391     * @see #setCameraDistance(float)
13392     *
13393     * @return The distance along the Z axis.
13394     */
13395    public float getCameraDistance() {
13396        final float dpi = mResources.getDisplayMetrics().densityDpi;
13397        return -(mRenderNode.getCameraDistance() * dpi);
13398    }
13399
13400    /**
13401     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
13402     * views are drawn) from the camera to this view. The camera's distance
13403     * affects 3D transformations, for instance rotations around the X and Y
13404     * axis. If the rotationX or rotationY properties are changed and this view is
13405     * large (more than half the size of the screen), it is recommended to always
13406     * use a camera distance that's greater than the height (X axis rotation) or
13407     * the width (Y axis rotation) of this view.</p>
13408     *
13409     * <p>The distance of the camera from the view plane can have an affect on the
13410     * perspective distortion of the view when it is rotated around the x or y axis.
13411     * For example, a large distance will result in a large viewing angle, and there
13412     * will not be much perspective distortion of the view as it rotates. A short
13413     * distance may cause much more perspective distortion upon rotation, and can
13414     * also result in some drawing artifacts if the rotated view ends up partially
13415     * behind the camera (which is why the recommendation is to use a distance at
13416     * least as far as the size of the view, if the view is to be rotated.)</p>
13417     *
13418     * <p>The distance is expressed in "depth pixels." The default distance depends
13419     * on the screen density. For instance, on a medium density display, the
13420     * default distance is 1280. On a high density display, the default distance
13421     * is 1920.</p>
13422     *
13423     * <p>If you want to specify a distance that leads to visually consistent
13424     * results across various densities, use the following formula:</p>
13425     * <pre>
13426     * float scale = context.getResources().getDisplayMetrics().density;
13427     * view.setCameraDistance(distance * scale);
13428     * </pre>
13429     *
13430     * <p>The density scale factor of a high density display is 1.5,
13431     * and 1920 = 1280 * 1.5.</p>
13432     *
13433     * @param distance The distance in "depth pixels", if negative the opposite
13434     *        value is used
13435     *
13436     * @see #setRotationX(float)
13437     * @see #setRotationY(float)
13438     */
13439    public void setCameraDistance(float distance) {
13440        final float dpi = mResources.getDisplayMetrics().densityDpi;
13441
13442        invalidateViewProperty(true, false);
13443        mRenderNode.setCameraDistance(-Math.abs(distance) / dpi);
13444        invalidateViewProperty(false, false);
13445
13446        invalidateParentIfNeededAndWasQuickRejected();
13447    }
13448
13449    /**
13450     * The degrees that the view is rotated around the pivot point.
13451     *
13452     * @see #setRotation(float)
13453     * @see #getPivotX()
13454     * @see #getPivotY()
13455     *
13456     * @return The degrees of rotation.
13457     */
13458    @ViewDebug.ExportedProperty(category = "drawing")
13459    public float getRotation() {
13460        return mRenderNode.getRotation();
13461    }
13462
13463    /**
13464     * Sets the degrees that the view is rotated around the pivot point. Increasing values
13465     * result in clockwise rotation.
13466     *
13467     * @param rotation The degrees of rotation.
13468     *
13469     * @see #getRotation()
13470     * @see #getPivotX()
13471     * @see #getPivotY()
13472     * @see #setRotationX(float)
13473     * @see #setRotationY(float)
13474     *
13475     * @attr ref android.R.styleable#View_rotation
13476     */
13477    public void setRotation(float rotation) {
13478        if (rotation != getRotation()) {
13479            // Double-invalidation is necessary to capture view's old and new areas
13480            invalidateViewProperty(true, false);
13481            mRenderNode.setRotation(rotation);
13482            invalidateViewProperty(false, true);
13483
13484            invalidateParentIfNeededAndWasQuickRejected();
13485            notifySubtreeAccessibilityStateChangedIfNeeded();
13486        }
13487    }
13488
13489    /**
13490     * The degrees that the view is rotated around the vertical axis through the pivot point.
13491     *
13492     * @see #getPivotX()
13493     * @see #getPivotY()
13494     * @see #setRotationY(float)
13495     *
13496     * @return The degrees of Y rotation.
13497     */
13498    @ViewDebug.ExportedProperty(category = "drawing")
13499    public float getRotationY() {
13500        return mRenderNode.getRotationY();
13501    }
13502
13503    /**
13504     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
13505     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
13506     * down the y axis.
13507     *
13508     * When rotating large views, it is recommended to adjust the camera distance
13509     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
13510     *
13511     * @param rotationY The degrees of Y rotation.
13512     *
13513     * @see #getRotationY()
13514     * @see #getPivotX()
13515     * @see #getPivotY()
13516     * @see #setRotation(float)
13517     * @see #setRotationX(float)
13518     * @see #setCameraDistance(float)
13519     *
13520     * @attr ref android.R.styleable#View_rotationY
13521     */
13522    public void setRotationY(float rotationY) {
13523        if (rotationY != getRotationY()) {
13524            invalidateViewProperty(true, false);
13525            mRenderNode.setRotationY(rotationY);
13526            invalidateViewProperty(false, true);
13527
13528            invalidateParentIfNeededAndWasQuickRejected();
13529            notifySubtreeAccessibilityStateChangedIfNeeded();
13530        }
13531    }
13532
13533    /**
13534     * The degrees that the view is rotated around the horizontal axis through the pivot point.
13535     *
13536     * @see #getPivotX()
13537     * @see #getPivotY()
13538     * @see #setRotationX(float)
13539     *
13540     * @return The degrees of X rotation.
13541     */
13542    @ViewDebug.ExportedProperty(category = "drawing")
13543    public float getRotationX() {
13544        return mRenderNode.getRotationX();
13545    }
13546
13547    /**
13548     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
13549     * Increasing values result in clockwise rotation from the viewpoint of looking down the
13550     * x axis.
13551     *
13552     * When rotating large views, it is recommended to adjust the camera distance
13553     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
13554     *
13555     * @param rotationX The degrees of X rotation.
13556     *
13557     * @see #getRotationX()
13558     * @see #getPivotX()
13559     * @see #getPivotY()
13560     * @see #setRotation(float)
13561     * @see #setRotationY(float)
13562     * @see #setCameraDistance(float)
13563     *
13564     * @attr ref android.R.styleable#View_rotationX
13565     */
13566    public void setRotationX(float rotationX) {
13567        if (rotationX != getRotationX()) {
13568            invalidateViewProperty(true, false);
13569            mRenderNode.setRotationX(rotationX);
13570            invalidateViewProperty(false, true);
13571
13572            invalidateParentIfNeededAndWasQuickRejected();
13573            notifySubtreeAccessibilityStateChangedIfNeeded();
13574        }
13575    }
13576
13577    /**
13578     * The amount that the view is scaled in x around the pivot point, as a proportion of
13579     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
13580     *
13581     * <p>By default, this is 1.0f.
13582     *
13583     * @see #getPivotX()
13584     * @see #getPivotY()
13585     * @return The scaling factor.
13586     */
13587    @ViewDebug.ExportedProperty(category = "drawing")
13588    public float getScaleX() {
13589        return mRenderNode.getScaleX();
13590    }
13591
13592    /**
13593     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
13594     * the view's unscaled width. A value of 1 means that no scaling is applied.
13595     *
13596     * @param scaleX The scaling factor.
13597     * @see #getPivotX()
13598     * @see #getPivotY()
13599     *
13600     * @attr ref android.R.styleable#View_scaleX
13601     */
13602    public void setScaleX(float scaleX) {
13603        if (scaleX != getScaleX()) {
13604            invalidateViewProperty(true, false);
13605            mRenderNode.setScaleX(scaleX);
13606            invalidateViewProperty(false, true);
13607
13608            invalidateParentIfNeededAndWasQuickRejected();
13609            notifySubtreeAccessibilityStateChangedIfNeeded();
13610        }
13611    }
13612
13613    /**
13614     * The amount that the view is scaled in y around the pivot point, as a proportion of
13615     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
13616     *
13617     * <p>By default, this is 1.0f.
13618     *
13619     * @see #getPivotX()
13620     * @see #getPivotY()
13621     * @return The scaling factor.
13622     */
13623    @ViewDebug.ExportedProperty(category = "drawing")
13624    public float getScaleY() {
13625        return mRenderNode.getScaleY();
13626    }
13627
13628    /**
13629     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
13630     * the view's unscaled width. A value of 1 means that no scaling is applied.
13631     *
13632     * @param scaleY The scaling factor.
13633     * @see #getPivotX()
13634     * @see #getPivotY()
13635     *
13636     * @attr ref android.R.styleable#View_scaleY
13637     */
13638    public void setScaleY(float scaleY) {
13639        if (scaleY != getScaleY()) {
13640            invalidateViewProperty(true, false);
13641            mRenderNode.setScaleY(scaleY);
13642            invalidateViewProperty(false, true);
13643
13644            invalidateParentIfNeededAndWasQuickRejected();
13645            notifySubtreeAccessibilityStateChangedIfNeeded();
13646        }
13647    }
13648
13649    /**
13650     * The x location of the point around which the view is {@link #setRotation(float) rotated}
13651     * and {@link #setScaleX(float) scaled}.
13652     *
13653     * @see #getRotation()
13654     * @see #getScaleX()
13655     * @see #getScaleY()
13656     * @see #getPivotY()
13657     * @return The x location of the pivot point.
13658     *
13659     * @attr ref android.R.styleable#View_transformPivotX
13660     */
13661    @ViewDebug.ExportedProperty(category = "drawing")
13662    public float getPivotX() {
13663        return mRenderNode.getPivotX();
13664    }
13665
13666    /**
13667     * Sets the x location of the point around which the view is
13668     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
13669     * By default, the pivot point is centered on the object.
13670     * Setting this property disables this behavior and causes the view to use only the
13671     * explicitly set pivotX and pivotY values.
13672     *
13673     * @param pivotX The x location of the pivot point.
13674     * @see #getRotation()
13675     * @see #getScaleX()
13676     * @see #getScaleY()
13677     * @see #getPivotY()
13678     *
13679     * @attr ref android.R.styleable#View_transformPivotX
13680     */
13681    public void setPivotX(float pivotX) {
13682        if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) {
13683            invalidateViewProperty(true, false);
13684            mRenderNode.setPivotX(pivotX);
13685            invalidateViewProperty(false, true);
13686
13687            invalidateParentIfNeededAndWasQuickRejected();
13688        }
13689    }
13690
13691    /**
13692     * The y location of the point around which the view is {@link #setRotation(float) rotated}
13693     * and {@link #setScaleY(float) scaled}.
13694     *
13695     * @see #getRotation()
13696     * @see #getScaleX()
13697     * @see #getScaleY()
13698     * @see #getPivotY()
13699     * @return The y location of the pivot point.
13700     *
13701     * @attr ref android.R.styleable#View_transformPivotY
13702     */
13703    @ViewDebug.ExportedProperty(category = "drawing")
13704    public float getPivotY() {
13705        return mRenderNode.getPivotY();
13706    }
13707
13708    /**
13709     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
13710     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
13711     * Setting this property disables this behavior and causes the view to use only the
13712     * explicitly set pivotX and pivotY values.
13713     *
13714     * @param pivotY The y location of the pivot point.
13715     * @see #getRotation()
13716     * @see #getScaleX()
13717     * @see #getScaleY()
13718     * @see #getPivotY()
13719     *
13720     * @attr ref android.R.styleable#View_transformPivotY
13721     */
13722    public void setPivotY(float pivotY) {
13723        if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) {
13724            invalidateViewProperty(true, false);
13725            mRenderNode.setPivotY(pivotY);
13726            invalidateViewProperty(false, true);
13727
13728            invalidateParentIfNeededAndWasQuickRejected();
13729        }
13730    }
13731
13732    /**
13733     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
13734     * completely transparent and 1 means the view is completely opaque.
13735     *
13736     * <p>By default this is 1.0f.
13737     * @return The opacity of the view.
13738     */
13739    @ViewDebug.ExportedProperty(category = "drawing")
13740    public float getAlpha() {
13741        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
13742    }
13743
13744    /**
13745     * Sets the behavior for overlapping rendering for this view (see {@link
13746     * #hasOverlappingRendering()} for more details on this behavior). Calling this method
13747     * is an alternative to overriding {@link #hasOverlappingRendering()} in a subclass,
13748     * providing the value which is then used internally. That is, when {@link
13749     * #forceHasOverlappingRendering(boolean)} is called, the value of {@link
13750     * #hasOverlappingRendering()} is ignored and the value passed into this method is used
13751     * instead.
13752     *
13753     * @param hasOverlappingRendering The value for overlapping rendering to be used internally
13754     * instead of that returned by {@link #hasOverlappingRendering()}.
13755     *
13756     * @attr ref android.R.styleable#View_forceHasOverlappingRendering
13757     */
13758    public void forceHasOverlappingRendering(boolean hasOverlappingRendering) {
13759        mPrivateFlags3 |= PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED;
13760        if (hasOverlappingRendering) {
13761            mPrivateFlags3 |= PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE;
13762        } else {
13763            mPrivateFlags3 &= ~PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE;
13764        }
13765    }
13766
13767    /**
13768     * Returns the value for overlapping rendering that is used internally. This is either
13769     * the value passed into {@link #forceHasOverlappingRendering(boolean)}, if called, or
13770     * the return value of {@link #hasOverlappingRendering()}, otherwise.
13771     *
13772     * @return The value for overlapping rendering being used internally.
13773     */
13774    public final boolean getHasOverlappingRendering() {
13775        return (mPrivateFlags3 & PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED) != 0 ?
13776                (mPrivateFlags3 & PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE) != 0 :
13777                hasOverlappingRendering();
13778    }
13779
13780    /**
13781     * Returns whether this View has content which overlaps.
13782     *
13783     * <p>This function, intended to be overridden by specific View types, is an optimization when
13784     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
13785     * an offscreen buffer and then composited into place, which can be expensive. If the view has
13786     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
13787     * directly. An example of overlapping rendering is a TextView with a background image, such as
13788     * a Button. An example of non-overlapping rendering is a TextView with no background, or an
13789     * ImageView with only the foreground image. The default implementation returns true; subclasses
13790     * should override if they have cases which can be optimized.</p>
13791     *
13792     * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas}
13793     * necessitates that a View return true if it uses the methods internally without passing the
13794     * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p>
13795     *
13796     * <p><strong>Note:</strong> The return value of this method is ignored if {@link
13797     * #forceHasOverlappingRendering(boolean)} has been called on this view.</p>
13798     *
13799     * @return true if the content in this view might overlap, false otherwise.
13800     */
13801    @ViewDebug.ExportedProperty(category = "drawing")
13802    public boolean hasOverlappingRendering() {
13803        return true;
13804    }
13805
13806    /**
13807     * Sets the opacity of the view to a value from 0 to 1, where 0 means the view is
13808     * completely transparent and 1 means the view is completely opaque.
13809     *
13810     * <p class="note"><strong>Note:</strong> setting alpha to a translucent value (0 < alpha < 1)
13811     * can have significant performance implications, especially for large views. It is best to use
13812     * the alpha property sparingly and transiently, as in the case of fading animations.</p>
13813     *
13814     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
13815     * strongly recommended for performance reasons to either override
13816     * {@link #hasOverlappingRendering()} to return <code>false</code> if appropriate, or setting a
13817     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view for the duration
13818     * of the animation. On versions {@link android.os.Build.VERSION_CODES#M} and below,
13819     * the default path for rendering an unlayered View with alpha could add multiple milliseconds
13820     * of rendering cost, even for simple or small views. Starting with
13821     * {@link android.os.Build.VERSION_CODES#M}, {@link #LAYER_TYPE_HARDWARE} is automatically
13822     * applied to the view at the rendering level.</p>
13823     *
13824     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
13825     * responsible for applying the opacity itself.</p>
13826     *
13827     * <p>On versions {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} and below, note that if
13828     * the view is backed by a {@link #setLayerType(int, android.graphics.Paint) layer} and is
13829     * associated with a {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an
13830     * alpha value less than 1.0 will supersede the alpha of the layer paint.</p>
13831     *
13832     * <p>Starting with {@link android.os.Build.VERSION_CODES#M}, setting a translucent alpha
13833     * value will clip a View to its bounds, unless the View returns <code>false</code> from
13834     * {@link #hasOverlappingRendering}.</p>
13835     *
13836     * @param alpha The opacity of the view.
13837     *
13838     * @see #hasOverlappingRendering()
13839     * @see #setLayerType(int, android.graphics.Paint)
13840     *
13841     * @attr ref android.R.styleable#View_alpha
13842     */
13843    public void setAlpha(@FloatRange(from=0.0, to=1.0) float alpha) {
13844        ensureTransformationInfo();
13845        if (mTransformationInfo.mAlpha != alpha) {
13846            // Report visibility changes, which can affect children, to accessibility
13847            if ((alpha == 0) ^ (mTransformationInfo.mAlpha == 0)) {
13848                notifySubtreeAccessibilityStateChangedIfNeeded();
13849            }
13850            mTransformationInfo.mAlpha = alpha;
13851            if (onSetAlpha((int) (alpha * 255))) {
13852                mPrivateFlags |= PFLAG_ALPHA_SET;
13853                // subclass is handling alpha - don't optimize rendering cache invalidation
13854                invalidateParentCaches();
13855                invalidate(true);
13856            } else {
13857                mPrivateFlags &= ~PFLAG_ALPHA_SET;
13858                invalidateViewProperty(true, false);
13859                mRenderNode.setAlpha(getFinalAlpha());
13860            }
13861        }
13862    }
13863
13864    /**
13865     * Faster version of setAlpha() which performs the same steps except there are
13866     * no calls to invalidate(). The caller of this function should perform proper invalidation
13867     * on the parent and this object. The return value indicates whether the subclass handles
13868     * alpha (the return value for onSetAlpha()).
13869     *
13870     * @param alpha The new value for the alpha property
13871     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
13872     *         the new value for the alpha property is different from the old value
13873     */
13874    boolean setAlphaNoInvalidation(float alpha) {
13875        ensureTransformationInfo();
13876        if (mTransformationInfo.mAlpha != alpha) {
13877            mTransformationInfo.mAlpha = alpha;
13878            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
13879            if (subclassHandlesAlpha) {
13880                mPrivateFlags |= PFLAG_ALPHA_SET;
13881                return true;
13882            } else {
13883                mPrivateFlags &= ~PFLAG_ALPHA_SET;
13884                mRenderNode.setAlpha(getFinalAlpha());
13885            }
13886        }
13887        return false;
13888    }
13889
13890    /**
13891     * This property is hidden and intended only for use by the Fade transition, which
13892     * animates it to produce a visual translucency that does not side-effect (or get
13893     * affected by) the real alpha property. This value is composited with the other
13894     * alpha value (and the AlphaAnimation value, when that is present) to produce
13895     * a final visual translucency result, which is what is passed into the DisplayList.
13896     *
13897     * @hide
13898     */
13899    public void setTransitionAlpha(float alpha) {
13900        ensureTransformationInfo();
13901        if (mTransformationInfo.mTransitionAlpha != alpha) {
13902            mTransformationInfo.mTransitionAlpha = alpha;
13903            mPrivateFlags &= ~PFLAG_ALPHA_SET;
13904            invalidateViewProperty(true, false);
13905            mRenderNode.setAlpha(getFinalAlpha());
13906        }
13907    }
13908
13909    /**
13910     * Calculates the visual alpha of this view, which is a combination of the actual
13911     * alpha value and the transitionAlpha value (if set).
13912     */
13913    private float getFinalAlpha() {
13914        if (mTransformationInfo != null) {
13915            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
13916        }
13917        return 1;
13918    }
13919
13920    /**
13921     * This property is hidden and intended only for use by the Fade transition, which
13922     * animates it to produce a visual translucency that does not side-effect (or get
13923     * affected by) the real alpha property. This value is composited with the other
13924     * alpha value (and the AlphaAnimation value, when that is present) to produce
13925     * a final visual translucency result, which is what is passed into the DisplayList.
13926     *
13927     * @hide
13928     */
13929    @ViewDebug.ExportedProperty(category = "drawing")
13930    public float getTransitionAlpha() {
13931        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
13932    }
13933
13934    /**
13935     * Top position of this view relative to its parent.
13936     *
13937     * @return The top of this view, in pixels.
13938     */
13939    @ViewDebug.CapturedViewProperty
13940    public final int getTop() {
13941        return mTop;
13942    }
13943
13944    /**
13945     * Sets the top position of this view relative to its parent. This method is meant to be called
13946     * by the layout system and should not generally be called otherwise, because the property
13947     * may be changed at any time by the layout.
13948     *
13949     * @param top The top of this view, in pixels.
13950     */
13951    public final void setTop(int top) {
13952        if (top != mTop) {
13953            final boolean matrixIsIdentity = hasIdentityMatrix();
13954            if (matrixIsIdentity) {
13955                if (mAttachInfo != null) {
13956                    int minTop;
13957                    int yLoc;
13958                    if (top < mTop) {
13959                        minTop = top;
13960                        yLoc = top - mTop;
13961                    } else {
13962                        minTop = mTop;
13963                        yLoc = 0;
13964                    }
13965                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
13966                }
13967            } else {
13968                // Double-invalidation is necessary to capture view's old and new areas
13969                invalidate(true);
13970            }
13971
13972            int width = mRight - mLeft;
13973            int oldHeight = mBottom - mTop;
13974
13975            mTop = top;
13976            mRenderNode.setTop(mTop);
13977
13978            sizeChange(width, mBottom - mTop, width, oldHeight);
13979
13980            if (!matrixIsIdentity) {
13981                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
13982                invalidate(true);
13983            }
13984            mBackgroundSizeChanged = true;
13985            mDefaultFocusHighlightSizeChanged = true;
13986            if (mForegroundInfo != null) {
13987                mForegroundInfo.mBoundsChanged = true;
13988            }
13989            invalidateParentIfNeeded();
13990            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
13991                // View was rejected last time it was drawn by its parent; this may have changed
13992                invalidateParentIfNeeded();
13993            }
13994        }
13995    }
13996
13997    /**
13998     * Bottom position of this view relative to its parent.
13999     *
14000     * @return The bottom of this view, in pixels.
14001     */
14002    @ViewDebug.CapturedViewProperty
14003    public final int getBottom() {
14004        return mBottom;
14005    }
14006
14007    /**
14008     * True if this view has changed since the last time being drawn.
14009     *
14010     * @return The dirty state of this view.
14011     */
14012    public boolean isDirty() {
14013        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
14014    }
14015
14016    /**
14017     * Sets the bottom position of this view relative to its parent. This method is meant to be
14018     * called by the layout system and should not generally be called otherwise, because the
14019     * property may be changed at any time by the layout.
14020     *
14021     * @param bottom The bottom of this view, in pixels.
14022     */
14023    public final void setBottom(int bottom) {
14024        if (bottom != mBottom) {
14025            final boolean matrixIsIdentity = hasIdentityMatrix();
14026            if (matrixIsIdentity) {
14027                if (mAttachInfo != null) {
14028                    int maxBottom;
14029                    if (bottom < mBottom) {
14030                        maxBottom = mBottom;
14031                    } else {
14032                        maxBottom = bottom;
14033                    }
14034                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
14035                }
14036            } else {
14037                // Double-invalidation is necessary to capture view's old and new areas
14038                invalidate(true);
14039            }
14040
14041            int width = mRight - mLeft;
14042            int oldHeight = mBottom - mTop;
14043
14044            mBottom = bottom;
14045            mRenderNode.setBottom(mBottom);
14046
14047            sizeChange(width, mBottom - mTop, width, oldHeight);
14048
14049            if (!matrixIsIdentity) {
14050                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
14051                invalidate(true);
14052            }
14053            mBackgroundSizeChanged = true;
14054            mDefaultFocusHighlightSizeChanged = true;
14055            if (mForegroundInfo != null) {
14056                mForegroundInfo.mBoundsChanged = true;
14057            }
14058            invalidateParentIfNeeded();
14059            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
14060                // View was rejected last time it was drawn by its parent; this may have changed
14061                invalidateParentIfNeeded();
14062            }
14063        }
14064    }
14065
14066    /**
14067     * Left position of this view relative to its parent.
14068     *
14069     * @return The left edge of this view, in pixels.
14070     */
14071    @ViewDebug.CapturedViewProperty
14072    public final int getLeft() {
14073        return mLeft;
14074    }
14075
14076    /**
14077     * Sets the left position of this view relative to its parent. This method is meant to be called
14078     * by the layout system and should not generally be called otherwise, because the property
14079     * may be changed at any time by the layout.
14080     *
14081     * @param left The left of this view, in pixels.
14082     */
14083    public final void setLeft(int left) {
14084        if (left != mLeft) {
14085            final boolean matrixIsIdentity = hasIdentityMatrix();
14086            if (matrixIsIdentity) {
14087                if (mAttachInfo != null) {
14088                    int minLeft;
14089                    int xLoc;
14090                    if (left < mLeft) {
14091                        minLeft = left;
14092                        xLoc = left - mLeft;
14093                    } else {
14094                        minLeft = mLeft;
14095                        xLoc = 0;
14096                    }
14097                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
14098                }
14099            } else {
14100                // Double-invalidation is necessary to capture view's old and new areas
14101                invalidate(true);
14102            }
14103
14104            int oldWidth = mRight - mLeft;
14105            int height = mBottom - mTop;
14106
14107            mLeft = left;
14108            mRenderNode.setLeft(left);
14109
14110            sizeChange(mRight - mLeft, height, oldWidth, height);
14111
14112            if (!matrixIsIdentity) {
14113                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
14114                invalidate(true);
14115            }
14116            mBackgroundSizeChanged = true;
14117            mDefaultFocusHighlightSizeChanged = true;
14118            if (mForegroundInfo != null) {
14119                mForegroundInfo.mBoundsChanged = true;
14120            }
14121            invalidateParentIfNeeded();
14122            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
14123                // View was rejected last time it was drawn by its parent; this may have changed
14124                invalidateParentIfNeeded();
14125            }
14126        }
14127    }
14128
14129    /**
14130     * Right position of this view relative to its parent.
14131     *
14132     * @return The right edge of this view, in pixels.
14133     */
14134    @ViewDebug.CapturedViewProperty
14135    public final int getRight() {
14136        return mRight;
14137    }
14138
14139    /**
14140     * Sets the right position of this view relative to its parent. This method is meant to be called
14141     * by the layout system and should not generally be called otherwise, because the property
14142     * may be changed at any time by the layout.
14143     *
14144     * @param right The right of this view, in pixels.
14145     */
14146    public final void setRight(int right) {
14147        if (right != mRight) {
14148            final boolean matrixIsIdentity = hasIdentityMatrix();
14149            if (matrixIsIdentity) {
14150                if (mAttachInfo != null) {
14151                    int maxRight;
14152                    if (right < mRight) {
14153                        maxRight = mRight;
14154                    } else {
14155                        maxRight = right;
14156                    }
14157                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
14158                }
14159            } else {
14160                // Double-invalidation is necessary to capture view's old and new areas
14161                invalidate(true);
14162            }
14163
14164            int oldWidth = mRight - mLeft;
14165            int height = mBottom - mTop;
14166
14167            mRight = right;
14168            mRenderNode.setRight(mRight);
14169
14170            sizeChange(mRight - mLeft, height, oldWidth, height);
14171
14172            if (!matrixIsIdentity) {
14173                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
14174                invalidate(true);
14175            }
14176            mBackgroundSizeChanged = true;
14177            mDefaultFocusHighlightSizeChanged = true;
14178            if (mForegroundInfo != null) {
14179                mForegroundInfo.mBoundsChanged = true;
14180            }
14181            invalidateParentIfNeeded();
14182            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
14183                // View was rejected last time it was drawn by its parent; this may have changed
14184                invalidateParentIfNeeded();
14185            }
14186        }
14187    }
14188
14189    /**
14190     * The visual x position of this view, in pixels. This is equivalent to the
14191     * {@link #setTranslationX(float) translationX} property plus the current
14192     * {@link #getLeft() left} property.
14193     *
14194     * @return The visual x position of this view, in pixels.
14195     */
14196    @ViewDebug.ExportedProperty(category = "drawing")
14197    public float getX() {
14198        return mLeft + getTranslationX();
14199    }
14200
14201    /**
14202     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
14203     * {@link #setTranslationX(float) translationX} property to be the difference between
14204     * the x value passed in and the current {@link #getLeft() left} property.
14205     *
14206     * @param x The visual x position of this view, in pixels.
14207     */
14208    public void setX(float x) {
14209        setTranslationX(x - mLeft);
14210    }
14211
14212    /**
14213     * The visual y position of this view, in pixels. This is equivalent to the
14214     * {@link #setTranslationY(float) translationY} property plus the current
14215     * {@link #getTop() top} property.
14216     *
14217     * @return The visual y position of this view, in pixels.
14218     */
14219    @ViewDebug.ExportedProperty(category = "drawing")
14220    public float getY() {
14221        return mTop + getTranslationY();
14222    }
14223
14224    /**
14225     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
14226     * {@link #setTranslationY(float) translationY} property to be the difference between
14227     * the y value passed in and the current {@link #getTop() top} property.
14228     *
14229     * @param y The visual y position of this view, in pixels.
14230     */
14231    public void setY(float y) {
14232        setTranslationY(y - mTop);
14233    }
14234
14235    /**
14236     * The visual z position of this view, in pixels. This is equivalent to the
14237     * {@link #setTranslationZ(float) translationZ} property plus the current
14238     * {@link #getElevation() elevation} property.
14239     *
14240     * @return The visual z position of this view, in pixels.
14241     */
14242    @ViewDebug.ExportedProperty(category = "drawing")
14243    public float getZ() {
14244        return getElevation() + getTranslationZ();
14245    }
14246
14247    /**
14248     * Sets the visual z position of this view, in pixels. This is equivalent to setting the
14249     * {@link #setTranslationZ(float) translationZ} property to be the difference between
14250     * the x value passed in and the current {@link #getElevation() elevation} property.
14251     *
14252     * @param z The visual z position of this view, in pixels.
14253     */
14254    public void setZ(float z) {
14255        setTranslationZ(z - getElevation());
14256    }
14257
14258    /**
14259     * The base elevation of this view relative to its parent, in pixels.
14260     *
14261     * @return The base depth position of the view, in pixels.
14262     */
14263    @ViewDebug.ExportedProperty(category = "drawing")
14264    public float getElevation() {
14265        return mRenderNode.getElevation();
14266    }
14267
14268    /**
14269     * Sets the base elevation of this view, in pixels.
14270     *
14271     * @attr ref android.R.styleable#View_elevation
14272     */
14273    public void setElevation(float elevation) {
14274        if (elevation != getElevation()) {
14275            invalidateViewProperty(true, false);
14276            mRenderNode.setElevation(elevation);
14277            invalidateViewProperty(false, true);
14278
14279            invalidateParentIfNeededAndWasQuickRejected();
14280        }
14281    }
14282
14283    /**
14284     * The horizontal location of this view relative to its {@link #getLeft() left} position.
14285     * This position is post-layout, in addition to wherever the object's
14286     * layout placed it.
14287     *
14288     * @return The horizontal position of this view relative to its left position, in pixels.
14289     */
14290    @ViewDebug.ExportedProperty(category = "drawing")
14291    public float getTranslationX() {
14292        return mRenderNode.getTranslationX();
14293    }
14294
14295    /**
14296     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
14297     * This effectively positions the object post-layout, in addition to wherever the object's
14298     * layout placed it.
14299     *
14300     * @param translationX The horizontal position of this view relative to its left position,
14301     * in pixels.
14302     *
14303     * @attr ref android.R.styleable#View_translationX
14304     */
14305    public void setTranslationX(float translationX) {
14306        if (translationX != getTranslationX()) {
14307            invalidateViewProperty(true, false);
14308            mRenderNode.setTranslationX(translationX);
14309            invalidateViewProperty(false, true);
14310
14311            invalidateParentIfNeededAndWasQuickRejected();
14312            notifySubtreeAccessibilityStateChangedIfNeeded();
14313        }
14314    }
14315
14316    /**
14317     * The vertical location of this view relative to its {@link #getTop() top} position.
14318     * This position is post-layout, in addition to wherever the object's
14319     * layout placed it.
14320     *
14321     * @return The vertical position of this view relative to its top position,
14322     * in pixels.
14323     */
14324    @ViewDebug.ExportedProperty(category = "drawing")
14325    public float getTranslationY() {
14326        return mRenderNode.getTranslationY();
14327    }
14328
14329    /**
14330     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
14331     * This effectively positions the object post-layout, in addition to wherever the object's
14332     * layout placed it.
14333     *
14334     * @param translationY The vertical position of this view relative to its top position,
14335     * in pixels.
14336     *
14337     * @attr ref android.R.styleable#View_translationY
14338     */
14339    public void setTranslationY(float translationY) {
14340        if (translationY != getTranslationY()) {
14341            invalidateViewProperty(true, false);
14342            mRenderNode.setTranslationY(translationY);
14343            invalidateViewProperty(false, true);
14344
14345            invalidateParentIfNeededAndWasQuickRejected();
14346            notifySubtreeAccessibilityStateChangedIfNeeded();
14347        }
14348    }
14349
14350    /**
14351     * The depth location of this view relative to its {@link #getElevation() elevation}.
14352     *
14353     * @return The depth of this view relative to its elevation.
14354     */
14355    @ViewDebug.ExportedProperty(category = "drawing")
14356    public float getTranslationZ() {
14357        return mRenderNode.getTranslationZ();
14358    }
14359
14360    /**
14361     * Sets the depth location of this view relative to its {@link #getElevation() elevation}.
14362     *
14363     * @attr ref android.R.styleable#View_translationZ
14364     */
14365    public void setTranslationZ(float translationZ) {
14366        if (translationZ != getTranslationZ()) {
14367            invalidateViewProperty(true, false);
14368            mRenderNode.setTranslationZ(translationZ);
14369            invalidateViewProperty(false, true);
14370
14371            invalidateParentIfNeededAndWasQuickRejected();
14372        }
14373    }
14374
14375    /** @hide */
14376    public void setAnimationMatrix(Matrix matrix) {
14377        invalidateViewProperty(true, false);
14378        mRenderNode.setAnimationMatrix(matrix);
14379        invalidateViewProperty(false, true);
14380
14381        invalidateParentIfNeededAndWasQuickRejected();
14382    }
14383
14384    /**
14385     * Returns the current StateListAnimator if exists.
14386     *
14387     * @return StateListAnimator or null if it does not exists
14388     * @see    #setStateListAnimator(android.animation.StateListAnimator)
14389     */
14390    public StateListAnimator getStateListAnimator() {
14391        return mStateListAnimator;
14392    }
14393
14394    /**
14395     * Attaches the provided StateListAnimator to this View.
14396     * <p>
14397     * Any previously attached StateListAnimator will be detached.
14398     *
14399     * @param stateListAnimator The StateListAnimator to update the view
14400     * @see android.animation.StateListAnimator
14401     */
14402    public void setStateListAnimator(StateListAnimator stateListAnimator) {
14403        if (mStateListAnimator == stateListAnimator) {
14404            return;
14405        }
14406        if (mStateListAnimator != null) {
14407            mStateListAnimator.setTarget(null);
14408        }
14409        mStateListAnimator = stateListAnimator;
14410        if (stateListAnimator != null) {
14411            stateListAnimator.setTarget(this);
14412            if (isAttachedToWindow()) {
14413                stateListAnimator.setState(getDrawableState());
14414            }
14415        }
14416    }
14417
14418    /**
14419     * Returns whether the Outline should be used to clip the contents of the View.
14420     * <p>
14421     * Note that this flag will only be respected if the View's Outline returns true from
14422     * {@link Outline#canClip()}.
14423     *
14424     * @see #setOutlineProvider(ViewOutlineProvider)
14425     * @see #setClipToOutline(boolean)
14426     */
14427    public final boolean getClipToOutline() {
14428        return mRenderNode.getClipToOutline();
14429    }
14430
14431    /**
14432     * Sets whether the View's Outline should be used to clip the contents of the View.
14433     * <p>
14434     * Only a single non-rectangular clip can be applied on a View at any time.
14435     * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float)
14436     * circular reveal} animation take priority over Outline clipping, and
14437     * child Outline clipping takes priority over Outline clipping done by a
14438     * parent.
14439     * <p>
14440     * Note that this flag will only be respected if the View's Outline returns true from
14441     * {@link Outline#canClip()}.
14442     *
14443     * @see #setOutlineProvider(ViewOutlineProvider)
14444     * @see #getClipToOutline()
14445     */
14446    public void setClipToOutline(boolean clipToOutline) {
14447        damageInParent();
14448        if (getClipToOutline() != clipToOutline) {
14449            mRenderNode.setClipToOutline(clipToOutline);
14450        }
14451    }
14452
14453    // correspond to the enum values of View_outlineProvider
14454    private static final int PROVIDER_BACKGROUND = 0;
14455    private static final int PROVIDER_NONE = 1;
14456    private static final int PROVIDER_BOUNDS = 2;
14457    private static final int PROVIDER_PADDED_BOUNDS = 3;
14458    private void setOutlineProviderFromAttribute(int providerInt) {
14459        switch (providerInt) {
14460            case PROVIDER_BACKGROUND:
14461                setOutlineProvider(ViewOutlineProvider.BACKGROUND);
14462                break;
14463            case PROVIDER_NONE:
14464                setOutlineProvider(null);
14465                break;
14466            case PROVIDER_BOUNDS:
14467                setOutlineProvider(ViewOutlineProvider.BOUNDS);
14468                break;
14469            case PROVIDER_PADDED_BOUNDS:
14470                setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS);
14471                break;
14472        }
14473    }
14474
14475    /**
14476     * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines
14477     * the shape of the shadow it casts, and enables outline clipping.
14478     * <p>
14479     * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline
14480     * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the
14481     * outline provider with this method allows this behavior to be overridden.
14482     * <p>
14483     * If the ViewOutlineProvider is null, if querying it for an outline returns false,
14484     * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast.
14485     * <p>
14486     * Only outlines that return true from {@link Outline#canClip()} may be used for clipping.
14487     *
14488     * @see #setClipToOutline(boolean)
14489     * @see #getClipToOutline()
14490     * @see #getOutlineProvider()
14491     */
14492    public void setOutlineProvider(ViewOutlineProvider provider) {
14493        mOutlineProvider = provider;
14494        invalidateOutline();
14495    }
14496
14497    /**
14498     * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline
14499     * that defines the shape of the shadow it casts, and enables outline clipping.
14500     *
14501     * @see #setOutlineProvider(ViewOutlineProvider)
14502     */
14503    public ViewOutlineProvider getOutlineProvider() {
14504        return mOutlineProvider;
14505    }
14506
14507    /**
14508     * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider}
14509     *
14510     * @see #setOutlineProvider(ViewOutlineProvider)
14511     */
14512    public void invalidateOutline() {
14513        rebuildOutline();
14514
14515        notifySubtreeAccessibilityStateChangedIfNeeded();
14516        invalidateViewProperty(false, false);
14517    }
14518
14519    /**
14520     * Internal version of {@link #invalidateOutline()} which invalidates the
14521     * outline without invalidating the view itself. This is intended to be called from
14522     * within methods in the View class itself which are the result of the view being
14523     * invalidated already. For example, when we are drawing the background of a View,
14524     * we invalidate the outline in case it changed in the meantime, but we do not
14525     * need to invalidate the view because we're already drawing the background as part
14526     * of drawing the view in response to an earlier invalidation of the view.
14527     */
14528    private void rebuildOutline() {
14529        // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow()
14530        if (mAttachInfo == null) return;
14531
14532        if (mOutlineProvider == null) {
14533            // no provider, remove outline
14534            mRenderNode.setOutline(null);
14535        } else {
14536            final Outline outline = mAttachInfo.mTmpOutline;
14537            outline.setEmpty();
14538            outline.setAlpha(1.0f);
14539
14540            mOutlineProvider.getOutline(this, outline);
14541            mRenderNode.setOutline(outline);
14542        }
14543    }
14544
14545    /**
14546     * HierarchyViewer only
14547     *
14548     * @hide
14549     */
14550    @ViewDebug.ExportedProperty(category = "drawing")
14551    public boolean hasShadow() {
14552        return mRenderNode.hasShadow();
14553    }
14554
14555
14556    /** @hide */
14557    public void setRevealClip(boolean shouldClip, float x, float y, float radius) {
14558        mRenderNode.setRevealClip(shouldClip, x, y, radius);
14559        invalidateViewProperty(false, false);
14560    }
14561
14562    /**
14563     * Hit rectangle in parent's coordinates
14564     *
14565     * @param outRect The hit rectangle of the view.
14566     */
14567    public void getHitRect(Rect outRect) {
14568        if (hasIdentityMatrix() || mAttachInfo == null) {
14569            outRect.set(mLeft, mTop, mRight, mBottom);
14570        } else {
14571            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
14572            tmpRect.set(0, 0, getWidth(), getHeight());
14573            getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect)
14574            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
14575                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
14576        }
14577    }
14578
14579    /**
14580     * Determines whether the given point, in local coordinates is inside the view.
14581     */
14582    /*package*/ final boolean pointInView(float localX, float localY) {
14583        return pointInView(localX, localY, 0);
14584    }
14585
14586    /**
14587     * Utility method to determine whether the given point, in local coordinates,
14588     * is inside the view, where the area of the view is expanded by the slop factor.
14589     * This method is called while processing touch-move events to determine if the event
14590     * is still within the view.
14591     *
14592     * @hide
14593     */
14594    public boolean pointInView(float localX, float localY, float slop) {
14595        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
14596                localY < ((mBottom - mTop) + slop);
14597    }
14598
14599    /**
14600     * When a view has focus and the user navigates away from it, the next view is searched for
14601     * starting from the rectangle filled in by this method.
14602     *
14603     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
14604     * of the view.  However, if your view maintains some idea of internal selection,
14605     * such as a cursor, or a selected row or column, you should override this method and
14606     * fill in a more specific rectangle.
14607     *
14608     * @param r The rectangle to fill in, in this view's coordinates.
14609     */
14610    public void getFocusedRect(Rect r) {
14611        getDrawingRect(r);
14612    }
14613
14614    /**
14615     * If some part of this view is not clipped by any of its parents, then
14616     * return that area in r in global (root) coordinates. To convert r to local
14617     * coordinates (without taking possible View rotations into account), offset
14618     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
14619     * If the view is completely clipped or translated out, return false.
14620     *
14621     * @param r If true is returned, r holds the global coordinates of the
14622     *        visible portion of this view.
14623     * @param globalOffset If true is returned, globalOffset holds the dx,dy
14624     *        between this view and its root. globalOffet may be null.
14625     * @return true if r is non-empty (i.e. part of the view is visible at the
14626     *         root level.
14627     */
14628    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
14629        int width = mRight - mLeft;
14630        int height = mBottom - mTop;
14631        if (width > 0 && height > 0) {
14632            r.set(0, 0, width, height);
14633            if (globalOffset != null) {
14634                globalOffset.set(-mScrollX, -mScrollY);
14635            }
14636            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
14637        }
14638        return false;
14639    }
14640
14641    public final boolean getGlobalVisibleRect(Rect r) {
14642        return getGlobalVisibleRect(r, null);
14643    }
14644
14645    public final boolean getLocalVisibleRect(Rect r) {
14646        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
14647        if (getGlobalVisibleRect(r, offset)) {
14648            r.offset(-offset.x, -offset.y); // make r local
14649            return true;
14650        }
14651        return false;
14652    }
14653
14654    /**
14655     * Offset this view's vertical location by the specified number of pixels.
14656     *
14657     * @param offset the number of pixels to offset the view by
14658     */
14659    public void offsetTopAndBottom(int offset) {
14660        if (offset != 0) {
14661            final boolean matrixIsIdentity = hasIdentityMatrix();
14662            if (matrixIsIdentity) {
14663                if (isHardwareAccelerated()) {
14664                    invalidateViewProperty(false, false);
14665                } else {
14666                    final ViewParent p = mParent;
14667                    if (p != null && mAttachInfo != null) {
14668                        final Rect r = mAttachInfo.mTmpInvalRect;
14669                        int minTop;
14670                        int maxBottom;
14671                        int yLoc;
14672                        if (offset < 0) {
14673                            minTop = mTop + offset;
14674                            maxBottom = mBottom;
14675                            yLoc = offset;
14676                        } else {
14677                            minTop = mTop;
14678                            maxBottom = mBottom + offset;
14679                            yLoc = 0;
14680                        }
14681                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
14682                        p.invalidateChild(this, r);
14683                    }
14684                }
14685            } else {
14686                invalidateViewProperty(false, false);
14687            }
14688
14689            mTop += offset;
14690            mBottom += offset;
14691            mRenderNode.offsetTopAndBottom(offset);
14692            if (isHardwareAccelerated()) {
14693                invalidateViewProperty(false, false);
14694                invalidateParentIfNeededAndWasQuickRejected();
14695            } else {
14696                if (!matrixIsIdentity) {
14697                    invalidateViewProperty(false, true);
14698                }
14699                invalidateParentIfNeeded();
14700            }
14701            notifySubtreeAccessibilityStateChangedIfNeeded();
14702        }
14703    }
14704
14705    /**
14706     * Offset this view's horizontal location by the specified amount of pixels.
14707     *
14708     * @param offset the number of pixels to offset the view by
14709     */
14710    public void offsetLeftAndRight(int offset) {
14711        if (offset != 0) {
14712            final boolean matrixIsIdentity = hasIdentityMatrix();
14713            if (matrixIsIdentity) {
14714                if (isHardwareAccelerated()) {
14715                    invalidateViewProperty(false, false);
14716                } else {
14717                    final ViewParent p = mParent;
14718                    if (p != null && mAttachInfo != null) {
14719                        final Rect r = mAttachInfo.mTmpInvalRect;
14720                        int minLeft;
14721                        int maxRight;
14722                        if (offset < 0) {
14723                            minLeft = mLeft + offset;
14724                            maxRight = mRight;
14725                        } else {
14726                            minLeft = mLeft;
14727                            maxRight = mRight + offset;
14728                        }
14729                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
14730                        p.invalidateChild(this, r);
14731                    }
14732                }
14733            } else {
14734                invalidateViewProperty(false, false);
14735            }
14736
14737            mLeft += offset;
14738            mRight += offset;
14739            mRenderNode.offsetLeftAndRight(offset);
14740            if (isHardwareAccelerated()) {
14741                invalidateViewProperty(false, false);
14742                invalidateParentIfNeededAndWasQuickRejected();
14743            } else {
14744                if (!matrixIsIdentity) {
14745                    invalidateViewProperty(false, true);
14746                }
14747                invalidateParentIfNeeded();
14748            }
14749            notifySubtreeAccessibilityStateChangedIfNeeded();
14750        }
14751    }
14752
14753    /**
14754     * Get the LayoutParams associated with this view. All views should have
14755     * layout parameters. These supply parameters to the <i>parent</i> of this
14756     * view specifying how it should be arranged. There are many subclasses of
14757     * ViewGroup.LayoutParams, and these correspond to the different subclasses
14758     * of ViewGroup that are responsible for arranging their children.
14759     *
14760     * This method may return null if this View is not attached to a parent
14761     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
14762     * was not invoked successfully. When a View is attached to a parent
14763     * ViewGroup, this method must not return null.
14764     *
14765     * @return The LayoutParams associated with this view, or null if no
14766     *         parameters have been set yet
14767     */
14768    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
14769    public ViewGroup.LayoutParams getLayoutParams() {
14770        return mLayoutParams;
14771    }
14772
14773    /**
14774     * Set the layout parameters associated with this view. These supply
14775     * parameters to the <i>parent</i> of this view specifying how it should be
14776     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
14777     * correspond to the different subclasses of ViewGroup that are responsible
14778     * for arranging their children.
14779     *
14780     * @param params The layout parameters for this view, cannot be null
14781     */
14782    public void setLayoutParams(ViewGroup.LayoutParams params) {
14783        if (params == null) {
14784            throw new NullPointerException("Layout parameters cannot be null");
14785        }
14786        mLayoutParams = params;
14787        resolveLayoutParams();
14788        if (mParent instanceof ViewGroup) {
14789            ((ViewGroup) mParent).onSetLayoutParams(this, params);
14790        }
14791        requestLayout();
14792    }
14793
14794    /**
14795     * Resolve the layout parameters depending on the resolved layout direction
14796     *
14797     * @hide
14798     */
14799    public void resolveLayoutParams() {
14800        if (mLayoutParams != null) {
14801            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
14802        }
14803    }
14804
14805    /**
14806     * Set the scrolled position of your view. This will cause a call to
14807     * {@link #onScrollChanged(int, int, int, int)} and the view will be
14808     * invalidated.
14809     * @param x the x position to scroll to
14810     * @param y the y position to scroll to
14811     */
14812    public void scrollTo(int x, int y) {
14813        if (mScrollX != x || mScrollY != y) {
14814            int oldX = mScrollX;
14815            int oldY = mScrollY;
14816            mScrollX = x;
14817            mScrollY = y;
14818            invalidateParentCaches();
14819            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
14820            if (!awakenScrollBars()) {
14821                postInvalidateOnAnimation();
14822            }
14823        }
14824    }
14825
14826    /**
14827     * Move the scrolled position of your view. This will cause a call to
14828     * {@link #onScrollChanged(int, int, int, int)} and the view will be
14829     * invalidated.
14830     * @param x the amount of pixels to scroll by horizontally
14831     * @param y the amount of pixels to scroll by vertically
14832     */
14833    public void scrollBy(int x, int y) {
14834        scrollTo(mScrollX + x, mScrollY + y);
14835    }
14836
14837    /**
14838     * <p>Trigger the scrollbars to draw. When invoked this method starts an
14839     * animation to fade the scrollbars out after a default delay. If a subclass
14840     * provides animated scrolling, the start delay should equal the duration
14841     * of the scrolling animation.</p>
14842     *
14843     * <p>The animation starts only if at least one of the scrollbars is
14844     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
14845     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
14846     * this method returns true, and false otherwise. If the animation is
14847     * started, this method calls {@link #invalidate()}; in that case the
14848     * caller should not call {@link #invalidate()}.</p>
14849     *
14850     * <p>This method should be invoked every time a subclass directly updates
14851     * the scroll parameters.</p>
14852     *
14853     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
14854     * and {@link #scrollTo(int, int)}.</p>
14855     *
14856     * @return true if the animation is played, false otherwise
14857     *
14858     * @see #awakenScrollBars(int)
14859     * @see #scrollBy(int, int)
14860     * @see #scrollTo(int, int)
14861     * @see #isHorizontalScrollBarEnabled()
14862     * @see #isVerticalScrollBarEnabled()
14863     * @see #setHorizontalScrollBarEnabled(boolean)
14864     * @see #setVerticalScrollBarEnabled(boolean)
14865     */
14866    protected boolean awakenScrollBars() {
14867        return mScrollCache != null &&
14868                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
14869    }
14870
14871    /**
14872     * Trigger the scrollbars to draw.
14873     * This method differs from awakenScrollBars() only in its default duration.
14874     * initialAwakenScrollBars() will show the scroll bars for longer than
14875     * usual to give the user more of a chance to notice them.
14876     *
14877     * @return true if the animation is played, false otherwise.
14878     */
14879    private boolean initialAwakenScrollBars() {
14880        return mScrollCache != null &&
14881                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
14882    }
14883
14884    /**
14885     * <p>
14886     * Trigger the scrollbars to draw. When invoked this method starts an
14887     * animation to fade the scrollbars out after a fixed delay. If a subclass
14888     * provides animated scrolling, the start delay should equal the duration of
14889     * the scrolling animation.
14890     * </p>
14891     *
14892     * <p>
14893     * The animation starts only if at least one of the scrollbars is enabled,
14894     * as specified by {@link #isHorizontalScrollBarEnabled()} and
14895     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
14896     * this method returns true, and false otherwise. If the animation is
14897     * started, this method calls {@link #invalidate()}; in that case the caller
14898     * should not call {@link #invalidate()}.
14899     * </p>
14900     *
14901     * <p>
14902     * This method should be invoked every time a subclass directly updates the
14903     * scroll parameters.
14904     * </p>
14905     *
14906     * @param startDelay the delay, in milliseconds, after which the animation
14907     *        should start; when the delay is 0, the animation starts
14908     *        immediately
14909     * @return true if the animation is played, false otherwise
14910     *
14911     * @see #scrollBy(int, int)
14912     * @see #scrollTo(int, int)
14913     * @see #isHorizontalScrollBarEnabled()
14914     * @see #isVerticalScrollBarEnabled()
14915     * @see #setHorizontalScrollBarEnabled(boolean)
14916     * @see #setVerticalScrollBarEnabled(boolean)
14917     */
14918    protected boolean awakenScrollBars(int startDelay) {
14919        return awakenScrollBars(startDelay, true);
14920    }
14921
14922    /**
14923     * <p>
14924     * Trigger the scrollbars to draw. When invoked this method starts an
14925     * animation to fade the scrollbars out after a fixed delay. If a subclass
14926     * provides animated scrolling, the start delay should equal the duration of
14927     * the scrolling animation.
14928     * </p>
14929     *
14930     * <p>
14931     * The animation starts only if at least one of the scrollbars is enabled,
14932     * as specified by {@link #isHorizontalScrollBarEnabled()} and
14933     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
14934     * this method returns true, and false otherwise. If the animation is
14935     * started, this method calls {@link #invalidate()} if the invalidate parameter
14936     * is set to true; in that case the caller
14937     * should not call {@link #invalidate()}.
14938     * </p>
14939     *
14940     * <p>
14941     * This method should be invoked every time a subclass directly updates the
14942     * scroll parameters.
14943     * </p>
14944     *
14945     * @param startDelay the delay, in milliseconds, after which the animation
14946     *        should start; when the delay is 0, the animation starts
14947     *        immediately
14948     *
14949     * @param invalidate Whether this method should call invalidate
14950     *
14951     * @return true if the animation is played, false otherwise
14952     *
14953     * @see #scrollBy(int, int)
14954     * @see #scrollTo(int, int)
14955     * @see #isHorizontalScrollBarEnabled()
14956     * @see #isVerticalScrollBarEnabled()
14957     * @see #setHorizontalScrollBarEnabled(boolean)
14958     * @see #setVerticalScrollBarEnabled(boolean)
14959     */
14960    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
14961        final ScrollabilityCache scrollCache = mScrollCache;
14962
14963        if (scrollCache == null || !scrollCache.fadeScrollBars) {
14964            return false;
14965        }
14966
14967        if (scrollCache.scrollBar == null) {
14968            scrollCache.scrollBar = new ScrollBarDrawable();
14969            scrollCache.scrollBar.setState(getDrawableState());
14970            scrollCache.scrollBar.setCallback(this);
14971        }
14972
14973        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
14974
14975            if (invalidate) {
14976                // Invalidate to show the scrollbars
14977                postInvalidateOnAnimation();
14978            }
14979
14980            if (scrollCache.state == ScrollabilityCache.OFF) {
14981                // FIXME: this is copied from WindowManagerService.
14982                // We should get this value from the system when it
14983                // is possible to do so.
14984                final int KEY_REPEAT_FIRST_DELAY = 750;
14985                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
14986            }
14987
14988            // Tell mScrollCache when we should start fading. This may
14989            // extend the fade start time if one was already scheduled
14990            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
14991            scrollCache.fadeStartTime = fadeStartTime;
14992            scrollCache.state = ScrollabilityCache.ON;
14993
14994            // Schedule our fader to run, unscheduling any old ones first
14995            if (mAttachInfo != null) {
14996                mAttachInfo.mHandler.removeCallbacks(scrollCache);
14997                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
14998            }
14999
15000            return true;
15001        }
15002
15003        return false;
15004    }
15005
15006    /**
15007     * Do not invalidate views which are not visible and which are not running an animation. They
15008     * will not get drawn and they should not set dirty flags as if they will be drawn
15009     */
15010    private boolean skipInvalidate() {
15011        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
15012                (!(mParent instanceof ViewGroup) ||
15013                        !((ViewGroup) mParent).isViewTransitioning(this));
15014    }
15015
15016    /**
15017     * Mark the area defined by dirty as needing to be drawn. If the view is
15018     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
15019     * point in the future.
15020     * <p>
15021     * This must be called from a UI thread. To call from a non-UI thread, call
15022     * {@link #postInvalidate()}.
15023     * <p>
15024     * <b>WARNING:</b> In API 19 and below, this method may be destructive to
15025     * {@code dirty}.
15026     *
15027     * @param dirty the rectangle representing the bounds of the dirty region
15028     */
15029    public void invalidate(Rect dirty) {
15030        final int scrollX = mScrollX;
15031        final int scrollY = mScrollY;
15032        invalidateInternal(dirty.left - scrollX, dirty.top - scrollY,
15033                dirty.right - scrollX, dirty.bottom - scrollY, true, false);
15034    }
15035
15036    /**
15037     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The
15038     * coordinates of the dirty rect are relative to the view. If the view is
15039     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
15040     * point in the future.
15041     * <p>
15042     * This must be called from a UI thread. To call from a non-UI thread, call
15043     * {@link #postInvalidate()}.
15044     *
15045     * @param l the left position of the dirty region
15046     * @param t the top position of the dirty region
15047     * @param r the right position of the dirty region
15048     * @param b the bottom position of the dirty region
15049     */
15050    public void invalidate(int l, int t, int r, int b) {
15051        final int scrollX = mScrollX;
15052        final int scrollY = mScrollY;
15053        invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false);
15054    }
15055
15056    /**
15057     * Invalidate the whole view. If the view is visible,
15058     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
15059     * the future.
15060     * <p>
15061     * This must be called from a UI thread. To call from a non-UI thread, call
15062     * {@link #postInvalidate()}.
15063     */
15064    public void invalidate() {
15065        invalidate(true);
15066    }
15067
15068    /**
15069     * This is where the invalidate() work actually happens. A full invalidate()
15070     * causes the drawing cache to be invalidated, but this function can be
15071     * called with invalidateCache set to false to skip that invalidation step
15072     * for cases that do not need it (for example, a component that remains at
15073     * the same dimensions with the same content).
15074     *
15075     * @param invalidateCache Whether the drawing cache for this view should be
15076     *            invalidated as well. This is usually true for a full
15077     *            invalidate, but may be set to false if the View's contents or
15078     *            dimensions have not changed.
15079     * @hide
15080     */
15081    public void invalidate(boolean invalidateCache) {
15082        invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
15083    }
15084
15085    void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
15086            boolean fullInvalidate) {
15087        if (mGhostView != null) {
15088            mGhostView.invalidate(true);
15089            return;
15090        }
15091
15092        if (skipInvalidate()) {
15093            return;
15094        }
15095
15096        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)
15097                || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID)
15098                || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED
15099                || (fullInvalidate && isOpaque() != mLastIsOpaque)) {
15100            if (fullInvalidate) {
15101                mLastIsOpaque = isOpaque();
15102                mPrivateFlags &= ~PFLAG_DRAWN;
15103            }
15104
15105            mPrivateFlags |= PFLAG_DIRTY;
15106
15107            if (invalidateCache) {
15108                mPrivateFlags |= PFLAG_INVALIDATED;
15109                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
15110            }
15111
15112            // Propagate the damage rectangle to the parent view.
15113            final AttachInfo ai = mAttachInfo;
15114            final ViewParent p = mParent;
15115            if (p != null && ai != null && l < r && t < b) {
15116                final Rect damage = ai.mTmpInvalRect;
15117                damage.set(l, t, r, b);
15118                p.invalidateChild(this, damage);
15119            }
15120
15121            // Damage the entire projection receiver, if necessary.
15122            if (mBackground != null && mBackground.isProjected()) {
15123                final View receiver = getProjectionReceiver();
15124                if (receiver != null) {
15125                    receiver.damageInParent();
15126                }
15127            }
15128        }
15129    }
15130
15131    /**
15132     * @return this view's projection receiver, or {@code null} if none exists
15133     */
15134    private View getProjectionReceiver() {
15135        ViewParent p = getParent();
15136        while (p != null && p instanceof View) {
15137            final View v = (View) p;
15138            if (v.isProjectionReceiver()) {
15139                return v;
15140            }
15141            p = p.getParent();
15142        }
15143
15144        return null;
15145    }
15146
15147    /**
15148     * @return whether the view is a projection receiver
15149     */
15150    private boolean isProjectionReceiver() {
15151        return mBackground != null;
15152    }
15153
15154    /**
15155     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
15156     * set any flags or handle all of the cases handled by the default invalidation methods.
15157     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
15158     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
15159     * walk up the hierarchy, transforming the dirty rect as necessary.
15160     *
15161     * The method also handles normal invalidation logic if display list properties are not
15162     * being used in this view. The invalidateParent and forceRedraw flags are used by that
15163     * backup approach, to handle these cases used in the various property-setting methods.
15164     *
15165     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
15166     * are not being used in this view
15167     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
15168     * list properties are not being used in this view
15169     */
15170    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
15171        if (!isHardwareAccelerated()
15172                || !mRenderNode.isValid()
15173                || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) {
15174            if (invalidateParent) {
15175                invalidateParentCaches();
15176            }
15177            if (forceRedraw) {
15178                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
15179            }
15180            invalidate(false);
15181        } else {
15182            damageInParent();
15183        }
15184    }
15185
15186    /**
15187     * Tells the parent view to damage this view's bounds.
15188     *
15189     * @hide
15190     */
15191    protected void damageInParent() {
15192        if (mParent != null && mAttachInfo != null) {
15193            mParent.onDescendantInvalidated(this, this);
15194        }
15195    }
15196
15197    /**
15198     * Utility method to transform a given Rect by the current matrix of this view.
15199     */
15200    void transformRect(final Rect rect) {
15201        if (!getMatrix().isIdentity()) {
15202            RectF boundingRect = mAttachInfo.mTmpTransformRect;
15203            boundingRect.set(rect);
15204            getMatrix().mapRect(boundingRect);
15205            rect.set((int) Math.floor(boundingRect.left),
15206                    (int) Math.floor(boundingRect.top),
15207                    (int) Math.ceil(boundingRect.right),
15208                    (int) Math.ceil(boundingRect.bottom));
15209        }
15210    }
15211
15212    /**
15213     * Used to indicate that the parent of this view should clear its caches. This functionality
15214     * is used to force the parent to rebuild its display list (when hardware-accelerated),
15215     * which is necessary when various parent-managed properties of the view change, such as
15216     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
15217     * clears the parent caches and does not causes an invalidate event.
15218     *
15219     * @hide
15220     */
15221    protected void invalidateParentCaches() {
15222        if (mParent instanceof View) {
15223            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
15224        }
15225    }
15226
15227    /**
15228     * Used to indicate that the parent of this view should be invalidated. This functionality
15229     * is used to force the parent to rebuild its display list (when hardware-accelerated),
15230     * which is necessary when various parent-managed properties of the view change, such as
15231     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
15232     * an invalidation event to the parent.
15233     *
15234     * @hide
15235     */
15236    protected void invalidateParentIfNeeded() {
15237        if (isHardwareAccelerated() && mParent instanceof View) {
15238            ((View) mParent).invalidate(true);
15239        }
15240    }
15241
15242    /**
15243     * @hide
15244     */
15245    protected void invalidateParentIfNeededAndWasQuickRejected() {
15246        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) {
15247            // View was rejected last time it was drawn by its parent; this may have changed
15248            invalidateParentIfNeeded();
15249        }
15250    }
15251
15252    /**
15253     * Indicates whether this View is opaque. An opaque View guarantees that it will
15254     * draw all the pixels overlapping its bounds using a fully opaque color.
15255     *
15256     * Subclasses of View should override this method whenever possible to indicate
15257     * whether an instance is opaque. Opaque Views are treated in a special way by
15258     * the View hierarchy, possibly allowing it to perform optimizations during
15259     * invalidate/draw passes.
15260     *
15261     * @return True if this View is guaranteed to be fully opaque, false otherwise.
15262     */
15263    @ViewDebug.ExportedProperty(category = "drawing")
15264    public boolean isOpaque() {
15265        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
15266                getFinalAlpha() >= 1.0f;
15267    }
15268
15269    /**
15270     * @hide
15271     */
15272    protected void computeOpaqueFlags() {
15273        // Opaque if:
15274        //   - Has a background
15275        //   - Background is opaque
15276        //   - Doesn't have scrollbars or scrollbars overlay
15277
15278        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
15279            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
15280        } else {
15281            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
15282        }
15283
15284        final int flags = mViewFlags;
15285        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
15286                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
15287                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
15288            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
15289        } else {
15290            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
15291        }
15292    }
15293
15294    /**
15295     * @hide
15296     */
15297    protected boolean hasOpaqueScrollbars() {
15298        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
15299    }
15300
15301    /**
15302     * @return A handler associated with the thread running the View. This
15303     * handler can be used to pump events in the UI events queue.
15304     */
15305    public Handler getHandler() {
15306        final AttachInfo attachInfo = mAttachInfo;
15307        if (attachInfo != null) {
15308            return attachInfo.mHandler;
15309        }
15310        return null;
15311    }
15312
15313    /**
15314     * Returns the queue of runnable for this view.
15315     *
15316     * @return the queue of runnables for this view
15317     */
15318    private HandlerActionQueue getRunQueue() {
15319        if (mRunQueue == null) {
15320            mRunQueue = new HandlerActionQueue();
15321        }
15322        return mRunQueue;
15323    }
15324
15325    /**
15326     * Gets the view root associated with the View.
15327     * @return The view root, or null if none.
15328     * @hide
15329     */
15330    public ViewRootImpl getViewRootImpl() {
15331        if (mAttachInfo != null) {
15332            return mAttachInfo.mViewRootImpl;
15333        }
15334        return null;
15335    }
15336
15337    /**
15338     * @hide
15339     */
15340    public ThreadedRenderer getThreadedRenderer() {
15341        return mAttachInfo != null ? mAttachInfo.mThreadedRenderer : null;
15342    }
15343
15344    /**
15345     * <p>Causes the Runnable to be added to the message queue.
15346     * The runnable will be run on the user interface thread.</p>
15347     *
15348     * @param action The Runnable that will be executed.
15349     *
15350     * @return Returns true if the Runnable was successfully placed in to the
15351     *         message queue.  Returns false on failure, usually because the
15352     *         looper processing the message queue is exiting.
15353     *
15354     * @see #postDelayed
15355     * @see #removeCallbacks
15356     */
15357    public boolean post(Runnable action) {
15358        final AttachInfo attachInfo = mAttachInfo;
15359        if (attachInfo != null) {
15360            return attachInfo.mHandler.post(action);
15361        }
15362
15363        // Postpone the runnable until we know on which thread it needs to run.
15364        // Assume that the runnable will be successfully placed after attach.
15365        getRunQueue().post(action);
15366        return true;
15367    }
15368
15369    /**
15370     * <p>Causes the Runnable to be added to the message queue, to be run
15371     * after the specified amount of time elapses.
15372     * The runnable will be run on the user interface thread.</p>
15373     *
15374     * @param action The Runnable that will be executed.
15375     * @param delayMillis The delay (in milliseconds) until the Runnable
15376     *        will be executed.
15377     *
15378     * @return true if the Runnable was successfully placed in to the
15379     *         message queue.  Returns false on failure, usually because the
15380     *         looper processing the message queue is exiting.  Note that a
15381     *         result of true does not mean the Runnable will be processed --
15382     *         if the looper is quit before the delivery time of the message
15383     *         occurs then the message will be dropped.
15384     *
15385     * @see #post
15386     * @see #removeCallbacks
15387     */
15388    public boolean postDelayed(Runnable action, long delayMillis) {
15389        final AttachInfo attachInfo = mAttachInfo;
15390        if (attachInfo != null) {
15391            return attachInfo.mHandler.postDelayed(action, delayMillis);
15392        }
15393
15394        // Postpone the runnable until we know on which thread it needs to run.
15395        // Assume that the runnable will be successfully placed after attach.
15396        getRunQueue().postDelayed(action, delayMillis);
15397        return true;
15398    }
15399
15400    /**
15401     * <p>Causes the Runnable to execute on the next animation time step.
15402     * The runnable will be run on the user interface thread.</p>
15403     *
15404     * @param action The Runnable that will be executed.
15405     *
15406     * @see #postOnAnimationDelayed
15407     * @see #removeCallbacks
15408     */
15409    public void postOnAnimation(Runnable action) {
15410        final AttachInfo attachInfo = mAttachInfo;
15411        if (attachInfo != null) {
15412            attachInfo.mViewRootImpl.mChoreographer.postCallback(
15413                    Choreographer.CALLBACK_ANIMATION, action, null);
15414        } else {
15415            // Postpone the runnable until we know
15416            // on which thread it needs to run.
15417            getRunQueue().post(action);
15418        }
15419    }
15420
15421    /**
15422     * <p>Causes the Runnable to execute on the next animation time step,
15423     * after the specified amount of time elapses.
15424     * The runnable will be run on the user interface thread.</p>
15425     *
15426     * @param action The Runnable that will be executed.
15427     * @param delayMillis The delay (in milliseconds) until the Runnable
15428     *        will be executed.
15429     *
15430     * @see #postOnAnimation
15431     * @see #removeCallbacks
15432     */
15433    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
15434        final AttachInfo attachInfo = mAttachInfo;
15435        if (attachInfo != null) {
15436            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
15437                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
15438        } else {
15439            // Postpone the runnable until we know
15440            // on which thread it needs to run.
15441            getRunQueue().postDelayed(action, delayMillis);
15442        }
15443    }
15444
15445    /**
15446     * <p>Removes the specified Runnable from the message queue.</p>
15447     *
15448     * @param action The Runnable to remove from the message handling queue
15449     *
15450     * @return true if this view could ask the Handler to remove the Runnable,
15451     *         false otherwise. When the returned value is true, the Runnable
15452     *         may or may not have been actually removed from the message queue
15453     *         (for instance, if the Runnable was not in the queue already.)
15454     *
15455     * @see #post
15456     * @see #postDelayed
15457     * @see #postOnAnimation
15458     * @see #postOnAnimationDelayed
15459     */
15460    public boolean removeCallbacks(Runnable action) {
15461        if (action != null) {
15462            final AttachInfo attachInfo = mAttachInfo;
15463            if (attachInfo != null) {
15464                attachInfo.mHandler.removeCallbacks(action);
15465                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15466                        Choreographer.CALLBACK_ANIMATION, action, null);
15467            }
15468            getRunQueue().removeCallbacks(action);
15469        }
15470        return true;
15471    }
15472
15473    /**
15474     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
15475     * Use this to invalidate the View from a non-UI thread.</p>
15476     *
15477     * <p>This method can be invoked from outside of the UI thread
15478     * only when this View is attached to a window.</p>
15479     *
15480     * @see #invalidate()
15481     * @see #postInvalidateDelayed(long)
15482     */
15483    public void postInvalidate() {
15484        postInvalidateDelayed(0);
15485    }
15486
15487    /**
15488     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
15489     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
15490     *
15491     * <p>This method can be invoked from outside of the UI thread
15492     * only when this View is attached to a window.</p>
15493     *
15494     * @param left The left coordinate of the rectangle to invalidate.
15495     * @param top The top coordinate of the rectangle to invalidate.
15496     * @param right The right coordinate of the rectangle to invalidate.
15497     * @param bottom The bottom coordinate of the rectangle to invalidate.
15498     *
15499     * @see #invalidate(int, int, int, int)
15500     * @see #invalidate(Rect)
15501     * @see #postInvalidateDelayed(long, int, int, int, int)
15502     */
15503    public void postInvalidate(int left, int top, int right, int bottom) {
15504        postInvalidateDelayed(0, left, top, right, bottom);
15505    }
15506
15507    /**
15508     * <p>Cause an invalidate to happen on a subsequent cycle through the event
15509     * loop. Waits for the specified amount of time.</p>
15510     *
15511     * <p>This method can be invoked from outside of the UI thread
15512     * only when this View is attached to a window.</p>
15513     *
15514     * @param delayMilliseconds the duration in milliseconds to delay the
15515     *         invalidation by
15516     *
15517     * @see #invalidate()
15518     * @see #postInvalidate()
15519     */
15520    public void postInvalidateDelayed(long delayMilliseconds) {
15521        // We try only with the AttachInfo because there's no point in invalidating
15522        // if we are not attached to our window
15523        final AttachInfo attachInfo = mAttachInfo;
15524        if (attachInfo != null) {
15525            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
15526        }
15527    }
15528
15529    /**
15530     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
15531     * through the event loop. Waits for the specified amount of time.</p>
15532     *
15533     * <p>This method can be invoked from outside of the UI thread
15534     * only when this View is attached to a window.</p>
15535     *
15536     * @param delayMilliseconds the duration in milliseconds to delay the
15537     *         invalidation by
15538     * @param left The left coordinate of the rectangle to invalidate.
15539     * @param top The top coordinate of the rectangle to invalidate.
15540     * @param right The right coordinate of the rectangle to invalidate.
15541     * @param bottom The bottom coordinate of the rectangle to invalidate.
15542     *
15543     * @see #invalidate(int, int, int, int)
15544     * @see #invalidate(Rect)
15545     * @see #postInvalidate(int, int, int, int)
15546     */
15547    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
15548            int right, int bottom) {
15549
15550        // We try only with the AttachInfo because there's no point in invalidating
15551        // if we are not attached to our window
15552        final AttachInfo attachInfo = mAttachInfo;
15553        if (attachInfo != null) {
15554            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
15555            info.target = this;
15556            info.left = left;
15557            info.top = top;
15558            info.right = right;
15559            info.bottom = bottom;
15560
15561            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
15562        }
15563    }
15564
15565    /**
15566     * <p>Cause an invalidate to happen on the next animation time step, typically the
15567     * next display frame.</p>
15568     *
15569     * <p>This method can be invoked from outside of the UI thread
15570     * only when this View is attached to a window.</p>
15571     *
15572     * @see #invalidate()
15573     */
15574    public void postInvalidateOnAnimation() {
15575        // We try only with the AttachInfo because there's no point in invalidating
15576        // if we are not attached to our window
15577        final AttachInfo attachInfo = mAttachInfo;
15578        if (attachInfo != null) {
15579            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
15580        }
15581    }
15582
15583    /**
15584     * <p>Cause an invalidate of the specified area to happen on the next animation
15585     * time step, typically the next display frame.</p>
15586     *
15587     * <p>This method can be invoked from outside of the UI thread
15588     * only when this View is attached to a window.</p>
15589     *
15590     * @param left The left coordinate of the rectangle to invalidate.
15591     * @param top The top coordinate of the rectangle to invalidate.
15592     * @param right The right coordinate of the rectangle to invalidate.
15593     * @param bottom The bottom coordinate of the rectangle to invalidate.
15594     *
15595     * @see #invalidate(int, int, int, int)
15596     * @see #invalidate(Rect)
15597     */
15598    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
15599        // We try only with the AttachInfo because there's no point in invalidating
15600        // if we are not attached to our window
15601        final AttachInfo attachInfo = mAttachInfo;
15602        if (attachInfo != null) {
15603            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
15604            info.target = this;
15605            info.left = left;
15606            info.top = top;
15607            info.right = right;
15608            info.bottom = bottom;
15609
15610            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
15611        }
15612    }
15613
15614    /**
15615     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
15616     * This event is sent at most once every
15617     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
15618     */
15619    private void postSendViewScrolledAccessibilityEventCallback() {
15620        if (mSendViewScrolledAccessibilityEvent == null) {
15621            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
15622        }
15623        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
15624            mSendViewScrolledAccessibilityEvent.mIsPending = true;
15625            postDelayed(mSendViewScrolledAccessibilityEvent,
15626                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
15627        }
15628    }
15629
15630    /**
15631     * Called by a parent to request that a child update its values for mScrollX
15632     * and mScrollY if necessary. This will typically be done if the child is
15633     * animating a scroll using a {@link android.widget.Scroller Scroller}
15634     * object.
15635     */
15636    public void computeScroll() {
15637    }
15638
15639    /**
15640     * <p>Indicate whether the horizontal edges are faded when the view is
15641     * scrolled horizontally.</p>
15642     *
15643     * @return true if the horizontal edges should are faded on scroll, false
15644     *         otherwise
15645     *
15646     * @see #setHorizontalFadingEdgeEnabled(boolean)
15647     *
15648     * @attr ref android.R.styleable#View_requiresFadingEdge
15649     */
15650    public boolean isHorizontalFadingEdgeEnabled() {
15651        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
15652    }
15653
15654    /**
15655     * <p>Define whether the horizontal edges should be faded when this view
15656     * is scrolled horizontally.</p>
15657     *
15658     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
15659     *                                    be faded when the view is scrolled
15660     *                                    horizontally
15661     *
15662     * @see #isHorizontalFadingEdgeEnabled()
15663     *
15664     * @attr ref android.R.styleable#View_requiresFadingEdge
15665     */
15666    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
15667        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
15668            if (horizontalFadingEdgeEnabled) {
15669                initScrollCache();
15670            }
15671
15672            mViewFlags ^= FADING_EDGE_HORIZONTAL;
15673        }
15674    }
15675
15676    /**
15677     * <p>Indicate whether the vertical edges are faded when the view is
15678     * scrolled horizontally.</p>
15679     *
15680     * @return true if the vertical edges should are faded on scroll, false
15681     *         otherwise
15682     *
15683     * @see #setVerticalFadingEdgeEnabled(boolean)
15684     *
15685     * @attr ref android.R.styleable#View_requiresFadingEdge
15686     */
15687    public boolean isVerticalFadingEdgeEnabled() {
15688        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
15689    }
15690
15691    /**
15692     * <p>Define whether the vertical edges should be faded when this view
15693     * is scrolled vertically.</p>
15694     *
15695     * @param verticalFadingEdgeEnabled true if the vertical edges should
15696     *                                  be faded when the view is scrolled
15697     *                                  vertically
15698     *
15699     * @see #isVerticalFadingEdgeEnabled()
15700     *
15701     * @attr ref android.R.styleable#View_requiresFadingEdge
15702     */
15703    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
15704        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
15705            if (verticalFadingEdgeEnabled) {
15706                initScrollCache();
15707            }
15708
15709            mViewFlags ^= FADING_EDGE_VERTICAL;
15710        }
15711    }
15712
15713    /**
15714     * Returns the strength, or intensity, of the top faded edge. The strength is
15715     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
15716     * returns 0.0 or 1.0 but no value in between.
15717     *
15718     * Subclasses should override this method to provide a smoother fade transition
15719     * when scrolling occurs.
15720     *
15721     * @return the intensity of the top fade as a float between 0.0f and 1.0f
15722     */
15723    protected float getTopFadingEdgeStrength() {
15724        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
15725    }
15726
15727    /**
15728     * Returns the strength, or intensity, of the bottom faded edge. The strength is
15729     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
15730     * returns 0.0 or 1.0 but no value in between.
15731     *
15732     * Subclasses should override this method to provide a smoother fade transition
15733     * when scrolling occurs.
15734     *
15735     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
15736     */
15737    protected float getBottomFadingEdgeStrength() {
15738        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
15739                computeVerticalScrollRange() ? 1.0f : 0.0f;
15740    }
15741
15742    /**
15743     * Returns the strength, or intensity, of the left faded edge. The strength is
15744     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
15745     * returns 0.0 or 1.0 but no value in between.
15746     *
15747     * Subclasses should override this method to provide a smoother fade transition
15748     * when scrolling occurs.
15749     *
15750     * @return the intensity of the left fade as a float between 0.0f and 1.0f
15751     */
15752    protected float getLeftFadingEdgeStrength() {
15753        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
15754    }
15755
15756    /**
15757     * Returns the strength, or intensity, of the right faded edge. The strength is
15758     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
15759     * returns 0.0 or 1.0 but no value in between.
15760     *
15761     * Subclasses should override this method to provide a smoother fade transition
15762     * when scrolling occurs.
15763     *
15764     * @return the intensity of the right fade as a float between 0.0f and 1.0f
15765     */
15766    protected float getRightFadingEdgeStrength() {
15767        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
15768                computeHorizontalScrollRange() ? 1.0f : 0.0f;
15769    }
15770
15771    /**
15772     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
15773     * scrollbar is not drawn by default.</p>
15774     *
15775     * @return true if the horizontal scrollbar should be painted, false
15776     *         otherwise
15777     *
15778     * @see #setHorizontalScrollBarEnabled(boolean)
15779     */
15780    public boolean isHorizontalScrollBarEnabled() {
15781        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
15782    }
15783
15784    /**
15785     * <p>Define whether the horizontal scrollbar should be drawn or not. The
15786     * scrollbar is not drawn by default.</p>
15787     *
15788     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
15789     *                                   be painted
15790     *
15791     * @see #isHorizontalScrollBarEnabled()
15792     */
15793    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
15794        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
15795            mViewFlags ^= SCROLLBARS_HORIZONTAL;
15796            computeOpaqueFlags();
15797            resolvePadding();
15798        }
15799    }
15800
15801    /**
15802     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
15803     * scrollbar is not drawn by default.</p>
15804     *
15805     * @return true if the vertical scrollbar should be painted, false
15806     *         otherwise
15807     *
15808     * @see #setVerticalScrollBarEnabled(boolean)
15809     */
15810    public boolean isVerticalScrollBarEnabled() {
15811        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
15812    }
15813
15814    /**
15815     * <p>Define whether the vertical scrollbar should be drawn or not. The
15816     * scrollbar is not drawn by default.</p>
15817     *
15818     * @param verticalScrollBarEnabled true if the vertical scrollbar should
15819     *                                 be painted
15820     *
15821     * @see #isVerticalScrollBarEnabled()
15822     */
15823    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
15824        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
15825            mViewFlags ^= SCROLLBARS_VERTICAL;
15826            computeOpaqueFlags();
15827            resolvePadding();
15828        }
15829    }
15830
15831    /**
15832     * @hide
15833     */
15834    protected void recomputePadding() {
15835        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
15836    }
15837
15838    /**
15839     * Define whether scrollbars will fade when the view is not scrolling.
15840     *
15841     * @param fadeScrollbars whether to enable fading
15842     *
15843     * @attr ref android.R.styleable#View_fadeScrollbars
15844     */
15845    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
15846        initScrollCache();
15847        final ScrollabilityCache scrollabilityCache = mScrollCache;
15848        scrollabilityCache.fadeScrollBars = fadeScrollbars;
15849        if (fadeScrollbars) {
15850            scrollabilityCache.state = ScrollabilityCache.OFF;
15851        } else {
15852            scrollabilityCache.state = ScrollabilityCache.ON;
15853        }
15854    }
15855
15856    /**
15857     *
15858     * Returns true if scrollbars will fade when this view is not scrolling
15859     *
15860     * @return true if scrollbar fading is enabled
15861     *
15862     * @attr ref android.R.styleable#View_fadeScrollbars
15863     */
15864    public boolean isScrollbarFadingEnabled() {
15865        return mScrollCache != null && mScrollCache.fadeScrollBars;
15866    }
15867
15868    /**
15869     *
15870     * Returns the delay before scrollbars fade.
15871     *
15872     * @return the delay before scrollbars fade
15873     *
15874     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
15875     */
15876    public int getScrollBarDefaultDelayBeforeFade() {
15877        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
15878                mScrollCache.scrollBarDefaultDelayBeforeFade;
15879    }
15880
15881    /**
15882     * Define the delay before scrollbars fade.
15883     *
15884     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
15885     *
15886     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
15887     */
15888    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
15889        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
15890    }
15891
15892    /**
15893     *
15894     * Returns the scrollbar fade duration.
15895     *
15896     * @return the scrollbar fade duration, in milliseconds
15897     *
15898     * @attr ref android.R.styleable#View_scrollbarFadeDuration
15899     */
15900    public int getScrollBarFadeDuration() {
15901        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
15902                mScrollCache.scrollBarFadeDuration;
15903    }
15904
15905    /**
15906     * Define the scrollbar fade duration.
15907     *
15908     * @param scrollBarFadeDuration - the scrollbar fade duration, in milliseconds
15909     *
15910     * @attr ref android.R.styleable#View_scrollbarFadeDuration
15911     */
15912    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
15913        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
15914    }
15915
15916    /**
15917     *
15918     * Returns the scrollbar size.
15919     *
15920     * @return the scrollbar size
15921     *
15922     * @attr ref android.R.styleable#View_scrollbarSize
15923     */
15924    public int getScrollBarSize() {
15925        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
15926                mScrollCache.scrollBarSize;
15927    }
15928
15929    /**
15930     * Define the scrollbar size.
15931     *
15932     * @param scrollBarSize - the scrollbar size
15933     *
15934     * @attr ref android.R.styleable#View_scrollbarSize
15935     */
15936    public void setScrollBarSize(int scrollBarSize) {
15937        getScrollCache().scrollBarSize = scrollBarSize;
15938    }
15939
15940    /**
15941     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
15942     * inset. When inset, they add to the padding of the view. And the scrollbars
15943     * can be drawn inside the padding area or on the edge of the view. For example,
15944     * if a view has a background drawable and you want to draw the scrollbars
15945     * inside the padding specified by the drawable, you can use
15946     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
15947     * appear at the edge of the view, ignoring the padding, then you can use
15948     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
15949     * @param style the style of the scrollbars. Should be one of
15950     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
15951     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
15952     * @see #SCROLLBARS_INSIDE_OVERLAY
15953     * @see #SCROLLBARS_INSIDE_INSET
15954     * @see #SCROLLBARS_OUTSIDE_OVERLAY
15955     * @see #SCROLLBARS_OUTSIDE_INSET
15956     *
15957     * @attr ref android.R.styleable#View_scrollbarStyle
15958     */
15959    public void setScrollBarStyle(@ScrollBarStyle int style) {
15960        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
15961            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
15962            computeOpaqueFlags();
15963            resolvePadding();
15964        }
15965    }
15966
15967    /**
15968     * <p>Returns the current scrollbar style.</p>
15969     * @return the current scrollbar style
15970     * @see #SCROLLBARS_INSIDE_OVERLAY
15971     * @see #SCROLLBARS_INSIDE_INSET
15972     * @see #SCROLLBARS_OUTSIDE_OVERLAY
15973     * @see #SCROLLBARS_OUTSIDE_INSET
15974     *
15975     * @attr ref android.R.styleable#View_scrollbarStyle
15976     */
15977    @ViewDebug.ExportedProperty(mapping = {
15978            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
15979            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
15980            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
15981            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
15982    })
15983    @ScrollBarStyle
15984    public int getScrollBarStyle() {
15985        return mViewFlags & SCROLLBARS_STYLE_MASK;
15986    }
15987
15988    /**
15989     * <p>Compute the horizontal range that the horizontal scrollbar
15990     * represents.</p>
15991     *
15992     * <p>The range is expressed in arbitrary units that must be the same as the
15993     * units used by {@link #computeHorizontalScrollExtent()} and
15994     * {@link #computeHorizontalScrollOffset()}.</p>
15995     *
15996     * <p>The default range is the drawing width of this view.</p>
15997     *
15998     * @return the total horizontal range represented by the horizontal
15999     *         scrollbar
16000     *
16001     * @see #computeHorizontalScrollExtent()
16002     * @see #computeHorizontalScrollOffset()
16003     * @see android.widget.ScrollBarDrawable
16004     */
16005    protected int computeHorizontalScrollRange() {
16006        return getWidth();
16007    }
16008
16009    /**
16010     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
16011     * within the horizontal range. This value is used to compute the position
16012     * of the thumb within the scrollbar's track.</p>
16013     *
16014     * <p>The range is expressed in arbitrary units that must be the same as the
16015     * units used by {@link #computeHorizontalScrollRange()} and
16016     * {@link #computeHorizontalScrollExtent()}.</p>
16017     *
16018     * <p>The default offset is the scroll offset of this view.</p>
16019     *
16020     * @return the horizontal offset of the scrollbar's thumb
16021     *
16022     * @see #computeHorizontalScrollRange()
16023     * @see #computeHorizontalScrollExtent()
16024     * @see android.widget.ScrollBarDrawable
16025     */
16026    protected int computeHorizontalScrollOffset() {
16027        return mScrollX;
16028    }
16029
16030    /**
16031     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
16032     * within the horizontal range. This value is used to compute the length
16033     * of the thumb within the scrollbar's track.</p>
16034     *
16035     * <p>The range is expressed in arbitrary units that must be the same as the
16036     * units used by {@link #computeHorizontalScrollRange()} and
16037     * {@link #computeHorizontalScrollOffset()}.</p>
16038     *
16039     * <p>The default extent is the drawing width of this view.</p>
16040     *
16041     * @return the horizontal extent of the scrollbar's thumb
16042     *
16043     * @see #computeHorizontalScrollRange()
16044     * @see #computeHorizontalScrollOffset()
16045     * @see android.widget.ScrollBarDrawable
16046     */
16047    protected int computeHorizontalScrollExtent() {
16048        return getWidth();
16049    }
16050
16051    /**
16052     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
16053     *
16054     * <p>The range is expressed in arbitrary units that must be the same as the
16055     * units used by {@link #computeVerticalScrollExtent()} and
16056     * {@link #computeVerticalScrollOffset()}.</p>
16057     *
16058     * @return the total vertical range represented by the vertical scrollbar
16059     *
16060     * <p>The default range is the drawing height of this view.</p>
16061     *
16062     * @see #computeVerticalScrollExtent()
16063     * @see #computeVerticalScrollOffset()
16064     * @see android.widget.ScrollBarDrawable
16065     */
16066    protected int computeVerticalScrollRange() {
16067        return getHeight();
16068    }
16069
16070    /**
16071     * <p>Compute the vertical offset of the vertical scrollbar's thumb
16072     * within the horizontal range. This value is used to compute the position
16073     * of the thumb within the scrollbar's track.</p>
16074     *
16075     * <p>The range is expressed in arbitrary units that must be the same as the
16076     * units used by {@link #computeVerticalScrollRange()} and
16077     * {@link #computeVerticalScrollExtent()}.</p>
16078     *
16079     * <p>The default offset is the scroll offset of this view.</p>
16080     *
16081     * @return the vertical offset of the scrollbar's thumb
16082     *
16083     * @see #computeVerticalScrollRange()
16084     * @see #computeVerticalScrollExtent()
16085     * @see android.widget.ScrollBarDrawable
16086     */
16087    protected int computeVerticalScrollOffset() {
16088        return mScrollY;
16089    }
16090
16091    /**
16092     * <p>Compute the vertical extent of the vertical scrollbar's thumb
16093     * within the vertical range. This value is used to compute the length
16094     * of the thumb within the scrollbar's track.</p>
16095     *
16096     * <p>The range is expressed in arbitrary units that must be the same as the
16097     * units used by {@link #computeVerticalScrollRange()} and
16098     * {@link #computeVerticalScrollOffset()}.</p>
16099     *
16100     * <p>The default extent is the drawing height of this view.</p>
16101     *
16102     * @return the vertical extent of the scrollbar's thumb
16103     *
16104     * @see #computeVerticalScrollRange()
16105     * @see #computeVerticalScrollOffset()
16106     * @see android.widget.ScrollBarDrawable
16107     */
16108    protected int computeVerticalScrollExtent() {
16109        return getHeight();
16110    }
16111
16112    /**
16113     * Check if this view can be scrolled horizontally in a certain direction.
16114     *
16115     * @param direction Negative to check scrolling left, positive to check scrolling right.
16116     * @return true if this view can be scrolled in the specified direction, false otherwise.
16117     */
16118    public boolean canScrollHorizontally(int direction) {
16119        final int offset = computeHorizontalScrollOffset();
16120        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
16121        if (range == 0) return false;
16122        if (direction < 0) {
16123            return offset > 0;
16124        } else {
16125            return offset < range - 1;
16126        }
16127    }
16128
16129    /**
16130     * Check if this view can be scrolled vertically in a certain direction.
16131     *
16132     * @param direction Negative to check scrolling up, positive to check scrolling down.
16133     * @return true if this view can be scrolled in the specified direction, false otherwise.
16134     */
16135    public boolean canScrollVertically(int direction) {
16136        final int offset = computeVerticalScrollOffset();
16137        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
16138        if (range == 0) return false;
16139        if (direction < 0) {
16140            return offset > 0;
16141        } else {
16142            return offset < range - 1;
16143        }
16144    }
16145
16146    void getScrollIndicatorBounds(@NonNull Rect out) {
16147        out.left = mScrollX;
16148        out.right = mScrollX + mRight - mLeft;
16149        out.top = mScrollY;
16150        out.bottom = mScrollY + mBottom - mTop;
16151    }
16152
16153    private void onDrawScrollIndicators(Canvas c) {
16154        if ((mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK) == 0) {
16155            // No scroll indicators enabled.
16156            return;
16157        }
16158
16159        final Drawable dr = mScrollIndicatorDrawable;
16160        if (dr == null) {
16161            // Scroll indicators aren't supported here.
16162            return;
16163        }
16164
16165        final int h = dr.getIntrinsicHeight();
16166        final int w = dr.getIntrinsicWidth();
16167        final Rect rect = mAttachInfo.mTmpInvalRect;
16168        getScrollIndicatorBounds(rect);
16169
16170        if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_TOP) != 0) {
16171            final boolean canScrollUp = canScrollVertically(-1);
16172            if (canScrollUp) {
16173                dr.setBounds(rect.left, rect.top, rect.right, rect.top + h);
16174                dr.draw(c);
16175            }
16176        }
16177
16178        if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_BOTTOM) != 0) {
16179            final boolean canScrollDown = canScrollVertically(1);
16180            if (canScrollDown) {
16181                dr.setBounds(rect.left, rect.bottom - h, rect.right, rect.bottom);
16182                dr.draw(c);
16183            }
16184        }
16185
16186        final int leftRtl;
16187        final int rightRtl;
16188        if (getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
16189            leftRtl = PFLAG3_SCROLL_INDICATOR_END;
16190            rightRtl = PFLAG3_SCROLL_INDICATOR_START;
16191        } else {
16192            leftRtl = PFLAG3_SCROLL_INDICATOR_START;
16193            rightRtl = PFLAG3_SCROLL_INDICATOR_END;
16194        }
16195
16196        final int leftMask = PFLAG3_SCROLL_INDICATOR_LEFT | leftRtl;
16197        if ((mPrivateFlags3 & leftMask) != 0) {
16198            final boolean canScrollLeft = canScrollHorizontally(-1);
16199            if (canScrollLeft) {
16200                dr.setBounds(rect.left, rect.top, rect.left + w, rect.bottom);
16201                dr.draw(c);
16202            }
16203        }
16204
16205        final int rightMask = PFLAG3_SCROLL_INDICATOR_RIGHT | rightRtl;
16206        if ((mPrivateFlags3 & rightMask) != 0) {
16207            final boolean canScrollRight = canScrollHorizontally(1);
16208            if (canScrollRight) {
16209                dr.setBounds(rect.right - w, rect.top, rect.right, rect.bottom);
16210                dr.draw(c);
16211            }
16212        }
16213    }
16214
16215    private void getHorizontalScrollBarBounds(@Nullable Rect drawBounds,
16216            @Nullable Rect touchBounds) {
16217        final Rect bounds = drawBounds != null ? drawBounds : touchBounds;
16218        if (bounds == null) {
16219            return;
16220        }
16221        final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
16222        final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled()
16223                && !isVerticalScrollBarHidden();
16224        final int size = getHorizontalScrollbarHeight();
16225        final int verticalScrollBarGap = drawVerticalScrollBar ?
16226                getVerticalScrollbarWidth() : 0;
16227        final int width = mRight - mLeft;
16228        final int height = mBottom - mTop;
16229        bounds.top = mScrollY + height - size - (mUserPaddingBottom & inside);
16230        bounds.left = mScrollX + (mPaddingLeft & inside);
16231        bounds.right = mScrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
16232        bounds.bottom = bounds.top + size;
16233
16234        if (touchBounds == null) {
16235            return;
16236        }
16237        if (touchBounds != bounds) {
16238            touchBounds.set(bounds);
16239        }
16240        final int minTouchTarget = mScrollCache.scrollBarMinTouchTarget;
16241        if (touchBounds.height() < minTouchTarget) {
16242            final int adjust = (minTouchTarget - touchBounds.height()) / 2;
16243            touchBounds.bottom = Math.min(touchBounds.bottom + adjust, mScrollY + height);
16244            touchBounds.top = touchBounds.bottom - minTouchTarget;
16245        }
16246        if (touchBounds.width() < minTouchTarget) {
16247            final int adjust = (minTouchTarget - touchBounds.width()) / 2;
16248            touchBounds.left -= adjust;
16249            touchBounds.right = touchBounds.left + minTouchTarget;
16250        }
16251    }
16252
16253    private void getVerticalScrollBarBounds(@Nullable Rect bounds, @Nullable Rect touchBounds) {
16254        if (mRoundScrollbarRenderer == null) {
16255            getStraightVerticalScrollBarBounds(bounds, touchBounds);
16256        } else {
16257            getRoundVerticalScrollBarBounds(bounds != null ? bounds : touchBounds);
16258        }
16259    }
16260
16261    private void getRoundVerticalScrollBarBounds(Rect bounds) {
16262        final int width = mRight - mLeft;
16263        final int height = mBottom - mTop;
16264        // Do not take padding into account as we always want the scrollbars
16265        // to hug the screen for round wearable devices.
16266        bounds.left = mScrollX;
16267        bounds.top = mScrollY;
16268        bounds.right = bounds.left + width;
16269        bounds.bottom = mScrollY + height;
16270    }
16271
16272    private void getStraightVerticalScrollBarBounds(@Nullable Rect drawBounds,
16273            @Nullable Rect touchBounds) {
16274        final Rect bounds = drawBounds != null ? drawBounds : touchBounds;
16275        if (bounds == null) {
16276            return;
16277        }
16278        final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
16279        final int size = getVerticalScrollbarWidth();
16280        int verticalScrollbarPosition = mVerticalScrollbarPosition;
16281        if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
16282            verticalScrollbarPosition = isLayoutRtl() ?
16283                    SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
16284        }
16285        final int width = mRight - mLeft;
16286        final int height = mBottom - mTop;
16287        switch (verticalScrollbarPosition) {
16288            default:
16289            case SCROLLBAR_POSITION_RIGHT:
16290                bounds.left = mScrollX + width - size - (mUserPaddingRight & inside);
16291                break;
16292            case SCROLLBAR_POSITION_LEFT:
16293                bounds.left = mScrollX + (mUserPaddingLeft & inside);
16294                break;
16295        }
16296        bounds.top = mScrollY + (mPaddingTop & inside);
16297        bounds.right = bounds.left + size;
16298        bounds.bottom = mScrollY + height - (mUserPaddingBottom & inside);
16299
16300        if (touchBounds == null) {
16301            return;
16302        }
16303        if (touchBounds != bounds) {
16304            touchBounds.set(bounds);
16305        }
16306        final int minTouchTarget = mScrollCache.scrollBarMinTouchTarget;
16307        if (touchBounds.width() < minTouchTarget) {
16308            final int adjust = (minTouchTarget - touchBounds.width()) / 2;
16309            if (verticalScrollbarPosition == SCROLLBAR_POSITION_RIGHT) {
16310                touchBounds.right = Math.min(touchBounds.right + adjust, mScrollX + width);
16311                touchBounds.left = touchBounds.right - minTouchTarget;
16312            } else {
16313                touchBounds.left = Math.max(touchBounds.left + adjust, mScrollX);
16314                touchBounds.right = touchBounds.left + minTouchTarget;
16315            }
16316        }
16317        if (touchBounds.height() < minTouchTarget) {
16318            final int adjust = (minTouchTarget - touchBounds.height()) / 2;
16319            touchBounds.top -= adjust;
16320            touchBounds.bottom = touchBounds.top + minTouchTarget;
16321        }
16322    }
16323
16324    /**
16325     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
16326     * scrollbars are painted only if they have been awakened first.</p>
16327     *
16328     * @param canvas the canvas on which to draw the scrollbars
16329     *
16330     * @see #awakenScrollBars(int)
16331     */
16332    protected final void onDrawScrollBars(Canvas canvas) {
16333        // scrollbars are drawn only when the animation is running
16334        final ScrollabilityCache cache = mScrollCache;
16335
16336        if (cache != null) {
16337
16338            int state = cache.state;
16339
16340            if (state == ScrollabilityCache.OFF) {
16341                return;
16342            }
16343
16344            boolean invalidate = false;
16345
16346            if (state == ScrollabilityCache.FADING) {
16347                // We're fading -- get our fade interpolation
16348                if (cache.interpolatorValues == null) {
16349                    cache.interpolatorValues = new float[1];
16350                }
16351
16352                float[] values = cache.interpolatorValues;
16353
16354                // Stops the animation if we're done
16355                if (cache.scrollBarInterpolator.timeToValues(values) ==
16356                        Interpolator.Result.FREEZE_END) {
16357                    cache.state = ScrollabilityCache.OFF;
16358                } else {
16359                    cache.scrollBar.mutate().setAlpha(Math.round(values[0]));
16360                }
16361
16362                // This will make the scroll bars inval themselves after
16363                // drawing. We only want this when we're fading so that
16364                // we prevent excessive redraws
16365                invalidate = true;
16366            } else {
16367                // We're just on -- but we may have been fading before so
16368                // reset alpha
16369                cache.scrollBar.mutate().setAlpha(255);
16370            }
16371
16372            final boolean drawHorizontalScrollBar = isHorizontalScrollBarEnabled();
16373            final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled()
16374                    && !isVerticalScrollBarHidden();
16375
16376            // Fork out the scroll bar drawing for round wearable devices.
16377            if (mRoundScrollbarRenderer != null) {
16378                if (drawVerticalScrollBar) {
16379                    final Rect bounds = cache.mScrollBarBounds;
16380                    getVerticalScrollBarBounds(bounds, null);
16381                    mRoundScrollbarRenderer.drawRoundScrollbars(
16382                            canvas, (float) cache.scrollBar.getAlpha() / 255f, bounds);
16383                    if (invalidate) {
16384                        invalidate();
16385                    }
16386                }
16387                // Do not draw horizontal scroll bars for round wearable devices.
16388            } else if (drawVerticalScrollBar || drawHorizontalScrollBar) {
16389                final ScrollBarDrawable scrollBar = cache.scrollBar;
16390
16391                if (drawHorizontalScrollBar) {
16392                    scrollBar.setParameters(computeHorizontalScrollRange(),
16393                            computeHorizontalScrollOffset(),
16394                            computeHorizontalScrollExtent(), false);
16395                    final Rect bounds = cache.mScrollBarBounds;
16396                    getHorizontalScrollBarBounds(bounds, null);
16397                    onDrawHorizontalScrollBar(canvas, scrollBar, bounds.left, bounds.top,
16398                            bounds.right, bounds.bottom);
16399                    if (invalidate) {
16400                        invalidate(bounds);
16401                    }
16402                }
16403
16404                if (drawVerticalScrollBar) {
16405                    scrollBar.setParameters(computeVerticalScrollRange(),
16406                            computeVerticalScrollOffset(),
16407                            computeVerticalScrollExtent(), true);
16408                    final Rect bounds = cache.mScrollBarBounds;
16409                    getVerticalScrollBarBounds(bounds, null);
16410                    onDrawVerticalScrollBar(canvas, scrollBar, bounds.left, bounds.top,
16411                            bounds.right, bounds.bottom);
16412                    if (invalidate) {
16413                        invalidate(bounds);
16414                    }
16415                }
16416            }
16417        }
16418    }
16419
16420    /**
16421     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
16422     * FastScroller is visible.
16423     * @return whether to temporarily hide the vertical scrollbar
16424     * @hide
16425     */
16426    protected boolean isVerticalScrollBarHidden() {
16427        return false;
16428    }
16429
16430    /**
16431     * <p>Draw the horizontal scrollbar if
16432     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
16433     *
16434     * @param canvas the canvas on which to draw the scrollbar
16435     * @param scrollBar the scrollbar's drawable
16436     *
16437     * @see #isHorizontalScrollBarEnabled()
16438     * @see #computeHorizontalScrollRange()
16439     * @see #computeHorizontalScrollExtent()
16440     * @see #computeHorizontalScrollOffset()
16441     * @see android.widget.ScrollBarDrawable
16442     * @hide
16443     */
16444    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
16445            int l, int t, int r, int b) {
16446        scrollBar.setBounds(l, t, r, b);
16447        scrollBar.draw(canvas);
16448    }
16449
16450    /**
16451     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
16452     * returns true.</p>
16453     *
16454     * @param canvas the canvas on which to draw the scrollbar
16455     * @param scrollBar the scrollbar's drawable
16456     *
16457     * @see #isVerticalScrollBarEnabled()
16458     * @see #computeVerticalScrollRange()
16459     * @see #computeVerticalScrollExtent()
16460     * @see #computeVerticalScrollOffset()
16461     * @see android.widget.ScrollBarDrawable
16462     * @hide
16463     */
16464    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
16465            int l, int t, int r, int b) {
16466        scrollBar.setBounds(l, t, r, b);
16467        scrollBar.draw(canvas);
16468    }
16469
16470    /**
16471     * Implement this to do your drawing.
16472     *
16473     * @param canvas the canvas on which the background will be drawn
16474     */
16475    protected void onDraw(Canvas canvas) {
16476    }
16477
16478    /*
16479     * Caller is responsible for calling requestLayout if necessary.
16480     * (This allows addViewInLayout to not request a new layout.)
16481     */
16482    void assignParent(ViewParent parent) {
16483        if (mParent == null) {
16484            mParent = parent;
16485        } else if (parent == null) {
16486            mParent = null;
16487        } else {
16488            throw new RuntimeException("view " + this + " being added, but"
16489                    + " it already has a parent");
16490        }
16491    }
16492
16493    /**
16494     * This is called when the view is attached to a window.  At this point it
16495     * has a Surface and will start drawing.  Note that this function is
16496     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
16497     * however it may be called any time before the first onDraw -- including
16498     * before or after {@link #onMeasure(int, int)}.
16499     *
16500     * @see #onDetachedFromWindow()
16501     */
16502    @CallSuper
16503    protected void onAttachedToWindow() {
16504        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
16505            mParent.requestTransparentRegion(this);
16506        }
16507
16508        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
16509
16510        jumpDrawablesToCurrentState();
16511
16512        resetSubtreeAccessibilityStateChanged();
16513
16514        // rebuild, since Outline not maintained while View is detached
16515        rebuildOutline();
16516
16517        if (isFocused()) {
16518            InputMethodManager imm = InputMethodManager.peekInstance();
16519            if (imm != null) {
16520                imm.focusIn(this);
16521            }
16522        }
16523    }
16524
16525    /**
16526     * Resolve all RTL related properties.
16527     *
16528     * @return true if resolution of RTL properties has been done
16529     *
16530     * @hide
16531     */
16532    public boolean resolveRtlPropertiesIfNeeded() {
16533        if (!needRtlPropertiesResolution()) return false;
16534
16535        // Order is important here: LayoutDirection MUST be resolved first
16536        if (!isLayoutDirectionResolved()) {
16537            resolveLayoutDirection();
16538            resolveLayoutParams();
16539        }
16540        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
16541        if (!isTextDirectionResolved()) {
16542            resolveTextDirection();
16543        }
16544        if (!isTextAlignmentResolved()) {
16545            resolveTextAlignment();
16546        }
16547        // Should resolve Drawables before Padding because we need the layout direction of the
16548        // Drawable to correctly resolve Padding.
16549        if (!areDrawablesResolved()) {
16550            resolveDrawables();
16551        }
16552        if (!isPaddingResolved()) {
16553            resolvePadding();
16554        }
16555        onRtlPropertiesChanged(getLayoutDirection());
16556        return true;
16557    }
16558
16559    /**
16560     * Reset resolution of all RTL related properties.
16561     *
16562     * @hide
16563     */
16564    public void resetRtlProperties() {
16565        resetResolvedLayoutDirection();
16566        resetResolvedTextDirection();
16567        resetResolvedTextAlignment();
16568        resetResolvedPadding();
16569        resetResolvedDrawables();
16570    }
16571
16572    /**
16573     * @see #onScreenStateChanged(int)
16574     */
16575    void dispatchScreenStateChanged(int screenState) {
16576        onScreenStateChanged(screenState);
16577    }
16578
16579    /**
16580     * This method is called whenever the state of the screen this view is
16581     * attached to changes. A state change will usually occurs when the screen
16582     * turns on or off (whether it happens automatically or the user does it
16583     * manually.)
16584     *
16585     * @param screenState The new state of the screen. Can be either
16586     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
16587     */
16588    public void onScreenStateChanged(int screenState) {
16589    }
16590
16591    /**
16592     * @see #onMovedToDisplay(int, Configuration)
16593     */
16594    void dispatchMovedToDisplay(Display display, Configuration config) {
16595        mAttachInfo.mDisplay = display;
16596        mAttachInfo.mDisplayState = display.getState();
16597        onMovedToDisplay(display.getDisplayId(), config);
16598    }
16599
16600    /**
16601     * Called by the system when the hosting activity is moved from one display to another without
16602     * recreation. This means that the activity is declared to handle all changes to configuration
16603     * that happened when it was switched to another display, so it wasn't destroyed and created
16604     * again.
16605     *
16606     * <p>This call will be followed by {@link #onConfigurationChanged(Configuration)} if the
16607     * applied configuration actually changed. It is up to app developer to choose whether to handle
16608     * the change in this method or in the following {@link #onConfigurationChanged(Configuration)}
16609     * call.
16610     *
16611     * <p>Use this callback to track changes to the displays if some functionality relies on an
16612     * association with some display properties.
16613     *
16614     * @param displayId The id of the display to which the view was moved.
16615     * @param config Configuration of the resources on new display after move.
16616     *
16617     * @see #onConfigurationChanged(Configuration)
16618     */
16619    public void onMovedToDisplay(int displayId, Configuration config) {
16620    }
16621
16622    /**
16623     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
16624     */
16625    private boolean hasRtlSupport() {
16626        return mContext.getApplicationInfo().hasRtlSupport();
16627    }
16628
16629    /**
16630     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
16631     * RTL not supported)
16632     */
16633    private boolean isRtlCompatibilityMode() {
16634        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
16635        return targetSdkVersion < Build.VERSION_CODES.JELLY_BEAN_MR1 || !hasRtlSupport();
16636    }
16637
16638    /**
16639     * @return true if RTL properties need resolution.
16640     *
16641     */
16642    private boolean needRtlPropertiesResolution() {
16643        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
16644    }
16645
16646    /**
16647     * Called when any RTL property (layout direction or text direction or text alignment) has
16648     * been changed.
16649     *
16650     * Subclasses need to override this method to take care of cached information that depends on the
16651     * resolved layout direction, or to inform child views that inherit their layout direction.
16652     *
16653     * The default implementation does nothing.
16654     *
16655     * @param layoutDirection the direction of the layout
16656     *
16657     * @see #LAYOUT_DIRECTION_LTR
16658     * @see #LAYOUT_DIRECTION_RTL
16659     */
16660    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
16661    }
16662
16663    /**
16664     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
16665     * that the parent directionality can and will be resolved before its children.
16666     *
16667     * @return true if resolution has been done, false otherwise.
16668     *
16669     * @hide
16670     */
16671    public boolean resolveLayoutDirection() {
16672        // Clear any previous layout direction resolution
16673        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
16674
16675        if (hasRtlSupport()) {
16676            // Set resolved depending on layout direction
16677            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
16678                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
16679                case LAYOUT_DIRECTION_INHERIT:
16680                    // We cannot resolve yet. LTR is by default and let the resolution happen again
16681                    // later to get the correct resolved value
16682                    if (!canResolveLayoutDirection()) return false;
16683
16684                    // Parent has not yet resolved, LTR is still the default
16685                    try {
16686                        if (!mParent.isLayoutDirectionResolved()) return false;
16687
16688                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
16689                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
16690                        }
16691                    } catch (AbstractMethodError e) {
16692                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
16693                                " does not fully implement ViewParent", e);
16694                    }
16695                    break;
16696                case LAYOUT_DIRECTION_RTL:
16697                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
16698                    break;
16699                case LAYOUT_DIRECTION_LOCALE:
16700                    if((LAYOUT_DIRECTION_RTL ==
16701                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
16702                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
16703                    }
16704                    break;
16705                default:
16706                    // Nothing to do, LTR by default
16707            }
16708        }
16709
16710        // Set to resolved
16711        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
16712        return true;
16713    }
16714
16715    /**
16716     * Check if layout direction resolution can be done.
16717     *
16718     * @return true if layout direction resolution can be done otherwise return false.
16719     */
16720    public boolean canResolveLayoutDirection() {
16721        switch (getRawLayoutDirection()) {
16722            case LAYOUT_DIRECTION_INHERIT:
16723                if (mParent != null) {
16724                    try {
16725                        return mParent.canResolveLayoutDirection();
16726                    } catch (AbstractMethodError e) {
16727                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
16728                                " does not fully implement ViewParent", e);
16729                    }
16730                }
16731                return false;
16732
16733            default:
16734                return true;
16735        }
16736    }
16737
16738    /**
16739     * Reset the resolved layout direction. Layout direction will be resolved during a call to
16740     * {@link #onMeasure(int, int)}.
16741     *
16742     * @hide
16743     */
16744    public void resetResolvedLayoutDirection() {
16745        // Reset the current resolved bits
16746        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
16747    }
16748
16749    /**
16750     * @return true if the layout direction is inherited.
16751     *
16752     * @hide
16753     */
16754    public boolean isLayoutDirectionInherited() {
16755        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
16756    }
16757
16758    /**
16759     * @return true if layout direction has been resolved.
16760     */
16761    public boolean isLayoutDirectionResolved() {
16762        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
16763    }
16764
16765    /**
16766     * Return if padding has been resolved
16767     *
16768     * @hide
16769     */
16770    boolean isPaddingResolved() {
16771        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
16772    }
16773
16774    /**
16775     * Resolves padding depending on layout direction, if applicable, and
16776     * recomputes internal padding values to adjust for scroll bars.
16777     *
16778     * @hide
16779     */
16780    public void resolvePadding() {
16781        final int resolvedLayoutDirection = getLayoutDirection();
16782
16783        if (!isRtlCompatibilityMode()) {
16784            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
16785            // If start / end padding are defined, they will be resolved (hence overriding) to
16786            // left / right or right / left depending on the resolved layout direction.
16787            // If start / end padding are not defined, use the left / right ones.
16788            if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
16789                Rect padding = sThreadLocal.get();
16790                if (padding == null) {
16791                    padding = new Rect();
16792                    sThreadLocal.set(padding);
16793                }
16794                mBackground.getPadding(padding);
16795                if (!mLeftPaddingDefined) {
16796                    mUserPaddingLeftInitial = padding.left;
16797                }
16798                if (!mRightPaddingDefined) {
16799                    mUserPaddingRightInitial = padding.right;
16800                }
16801            }
16802            switch (resolvedLayoutDirection) {
16803                case LAYOUT_DIRECTION_RTL:
16804                    if (mUserPaddingStart != UNDEFINED_PADDING) {
16805                        mUserPaddingRight = mUserPaddingStart;
16806                    } else {
16807                        mUserPaddingRight = mUserPaddingRightInitial;
16808                    }
16809                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
16810                        mUserPaddingLeft = mUserPaddingEnd;
16811                    } else {
16812                        mUserPaddingLeft = mUserPaddingLeftInitial;
16813                    }
16814                    break;
16815                case LAYOUT_DIRECTION_LTR:
16816                default:
16817                    if (mUserPaddingStart != UNDEFINED_PADDING) {
16818                        mUserPaddingLeft = mUserPaddingStart;
16819                    } else {
16820                        mUserPaddingLeft = mUserPaddingLeftInitial;
16821                    }
16822                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
16823                        mUserPaddingRight = mUserPaddingEnd;
16824                    } else {
16825                        mUserPaddingRight = mUserPaddingRightInitial;
16826                    }
16827            }
16828
16829            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
16830        }
16831
16832        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
16833        onRtlPropertiesChanged(resolvedLayoutDirection);
16834
16835        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
16836    }
16837
16838    /**
16839     * Reset the resolved layout direction.
16840     *
16841     * @hide
16842     */
16843    public void resetResolvedPadding() {
16844        resetResolvedPaddingInternal();
16845    }
16846
16847    /**
16848     * Used when we only want to reset *this* view's padding and not trigger overrides
16849     * in ViewGroup that reset children too.
16850     */
16851    void resetResolvedPaddingInternal() {
16852        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
16853    }
16854
16855    /**
16856     * This is called when the view is detached from a window.  At this point it
16857     * no longer has a surface for drawing.
16858     *
16859     * @see #onAttachedToWindow()
16860     */
16861    @CallSuper
16862    protected void onDetachedFromWindow() {
16863    }
16864
16865    /**
16866     * This is a framework-internal mirror of onDetachedFromWindow() that's called
16867     * after onDetachedFromWindow().
16868     *
16869     * If you override this you *MUST* call super.onDetachedFromWindowInternal()!
16870     * The super method should be called at the end of the overridden method to ensure
16871     * subclasses are destroyed first
16872     *
16873     * @hide
16874     */
16875    @CallSuper
16876    protected void onDetachedFromWindowInternal() {
16877        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
16878        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
16879        mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH;
16880
16881        removeUnsetPressCallback();
16882        removeLongPressCallback();
16883        removePerformClickCallback();
16884        removeSendViewScrolledAccessibilityEventCallback();
16885        stopNestedScroll();
16886
16887        // Anything that started animating right before detach should already
16888        // be in its final state when re-attached.
16889        jumpDrawablesToCurrentState();
16890
16891        destroyDrawingCache();
16892
16893        cleanupDraw();
16894        mCurrentAnimation = null;
16895
16896        if ((mViewFlags & TOOLTIP) == TOOLTIP) {
16897            hideTooltip();
16898        }
16899    }
16900
16901    private void cleanupDraw() {
16902        resetDisplayList();
16903        if (mAttachInfo != null) {
16904            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
16905        }
16906    }
16907
16908    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
16909    }
16910
16911    /**
16912     * @return The number of times this view has been attached to a window
16913     */
16914    protected int getWindowAttachCount() {
16915        return mWindowAttachCount;
16916    }
16917
16918    /**
16919     * Retrieve a unique token identifying the window this view is attached to.
16920     * @return Return the window's token for use in
16921     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
16922     */
16923    public IBinder getWindowToken() {
16924        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
16925    }
16926
16927    /**
16928     * Retrieve the {@link WindowId} for the window this view is
16929     * currently attached to.
16930     */
16931    public WindowId getWindowId() {
16932        if (mAttachInfo == null) {
16933            return null;
16934        }
16935        if (mAttachInfo.mWindowId == null) {
16936            try {
16937                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
16938                        mAttachInfo.mWindowToken);
16939                mAttachInfo.mWindowId = new WindowId(
16940                        mAttachInfo.mIWindowId);
16941            } catch (RemoteException e) {
16942            }
16943        }
16944        return mAttachInfo.mWindowId;
16945    }
16946
16947    /**
16948     * Retrieve a unique token identifying the top-level "real" window of
16949     * the window that this view is attached to.  That is, this is like
16950     * {@link #getWindowToken}, except if the window this view in is a panel
16951     * window (attached to another containing window), then the token of
16952     * the containing window is returned instead.
16953     *
16954     * @return Returns the associated window token, either
16955     * {@link #getWindowToken()} or the containing window's token.
16956     */
16957    public IBinder getApplicationWindowToken() {
16958        AttachInfo ai = mAttachInfo;
16959        if (ai != null) {
16960            IBinder appWindowToken = ai.mPanelParentWindowToken;
16961            if (appWindowToken == null) {
16962                appWindowToken = ai.mWindowToken;
16963            }
16964            return appWindowToken;
16965        }
16966        return null;
16967    }
16968
16969    /**
16970     * Gets the logical display to which the view's window has been attached.
16971     *
16972     * @return The logical display, or null if the view is not currently attached to a window.
16973     */
16974    public Display getDisplay() {
16975        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
16976    }
16977
16978    /**
16979     * Retrieve private session object this view hierarchy is using to
16980     * communicate with the window manager.
16981     * @return the session object to communicate with the window manager
16982     */
16983    /*package*/ IWindowSession getWindowSession() {
16984        return mAttachInfo != null ? mAttachInfo.mSession : null;
16985    }
16986
16987    /**
16988     * Return the visibility value of the least visible component passed.
16989     */
16990    int combineVisibility(int vis1, int vis2) {
16991        // This works because VISIBLE < INVISIBLE < GONE.
16992        return Math.max(vis1, vis2);
16993    }
16994
16995    /**
16996     * @param info the {@link android.view.View.AttachInfo} to associated with
16997     *        this view
16998     */
16999    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
17000        mAttachInfo = info;
17001        if (mOverlay != null) {
17002            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
17003        }
17004        mWindowAttachCount++;
17005        // We will need to evaluate the drawable state at least once.
17006        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
17007        if (mFloatingTreeObserver != null) {
17008            info.mTreeObserver.merge(mFloatingTreeObserver);
17009            mFloatingTreeObserver = null;
17010        }
17011
17012        registerPendingFrameMetricsObservers();
17013
17014        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
17015            mAttachInfo.mScrollContainers.add(this);
17016            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
17017        }
17018        // Transfer all pending runnables.
17019        if (mRunQueue != null) {
17020            mRunQueue.executeActions(info.mHandler);
17021            mRunQueue = null;
17022        }
17023        performCollectViewAttributes(mAttachInfo, visibility);
17024        onAttachedToWindow();
17025
17026        ListenerInfo li = mListenerInfo;
17027        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
17028                li != null ? li.mOnAttachStateChangeListeners : null;
17029        if (listeners != null && listeners.size() > 0) {
17030            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
17031            // perform the dispatching. The iterator is a safe guard against listeners that
17032            // could mutate the list by calling the various add/remove methods. This prevents
17033            // the array from being modified while we iterate it.
17034            for (OnAttachStateChangeListener listener : listeners) {
17035                listener.onViewAttachedToWindow(this);
17036            }
17037        }
17038
17039        int vis = info.mWindowVisibility;
17040        if (vis != GONE) {
17041            onWindowVisibilityChanged(vis);
17042            if (isShown()) {
17043                // Calling onVisibilityAggregated directly here since the subtree will also
17044                // receive dispatchAttachedToWindow and this same call
17045                onVisibilityAggregated(vis == VISIBLE);
17046            }
17047        }
17048
17049        // Send onVisibilityChanged directly instead of dispatchVisibilityChanged.
17050        // As all views in the subtree will already receive dispatchAttachedToWindow
17051        // traversing the subtree again here is not desired.
17052        onVisibilityChanged(this, visibility);
17053
17054        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
17055            // If nobody has evaluated the drawable state yet, then do it now.
17056            refreshDrawableState();
17057        }
17058        needGlobalAttributesUpdate(false);
17059
17060        notifyEnterOrExitForAutoFillIfNeeded(true);
17061    }
17062
17063    void dispatchDetachedFromWindow() {
17064        AttachInfo info = mAttachInfo;
17065        if (info != null) {
17066            int vis = info.mWindowVisibility;
17067            if (vis != GONE) {
17068                onWindowVisibilityChanged(GONE);
17069                if (isShown()) {
17070                    // Invoking onVisibilityAggregated directly here since the subtree
17071                    // will also receive detached from window
17072                    onVisibilityAggregated(false);
17073                }
17074            }
17075        }
17076
17077        onDetachedFromWindow();
17078        onDetachedFromWindowInternal();
17079
17080        InputMethodManager imm = InputMethodManager.peekInstance();
17081        if (imm != null) {
17082            imm.onViewDetachedFromWindow(this);
17083        }
17084
17085        ListenerInfo li = mListenerInfo;
17086        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
17087                li != null ? li.mOnAttachStateChangeListeners : null;
17088        if (listeners != null && listeners.size() > 0) {
17089            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
17090            // perform the dispatching. The iterator is a safe guard against listeners that
17091            // could mutate the list by calling the various add/remove methods. This prevents
17092            // the array from being modified while we iterate it.
17093            for (OnAttachStateChangeListener listener : listeners) {
17094                listener.onViewDetachedFromWindow(this);
17095            }
17096        }
17097
17098        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
17099            mAttachInfo.mScrollContainers.remove(this);
17100            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
17101        }
17102
17103        mAttachInfo = null;
17104        if (mOverlay != null) {
17105            mOverlay.getOverlayView().dispatchDetachedFromWindow();
17106        }
17107
17108        notifyEnterOrExitForAutoFillIfNeeded(false);
17109    }
17110
17111    /**
17112     * Cancel any deferred high-level input events that were previously posted to the event queue.
17113     *
17114     * <p>Many views post high-level events such as click handlers to the event queue
17115     * to run deferred in order to preserve a desired user experience - clearing visible
17116     * pressed states before executing, etc. This method will abort any events of this nature
17117     * that are currently in flight.</p>
17118     *
17119     * <p>Custom views that generate their own high-level deferred input events should override
17120     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
17121     *
17122     * <p>This will also cancel pending input events for any child views.</p>
17123     *
17124     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
17125     * This will not impact newer events posted after this call that may occur as a result of
17126     * lower-level input events still waiting in the queue. If you are trying to prevent
17127     * double-submitted  events for the duration of some sort of asynchronous transaction
17128     * you should also take other steps to protect against unexpected double inputs e.g. calling
17129     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
17130     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
17131     */
17132    public final void cancelPendingInputEvents() {
17133        dispatchCancelPendingInputEvents();
17134    }
17135
17136    /**
17137     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
17138     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
17139     */
17140    void dispatchCancelPendingInputEvents() {
17141        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
17142        onCancelPendingInputEvents();
17143        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
17144            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
17145                    " did not call through to super.onCancelPendingInputEvents()");
17146        }
17147    }
17148
17149    /**
17150     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
17151     * a parent view.
17152     *
17153     * <p>This method is responsible for removing any pending high-level input events that were
17154     * posted to the event queue to run later. Custom view classes that post their own deferred
17155     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
17156     * {@link android.os.Handler} should override this method, call
17157     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
17158     * </p>
17159     */
17160    public void onCancelPendingInputEvents() {
17161        removePerformClickCallback();
17162        cancelLongPress();
17163        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
17164    }
17165
17166    /**
17167     * Store this view hierarchy's frozen state into the given container.
17168     *
17169     * @param container The SparseArray in which to save the view's state.
17170     *
17171     * @see #restoreHierarchyState(android.util.SparseArray)
17172     * @see #dispatchSaveInstanceState(android.util.SparseArray)
17173     * @see #onSaveInstanceState()
17174     */
17175    public void saveHierarchyState(SparseArray<Parcelable> container) {
17176        dispatchSaveInstanceState(container);
17177    }
17178
17179    /**
17180     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
17181     * this view and its children. May be overridden to modify how freezing happens to a
17182     * view's children; for example, some views may want to not store state for their children.
17183     *
17184     * @param container The SparseArray in which to save the view's state.
17185     *
17186     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
17187     * @see #saveHierarchyState(android.util.SparseArray)
17188     * @see #onSaveInstanceState()
17189     */
17190    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
17191        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
17192            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
17193            Parcelable state = onSaveInstanceState();
17194            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
17195                throw new IllegalStateException(
17196                        "Derived class did not call super.onSaveInstanceState()");
17197            }
17198            if (state != null) {
17199                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
17200                // + ": " + state);
17201                container.put(mID, state);
17202            }
17203        }
17204    }
17205
17206    /**
17207     * Hook allowing a view to generate a representation of its internal state
17208     * that can later be used to create a new instance with that same state.
17209     * This state should only contain information that is not persistent or can
17210     * not be reconstructed later. For example, you will never store your
17211     * current position on screen because that will be computed again when a
17212     * new instance of the view is placed in its view hierarchy.
17213     * <p>
17214     * Some examples of things you may store here: the current cursor position
17215     * in a text view (but usually not the text itself since that is stored in a
17216     * content provider or other persistent storage), the currently selected
17217     * item in a list view.
17218     *
17219     * @return Returns a Parcelable object containing the view's current dynamic
17220     *         state, or null if there is nothing interesting to save. The
17221     *         default implementation returns null.
17222     * @see #onRestoreInstanceState(android.os.Parcelable)
17223     * @see #saveHierarchyState(android.util.SparseArray)
17224     * @see #dispatchSaveInstanceState(android.util.SparseArray)
17225     * @see #setSaveEnabled(boolean)
17226     */
17227    @CallSuper
17228    protected Parcelable onSaveInstanceState() {
17229        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
17230        if (mStartActivityRequestWho != null || isAutofilled()
17231                || mAccessibilityViewId > LAST_APP_ACCESSIBILITY_ID) {
17232            BaseSavedState state = new BaseSavedState(AbsSavedState.EMPTY_STATE);
17233
17234            if (mStartActivityRequestWho != null) {
17235                state.mSavedData |= BaseSavedState.START_ACTIVITY_REQUESTED_WHO_SAVED;
17236            }
17237
17238            if (isAutofilled()) {
17239                state.mSavedData |= BaseSavedState.IS_AUTOFILLED;
17240            }
17241
17242            if (mAccessibilityViewId > LAST_APP_ACCESSIBILITY_ID) {
17243                state.mSavedData |= BaseSavedState.ACCESSIBILITY_ID;
17244            }
17245
17246            state.mStartActivityRequestWhoSaved = mStartActivityRequestWho;
17247            state.mIsAutofilled = isAutofilled();
17248            state.mAccessibilityViewId = mAccessibilityViewId;
17249            return state;
17250        }
17251        return BaseSavedState.EMPTY_STATE;
17252    }
17253
17254    /**
17255     * Restore this view hierarchy's frozen state from the given container.
17256     *
17257     * @param container The SparseArray which holds previously frozen states.
17258     *
17259     * @see #saveHierarchyState(android.util.SparseArray)
17260     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
17261     * @see #onRestoreInstanceState(android.os.Parcelable)
17262     */
17263    public void restoreHierarchyState(SparseArray<Parcelable> container) {
17264        dispatchRestoreInstanceState(container);
17265    }
17266
17267    /**
17268     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
17269     * state for this view and its children. May be overridden to modify how restoring
17270     * happens to a view's children; for example, some views may want to not store state
17271     * for their children.
17272     *
17273     * @param container The SparseArray which holds previously saved state.
17274     *
17275     * @see #dispatchSaveInstanceState(android.util.SparseArray)
17276     * @see #restoreHierarchyState(android.util.SparseArray)
17277     * @see #onRestoreInstanceState(android.os.Parcelable)
17278     */
17279    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
17280        if (mID != NO_ID) {
17281            Parcelable state = container.get(mID);
17282            if (state != null) {
17283                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
17284                // + ": " + state);
17285                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
17286                onRestoreInstanceState(state);
17287                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
17288                    throw new IllegalStateException(
17289                            "Derived class did not call super.onRestoreInstanceState()");
17290                }
17291            }
17292        }
17293    }
17294
17295    /**
17296     * Hook allowing a view to re-apply a representation of its internal state that had previously
17297     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
17298     * null state.
17299     *
17300     * @param state The frozen state that had previously been returned by
17301     *        {@link #onSaveInstanceState}.
17302     *
17303     * @see #onSaveInstanceState()
17304     * @see #restoreHierarchyState(android.util.SparseArray)
17305     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
17306     */
17307    @CallSuper
17308    protected void onRestoreInstanceState(Parcelable state) {
17309        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
17310        if (state != null && !(state instanceof AbsSavedState)) {
17311            throw new IllegalArgumentException("Wrong state class, expecting View State but "
17312                    + "received " + state.getClass().toString() + " instead. This usually happens "
17313                    + "when two views of different type have the same id in the same hierarchy. "
17314                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
17315                    + "other views do not use the same id.");
17316        }
17317        if (state != null && state instanceof BaseSavedState) {
17318            BaseSavedState baseState = (BaseSavedState) state;
17319
17320            if ((baseState.mSavedData & BaseSavedState.START_ACTIVITY_REQUESTED_WHO_SAVED) != 0) {
17321                mStartActivityRequestWho = baseState.mStartActivityRequestWhoSaved;
17322            }
17323            if ((baseState.mSavedData & BaseSavedState.IS_AUTOFILLED) != 0) {
17324                setAutofilled(baseState.mIsAutofilled);
17325            }
17326            if ((baseState.mSavedData & BaseSavedState.ACCESSIBILITY_ID) != 0) {
17327                mAccessibilityViewId = baseState.mAccessibilityViewId;
17328            }
17329        }
17330    }
17331
17332    /**
17333     * <p>Return the time at which the drawing of the view hierarchy started.</p>
17334     *
17335     * @return the drawing start time in milliseconds
17336     */
17337    public long getDrawingTime() {
17338        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
17339    }
17340
17341    /**
17342     * <p>Enables or disables the duplication of the parent's state into this view. When
17343     * duplication is enabled, this view gets its drawable state from its parent rather
17344     * than from its own internal properties.</p>
17345     *
17346     * <p>Note: in the current implementation, setting this property to true after the
17347     * view was added to a ViewGroup might have no effect at all. This property should
17348     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
17349     *
17350     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
17351     * property is enabled, an exception will be thrown.</p>
17352     *
17353     * <p>Note: if the child view uses and updates additional states which are unknown to the
17354     * parent, these states should not be affected by this method.</p>
17355     *
17356     * @param enabled True to enable duplication of the parent's drawable state, false
17357     *                to disable it.
17358     *
17359     * @see #getDrawableState()
17360     * @see #isDuplicateParentStateEnabled()
17361     */
17362    public void setDuplicateParentStateEnabled(boolean enabled) {
17363        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
17364    }
17365
17366    /**
17367     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
17368     *
17369     * @return True if this view's drawable state is duplicated from the parent,
17370     *         false otherwise
17371     *
17372     * @see #getDrawableState()
17373     * @see #setDuplicateParentStateEnabled(boolean)
17374     */
17375    public boolean isDuplicateParentStateEnabled() {
17376        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
17377    }
17378
17379    /**
17380     * <p>Specifies the type of layer backing this view. The layer can be
17381     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
17382     * {@link #LAYER_TYPE_HARDWARE}.</p>
17383     *
17384     * <p>A layer is associated with an optional {@link android.graphics.Paint}
17385     * instance that controls how the layer is composed on screen. The following
17386     * properties of the paint are taken into account when composing the layer:</p>
17387     * <ul>
17388     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
17389     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
17390     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
17391     * </ul>
17392     *
17393     * <p>If this view has an alpha value set to < 1.0 by calling
17394     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superseded
17395     * by this view's alpha value.</p>
17396     *
17397     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
17398     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
17399     * for more information on when and how to use layers.</p>
17400     *
17401     * @param layerType The type of layer to use with this view, must be one of
17402     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
17403     *        {@link #LAYER_TYPE_HARDWARE}
17404     * @param paint The paint used to compose the layer. This argument is optional
17405     *        and can be null. It is ignored when the layer type is
17406     *        {@link #LAYER_TYPE_NONE}
17407     *
17408     * @see #getLayerType()
17409     * @see #LAYER_TYPE_NONE
17410     * @see #LAYER_TYPE_SOFTWARE
17411     * @see #LAYER_TYPE_HARDWARE
17412     * @see #setAlpha(float)
17413     *
17414     * @attr ref android.R.styleable#View_layerType
17415     */
17416    public void setLayerType(int layerType, @Nullable Paint paint) {
17417        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
17418            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
17419                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
17420        }
17421
17422        boolean typeChanged = mRenderNode.setLayerType(layerType);
17423
17424        if (!typeChanged) {
17425            setLayerPaint(paint);
17426            return;
17427        }
17428
17429        if (layerType != LAYER_TYPE_SOFTWARE) {
17430            // Destroy any previous software drawing cache if present
17431            // NOTE: even if previous layer type is HW, we do this to ensure we've cleaned up
17432            // drawing cache created in View#draw when drawing to a SW canvas.
17433            destroyDrawingCache();
17434        }
17435
17436        mLayerType = layerType;
17437        mLayerPaint = mLayerType == LAYER_TYPE_NONE ? null : paint;
17438        mRenderNode.setLayerPaint(mLayerPaint);
17439
17440        // draw() behaves differently if we are on a layer, so we need to
17441        // invalidate() here
17442        invalidateParentCaches();
17443        invalidate(true);
17444    }
17445
17446    /**
17447     * Updates the {@link Paint} object used with the current layer (used only if the current
17448     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
17449     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
17450     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
17451     * ensure that the view gets redrawn immediately.
17452     *
17453     * <p>A layer is associated with an optional {@link android.graphics.Paint}
17454     * instance that controls how the layer is composed on screen. The following
17455     * properties of the paint are taken into account when composing the layer:</p>
17456     * <ul>
17457     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
17458     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
17459     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
17460     * </ul>
17461     *
17462     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
17463     * alpha value of the layer's paint is superseded by this view's alpha value.</p>
17464     *
17465     * @param paint The paint used to compose the layer. This argument is optional
17466     *        and can be null. It is ignored when the layer type is
17467     *        {@link #LAYER_TYPE_NONE}
17468     *
17469     * @see #setLayerType(int, android.graphics.Paint)
17470     */
17471    public void setLayerPaint(@Nullable Paint paint) {
17472        int layerType = getLayerType();
17473        if (layerType != LAYER_TYPE_NONE) {
17474            mLayerPaint = paint;
17475            if (layerType == LAYER_TYPE_HARDWARE) {
17476                if (mRenderNode.setLayerPaint(paint)) {
17477                    invalidateViewProperty(false, false);
17478                }
17479            } else {
17480                invalidate();
17481            }
17482        }
17483    }
17484
17485    /**
17486     * Indicates what type of layer is currently associated with this view. By default
17487     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
17488     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
17489     * for more information on the different types of layers.
17490     *
17491     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
17492     *         {@link #LAYER_TYPE_HARDWARE}
17493     *
17494     * @see #setLayerType(int, android.graphics.Paint)
17495     * @see #buildLayer()
17496     * @see #LAYER_TYPE_NONE
17497     * @see #LAYER_TYPE_SOFTWARE
17498     * @see #LAYER_TYPE_HARDWARE
17499     */
17500    public int getLayerType() {
17501        return mLayerType;
17502    }
17503
17504    /**
17505     * Forces this view's layer to be created and this view to be rendered
17506     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
17507     * invoking this method will have no effect.
17508     *
17509     * This method can for instance be used to render a view into its layer before
17510     * starting an animation. If this view is complex, rendering into the layer
17511     * before starting the animation will avoid skipping frames.
17512     *
17513     * @throws IllegalStateException If this view is not attached to a window
17514     *
17515     * @see #setLayerType(int, android.graphics.Paint)
17516     */
17517    public void buildLayer() {
17518        if (mLayerType == LAYER_TYPE_NONE) return;
17519
17520        final AttachInfo attachInfo = mAttachInfo;
17521        if (attachInfo == null) {
17522            throw new IllegalStateException("This view must be attached to a window first");
17523        }
17524
17525        if (getWidth() == 0 || getHeight() == 0) {
17526            return;
17527        }
17528
17529        switch (mLayerType) {
17530            case LAYER_TYPE_HARDWARE:
17531                updateDisplayListIfDirty();
17532                if (attachInfo.mThreadedRenderer != null && mRenderNode.isValid()) {
17533                    attachInfo.mThreadedRenderer.buildLayer(mRenderNode);
17534                }
17535                break;
17536            case LAYER_TYPE_SOFTWARE:
17537                buildDrawingCache(true);
17538                break;
17539        }
17540    }
17541
17542    /**
17543     * Destroys all hardware rendering resources. This method is invoked
17544     * when the system needs to reclaim resources. Upon execution of this
17545     * method, you should free any OpenGL resources created by the view.
17546     *
17547     * Note: you <strong>must</strong> call
17548     * <code>super.destroyHardwareResources()</code> when overriding
17549     * this method.
17550     *
17551     * @hide
17552     */
17553    @CallSuper
17554    protected void destroyHardwareResources() {
17555        if (mOverlay != null) {
17556            mOverlay.getOverlayView().destroyHardwareResources();
17557        }
17558        if (mGhostView != null) {
17559            mGhostView.destroyHardwareResources();
17560        }
17561    }
17562
17563    /**
17564     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
17565     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
17566     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
17567     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
17568     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
17569     * null.</p>
17570     *
17571     * <p>Enabling the drawing cache is similar to
17572     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
17573     * acceleration is turned off. When hardware acceleration is turned on, enabling the
17574     * drawing cache has no effect on rendering because the system uses a different mechanism
17575     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
17576     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
17577     * for information on how to enable software and hardware layers.</p>
17578     *
17579     * <p>This API can be used to manually generate
17580     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
17581     * {@link #getDrawingCache()}.</p>
17582     *
17583     * @param enabled true to enable the drawing cache, false otherwise
17584     *
17585     * @see #isDrawingCacheEnabled()
17586     * @see #getDrawingCache()
17587     * @see #buildDrawingCache()
17588     * @see #setLayerType(int, android.graphics.Paint)
17589     */
17590    public void setDrawingCacheEnabled(boolean enabled) {
17591        mCachingFailed = false;
17592        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
17593    }
17594
17595    /**
17596     * <p>Indicates whether the drawing cache is enabled for this view.</p>
17597     *
17598     * @return true if the drawing cache is enabled
17599     *
17600     * @see #setDrawingCacheEnabled(boolean)
17601     * @see #getDrawingCache()
17602     */
17603    @ViewDebug.ExportedProperty(category = "drawing")
17604    public boolean isDrawingCacheEnabled() {
17605        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
17606    }
17607
17608    /**
17609     * Debugging utility which recursively outputs the dirty state of a view and its
17610     * descendants.
17611     *
17612     * @hide
17613     */
17614    @SuppressWarnings({"UnusedDeclaration"})
17615    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
17616        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
17617                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
17618                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
17619                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
17620        if (clear) {
17621            mPrivateFlags &= clearMask;
17622        }
17623        if (this instanceof ViewGroup) {
17624            ViewGroup parent = (ViewGroup) this;
17625            final int count = parent.getChildCount();
17626            for (int i = 0; i < count; i++) {
17627                final View child = parent.getChildAt(i);
17628                child.outputDirtyFlags(indent + "  ", clear, clearMask);
17629            }
17630        }
17631    }
17632
17633    /**
17634     * This method is used by ViewGroup to cause its children to restore or recreate their
17635     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
17636     * to recreate its own display list, which would happen if it went through the normal
17637     * draw/dispatchDraw mechanisms.
17638     *
17639     * @hide
17640     */
17641    protected void dispatchGetDisplayList() {}
17642
17643    /**
17644     * A view that is not attached or hardware accelerated cannot create a display list.
17645     * This method checks these conditions and returns the appropriate result.
17646     *
17647     * @return true if view has the ability to create a display list, false otherwise.
17648     *
17649     * @hide
17650     */
17651    public boolean canHaveDisplayList() {
17652        return !(mAttachInfo == null || mAttachInfo.mThreadedRenderer == null);
17653    }
17654
17655    /**
17656     * Gets the RenderNode for the view, and updates its DisplayList (if needed and supported)
17657     * @hide
17658     */
17659    @NonNull
17660    public RenderNode updateDisplayListIfDirty() {
17661        final RenderNode renderNode = mRenderNode;
17662        if (!canHaveDisplayList()) {
17663            // can't populate RenderNode, don't try
17664            return renderNode;
17665        }
17666
17667        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0
17668                || !renderNode.isValid()
17669                || (mRecreateDisplayList)) {
17670            // Don't need to recreate the display list, just need to tell our
17671            // children to restore/recreate theirs
17672            if (renderNode.isValid()
17673                    && !mRecreateDisplayList) {
17674                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
17675                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17676                dispatchGetDisplayList();
17677
17678                return renderNode; // no work needed
17679            }
17680
17681            // If we got here, we're recreating it. Mark it as such to ensure that
17682            // we copy in child display lists into ours in drawChild()
17683            mRecreateDisplayList = true;
17684
17685            int width = mRight - mLeft;
17686            int height = mBottom - mTop;
17687            int layerType = getLayerType();
17688
17689            final DisplayListCanvas canvas = renderNode.start(width, height);
17690            canvas.setHighContrastText(mAttachInfo.mHighContrastText);
17691
17692            try {
17693                if (layerType == LAYER_TYPE_SOFTWARE) {
17694                    buildDrawingCache(true);
17695                    Bitmap cache = getDrawingCache(true);
17696                    if (cache != null) {
17697                        canvas.drawBitmap(cache, 0, 0, mLayerPaint);
17698                    }
17699                } else {
17700                    computeScroll();
17701
17702                    canvas.translate(-mScrollX, -mScrollY);
17703                    mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
17704                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17705
17706                    // Fast path for layouts with no backgrounds
17707                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
17708                        dispatchDraw(canvas);
17709                        drawAutofilledHighlight(canvas);
17710                        if (mOverlay != null && !mOverlay.isEmpty()) {
17711                            mOverlay.getOverlayView().draw(canvas);
17712                        }
17713                        if (debugDraw()) {
17714                            debugDrawFocus(canvas);
17715                        }
17716                    } else {
17717                        draw(canvas);
17718                    }
17719                }
17720            } finally {
17721                renderNode.end(canvas);
17722                setDisplayListProperties(renderNode);
17723            }
17724        } else {
17725            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
17726            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17727        }
17728        return renderNode;
17729    }
17730
17731    private void resetDisplayList() {
17732        mRenderNode.discardDisplayList();
17733        if (mBackgroundRenderNode != null) {
17734            mBackgroundRenderNode.discardDisplayList();
17735        }
17736    }
17737
17738    /**
17739     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
17740     *
17741     * @return A non-scaled bitmap representing this view or null if cache is disabled.
17742     *
17743     * @see #getDrawingCache(boolean)
17744     */
17745    public Bitmap getDrawingCache() {
17746        return getDrawingCache(false);
17747    }
17748
17749    /**
17750     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
17751     * is null when caching is disabled. If caching is enabled and the cache is not ready,
17752     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
17753     * draw from the cache when the cache is enabled. To benefit from the cache, you must
17754     * request the drawing cache by calling this method and draw it on screen if the
17755     * returned bitmap is not null.</p>
17756     *
17757     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
17758     * this method will create a bitmap of the same size as this view. Because this bitmap
17759     * will be drawn scaled by the parent ViewGroup, the result on screen might show
17760     * scaling artifacts. To avoid such artifacts, you should call this method by setting
17761     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
17762     * size than the view. This implies that your application must be able to handle this
17763     * size.</p>
17764     *
17765     * @param autoScale Indicates whether the generated bitmap should be scaled based on
17766     *        the current density of the screen when the application is in compatibility
17767     *        mode.
17768     *
17769     * @return A bitmap representing this view or null if cache is disabled.
17770     *
17771     * @see #setDrawingCacheEnabled(boolean)
17772     * @see #isDrawingCacheEnabled()
17773     * @see #buildDrawingCache(boolean)
17774     * @see #destroyDrawingCache()
17775     */
17776    public Bitmap getDrawingCache(boolean autoScale) {
17777        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
17778            return null;
17779        }
17780        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
17781            buildDrawingCache(autoScale);
17782        }
17783        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
17784    }
17785
17786    /**
17787     * <p>Frees the resources used by the drawing cache. If you call
17788     * {@link #buildDrawingCache()} manually without calling
17789     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
17790     * should cleanup the cache with this method afterwards.</p>
17791     *
17792     * @see #setDrawingCacheEnabled(boolean)
17793     * @see #buildDrawingCache()
17794     * @see #getDrawingCache()
17795     */
17796    public void destroyDrawingCache() {
17797        if (mDrawingCache != null) {
17798            mDrawingCache.recycle();
17799            mDrawingCache = null;
17800        }
17801        if (mUnscaledDrawingCache != null) {
17802            mUnscaledDrawingCache.recycle();
17803            mUnscaledDrawingCache = null;
17804        }
17805    }
17806
17807    /**
17808     * Setting a solid background color for the drawing cache's bitmaps will improve
17809     * performance and memory usage. Note, though that this should only be used if this
17810     * view will always be drawn on top of a solid color.
17811     *
17812     * @param color The background color to use for the drawing cache's bitmap
17813     *
17814     * @see #setDrawingCacheEnabled(boolean)
17815     * @see #buildDrawingCache()
17816     * @see #getDrawingCache()
17817     */
17818    public void setDrawingCacheBackgroundColor(@ColorInt int color) {
17819        if (color != mDrawingCacheBackgroundColor) {
17820            mDrawingCacheBackgroundColor = color;
17821            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
17822        }
17823    }
17824
17825    /**
17826     * @see #setDrawingCacheBackgroundColor(int)
17827     *
17828     * @return The background color to used for the drawing cache's bitmap
17829     */
17830    @ColorInt
17831    public int getDrawingCacheBackgroundColor() {
17832        return mDrawingCacheBackgroundColor;
17833    }
17834
17835    /**
17836     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
17837     *
17838     * @see #buildDrawingCache(boolean)
17839     */
17840    public void buildDrawingCache() {
17841        buildDrawingCache(false);
17842    }
17843
17844    /**
17845     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
17846     *
17847     * <p>If you call {@link #buildDrawingCache()} manually without calling
17848     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
17849     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
17850     *
17851     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
17852     * this method will create a bitmap of the same size as this view. Because this bitmap
17853     * will be drawn scaled by the parent ViewGroup, the result on screen might show
17854     * scaling artifacts. To avoid such artifacts, you should call this method by setting
17855     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
17856     * size than the view. This implies that your application must be able to handle this
17857     * size.</p>
17858     *
17859     * <p>You should avoid calling this method when hardware acceleration is enabled. If
17860     * you do not need the drawing cache bitmap, calling this method will increase memory
17861     * usage and cause the view to be rendered in software once, thus negatively impacting
17862     * performance.</p>
17863     *
17864     * @see #getDrawingCache()
17865     * @see #destroyDrawingCache()
17866     */
17867    public void buildDrawingCache(boolean autoScale) {
17868        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
17869                mDrawingCache == null : mUnscaledDrawingCache == null)) {
17870            if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) {
17871                Trace.traceBegin(Trace.TRACE_TAG_VIEW,
17872                        "buildDrawingCache/SW Layer for " + getClass().getSimpleName());
17873            }
17874            try {
17875                buildDrawingCacheImpl(autoScale);
17876            } finally {
17877                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
17878            }
17879        }
17880    }
17881
17882    /**
17883     * private, internal implementation of buildDrawingCache, used to enable tracing
17884     */
17885    private void buildDrawingCacheImpl(boolean autoScale) {
17886        mCachingFailed = false;
17887
17888        int width = mRight - mLeft;
17889        int height = mBottom - mTop;
17890
17891        final AttachInfo attachInfo = mAttachInfo;
17892        final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
17893
17894        if (autoScale && scalingRequired) {
17895            width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
17896            height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
17897        }
17898
17899        final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
17900        final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
17901        final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
17902
17903        final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
17904        final long drawingCacheSize =
17905                ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
17906        if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
17907            if (width > 0 && height > 0) {
17908                Log.w(VIEW_LOG_TAG, getClass().getSimpleName() + " not displayed because it is"
17909                        + " too large to fit into a software layer (or drawing cache), needs "
17910                        + projectedBitmapSize + " bytes, only "
17911                        + drawingCacheSize + " available");
17912            }
17913            destroyDrawingCache();
17914            mCachingFailed = true;
17915            return;
17916        }
17917
17918        boolean clear = true;
17919        Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
17920
17921        if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
17922            Bitmap.Config quality;
17923            if (!opaque) {
17924                // Never pick ARGB_4444 because it looks awful
17925                // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
17926                switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
17927                    case DRAWING_CACHE_QUALITY_AUTO:
17928                    case DRAWING_CACHE_QUALITY_LOW:
17929                    case DRAWING_CACHE_QUALITY_HIGH:
17930                    default:
17931                        quality = Bitmap.Config.ARGB_8888;
17932                        break;
17933                }
17934            } else {
17935                // Optimization for translucent windows
17936                // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
17937                quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
17938            }
17939
17940            // Try to cleanup memory
17941            if (bitmap != null) bitmap.recycle();
17942
17943            try {
17944                bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
17945                        width, height, quality);
17946                bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
17947                if (autoScale) {
17948                    mDrawingCache = bitmap;
17949                } else {
17950                    mUnscaledDrawingCache = bitmap;
17951                }
17952                if (opaque && use32BitCache) bitmap.setHasAlpha(false);
17953            } catch (OutOfMemoryError e) {
17954                // If there is not enough memory to create the bitmap cache, just
17955                // ignore the issue as bitmap caches are not required to draw the
17956                // view hierarchy
17957                if (autoScale) {
17958                    mDrawingCache = null;
17959                } else {
17960                    mUnscaledDrawingCache = null;
17961                }
17962                mCachingFailed = true;
17963                return;
17964            }
17965
17966            clear = drawingCacheBackgroundColor != 0;
17967        }
17968
17969        Canvas canvas;
17970        if (attachInfo != null) {
17971            canvas = attachInfo.mCanvas;
17972            if (canvas == null) {
17973                canvas = new Canvas();
17974            }
17975            canvas.setBitmap(bitmap);
17976            // Temporarily clobber the cached Canvas in case one of our children
17977            // is also using a drawing cache. Without this, the children would
17978            // steal the canvas by attaching their own bitmap to it and bad, bad
17979            // thing would happen (invisible views, corrupted drawings, etc.)
17980            attachInfo.mCanvas = null;
17981        } else {
17982            // This case should hopefully never or seldom happen
17983            canvas = new Canvas(bitmap);
17984        }
17985
17986        if (clear) {
17987            bitmap.eraseColor(drawingCacheBackgroundColor);
17988        }
17989
17990        computeScroll();
17991        final int restoreCount = canvas.save();
17992
17993        if (autoScale && scalingRequired) {
17994            final float scale = attachInfo.mApplicationScale;
17995            canvas.scale(scale, scale);
17996        }
17997
17998        canvas.translate(-mScrollX, -mScrollY);
17999
18000        mPrivateFlags |= PFLAG_DRAWN;
18001        if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
18002                mLayerType != LAYER_TYPE_NONE) {
18003            mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
18004        }
18005
18006        // Fast path for layouts with no backgrounds
18007        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
18008            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
18009            dispatchDraw(canvas);
18010            drawAutofilledHighlight(canvas);
18011            if (mOverlay != null && !mOverlay.isEmpty()) {
18012                mOverlay.getOverlayView().draw(canvas);
18013            }
18014        } else {
18015            draw(canvas);
18016        }
18017
18018        canvas.restoreToCount(restoreCount);
18019        canvas.setBitmap(null);
18020
18021        if (attachInfo != null) {
18022            // Restore the cached Canvas for our siblings
18023            attachInfo.mCanvas = canvas;
18024        }
18025    }
18026
18027    /**
18028     * Create a snapshot of the view into a bitmap.  We should probably make
18029     * some form of this public, but should think about the API.
18030     *
18031     * @hide
18032     */
18033    public Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
18034        int width = mRight - mLeft;
18035        int height = mBottom - mTop;
18036
18037        final AttachInfo attachInfo = mAttachInfo;
18038        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
18039        width = (int) ((width * scale) + 0.5f);
18040        height = (int) ((height * scale) + 0.5f);
18041
18042        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
18043                width > 0 ? width : 1, height > 0 ? height : 1, quality);
18044        if (bitmap == null) {
18045            throw new OutOfMemoryError();
18046        }
18047
18048        Resources resources = getResources();
18049        if (resources != null) {
18050            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
18051        }
18052
18053        Canvas canvas;
18054        if (attachInfo != null) {
18055            canvas = attachInfo.mCanvas;
18056            if (canvas == null) {
18057                canvas = new Canvas();
18058            }
18059            canvas.setBitmap(bitmap);
18060            // Temporarily clobber the cached Canvas in case one of our children
18061            // is also using a drawing cache. Without this, the children would
18062            // steal the canvas by attaching their own bitmap to it and bad, bad
18063            // things would happen (invisible views, corrupted drawings, etc.)
18064            attachInfo.mCanvas = null;
18065        } else {
18066            // This case should hopefully never or seldom happen
18067            canvas = new Canvas(bitmap);
18068        }
18069        boolean enabledHwBitmapsInSwMode = canvas.isHwBitmapsInSwModeEnabled();
18070        canvas.setHwBitmapsInSwModeEnabled(true);
18071        if ((backgroundColor & 0xff000000) != 0) {
18072            bitmap.eraseColor(backgroundColor);
18073        }
18074
18075        computeScroll();
18076        final int restoreCount = canvas.save();
18077        canvas.scale(scale, scale);
18078        canvas.translate(-mScrollX, -mScrollY);
18079
18080        // Temporarily remove the dirty mask
18081        int flags = mPrivateFlags;
18082        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
18083
18084        // Fast path for layouts with no backgrounds
18085        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
18086            dispatchDraw(canvas);
18087            drawAutofilledHighlight(canvas);
18088            if (mOverlay != null && !mOverlay.isEmpty()) {
18089                mOverlay.getOverlayView().draw(canvas);
18090            }
18091        } else {
18092            draw(canvas);
18093        }
18094
18095        mPrivateFlags = flags;
18096
18097        canvas.restoreToCount(restoreCount);
18098        canvas.setBitmap(null);
18099        canvas.setHwBitmapsInSwModeEnabled(enabledHwBitmapsInSwMode);
18100
18101        if (attachInfo != null) {
18102            // Restore the cached Canvas for our siblings
18103            attachInfo.mCanvas = canvas;
18104        }
18105
18106        return bitmap;
18107    }
18108
18109    /**
18110     * Indicates whether this View is currently in edit mode. A View is usually
18111     * in edit mode when displayed within a developer tool. For instance, if
18112     * this View is being drawn by a visual user interface builder, this method
18113     * should return true.
18114     *
18115     * Subclasses should check the return value of this method to provide
18116     * different behaviors if their normal behavior might interfere with the
18117     * host environment. For instance: the class spawns a thread in its
18118     * constructor, the drawing code relies on device-specific features, etc.
18119     *
18120     * This method is usually checked in the drawing code of custom widgets.
18121     *
18122     * @return True if this View is in edit mode, false otherwise.
18123     */
18124    public boolean isInEditMode() {
18125        return false;
18126    }
18127
18128    /**
18129     * If the View draws content inside its padding and enables fading edges,
18130     * it needs to support padding offsets. Padding offsets are added to the
18131     * fading edges to extend the length of the fade so that it covers pixels
18132     * drawn inside the padding.
18133     *
18134     * Subclasses of this class should override this method if they need
18135     * to draw content inside the padding.
18136     *
18137     * @return True if padding offset must be applied, false otherwise.
18138     *
18139     * @see #getLeftPaddingOffset()
18140     * @see #getRightPaddingOffset()
18141     * @see #getTopPaddingOffset()
18142     * @see #getBottomPaddingOffset()
18143     *
18144     * @since CURRENT
18145     */
18146    protected boolean isPaddingOffsetRequired() {
18147        return false;
18148    }
18149
18150    /**
18151     * Amount by which to extend the left fading region. Called only when
18152     * {@link #isPaddingOffsetRequired()} returns true.
18153     *
18154     * @return The left padding offset in pixels.
18155     *
18156     * @see #isPaddingOffsetRequired()
18157     *
18158     * @since CURRENT
18159     */
18160    protected int getLeftPaddingOffset() {
18161        return 0;
18162    }
18163
18164    /**
18165     * Amount by which to extend the right fading region. Called only when
18166     * {@link #isPaddingOffsetRequired()} returns true.
18167     *
18168     * @return The right padding offset in pixels.
18169     *
18170     * @see #isPaddingOffsetRequired()
18171     *
18172     * @since CURRENT
18173     */
18174    protected int getRightPaddingOffset() {
18175        return 0;
18176    }
18177
18178    /**
18179     * Amount by which to extend the top fading region. Called only when
18180     * {@link #isPaddingOffsetRequired()} returns true.
18181     *
18182     * @return The top padding offset in pixels.
18183     *
18184     * @see #isPaddingOffsetRequired()
18185     *
18186     * @since CURRENT
18187     */
18188    protected int getTopPaddingOffset() {
18189        return 0;
18190    }
18191
18192    /**
18193     * Amount by which to extend the bottom fading region. Called only when
18194     * {@link #isPaddingOffsetRequired()} returns true.
18195     *
18196     * @return The bottom padding offset in pixels.
18197     *
18198     * @see #isPaddingOffsetRequired()
18199     *
18200     * @since CURRENT
18201     */
18202    protected int getBottomPaddingOffset() {
18203        return 0;
18204    }
18205
18206    /**
18207     * @hide
18208     * @param offsetRequired
18209     */
18210    protected int getFadeTop(boolean offsetRequired) {
18211        int top = mPaddingTop;
18212        if (offsetRequired) top += getTopPaddingOffset();
18213        return top;
18214    }
18215
18216    /**
18217     * @hide
18218     * @param offsetRequired
18219     */
18220    protected int getFadeHeight(boolean offsetRequired) {
18221        int padding = mPaddingTop;
18222        if (offsetRequired) padding += getTopPaddingOffset();
18223        return mBottom - mTop - mPaddingBottom - padding;
18224    }
18225
18226    /**
18227     * <p>Indicates whether this view is attached to a hardware accelerated
18228     * window or not.</p>
18229     *
18230     * <p>Even if this method returns true, it does not mean that every call
18231     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
18232     * accelerated {@link android.graphics.Canvas}. For instance, if this view
18233     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
18234     * window is hardware accelerated,
18235     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
18236     * return false, and this method will return true.</p>
18237     *
18238     * @return True if the view is attached to a window and the window is
18239     *         hardware accelerated; false in any other case.
18240     */
18241    @ViewDebug.ExportedProperty(category = "drawing")
18242    public boolean isHardwareAccelerated() {
18243        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
18244    }
18245
18246    /**
18247     * Sets a rectangular area on this view to which the view will be clipped
18248     * when it is drawn. Setting the value to null will remove the clip bounds
18249     * and the view will draw normally, using its full bounds.
18250     *
18251     * @param clipBounds The rectangular area, in the local coordinates of
18252     * this view, to which future drawing operations will be clipped.
18253     */
18254    public void setClipBounds(Rect clipBounds) {
18255        if (clipBounds == mClipBounds
18256                || (clipBounds != null && clipBounds.equals(mClipBounds))) {
18257            return;
18258        }
18259        if (clipBounds != null) {
18260            if (mClipBounds == null) {
18261                mClipBounds = new Rect(clipBounds);
18262            } else {
18263                mClipBounds.set(clipBounds);
18264            }
18265        } else {
18266            mClipBounds = null;
18267        }
18268        mRenderNode.setClipBounds(mClipBounds);
18269        invalidateViewProperty(false, false);
18270    }
18271
18272    /**
18273     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
18274     *
18275     * @return A copy of the current clip bounds if clip bounds are set,
18276     * otherwise null.
18277     */
18278    public Rect getClipBounds() {
18279        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
18280    }
18281
18282
18283    /**
18284     * Populates an output rectangle with the clip bounds of the view,
18285     * returning {@code true} if successful or {@code false} if the view's
18286     * clip bounds are {@code null}.
18287     *
18288     * @param outRect rectangle in which to place the clip bounds of the view
18289     * @return {@code true} if successful or {@code false} if the view's
18290     *         clip bounds are {@code null}
18291     */
18292    public boolean getClipBounds(Rect outRect) {
18293        if (mClipBounds != null) {
18294            outRect.set(mClipBounds);
18295            return true;
18296        }
18297        return false;
18298    }
18299
18300    /**
18301     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
18302     * case of an active Animation being run on the view.
18303     */
18304    private boolean applyLegacyAnimation(ViewGroup parent, long drawingTime,
18305            Animation a, boolean scalingRequired) {
18306        Transformation invalidationTransform;
18307        final int flags = parent.mGroupFlags;
18308        final boolean initialized = a.isInitialized();
18309        if (!initialized) {
18310            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
18311            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
18312            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
18313            onAnimationStart();
18314        }
18315
18316        final Transformation t = parent.getChildTransformation();
18317        boolean more = a.getTransformation(drawingTime, t, 1f);
18318        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
18319            if (parent.mInvalidationTransformation == null) {
18320                parent.mInvalidationTransformation = new Transformation();
18321            }
18322            invalidationTransform = parent.mInvalidationTransformation;
18323            a.getTransformation(drawingTime, invalidationTransform, 1f);
18324        } else {
18325            invalidationTransform = t;
18326        }
18327
18328        if (more) {
18329            if (!a.willChangeBounds()) {
18330                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
18331                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
18332                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
18333                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
18334                    // The child need to draw an animation, potentially offscreen, so
18335                    // make sure we do not cancel invalidate requests
18336                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
18337                    parent.invalidate(mLeft, mTop, mRight, mBottom);
18338                }
18339            } else {
18340                if (parent.mInvalidateRegion == null) {
18341                    parent.mInvalidateRegion = new RectF();
18342                }
18343                final RectF region = parent.mInvalidateRegion;
18344                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
18345                        invalidationTransform);
18346
18347                // The child need to draw an animation, potentially offscreen, so
18348                // make sure we do not cancel invalidate requests
18349                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
18350
18351                final int left = mLeft + (int) region.left;
18352                final int top = mTop + (int) region.top;
18353                parent.invalidate(left, top, left + (int) (region.width() + .5f),
18354                        top + (int) (region.height() + .5f));
18355            }
18356        }
18357        return more;
18358    }
18359
18360    /**
18361     * This method is called by getDisplayList() when a display list is recorded for a View.
18362     * It pushes any properties to the RenderNode that aren't managed by the RenderNode.
18363     */
18364    void setDisplayListProperties(RenderNode renderNode) {
18365        if (renderNode != null) {
18366            renderNode.setHasOverlappingRendering(getHasOverlappingRendering());
18367            renderNode.setClipToBounds(mParent instanceof ViewGroup
18368                    && ((ViewGroup) mParent).getClipChildren());
18369
18370            float alpha = 1;
18371            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
18372                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
18373                ViewGroup parentVG = (ViewGroup) mParent;
18374                final Transformation t = parentVG.getChildTransformation();
18375                if (parentVG.getChildStaticTransformation(this, t)) {
18376                    final int transformType = t.getTransformationType();
18377                    if (transformType != Transformation.TYPE_IDENTITY) {
18378                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
18379                            alpha = t.getAlpha();
18380                        }
18381                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
18382                            renderNode.setStaticMatrix(t.getMatrix());
18383                        }
18384                    }
18385                }
18386            }
18387            if (mTransformationInfo != null) {
18388                alpha *= getFinalAlpha();
18389                if (alpha < 1) {
18390                    final int multipliedAlpha = (int) (255 * alpha);
18391                    if (onSetAlpha(multipliedAlpha)) {
18392                        alpha = 1;
18393                    }
18394                }
18395                renderNode.setAlpha(alpha);
18396            } else if (alpha < 1) {
18397                renderNode.setAlpha(alpha);
18398            }
18399        }
18400    }
18401
18402    /**
18403     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
18404     *
18405     * This is where the View specializes rendering behavior based on layer type,
18406     * and hardware acceleration.
18407     */
18408    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
18409        final boolean hardwareAcceleratedCanvas = canvas.isHardwareAccelerated();
18410        /* If an attached view draws to a HW canvas, it may use its RenderNode + DisplayList.
18411         *
18412         * If a view is dettached, its DisplayList shouldn't exist. If the canvas isn't
18413         * HW accelerated, it can't handle drawing RenderNodes.
18414         */
18415        boolean drawingWithRenderNode = mAttachInfo != null
18416                && mAttachInfo.mHardwareAccelerated
18417                && hardwareAcceleratedCanvas;
18418
18419        boolean more = false;
18420        final boolean childHasIdentityMatrix = hasIdentityMatrix();
18421        final int parentFlags = parent.mGroupFlags;
18422
18423        if ((parentFlags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) != 0) {
18424            parent.getChildTransformation().clear();
18425            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
18426        }
18427
18428        Transformation transformToApply = null;
18429        boolean concatMatrix = false;
18430        final boolean scalingRequired = mAttachInfo != null && mAttachInfo.mScalingRequired;
18431        final Animation a = getAnimation();
18432        if (a != null) {
18433            more = applyLegacyAnimation(parent, drawingTime, a, scalingRequired);
18434            concatMatrix = a.willChangeTransformationMatrix();
18435            if (concatMatrix) {
18436                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
18437            }
18438            transformToApply = parent.getChildTransformation();
18439        } else {
18440            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) {
18441                // No longer animating: clear out old animation matrix
18442                mRenderNode.setAnimationMatrix(null);
18443                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
18444            }
18445            if (!drawingWithRenderNode
18446                    && (parentFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
18447                final Transformation t = parent.getChildTransformation();
18448                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
18449                if (hasTransform) {
18450                    final int transformType = t.getTransformationType();
18451                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
18452                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
18453                }
18454            }
18455        }
18456
18457        concatMatrix |= !childHasIdentityMatrix;
18458
18459        // Sets the flag as early as possible to allow draw() implementations
18460        // to call invalidate() successfully when doing animations
18461        mPrivateFlags |= PFLAG_DRAWN;
18462
18463        if (!concatMatrix &&
18464                (parentFlags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
18465                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
18466                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
18467                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
18468            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
18469            return more;
18470        }
18471        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
18472
18473        if (hardwareAcceleratedCanvas) {
18474            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
18475            // retain the flag's value temporarily in the mRecreateDisplayList flag
18476            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) != 0;
18477            mPrivateFlags &= ~PFLAG_INVALIDATED;
18478        }
18479
18480        RenderNode renderNode = null;
18481        Bitmap cache = null;
18482        int layerType = getLayerType(); // TODO: signify cache state with just 'cache' local
18483        if (layerType == LAYER_TYPE_SOFTWARE || !drawingWithRenderNode) {
18484             if (layerType != LAYER_TYPE_NONE) {
18485                 // If not drawing with RenderNode, treat HW layers as SW
18486                 layerType = LAYER_TYPE_SOFTWARE;
18487                 buildDrawingCache(true);
18488            }
18489            cache = getDrawingCache(true);
18490        }
18491
18492        if (drawingWithRenderNode) {
18493            // Delay getting the display list until animation-driven alpha values are
18494            // set up and possibly passed on to the view
18495            renderNode = updateDisplayListIfDirty();
18496            if (!renderNode.isValid()) {
18497                // Uncommon, but possible. If a view is removed from the hierarchy during the call
18498                // to getDisplayList(), the display list will be marked invalid and we should not
18499                // try to use it again.
18500                renderNode = null;
18501                drawingWithRenderNode = false;
18502            }
18503        }
18504
18505        int sx = 0;
18506        int sy = 0;
18507        if (!drawingWithRenderNode) {
18508            computeScroll();
18509            sx = mScrollX;
18510            sy = mScrollY;
18511        }
18512
18513        final boolean drawingWithDrawingCache = cache != null && !drawingWithRenderNode;
18514        final boolean offsetForScroll = cache == null && !drawingWithRenderNode;
18515
18516        int restoreTo = -1;
18517        if (!drawingWithRenderNode || transformToApply != null) {
18518            restoreTo = canvas.save();
18519        }
18520        if (offsetForScroll) {
18521            canvas.translate(mLeft - sx, mTop - sy);
18522        } else {
18523            if (!drawingWithRenderNode) {
18524                canvas.translate(mLeft, mTop);
18525            }
18526            if (scalingRequired) {
18527                if (drawingWithRenderNode) {
18528                    // TODO: Might not need this if we put everything inside the DL
18529                    restoreTo = canvas.save();
18530                }
18531                // mAttachInfo cannot be null, otherwise scalingRequired == false
18532                final float scale = 1.0f / mAttachInfo.mApplicationScale;
18533                canvas.scale(scale, scale);
18534            }
18535        }
18536
18537        float alpha = drawingWithRenderNode ? 1 : (getAlpha() * getTransitionAlpha());
18538        if (transformToApply != null
18539                || alpha < 1
18540                || !hasIdentityMatrix()
18541                || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
18542            if (transformToApply != null || !childHasIdentityMatrix) {
18543                int transX = 0;
18544                int transY = 0;
18545
18546                if (offsetForScroll) {
18547                    transX = -sx;
18548                    transY = -sy;
18549                }
18550
18551                if (transformToApply != null) {
18552                    if (concatMatrix) {
18553                        if (drawingWithRenderNode) {
18554                            renderNode.setAnimationMatrix(transformToApply.getMatrix());
18555                        } else {
18556                            // Undo the scroll translation, apply the transformation matrix,
18557                            // then redo the scroll translate to get the correct result.
18558                            canvas.translate(-transX, -transY);
18559                            canvas.concat(transformToApply.getMatrix());
18560                            canvas.translate(transX, transY);
18561                        }
18562                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
18563                    }
18564
18565                    float transformAlpha = transformToApply.getAlpha();
18566                    if (transformAlpha < 1) {
18567                        alpha *= transformAlpha;
18568                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
18569                    }
18570                }
18571
18572                if (!childHasIdentityMatrix && !drawingWithRenderNode) {
18573                    canvas.translate(-transX, -transY);
18574                    canvas.concat(getMatrix());
18575                    canvas.translate(transX, transY);
18576                }
18577            }
18578
18579            // Deal with alpha if it is or used to be <1
18580            if (alpha < 1 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
18581                if (alpha < 1) {
18582                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
18583                } else {
18584                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
18585                }
18586                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
18587                if (!drawingWithDrawingCache) {
18588                    final int multipliedAlpha = (int) (255 * alpha);
18589                    if (!onSetAlpha(multipliedAlpha)) {
18590                        if (drawingWithRenderNode) {
18591                            renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha());
18592                        } else if (layerType == LAYER_TYPE_NONE) {
18593                            canvas.saveLayerAlpha(sx, sy, sx + getWidth(), sy + getHeight(),
18594                                    multipliedAlpha);
18595                        }
18596                    } else {
18597                        // Alpha is handled by the child directly, clobber the layer's alpha
18598                        mPrivateFlags |= PFLAG_ALPHA_SET;
18599                    }
18600                }
18601            }
18602        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
18603            onSetAlpha(255);
18604            mPrivateFlags &= ~PFLAG_ALPHA_SET;
18605        }
18606
18607        if (!drawingWithRenderNode) {
18608            // apply clips directly, since RenderNode won't do it for this draw
18609            if ((parentFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 && cache == null) {
18610                if (offsetForScroll) {
18611                    canvas.clipRect(sx, sy, sx + getWidth(), sy + getHeight());
18612                } else {
18613                    if (!scalingRequired || cache == null) {
18614                        canvas.clipRect(0, 0, getWidth(), getHeight());
18615                    } else {
18616                        canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
18617                    }
18618                }
18619            }
18620
18621            if (mClipBounds != null) {
18622                // clip bounds ignore scroll
18623                canvas.clipRect(mClipBounds);
18624            }
18625        }
18626
18627        if (!drawingWithDrawingCache) {
18628            if (drawingWithRenderNode) {
18629                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
18630                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
18631            } else {
18632                // Fast path for layouts with no backgrounds
18633                if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
18634                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
18635                    dispatchDraw(canvas);
18636                } else {
18637                    draw(canvas);
18638                }
18639            }
18640        } else if (cache != null) {
18641            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
18642            if (layerType == LAYER_TYPE_NONE || mLayerPaint == null) {
18643                // no layer paint, use temporary paint to draw bitmap
18644                Paint cachePaint = parent.mCachePaint;
18645                if (cachePaint == null) {
18646                    cachePaint = new Paint();
18647                    cachePaint.setDither(false);
18648                    parent.mCachePaint = cachePaint;
18649                }
18650                cachePaint.setAlpha((int) (alpha * 255));
18651                canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
18652            } else {
18653                // use layer paint to draw the bitmap, merging the two alphas, but also restore
18654                int layerPaintAlpha = mLayerPaint.getAlpha();
18655                if (alpha < 1) {
18656                    mLayerPaint.setAlpha((int) (alpha * layerPaintAlpha));
18657                }
18658                canvas.drawBitmap(cache, 0.0f, 0.0f, mLayerPaint);
18659                if (alpha < 1) {
18660                    mLayerPaint.setAlpha(layerPaintAlpha);
18661                }
18662            }
18663        }
18664
18665        if (restoreTo >= 0) {
18666            canvas.restoreToCount(restoreTo);
18667        }
18668
18669        if (a != null && !more) {
18670            if (!hardwareAcceleratedCanvas && !a.getFillAfter()) {
18671                onSetAlpha(255);
18672            }
18673            parent.finishAnimatingView(this, a);
18674        }
18675
18676        if (more && hardwareAcceleratedCanvas) {
18677            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
18678                // alpha animations should cause the child to recreate its display list
18679                invalidate(true);
18680            }
18681        }
18682
18683        mRecreateDisplayList = false;
18684
18685        return more;
18686    }
18687
18688    static Paint getDebugPaint() {
18689        if (sDebugPaint == null) {
18690            sDebugPaint = new Paint();
18691            sDebugPaint.setAntiAlias(false);
18692        }
18693        return sDebugPaint;
18694    }
18695
18696    final int dipsToPixels(int dips) {
18697        float scale = getContext().getResources().getDisplayMetrics().density;
18698        return (int) (dips * scale + 0.5f);
18699    }
18700
18701    final private void debugDrawFocus(Canvas canvas) {
18702        if (isFocused()) {
18703            final int cornerSquareSize = dipsToPixels(DEBUG_CORNERS_SIZE_DIP);
18704            final int l = mScrollX;
18705            final int r = l + mRight - mLeft;
18706            final int t = mScrollY;
18707            final int b = t + mBottom - mTop;
18708
18709            final Paint paint = getDebugPaint();
18710            paint.setColor(DEBUG_CORNERS_COLOR);
18711
18712            // Draw squares in corners.
18713            paint.setStyle(Paint.Style.FILL);
18714            canvas.drawRect(l, t, l + cornerSquareSize, t + cornerSquareSize, paint);
18715            canvas.drawRect(r - cornerSquareSize, t, r, t + cornerSquareSize, paint);
18716            canvas.drawRect(l, b - cornerSquareSize, l + cornerSquareSize, b, paint);
18717            canvas.drawRect(r - cornerSquareSize, b - cornerSquareSize, r, b, paint);
18718
18719            // Draw big X across the view.
18720            paint.setStyle(Paint.Style.STROKE);
18721            canvas.drawLine(l, t, r, b, paint);
18722            canvas.drawLine(l, b, r, t, paint);
18723        }
18724    }
18725
18726    /**
18727     * Manually render this view (and all of its children) to the given Canvas.
18728     * The view must have already done a full layout before this function is
18729     * called.  When implementing a view, implement
18730     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
18731     * If you do need to override this method, call the superclass version.
18732     *
18733     * @param canvas The Canvas to which the View is rendered.
18734     */
18735    @CallSuper
18736    public void draw(Canvas canvas) {
18737        final int privateFlags = mPrivateFlags;
18738        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
18739                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
18740        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
18741
18742        /*
18743         * Draw traversal performs several drawing steps which must be executed
18744         * in the appropriate order:
18745         *
18746         *      1. Draw the background
18747         *      2. If necessary, save the canvas' layers to prepare for fading
18748         *      3. Draw view's content
18749         *      4. Draw children
18750         *      5. If necessary, draw the fading edges and restore layers
18751         *      6. Draw decorations (scrollbars for instance)
18752         */
18753
18754        // Step 1, draw the background, if needed
18755        int saveCount;
18756
18757        if (!dirtyOpaque) {
18758            drawBackground(canvas);
18759        }
18760
18761        // skip step 2 & 5 if possible (common case)
18762        final int viewFlags = mViewFlags;
18763        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
18764        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
18765        if (!verticalEdges && !horizontalEdges) {
18766            // Step 3, draw the content
18767            if (!dirtyOpaque) onDraw(canvas);
18768
18769            // Step 4, draw the children
18770            dispatchDraw(canvas);
18771
18772            drawAutofilledHighlight(canvas);
18773
18774            // Overlay is part of the content and draws beneath Foreground
18775            if (mOverlay != null && !mOverlay.isEmpty()) {
18776                mOverlay.getOverlayView().dispatchDraw(canvas);
18777            }
18778
18779            // Step 6, draw decorations (foreground, scrollbars)
18780            onDrawForeground(canvas);
18781
18782            // Step 7, draw the default focus highlight
18783            drawDefaultFocusHighlight(canvas);
18784
18785            if (debugDraw()) {
18786                debugDrawFocus(canvas);
18787            }
18788
18789            // we're done...
18790            return;
18791        }
18792
18793        /*
18794         * Here we do the full fledged routine...
18795         * (this is an uncommon case where speed matters less,
18796         * this is why we repeat some of the tests that have been
18797         * done above)
18798         */
18799
18800        boolean drawTop = false;
18801        boolean drawBottom = false;
18802        boolean drawLeft = false;
18803        boolean drawRight = false;
18804
18805        float topFadeStrength = 0.0f;
18806        float bottomFadeStrength = 0.0f;
18807        float leftFadeStrength = 0.0f;
18808        float rightFadeStrength = 0.0f;
18809
18810        // Step 2, save the canvas' layers
18811        int paddingLeft = mPaddingLeft;
18812
18813        final boolean offsetRequired = isPaddingOffsetRequired();
18814        if (offsetRequired) {
18815            paddingLeft += getLeftPaddingOffset();
18816        }
18817
18818        int left = mScrollX + paddingLeft;
18819        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
18820        int top = mScrollY + getFadeTop(offsetRequired);
18821        int bottom = top + getFadeHeight(offsetRequired);
18822
18823        if (offsetRequired) {
18824            right += getRightPaddingOffset();
18825            bottom += getBottomPaddingOffset();
18826        }
18827
18828        final ScrollabilityCache scrollabilityCache = mScrollCache;
18829        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
18830        int length = (int) fadeHeight;
18831
18832        // clip the fade length if top and bottom fades overlap
18833        // overlapping fades produce odd-looking artifacts
18834        if (verticalEdges && (top + length > bottom - length)) {
18835            length = (bottom - top) / 2;
18836        }
18837
18838        // also clip horizontal fades if necessary
18839        if (horizontalEdges && (left + length > right - length)) {
18840            length = (right - left) / 2;
18841        }
18842
18843        if (verticalEdges) {
18844            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
18845            drawTop = topFadeStrength * fadeHeight > 1.0f;
18846            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
18847            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
18848        }
18849
18850        if (horizontalEdges) {
18851            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
18852            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
18853            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
18854            drawRight = rightFadeStrength * fadeHeight > 1.0f;
18855        }
18856
18857        saveCount = canvas.getSaveCount();
18858
18859        int solidColor = getSolidColor();
18860        if (solidColor == 0) {
18861            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
18862
18863            if (drawTop) {
18864                canvas.saveLayer(left, top, right, top + length, null, flags);
18865            }
18866
18867            if (drawBottom) {
18868                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
18869            }
18870
18871            if (drawLeft) {
18872                canvas.saveLayer(left, top, left + length, bottom, null, flags);
18873            }
18874
18875            if (drawRight) {
18876                canvas.saveLayer(right - length, top, right, bottom, null, flags);
18877            }
18878        } else {
18879            scrollabilityCache.setFadeColor(solidColor);
18880        }
18881
18882        // Step 3, draw the content
18883        if (!dirtyOpaque) onDraw(canvas);
18884
18885        // Step 4, draw the children
18886        dispatchDraw(canvas);
18887
18888        // Step 5, draw the fade effect and restore layers
18889        final Paint p = scrollabilityCache.paint;
18890        final Matrix matrix = scrollabilityCache.matrix;
18891        final Shader fade = scrollabilityCache.shader;
18892
18893        if (drawTop) {
18894            matrix.setScale(1, fadeHeight * topFadeStrength);
18895            matrix.postTranslate(left, top);
18896            fade.setLocalMatrix(matrix);
18897            p.setShader(fade);
18898            canvas.drawRect(left, top, right, top + length, p);
18899        }
18900
18901        if (drawBottom) {
18902            matrix.setScale(1, fadeHeight * bottomFadeStrength);
18903            matrix.postRotate(180);
18904            matrix.postTranslate(left, bottom);
18905            fade.setLocalMatrix(matrix);
18906            p.setShader(fade);
18907            canvas.drawRect(left, bottom - length, right, bottom, p);
18908        }
18909
18910        if (drawLeft) {
18911            matrix.setScale(1, fadeHeight * leftFadeStrength);
18912            matrix.postRotate(-90);
18913            matrix.postTranslate(left, top);
18914            fade.setLocalMatrix(matrix);
18915            p.setShader(fade);
18916            canvas.drawRect(left, top, left + length, bottom, p);
18917        }
18918
18919        if (drawRight) {
18920            matrix.setScale(1, fadeHeight * rightFadeStrength);
18921            matrix.postRotate(90);
18922            matrix.postTranslate(right, top);
18923            fade.setLocalMatrix(matrix);
18924            p.setShader(fade);
18925            canvas.drawRect(right - length, top, right, bottom, p);
18926        }
18927
18928        canvas.restoreToCount(saveCount);
18929
18930        drawAutofilledHighlight(canvas);
18931
18932        // Overlay is part of the content and draws beneath Foreground
18933        if (mOverlay != null && !mOverlay.isEmpty()) {
18934            mOverlay.getOverlayView().dispatchDraw(canvas);
18935        }
18936
18937        // Step 6, draw decorations (foreground, scrollbars)
18938        onDrawForeground(canvas);
18939
18940        if (debugDraw()) {
18941            debugDrawFocus(canvas);
18942        }
18943    }
18944
18945    /**
18946     * Draws the background onto the specified canvas.
18947     *
18948     * @param canvas Canvas on which to draw the background
18949     */
18950    private void drawBackground(Canvas canvas) {
18951        final Drawable background = mBackground;
18952        if (background == null) {
18953            return;
18954        }
18955
18956        setBackgroundBounds();
18957
18958        // Attempt to use a display list if requested.
18959        if (canvas.isHardwareAccelerated() && mAttachInfo != null
18960                && mAttachInfo.mThreadedRenderer != null) {
18961            mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode);
18962
18963            final RenderNode renderNode = mBackgroundRenderNode;
18964            if (renderNode != null && renderNode.isValid()) {
18965                setBackgroundRenderNodeProperties(renderNode);
18966                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
18967                return;
18968            }
18969        }
18970
18971        final int scrollX = mScrollX;
18972        final int scrollY = mScrollY;
18973        if ((scrollX | scrollY) == 0) {
18974            background.draw(canvas);
18975        } else {
18976            canvas.translate(scrollX, scrollY);
18977            background.draw(canvas);
18978            canvas.translate(-scrollX, -scrollY);
18979        }
18980    }
18981
18982    /**
18983     * Sets the correct background bounds and rebuilds the outline, if needed.
18984     * <p/>
18985     * This is called by LayoutLib.
18986     */
18987    void setBackgroundBounds() {
18988        if (mBackgroundSizeChanged && mBackground != null) {
18989            mBackground.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
18990            mBackgroundSizeChanged = false;
18991            rebuildOutline();
18992        }
18993    }
18994
18995    private void setBackgroundRenderNodeProperties(RenderNode renderNode) {
18996        renderNode.setTranslationX(mScrollX);
18997        renderNode.setTranslationY(mScrollY);
18998    }
18999
19000    /**
19001     * Creates a new display list or updates the existing display list for the
19002     * specified Drawable.
19003     *
19004     * @param drawable Drawable for which to create a display list
19005     * @param renderNode Existing RenderNode, or {@code null}
19006     * @return A valid display list for the specified drawable
19007     */
19008    private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) {
19009        if (renderNode == null) {
19010            renderNode = RenderNode.create(drawable.getClass().getName(), this);
19011        }
19012
19013        final Rect bounds = drawable.getBounds();
19014        final int width = bounds.width();
19015        final int height = bounds.height();
19016        final DisplayListCanvas canvas = renderNode.start(width, height);
19017
19018        // Reverse left/top translation done by drawable canvas, which will
19019        // instead be applied by rendernode's LTRB bounds below. This way, the
19020        // drawable's bounds match with its rendernode bounds and its content
19021        // will lie within those bounds in the rendernode tree.
19022        canvas.translate(-bounds.left, -bounds.top);
19023
19024        try {
19025            drawable.draw(canvas);
19026        } finally {
19027            renderNode.end(canvas);
19028        }
19029
19030        // Set up drawable properties that are view-independent.
19031        renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
19032        renderNode.setProjectBackwards(drawable.isProjected());
19033        renderNode.setProjectionReceiver(true);
19034        renderNode.setClipToBounds(false);
19035        return renderNode;
19036    }
19037
19038    /**
19039     * Returns the overlay for this view, creating it if it does not yet exist.
19040     * Adding drawables to the overlay will cause them to be displayed whenever
19041     * the view itself is redrawn. Objects in the overlay should be actively
19042     * managed: remove them when they should not be displayed anymore. The
19043     * overlay will always have the same size as its host view.
19044     *
19045     * <p>Note: Overlays do not currently work correctly with {@link
19046     * SurfaceView} or {@link TextureView}; contents in overlays for these
19047     * types of views may not display correctly.</p>
19048     *
19049     * @return The ViewOverlay object for this view.
19050     * @see ViewOverlay
19051     */
19052    public ViewOverlay getOverlay() {
19053        if (mOverlay == null) {
19054            mOverlay = new ViewOverlay(mContext, this);
19055        }
19056        return mOverlay;
19057    }
19058
19059    /**
19060     * Override this if your view is known to always be drawn on top of a solid color background,
19061     * and needs to draw fading edges. Returning a non-zero color enables the view system to
19062     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
19063     * should be set to 0xFF.
19064     *
19065     * @see #setVerticalFadingEdgeEnabled(boolean)
19066     * @see #setHorizontalFadingEdgeEnabled(boolean)
19067     *
19068     * @return The known solid color background for this view, or 0 if the color may vary
19069     */
19070    @ViewDebug.ExportedProperty(category = "drawing")
19071    @ColorInt
19072    public int getSolidColor() {
19073        return 0;
19074    }
19075
19076    /**
19077     * Build a human readable string representation of the specified view flags.
19078     *
19079     * @param flags the view flags to convert to a string
19080     * @return a String representing the supplied flags
19081     */
19082    private static String printFlags(int flags) {
19083        String output = "";
19084        int numFlags = 0;
19085        if ((flags & FOCUSABLE) == FOCUSABLE) {
19086            output += "TAKES_FOCUS";
19087            numFlags++;
19088        }
19089
19090        switch (flags & VISIBILITY_MASK) {
19091        case INVISIBLE:
19092            if (numFlags > 0) {
19093                output += " ";
19094            }
19095            output += "INVISIBLE";
19096            // USELESS HERE numFlags++;
19097            break;
19098        case GONE:
19099            if (numFlags > 0) {
19100                output += " ";
19101            }
19102            output += "GONE";
19103            // USELESS HERE numFlags++;
19104            break;
19105        default:
19106            break;
19107        }
19108        return output;
19109    }
19110
19111    /**
19112     * Build a human readable string representation of the specified private
19113     * view flags.
19114     *
19115     * @param privateFlags the private view flags to convert to a string
19116     * @return a String representing the supplied flags
19117     */
19118    private static String printPrivateFlags(int privateFlags) {
19119        String output = "";
19120        int numFlags = 0;
19121
19122        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
19123            output += "WANTS_FOCUS";
19124            numFlags++;
19125        }
19126
19127        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
19128            if (numFlags > 0) {
19129                output += " ";
19130            }
19131            output += "FOCUSED";
19132            numFlags++;
19133        }
19134
19135        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
19136            if (numFlags > 0) {
19137                output += " ";
19138            }
19139            output += "SELECTED";
19140            numFlags++;
19141        }
19142
19143        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
19144            if (numFlags > 0) {
19145                output += " ";
19146            }
19147            output += "IS_ROOT_NAMESPACE";
19148            numFlags++;
19149        }
19150
19151        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
19152            if (numFlags > 0) {
19153                output += " ";
19154            }
19155            output += "HAS_BOUNDS";
19156            numFlags++;
19157        }
19158
19159        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
19160            if (numFlags > 0) {
19161                output += " ";
19162            }
19163            output += "DRAWN";
19164            // USELESS HERE numFlags++;
19165        }
19166        return output;
19167    }
19168
19169    /**
19170     * <p>Indicates whether or not this view's layout will be requested during
19171     * the next hierarchy layout pass.</p>
19172     *
19173     * @return true if the layout will be forced during next layout pass
19174     */
19175    public boolean isLayoutRequested() {
19176        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
19177    }
19178
19179    /**
19180     * Return true if o is a ViewGroup that is laying out using optical bounds.
19181     * @hide
19182     */
19183    public static boolean isLayoutModeOptical(Object o) {
19184        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
19185    }
19186
19187    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
19188        Insets parentInsets = mParent instanceof View ?
19189                ((View) mParent).getOpticalInsets() : Insets.NONE;
19190        Insets childInsets = getOpticalInsets();
19191        return setFrame(
19192                left   + parentInsets.left - childInsets.left,
19193                top    + parentInsets.top  - childInsets.top,
19194                right  + parentInsets.left + childInsets.right,
19195                bottom + parentInsets.top  + childInsets.bottom);
19196    }
19197
19198    /**
19199     * Assign a size and position to a view and all of its
19200     * descendants
19201     *
19202     * <p>This is the second phase of the layout mechanism.
19203     * (The first is measuring). In this phase, each parent calls
19204     * layout on all of its children to position them.
19205     * This is typically done using the child measurements
19206     * that were stored in the measure pass().</p>
19207     *
19208     * <p>Derived classes should not override this method.
19209     * Derived classes with children should override
19210     * onLayout. In that method, they should
19211     * call layout on each of their children.</p>
19212     *
19213     * @param l Left position, relative to parent
19214     * @param t Top position, relative to parent
19215     * @param r Right position, relative to parent
19216     * @param b Bottom position, relative to parent
19217     */
19218    @SuppressWarnings({"unchecked"})
19219    public void layout(int l, int t, int r, int b) {
19220        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
19221            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
19222            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
19223        }
19224
19225        int oldL = mLeft;
19226        int oldT = mTop;
19227        int oldB = mBottom;
19228        int oldR = mRight;
19229
19230        boolean changed = isLayoutModeOptical(mParent) ?
19231                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
19232
19233        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
19234            onLayout(changed, l, t, r, b);
19235
19236            if (shouldDrawRoundScrollbar()) {
19237                if(mRoundScrollbarRenderer == null) {
19238                    mRoundScrollbarRenderer = new RoundScrollbarRenderer(this);
19239                }
19240            } else {
19241                mRoundScrollbarRenderer = null;
19242            }
19243
19244            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
19245
19246            ListenerInfo li = mListenerInfo;
19247            if (li != null && li.mOnLayoutChangeListeners != null) {
19248                ArrayList<OnLayoutChangeListener> listenersCopy =
19249                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
19250                int numListeners = listenersCopy.size();
19251                for (int i = 0; i < numListeners; ++i) {
19252                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
19253                }
19254            }
19255        }
19256
19257        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
19258        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
19259    }
19260
19261    /**
19262     * Called from layout when this view should
19263     * assign a size and position to each of its children.
19264     *
19265     * Derived classes with children should override
19266     * this method and call layout on each of
19267     * their children.
19268     * @param changed This is a new size or position for this view
19269     * @param left Left position, relative to parent
19270     * @param top Top position, relative to parent
19271     * @param right Right position, relative to parent
19272     * @param bottom Bottom position, relative to parent
19273     */
19274    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
19275    }
19276
19277    /**
19278     * Assign a size and position to this view.
19279     *
19280     * This is called from layout.
19281     *
19282     * @param left Left position, relative to parent
19283     * @param top Top position, relative to parent
19284     * @param right Right position, relative to parent
19285     * @param bottom Bottom position, relative to parent
19286     * @return true if the new size and position are different than the
19287     *         previous ones
19288     * {@hide}
19289     */
19290    protected boolean setFrame(int left, int top, int right, int bottom) {
19291        boolean changed = false;
19292
19293        if (DBG) {
19294            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
19295                    + right + "," + bottom + ")");
19296        }
19297
19298        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
19299            changed = true;
19300
19301            // Remember our drawn bit
19302            int drawn = mPrivateFlags & PFLAG_DRAWN;
19303
19304            int oldWidth = mRight - mLeft;
19305            int oldHeight = mBottom - mTop;
19306            int newWidth = right - left;
19307            int newHeight = bottom - top;
19308            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
19309
19310            // Invalidate our old position
19311            invalidate(sizeChanged);
19312
19313            mLeft = left;
19314            mTop = top;
19315            mRight = right;
19316            mBottom = bottom;
19317            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
19318
19319            mPrivateFlags |= PFLAG_HAS_BOUNDS;
19320
19321
19322            if (sizeChanged) {
19323                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
19324            }
19325
19326            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) {
19327                // If we are visible, force the DRAWN bit to on so that
19328                // this invalidate will go through (at least to our parent).
19329                // This is because someone may have invalidated this view
19330                // before this call to setFrame came in, thereby clearing
19331                // the DRAWN bit.
19332                mPrivateFlags |= PFLAG_DRAWN;
19333                invalidate(sizeChanged);
19334                // parent display list may need to be recreated based on a change in the bounds
19335                // of any child
19336                invalidateParentCaches();
19337            }
19338
19339            // Reset drawn bit to original value (invalidate turns it off)
19340            mPrivateFlags |= drawn;
19341
19342            mBackgroundSizeChanged = true;
19343            mDefaultFocusHighlightSizeChanged = true;
19344            if (mForegroundInfo != null) {
19345                mForegroundInfo.mBoundsChanged = true;
19346            }
19347
19348            notifySubtreeAccessibilityStateChangedIfNeeded();
19349        }
19350        return changed;
19351    }
19352
19353    /**
19354     * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}.
19355     * @hide
19356     */
19357    public void setLeftTopRightBottom(int left, int top, int right, int bottom) {
19358        setFrame(left, top, right, bottom);
19359    }
19360
19361    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
19362        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
19363        if (mOverlay != null) {
19364            mOverlay.getOverlayView().setRight(newWidth);
19365            mOverlay.getOverlayView().setBottom(newHeight);
19366        }
19367        rebuildOutline();
19368    }
19369
19370    /**
19371     * Finalize inflating a view from XML.  This is called as the last phase
19372     * of inflation, after all child views have been added.
19373     *
19374     * <p>Even if the subclass overrides onFinishInflate, they should always be
19375     * sure to call the super method, so that we get called.
19376     */
19377    @CallSuper
19378    protected void onFinishInflate() {
19379    }
19380
19381    /**
19382     * Returns the resources associated with this view.
19383     *
19384     * @return Resources object.
19385     */
19386    public Resources getResources() {
19387        return mResources;
19388    }
19389
19390    /**
19391     * Invalidates the specified Drawable.
19392     *
19393     * @param drawable the drawable to invalidate
19394     */
19395    @Override
19396    public void invalidateDrawable(@NonNull Drawable drawable) {
19397        if (verifyDrawable(drawable)) {
19398            final Rect dirty = drawable.getDirtyBounds();
19399            final int scrollX = mScrollX;
19400            final int scrollY = mScrollY;
19401
19402            invalidate(dirty.left + scrollX, dirty.top + scrollY,
19403                    dirty.right + scrollX, dirty.bottom + scrollY);
19404            rebuildOutline();
19405        }
19406    }
19407
19408    /**
19409     * Schedules an action on a drawable to occur at a specified time.
19410     *
19411     * @param who the recipient of the action
19412     * @param what the action to run on the drawable
19413     * @param when the time at which the action must occur. Uses the
19414     *        {@link SystemClock#uptimeMillis} timebase.
19415     */
19416    @Override
19417    public void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when) {
19418        if (verifyDrawable(who) && what != null) {
19419            final long delay = when - SystemClock.uptimeMillis();
19420            if (mAttachInfo != null) {
19421                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
19422                        Choreographer.CALLBACK_ANIMATION, what, who,
19423                        Choreographer.subtractFrameDelay(delay));
19424            } else {
19425                // Postpone the runnable until we know
19426                // on which thread it needs to run.
19427                getRunQueue().postDelayed(what, delay);
19428            }
19429        }
19430    }
19431
19432    /**
19433     * Cancels a scheduled action on a drawable.
19434     *
19435     * @param who the recipient of the action
19436     * @param what the action to cancel
19437     */
19438    @Override
19439    public void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what) {
19440        if (verifyDrawable(who) && what != null) {
19441            if (mAttachInfo != null) {
19442                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
19443                        Choreographer.CALLBACK_ANIMATION, what, who);
19444            }
19445            getRunQueue().removeCallbacks(what);
19446        }
19447    }
19448
19449    /**
19450     * Unschedule any events associated with the given Drawable.  This can be
19451     * used when selecting a new Drawable into a view, so that the previous
19452     * one is completely unscheduled.
19453     *
19454     * @param who The Drawable to unschedule.
19455     *
19456     * @see #drawableStateChanged
19457     */
19458    public void unscheduleDrawable(Drawable who) {
19459        if (mAttachInfo != null && who != null) {
19460            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
19461                    Choreographer.CALLBACK_ANIMATION, null, who);
19462        }
19463    }
19464
19465    /**
19466     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
19467     * that the View directionality can and will be resolved before its Drawables.
19468     *
19469     * Will call {@link View#onResolveDrawables} when resolution is done.
19470     *
19471     * @hide
19472     */
19473    protected void resolveDrawables() {
19474        // Drawables resolution may need to happen before resolving the layout direction (which is
19475        // done only during the measure() call).
19476        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
19477        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
19478        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
19479        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
19480        // direction to be resolved as its resolved value will be the same as its raw value.
19481        if (!isLayoutDirectionResolved() &&
19482                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
19483            return;
19484        }
19485
19486        final int layoutDirection = isLayoutDirectionResolved() ?
19487                getLayoutDirection() : getRawLayoutDirection();
19488
19489        if (mBackground != null) {
19490            mBackground.setLayoutDirection(layoutDirection);
19491        }
19492        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
19493            mForegroundInfo.mDrawable.setLayoutDirection(layoutDirection);
19494        }
19495        if (mDefaultFocusHighlight != null) {
19496            mDefaultFocusHighlight.setLayoutDirection(layoutDirection);
19497        }
19498        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
19499        onResolveDrawables(layoutDirection);
19500    }
19501
19502    boolean areDrawablesResolved() {
19503        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
19504    }
19505
19506    /**
19507     * Called when layout direction has been resolved.
19508     *
19509     * The default implementation does nothing.
19510     *
19511     * @param layoutDirection The resolved layout direction.
19512     *
19513     * @see #LAYOUT_DIRECTION_LTR
19514     * @see #LAYOUT_DIRECTION_RTL
19515     *
19516     * @hide
19517     */
19518    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
19519    }
19520
19521    /**
19522     * @hide
19523     */
19524    protected void resetResolvedDrawables() {
19525        resetResolvedDrawablesInternal();
19526    }
19527
19528    void resetResolvedDrawablesInternal() {
19529        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
19530    }
19531
19532    /**
19533     * If your view subclass is displaying its own Drawable objects, it should
19534     * override this function and return true for any Drawable it is
19535     * displaying.  This allows animations for those drawables to be
19536     * scheduled.
19537     *
19538     * <p>Be sure to call through to the super class when overriding this
19539     * function.
19540     *
19541     * @param who The Drawable to verify.  Return true if it is one you are
19542     *            displaying, else return the result of calling through to the
19543     *            super class.
19544     *
19545     * @return boolean If true than the Drawable is being displayed in the
19546     *         view; else false and it is not allowed to animate.
19547     *
19548     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
19549     * @see #drawableStateChanged()
19550     */
19551    @CallSuper
19552    protected boolean verifyDrawable(@NonNull Drawable who) {
19553        // Avoid verifying the scroll bar drawable so that we don't end up in
19554        // an invalidation loop. This effectively prevents the scroll bar
19555        // drawable from triggering invalidations and scheduling runnables.
19556        return who == mBackground || (mForegroundInfo != null && mForegroundInfo.mDrawable == who)
19557                || (mDefaultFocusHighlight == who);
19558    }
19559
19560    /**
19561     * This function is called whenever the state of the view changes in such
19562     * a way that it impacts the state of drawables being shown.
19563     * <p>
19564     * If the View has a StateListAnimator, it will also be called to run necessary state
19565     * change animations.
19566     * <p>
19567     * Be sure to call through to the superclass when overriding this function.
19568     *
19569     * @see Drawable#setState(int[])
19570     */
19571    @CallSuper
19572    protected void drawableStateChanged() {
19573        final int[] state = getDrawableState();
19574        boolean changed = false;
19575
19576        final Drawable bg = mBackground;
19577        if (bg != null && bg.isStateful()) {
19578            changed |= bg.setState(state);
19579        }
19580
19581        final Drawable hl = mDefaultFocusHighlight;
19582        if (hl != null && hl.isStateful()) {
19583            changed |= hl.setState(state);
19584        }
19585
19586        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
19587        if (fg != null && fg.isStateful()) {
19588            changed |= fg.setState(state);
19589        }
19590
19591        if (mScrollCache != null) {
19592            final Drawable scrollBar = mScrollCache.scrollBar;
19593            if (scrollBar != null && scrollBar.isStateful()) {
19594                changed |= scrollBar.setState(state)
19595                        && mScrollCache.state != ScrollabilityCache.OFF;
19596            }
19597        }
19598
19599        if (mStateListAnimator != null) {
19600            mStateListAnimator.setState(state);
19601        }
19602
19603        if (changed) {
19604            invalidate();
19605        }
19606    }
19607
19608    /**
19609     * This function is called whenever the view hotspot changes and needs to
19610     * be propagated to drawables or child views managed by the view.
19611     * <p>
19612     * Dispatching to child views is handled by
19613     * {@link #dispatchDrawableHotspotChanged(float, float)}.
19614     * <p>
19615     * Be sure to call through to the superclass when overriding this function.
19616     *
19617     * @param x hotspot x coordinate
19618     * @param y hotspot y coordinate
19619     */
19620    @CallSuper
19621    public void drawableHotspotChanged(float x, float y) {
19622        if (mBackground != null) {
19623            mBackground.setHotspot(x, y);
19624        }
19625        if (mDefaultFocusHighlight != null) {
19626            mDefaultFocusHighlight.setHotspot(x, y);
19627        }
19628        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
19629            mForegroundInfo.mDrawable.setHotspot(x, y);
19630        }
19631
19632        dispatchDrawableHotspotChanged(x, y);
19633    }
19634
19635    /**
19636     * Dispatches drawableHotspotChanged to all of this View's children.
19637     *
19638     * @param x hotspot x coordinate
19639     * @param y hotspot y coordinate
19640     * @see #drawableHotspotChanged(float, float)
19641     */
19642    public void dispatchDrawableHotspotChanged(float x, float y) {
19643    }
19644
19645    /**
19646     * Call this to force a view to update its drawable state. This will cause
19647     * drawableStateChanged to be called on this view. Views that are interested
19648     * in the new state should call getDrawableState.
19649     *
19650     * @see #drawableStateChanged
19651     * @see #getDrawableState
19652     */
19653    public void refreshDrawableState() {
19654        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
19655        drawableStateChanged();
19656
19657        ViewParent parent = mParent;
19658        if (parent != null) {
19659            parent.childDrawableStateChanged(this);
19660        }
19661    }
19662
19663    /**
19664     * Create a default focus highlight if it doesn't exist.
19665     * @return a default focus highlight.
19666     */
19667    private Drawable getDefaultFocusHighlightDrawable() {
19668        if (mDefaultFocusHighlightCache == null) {
19669            if (mContext != null) {
19670                final int[] attrs = new int[] { android.R.attr.selectableItemBackground };
19671                final TypedArray ta = mContext.obtainStyledAttributes(attrs);
19672                mDefaultFocusHighlightCache = ta.getDrawable(0);
19673                ta.recycle();
19674            }
19675        }
19676        return mDefaultFocusHighlightCache;
19677    }
19678
19679    /**
19680     * Set the current default focus highlight.
19681     * @param highlight the highlight drawable, or {@code null} if it's no longer needed.
19682     */
19683    private void setDefaultFocusHighlight(Drawable highlight) {
19684        mDefaultFocusHighlight = highlight;
19685        mDefaultFocusHighlightSizeChanged = true;
19686        if (highlight != null) {
19687            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
19688                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
19689            }
19690            highlight.setLayoutDirection(getLayoutDirection());
19691            if (highlight.isStateful()) {
19692                highlight.setState(getDrawableState());
19693            }
19694            if (isAttachedToWindow()) {
19695                highlight.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
19696            }
19697            // Set callback last, since the view may still be initializing.
19698            highlight.setCallback(this);
19699        } else if ((mViewFlags & WILL_NOT_DRAW) != 0 && mBackground == null
19700                && (mForegroundInfo == null || mForegroundInfo.mDrawable == null)) {
19701            mPrivateFlags |= PFLAG_SKIP_DRAW;
19702        }
19703        requestLayout();
19704        invalidate();
19705    }
19706
19707    /**
19708     * Check whether we need to draw a default focus highlight when this view gets focused,
19709     * which requires:
19710     * <ul>
19711     *     <li>In the background, {@link android.R.attr#state_focused} is not defined.</li>
19712     *     <li>This view is not in touch mode.</li>
19713     *     <li>This view doesn't opt out for a default focus highlight, via
19714     *         {@link #setDefaultFocusHighlightEnabled(boolean)}.</li>
19715     *     <li>This view is attached to window.</li>
19716     * </ul>
19717     * @return {@code true} if a default focus highlight is needed.
19718     */
19719    private boolean isDefaultFocusHighlightNeeded(Drawable background) {
19720        final boolean hasFocusStateSpecified = background == null || !background.isStateful()
19721                || !background.hasFocusStateSpecified();
19722        return !isInTouchMode() && getDefaultFocusHighlightEnabled() && hasFocusStateSpecified
19723                && isAttachedToWindow();
19724    }
19725
19726    /**
19727     * When this view is focused, switches on/off the default focused highlight.
19728     * <p>
19729     * This always happens when this view is focused, and only at this moment the default focus
19730     * highlight can be visible.
19731     */
19732    private void switchDefaultFocusHighlight() {
19733        if (isFocused()) {
19734            final boolean needed = isDefaultFocusHighlightNeeded(mBackground);
19735            final boolean active = mDefaultFocusHighlight != null;
19736            if (needed && !active) {
19737                setDefaultFocusHighlight(getDefaultFocusHighlightDrawable());
19738            } else if (!needed && active) {
19739                // The highlight is no longer needed, so tear it down.
19740                setDefaultFocusHighlight(null);
19741            }
19742        }
19743    }
19744
19745    /**
19746     * Draw the default focus highlight onto the canvas.
19747     * @param canvas the canvas where we're drawing the highlight.
19748     */
19749    private void drawDefaultFocusHighlight(Canvas canvas) {
19750        if (mDefaultFocusHighlight != null) {
19751            if (mDefaultFocusHighlightSizeChanged) {
19752                mDefaultFocusHighlightSizeChanged = false;
19753                final int l = mScrollX;
19754                final int r = l + mRight - mLeft;
19755                final int t = mScrollY;
19756                final int b = t + mBottom - mTop;
19757                mDefaultFocusHighlight.setBounds(l, t, r, b);
19758            }
19759            mDefaultFocusHighlight.draw(canvas);
19760        }
19761    }
19762
19763    /**
19764     * Return an array of resource IDs of the drawable states representing the
19765     * current state of the view.
19766     *
19767     * @return The current drawable state
19768     *
19769     * @see Drawable#setState(int[])
19770     * @see #drawableStateChanged()
19771     * @see #onCreateDrawableState(int)
19772     */
19773    public final int[] getDrawableState() {
19774        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
19775            return mDrawableState;
19776        } else {
19777            mDrawableState = onCreateDrawableState(0);
19778            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
19779            return mDrawableState;
19780        }
19781    }
19782
19783    /**
19784     * Generate the new {@link android.graphics.drawable.Drawable} state for
19785     * this view. This is called by the view
19786     * system when the cached Drawable state is determined to be invalid.  To
19787     * retrieve the current state, you should use {@link #getDrawableState}.
19788     *
19789     * @param extraSpace if non-zero, this is the number of extra entries you
19790     * would like in the returned array in which you can place your own
19791     * states.
19792     *
19793     * @return Returns an array holding the current {@link Drawable} state of
19794     * the view.
19795     *
19796     * @see #mergeDrawableStates(int[], int[])
19797     */
19798    protected int[] onCreateDrawableState(int extraSpace) {
19799        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
19800                mParent instanceof View) {
19801            return ((View) mParent).onCreateDrawableState(extraSpace);
19802        }
19803
19804        int[] drawableState;
19805
19806        int privateFlags = mPrivateFlags;
19807
19808        int viewStateIndex = 0;
19809        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= StateSet.VIEW_STATE_PRESSED;
19810        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= StateSet.VIEW_STATE_ENABLED;
19811        if (isFocused()) viewStateIndex |= StateSet.VIEW_STATE_FOCUSED;
19812        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= StateSet.VIEW_STATE_SELECTED;
19813        if (hasWindowFocus()) viewStateIndex |= StateSet.VIEW_STATE_WINDOW_FOCUSED;
19814        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= StateSet.VIEW_STATE_ACTIVATED;
19815        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
19816                ThreadedRenderer.isAvailable()) {
19817            // This is set if HW acceleration is requested, even if the current
19818            // process doesn't allow it.  This is just to allow app preview
19819            // windows to better match their app.
19820            viewStateIndex |= StateSet.VIEW_STATE_ACCELERATED;
19821        }
19822        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= StateSet.VIEW_STATE_HOVERED;
19823
19824        final int privateFlags2 = mPrivateFlags2;
19825        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) {
19826            viewStateIndex |= StateSet.VIEW_STATE_DRAG_CAN_ACCEPT;
19827        }
19828        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) {
19829            viewStateIndex |= StateSet.VIEW_STATE_DRAG_HOVERED;
19830        }
19831
19832        drawableState = StateSet.get(viewStateIndex);
19833
19834        //noinspection ConstantIfStatement
19835        if (false) {
19836            Log.i("View", "drawableStateIndex=" + viewStateIndex);
19837            Log.i("View", toString()
19838                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
19839                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
19840                    + " fo=" + hasFocus()
19841                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
19842                    + " wf=" + hasWindowFocus()
19843                    + ": " + Arrays.toString(drawableState));
19844        }
19845
19846        if (extraSpace == 0) {
19847            return drawableState;
19848        }
19849
19850        final int[] fullState;
19851        if (drawableState != null) {
19852            fullState = new int[drawableState.length + extraSpace];
19853            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
19854        } else {
19855            fullState = new int[extraSpace];
19856        }
19857
19858        return fullState;
19859    }
19860
19861    /**
19862     * Merge your own state values in <var>additionalState</var> into the base
19863     * state values <var>baseState</var> that were returned by
19864     * {@link #onCreateDrawableState(int)}.
19865     *
19866     * @param baseState The base state values returned by
19867     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
19868     * own additional state values.
19869     *
19870     * @param additionalState The additional state values you would like
19871     * added to <var>baseState</var>; this array is not modified.
19872     *
19873     * @return As a convenience, the <var>baseState</var> array you originally
19874     * passed into the function is returned.
19875     *
19876     * @see #onCreateDrawableState(int)
19877     */
19878    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
19879        final int N = baseState.length;
19880        int i = N - 1;
19881        while (i >= 0 && baseState[i] == 0) {
19882            i--;
19883        }
19884        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
19885        return baseState;
19886    }
19887
19888    /**
19889     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
19890     * on all Drawable objects associated with this view.
19891     * <p>
19892     * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator
19893     * attached to this view.
19894     */
19895    @CallSuper
19896    public void jumpDrawablesToCurrentState() {
19897        if (mBackground != null) {
19898            mBackground.jumpToCurrentState();
19899        }
19900        if (mStateListAnimator != null) {
19901            mStateListAnimator.jumpToCurrentState();
19902        }
19903        if (mDefaultFocusHighlight != null) {
19904            mDefaultFocusHighlight.jumpToCurrentState();
19905        }
19906        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
19907            mForegroundInfo.mDrawable.jumpToCurrentState();
19908        }
19909    }
19910
19911    /**
19912     * Sets the background color for this view.
19913     * @param color the color of the background
19914     */
19915    @RemotableViewMethod
19916    public void setBackgroundColor(@ColorInt int color) {
19917        if (mBackground instanceof ColorDrawable) {
19918            ((ColorDrawable) mBackground.mutate()).setColor(color);
19919            computeOpaqueFlags();
19920            mBackgroundResource = 0;
19921        } else {
19922            setBackground(new ColorDrawable(color));
19923        }
19924    }
19925
19926    /**
19927     * Set the background to a given resource. The resource should refer to
19928     * a Drawable object or 0 to remove the background.
19929     * @param resid The identifier of the resource.
19930     *
19931     * @attr ref android.R.styleable#View_background
19932     */
19933    @RemotableViewMethod
19934    public void setBackgroundResource(@DrawableRes int resid) {
19935        if (resid != 0 && resid == mBackgroundResource) {
19936            return;
19937        }
19938
19939        Drawable d = null;
19940        if (resid != 0) {
19941            d = mContext.getDrawable(resid);
19942        }
19943        setBackground(d);
19944
19945        mBackgroundResource = resid;
19946    }
19947
19948    /**
19949     * Set the background to a given Drawable, or remove the background. If the
19950     * background has padding, this View's padding is set to the background's
19951     * padding. However, when a background is removed, this View's padding isn't
19952     * touched. If setting the padding is desired, please use
19953     * {@link #setPadding(int, int, int, int)}.
19954     *
19955     * @param background The Drawable to use as the background, or null to remove the
19956     *        background
19957     */
19958    public void setBackground(Drawable background) {
19959        //noinspection deprecation
19960        setBackgroundDrawable(background);
19961    }
19962
19963    /**
19964     * @deprecated use {@link #setBackground(Drawable)} instead
19965     */
19966    @Deprecated
19967    public void setBackgroundDrawable(Drawable background) {
19968        computeOpaqueFlags();
19969
19970        if (background == mBackground) {
19971            return;
19972        }
19973
19974        boolean requestLayout = false;
19975
19976        mBackgroundResource = 0;
19977
19978        /*
19979         * Regardless of whether we're setting a new background or not, we want
19980         * to clear the previous drawable. setVisible first while we still have the callback set.
19981         */
19982        if (mBackground != null) {
19983            if (isAttachedToWindow()) {
19984                mBackground.setVisible(false, false);
19985            }
19986            mBackground.setCallback(null);
19987            unscheduleDrawable(mBackground);
19988        }
19989
19990        if (background != null) {
19991            Rect padding = sThreadLocal.get();
19992            if (padding == null) {
19993                padding = new Rect();
19994                sThreadLocal.set(padding);
19995            }
19996            resetResolvedDrawablesInternal();
19997            background.setLayoutDirection(getLayoutDirection());
19998            if (background.getPadding(padding)) {
19999                resetResolvedPaddingInternal();
20000                switch (background.getLayoutDirection()) {
20001                    case LAYOUT_DIRECTION_RTL:
20002                        mUserPaddingLeftInitial = padding.right;
20003                        mUserPaddingRightInitial = padding.left;
20004                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
20005                        break;
20006                    case LAYOUT_DIRECTION_LTR:
20007                    default:
20008                        mUserPaddingLeftInitial = padding.left;
20009                        mUserPaddingRightInitial = padding.right;
20010                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
20011                }
20012                mLeftPaddingDefined = false;
20013                mRightPaddingDefined = false;
20014            }
20015
20016            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
20017            // if it has a different minimum size, we should layout again
20018            if (mBackground == null
20019                    || mBackground.getMinimumHeight() != background.getMinimumHeight()
20020                    || mBackground.getMinimumWidth() != background.getMinimumWidth()) {
20021                requestLayout = true;
20022            }
20023
20024            // Set mBackground before we set this as the callback and start making other
20025            // background drawable state change calls. In particular, the setVisible call below
20026            // can result in drawables attempting to start animations or otherwise invalidate,
20027            // which requires the view set as the callback (us) to recognize the drawable as
20028            // belonging to it as per verifyDrawable.
20029            mBackground = background;
20030            if (background.isStateful()) {
20031                background.setState(getDrawableState());
20032            }
20033            if (isAttachedToWindow()) {
20034                background.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
20035            }
20036
20037            applyBackgroundTint();
20038
20039            // Set callback last, since the view may still be initializing.
20040            background.setCallback(this);
20041
20042            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
20043                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
20044                requestLayout = true;
20045            }
20046        } else {
20047            /* Remove the background */
20048            mBackground = null;
20049            if ((mViewFlags & WILL_NOT_DRAW) != 0
20050                    && (mDefaultFocusHighlight == null)
20051                    && (mForegroundInfo == null || mForegroundInfo.mDrawable == null)) {
20052                mPrivateFlags |= PFLAG_SKIP_DRAW;
20053            }
20054
20055            /*
20056             * When the background is set, we try to apply its padding to this
20057             * View. When the background is removed, we don't touch this View's
20058             * padding. This is noted in the Javadocs. Hence, we don't need to
20059             * requestLayout(), the invalidate() below is sufficient.
20060             */
20061
20062            // The old background's minimum size could have affected this
20063            // View's layout, so let's requestLayout
20064            requestLayout = true;
20065        }
20066
20067        computeOpaqueFlags();
20068
20069        if (requestLayout) {
20070            requestLayout();
20071        }
20072
20073        mBackgroundSizeChanged = true;
20074        invalidate(true);
20075        invalidateOutline();
20076    }
20077
20078    /**
20079     * Gets the background drawable
20080     *
20081     * @return The drawable used as the background for this view, if any.
20082     *
20083     * @see #setBackground(Drawable)
20084     *
20085     * @attr ref android.R.styleable#View_background
20086     */
20087    public Drawable getBackground() {
20088        return mBackground;
20089    }
20090
20091    /**
20092     * Applies a tint to the background drawable. Does not modify the current tint
20093     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
20094     * <p>
20095     * Subsequent calls to {@link #setBackground(Drawable)} will automatically
20096     * mutate the drawable and apply the specified tint and tint mode using
20097     * {@link Drawable#setTintList(ColorStateList)}.
20098     *
20099     * @param tint the tint to apply, may be {@code null} to clear tint
20100     *
20101     * @attr ref android.R.styleable#View_backgroundTint
20102     * @see #getBackgroundTintList()
20103     * @see Drawable#setTintList(ColorStateList)
20104     */
20105    public void setBackgroundTintList(@Nullable ColorStateList tint) {
20106        if (mBackgroundTint == null) {
20107            mBackgroundTint = new TintInfo();
20108        }
20109        mBackgroundTint.mTintList = tint;
20110        mBackgroundTint.mHasTintList = true;
20111
20112        applyBackgroundTint();
20113    }
20114
20115    /**
20116     * Return the tint applied to the background drawable, if specified.
20117     *
20118     * @return the tint applied to the background drawable
20119     * @attr ref android.R.styleable#View_backgroundTint
20120     * @see #setBackgroundTintList(ColorStateList)
20121     */
20122    @Nullable
20123    public ColorStateList getBackgroundTintList() {
20124        return mBackgroundTint != null ? mBackgroundTint.mTintList : null;
20125    }
20126
20127    /**
20128     * Specifies the blending mode used to apply the tint specified by
20129     * {@link #setBackgroundTintList(ColorStateList)}} to the background
20130     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
20131     *
20132     * @param tintMode the blending mode used to apply the tint, may be
20133     *                 {@code null} to clear tint
20134     * @attr ref android.R.styleable#View_backgroundTintMode
20135     * @see #getBackgroundTintMode()
20136     * @see Drawable#setTintMode(PorterDuff.Mode)
20137     */
20138    public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) {
20139        if (mBackgroundTint == null) {
20140            mBackgroundTint = new TintInfo();
20141        }
20142        mBackgroundTint.mTintMode = tintMode;
20143        mBackgroundTint.mHasTintMode = true;
20144
20145        applyBackgroundTint();
20146    }
20147
20148    /**
20149     * Return the blending mode used to apply the tint to the background
20150     * drawable, if specified.
20151     *
20152     * @return the blending mode used to apply the tint to the background
20153     *         drawable
20154     * @attr ref android.R.styleable#View_backgroundTintMode
20155     * @see #setBackgroundTintMode(PorterDuff.Mode)
20156     */
20157    @Nullable
20158    public PorterDuff.Mode getBackgroundTintMode() {
20159        return mBackgroundTint != null ? mBackgroundTint.mTintMode : null;
20160    }
20161
20162    private void applyBackgroundTint() {
20163        if (mBackground != null && mBackgroundTint != null) {
20164            final TintInfo tintInfo = mBackgroundTint;
20165            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
20166                mBackground = mBackground.mutate();
20167
20168                if (tintInfo.mHasTintList) {
20169                    mBackground.setTintList(tintInfo.mTintList);
20170                }
20171
20172                if (tintInfo.mHasTintMode) {
20173                    mBackground.setTintMode(tintInfo.mTintMode);
20174                }
20175
20176                // The drawable (or one of its children) may not have been
20177                // stateful before applying the tint, so let's try again.
20178                if (mBackground.isStateful()) {
20179                    mBackground.setState(getDrawableState());
20180                }
20181            }
20182        }
20183    }
20184
20185    /**
20186     * Returns the drawable used as the foreground of this View. The
20187     * foreground drawable, if non-null, is always drawn on top of the view's content.
20188     *
20189     * @return a Drawable or null if no foreground was set
20190     *
20191     * @see #onDrawForeground(Canvas)
20192     */
20193    public Drawable getForeground() {
20194        return mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
20195    }
20196
20197    /**
20198     * Supply a Drawable that is to be rendered on top of all of the content in the view.
20199     *
20200     * @param foreground the Drawable to be drawn on top of the children
20201     *
20202     * @attr ref android.R.styleable#View_foreground
20203     */
20204    public void setForeground(Drawable foreground) {
20205        if (mForegroundInfo == null) {
20206            if (foreground == null) {
20207                // Nothing to do.
20208                return;
20209            }
20210            mForegroundInfo = new ForegroundInfo();
20211        }
20212
20213        if (foreground == mForegroundInfo.mDrawable) {
20214            // Nothing to do
20215            return;
20216        }
20217
20218        if (mForegroundInfo.mDrawable != null) {
20219            if (isAttachedToWindow()) {
20220                mForegroundInfo.mDrawable.setVisible(false, false);
20221            }
20222            mForegroundInfo.mDrawable.setCallback(null);
20223            unscheduleDrawable(mForegroundInfo.mDrawable);
20224        }
20225
20226        mForegroundInfo.mDrawable = foreground;
20227        mForegroundInfo.mBoundsChanged = true;
20228        if (foreground != null) {
20229            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
20230                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
20231            }
20232            foreground.setLayoutDirection(getLayoutDirection());
20233            if (foreground.isStateful()) {
20234                foreground.setState(getDrawableState());
20235            }
20236            applyForegroundTint();
20237            if (isAttachedToWindow()) {
20238                foreground.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
20239            }
20240            // Set callback last, since the view may still be initializing.
20241            foreground.setCallback(this);
20242        } else if ((mViewFlags & WILL_NOT_DRAW) != 0 && mBackground == null
20243                && (mDefaultFocusHighlight == null)) {
20244            mPrivateFlags |= PFLAG_SKIP_DRAW;
20245        }
20246        requestLayout();
20247        invalidate();
20248    }
20249
20250    /**
20251     * Magic bit used to support features of framework-internal window decor implementation details.
20252     * This used to live exclusively in FrameLayout.
20253     *
20254     * @return true if the foreground should draw inside the padding region or false
20255     *         if it should draw inset by the view's padding
20256     * @hide internal use only; only used by FrameLayout and internal screen layouts.
20257     */
20258    public boolean isForegroundInsidePadding() {
20259        return mForegroundInfo != null ? mForegroundInfo.mInsidePadding : true;
20260    }
20261
20262    /**
20263     * Describes how the foreground is positioned.
20264     *
20265     * @return foreground gravity.
20266     *
20267     * @see #setForegroundGravity(int)
20268     *
20269     * @attr ref android.R.styleable#View_foregroundGravity
20270     */
20271    public int getForegroundGravity() {
20272        return mForegroundInfo != null ? mForegroundInfo.mGravity
20273                : Gravity.START | Gravity.TOP;
20274    }
20275
20276    /**
20277     * Describes how the foreground is positioned. Defaults to START and TOP.
20278     *
20279     * @param gravity see {@link android.view.Gravity}
20280     *
20281     * @see #getForegroundGravity()
20282     *
20283     * @attr ref android.R.styleable#View_foregroundGravity
20284     */
20285    public void setForegroundGravity(int gravity) {
20286        if (mForegroundInfo == null) {
20287            mForegroundInfo = new ForegroundInfo();
20288        }
20289
20290        if (mForegroundInfo.mGravity != gravity) {
20291            if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) {
20292                gravity |= Gravity.START;
20293            }
20294
20295            if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) {
20296                gravity |= Gravity.TOP;
20297            }
20298
20299            mForegroundInfo.mGravity = gravity;
20300            requestLayout();
20301        }
20302    }
20303
20304    /**
20305     * Applies a tint to the foreground drawable. Does not modify the current tint
20306     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
20307     * <p>
20308     * Subsequent calls to {@link #setForeground(Drawable)} will automatically
20309     * mutate the drawable and apply the specified tint and tint mode using
20310     * {@link Drawable#setTintList(ColorStateList)}.
20311     *
20312     * @param tint the tint to apply, may be {@code null} to clear tint
20313     *
20314     * @attr ref android.R.styleable#View_foregroundTint
20315     * @see #getForegroundTintList()
20316     * @see Drawable#setTintList(ColorStateList)
20317     */
20318    public void setForegroundTintList(@Nullable ColorStateList tint) {
20319        if (mForegroundInfo == null) {
20320            mForegroundInfo = new ForegroundInfo();
20321        }
20322        if (mForegroundInfo.mTintInfo == null) {
20323            mForegroundInfo.mTintInfo = new TintInfo();
20324        }
20325        mForegroundInfo.mTintInfo.mTintList = tint;
20326        mForegroundInfo.mTintInfo.mHasTintList = true;
20327
20328        applyForegroundTint();
20329    }
20330
20331    /**
20332     * Return the tint applied to the foreground drawable, if specified.
20333     *
20334     * @return the tint applied to the foreground drawable
20335     * @attr ref android.R.styleable#View_foregroundTint
20336     * @see #setForegroundTintList(ColorStateList)
20337     */
20338    @Nullable
20339    public ColorStateList getForegroundTintList() {
20340        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
20341                ? mForegroundInfo.mTintInfo.mTintList : null;
20342    }
20343
20344    /**
20345     * Specifies the blending mode used to apply the tint specified by
20346     * {@link #setForegroundTintList(ColorStateList)}} to the background
20347     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
20348     *
20349     * @param tintMode the blending mode used to apply the tint, may be
20350     *                 {@code null} to clear tint
20351     * @attr ref android.R.styleable#View_foregroundTintMode
20352     * @see #getForegroundTintMode()
20353     * @see Drawable#setTintMode(PorterDuff.Mode)
20354     */
20355    public void setForegroundTintMode(@Nullable PorterDuff.Mode tintMode) {
20356        if (mForegroundInfo == null) {
20357            mForegroundInfo = new ForegroundInfo();
20358        }
20359        if (mForegroundInfo.mTintInfo == null) {
20360            mForegroundInfo.mTintInfo = new TintInfo();
20361        }
20362        mForegroundInfo.mTintInfo.mTintMode = tintMode;
20363        mForegroundInfo.mTintInfo.mHasTintMode = true;
20364
20365        applyForegroundTint();
20366    }
20367
20368    /**
20369     * Return the blending mode used to apply the tint to the foreground
20370     * drawable, if specified.
20371     *
20372     * @return the blending mode used to apply the tint to the foreground
20373     *         drawable
20374     * @attr ref android.R.styleable#View_foregroundTintMode
20375     * @see #setForegroundTintMode(PorterDuff.Mode)
20376     */
20377    @Nullable
20378    public PorterDuff.Mode getForegroundTintMode() {
20379        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
20380                ? mForegroundInfo.mTintInfo.mTintMode : null;
20381    }
20382
20383    private void applyForegroundTint() {
20384        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
20385                && mForegroundInfo.mTintInfo != null) {
20386            final TintInfo tintInfo = mForegroundInfo.mTintInfo;
20387            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
20388                mForegroundInfo.mDrawable = mForegroundInfo.mDrawable.mutate();
20389
20390                if (tintInfo.mHasTintList) {
20391                    mForegroundInfo.mDrawable.setTintList(tintInfo.mTintList);
20392                }
20393
20394                if (tintInfo.mHasTintMode) {
20395                    mForegroundInfo.mDrawable.setTintMode(tintInfo.mTintMode);
20396                }
20397
20398                // The drawable (or one of its children) may not have been
20399                // stateful before applying the tint, so let's try again.
20400                if (mForegroundInfo.mDrawable.isStateful()) {
20401                    mForegroundInfo.mDrawable.setState(getDrawableState());
20402                }
20403            }
20404        }
20405    }
20406
20407    /**
20408     * Get the drawable to be overlayed when a view is autofilled
20409     *
20410     * @return The drawable
20411     *
20412     * @throws IllegalStateException if the drawable could not be found.
20413     */
20414    @NonNull private Drawable getAutofilledDrawable() {
20415        // Lazily load the isAutofilled drawable.
20416        if (mAttachInfo.mAutofilledDrawable == null) {
20417            mAttachInfo.mAutofilledDrawable = mContext.getDrawable(R.drawable.autofilled_highlight);
20418
20419            if (mAttachInfo.mAutofilledDrawable == null) {
20420                throw new IllegalStateException(
20421                        "Could not find android:drawable/autofilled_highlight");
20422            }
20423        }
20424
20425        return mAttachInfo.mAutofilledDrawable;
20426    }
20427
20428    /**
20429     * Draw {@link View#isAutofilled()} highlight over view if the view is autofilled.
20430     *
20431     * @param canvas The canvas to draw on
20432     */
20433    private void drawAutofilledHighlight(@NonNull Canvas canvas) {
20434        if (isAutofilled()) {
20435            Drawable autofilledHighlight = getAutofilledDrawable();
20436
20437            autofilledHighlight.setBounds(0, 0, getWidth(), getHeight());
20438            autofilledHighlight.draw(canvas);
20439        }
20440    }
20441
20442    /**
20443     * Draw any foreground content for this view.
20444     *
20445     * <p>Foreground content may consist of scroll bars, a {@link #setForeground foreground}
20446     * drawable or other view-specific decorations. The foreground is drawn on top of the
20447     * primary view content.</p>
20448     *
20449     * @param canvas canvas to draw into
20450     */
20451    public void onDrawForeground(Canvas canvas) {
20452        onDrawScrollIndicators(canvas);
20453        onDrawScrollBars(canvas);
20454
20455        final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
20456        if (foreground != null) {
20457            if (mForegroundInfo.mBoundsChanged) {
20458                mForegroundInfo.mBoundsChanged = false;
20459                final Rect selfBounds = mForegroundInfo.mSelfBounds;
20460                final Rect overlayBounds = mForegroundInfo.mOverlayBounds;
20461
20462                if (mForegroundInfo.mInsidePadding) {
20463                    selfBounds.set(0, 0, getWidth(), getHeight());
20464                } else {
20465                    selfBounds.set(getPaddingLeft(), getPaddingTop(),
20466                            getWidth() - getPaddingRight(), getHeight() - getPaddingBottom());
20467                }
20468
20469                final int ld = getLayoutDirection();
20470                Gravity.apply(mForegroundInfo.mGravity, foreground.getIntrinsicWidth(),
20471                        foreground.getIntrinsicHeight(), selfBounds, overlayBounds, ld);
20472                foreground.setBounds(overlayBounds);
20473            }
20474
20475            foreground.draw(canvas);
20476        }
20477    }
20478
20479    /**
20480     * Sets the padding. The view may add on the space required to display
20481     * the scrollbars, depending on the style and visibility of the scrollbars.
20482     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
20483     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
20484     * from the values set in this call.
20485     *
20486     * @attr ref android.R.styleable#View_padding
20487     * @attr ref android.R.styleable#View_paddingBottom
20488     * @attr ref android.R.styleable#View_paddingLeft
20489     * @attr ref android.R.styleable#View_paddingRight
20490     * @attr ref android.R.styleable#View_paddingTop
20491     * @param left the left padding in pixels
20492     * @param top the top padding in pixels
20493     * @param right the right padding in pixels
20494     * @param bottom the bottom padding in pixels
20495     */
20496    public void setPadding(int left, int top, int right, int bottom) {
20497        resetResolvedPaddingInternal();
20498
20499        mUserPaddingStart = UNDEFINED_PADDING;
20500        mUserPaddingEnd = UNDEFINED_PADDING;
20501
20502        mUserPaddingLeftInitial = left;
20503        mUserPaddingRightInitial = right;
20504
20505        mLeftPaddingDefined = true;
20506        mRightPaddingDefined = true;
20507
20508        internalSetPadding(left, top, right, bottom);
20509    }
20510
20511    /**
20512     * @hide
20513     */
20514    protected void internalSetPadding(int left, int top, int right, int bottom) {
20515        mUserPaddingLeft = left;
20516        mUserPaddingRight = right;
20517        mUserPaddingBottom = bottom;
20518
20519        final int viewFlags = mViewFlags;
20520        boolean changed = false;
20521
20522        // Common case is there are no scroll bars.
20523        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
20524            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
20525                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
20526                        ? 0 : getVerticalScrollbarWidth();
20527                switch (mVerticalScrollbarPosition) {
20528                    case SCROLLBAR_POSITION_DEFAULT:
20529                        if (isLayoutRtl()) {
20530                            left += offset;
20531                        } else {
20532                            right += offset;
20533                        }
20534                        break;
20535                    case SCROLLBAR_POSITION_RIGHT:
20536                        right += offset;
20537                        break;
20538                    case SCROLLBAR_POSITION_LEFT:
20539                        left += offset;
20540                        break;
20541                }
20542            }
20543            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
20544                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
20545                        ? 0 : getHorizontalScrollbarHeight();
20546            }
20547        }
20548
20549        if (mPaddingLeft != left) {
20550            changed = true;
20551            mPaddingLeft = left;
20552        }
20553        if (mPaddingTop != top) {
20554            changed = true;
20555            mPaddingTop = top;
20556        }
20557        if (mPaddingRight != right) {
20558            changed = true;
20559            mPaddingRight = right;
20560        }
20561        if (mPaddingBottom != bottom) {
20562            changed = true;
20563            mPaddingBottom = bottom;
20564        }
20565
20566        if (changed) {
20567            requestLayout();
20568            invalidateOutline();
20569        }
20570    }
20571
20572    /**
20573     * Sets the relative padding. The view may add on the space required to display
20574     * the scrollbars, depending on the style and visibility of the scrollbars.
20575     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
20576     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
20577     * from the values set in this call.
20578     *
20579     * @attr ref android.R.styleable#View_padding
20580     * @attr ref android.R.styleable#View_paddingBottom
20581     * @attr ref android.R.styleable#View_paddingStart
20582     * @attr ref android.R.styleable#View_paddingEnd
20583     * @attr ref android.R.styleable#View_paddingTop
20584     * @param start the start padding in pixels
20585     * @param top the top padding in pixels
20586     * @param end the end padding in pixels
20587     * @param bottom the bottom padding in pixels
20588     */
20589    public void setPaddingRelative(int start, int top, int end, int bottom) {
20590        resetResolvedPaddingInternal();
20591
20592        mUserPaddingStart = start;
20593        mUserPaddingEnd = end;
20594        mLeftPaddingDefined = true;
20595        mRightPaddingDefined = true;
20596
20597        switch(getLayoutDirection()) {
20598            case LAYOUT_DIRECTION_RTL:
20599                mUserPaddingLeftInitial = end;
20600                mUserPaddingRightInitial = start;
20601                internalSetPadding(end, top, start, bottom);
20602                break;
20603            case LAYOUT_DIRECTION_LTR:
20604            default:
20605                mUserPaddingLeftInitial = start;
20606                mUserPaddingRightInitial = end;
20607                internalSetPadding(start, top, end, bottom);
20608        }
20609    }
20610
20611    /**
20612     * Returns the top padding of this view.
20613     *
20614     * @return the top padding in pixels
20615     */
20616    public int getPaddingTop() {
20617        return mPaddingTop;
20618    }
20619
20620    /**
20621     * Returns the bottom padding of this view. If there are inset and enabled
20622     * scrollbars, this value may include the space required to display the
20623     * scrollbars as well.
20624     *
20625     * @return the bottom padding in pixels
20626     */
20627    public int getPaddingBottom() {
20628        return mPaddingBottom;
20629    }
20630
20631    /**
20632     * Returns the left padding of this view. If there are inset and enabled
20633     * scrollbars, this value may include the space required to display the
20634     * scrollbars as well.
20635     *
20636     * @return the left padding in pixels
20637     */
20638    public int getPaddingLeft() {
20639        if (!isPaddingResolved()) {
20640            resolvePadding();
20641        }
20642        return mPaddingLeft;
20643    }
20644
20645    /**
20646     * Returns the start padding of this view depending on its resolved layout direction.
20647     * If there are inset and enabled scrollbars, this value may include the space
20648     * required to display the scrollbars as well.
20649     *
20650     * @return the start padding in pixels
20651     */
20652    public int getPaddingStart() {
20653        if (!isPaddingResolved()) {
20654            resolvePadding();
20655        }
20656        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
20657                mPaddingRight : mPaddingLeft;
20658    }
20659
20660    /**
20661     * Returns the right padding of this view. If there are inset and enabled
20662     * scrollbars, this value may include the space required to display the
20663     * scrollbars as well.
20664     *
20665     * @return the right padding in pixels
20666     */
20667    public int getPaddingRight() {
20668        if (!isPaddingResolved()) {
20669            resolvePadding();
20670        }
20671        return mPaddingRight;
20672    }
20673
20674    /**
20675     * Returns the end padding of this view depending on its resolved layout direction.
20676     * If there are inset and enabled scrollbars, this value may include the space
20677     * required to display the scrollbars as well.
20678     *
20679     * @return the end padding in pixels
20680     */
20681    public int getPaddingEnd() {
20682        if (!isPaddingResolved()) {
20683            resolvePadding();
20684        }
20685        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
20686                mPaddingLeft : mPaddingRight;
20687    }
20688
20689    /**
20690     * Return if the padding has been set through relative values
20691     * {@link #setPaddingRelative(int, int, int, int)} or through
20692     * @attr ref android.R.styleable#View_paddingStart or
20693     * @attr ref android.R.styleable#View_paddingEnd
20694     *
20695     * @return true if the padding is relative or false if it is not.
20696     */
20697    public boolean isPaddingRelative() {
20698        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
20699    }
20700
20701    Insets computeOpticalInsets() {
20702        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
20703    }
20704
20705    /**
20706     * @hide
20707     */
20708    public void resetPaddingToInitialValues() {
20709        if (isRtlCompatibilityMode()) {
20710            mPaddingLeft = mUserPaddingLeftInitial;
20711            mPaddingRight = mUserPaddingRightInitial;
20712            return;
20713        }
20714        if (isLayoutRtl()) {
20715            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
20716            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
20717        } else {
20718            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
20719            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
20720        }
20721    }
20722
20723    /**
20724     * @hide
20725     */
20726    public Insets getOpticalInsets() {
20727        if (mLayoutInsets == null) {
20728            mLayoutInsets = computeOpticalInsets();
20729        }
20730        return mLayoutInsets;
20731    }
20732
20733    /**
20734     * Set this view's optical insets.
20735     *
20736     * <p>This method should be treated similarly to setMeasuredDimension and not as a general
20737     * property. Views that compute their own optical insets should call it as part of measurement.
20738     * This method does not request layout. If you are setting optical insets outside of
20739     * measure/layout itself you will want to call requestLayout() yourself.
20740     * </p>
20741     * @hide
20742     */
20743    public void setOpticalInsets(Insets insets) {
20744        mLayoutInsets = insets;
20745    }
20746
20747    /**
20748     * Changes the selection state of this view. A view can be selected or not.
20749     * Note that selection is not the same as focus. Views are typically
20750     * selected in the context of an AdapterView like ListView or GridView;
20751     * the selected view is the view that is highlighted.
20752     *
20753     * @param selected true if the view must be selected, false otherwise
20754     */
20755    public void setSelected(boolean selected) {
20756        //noinspection DoubleNegation
20757        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
20758            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
20759            if (!selected) resetPressedState();
20760            invalidate(true);
20761            refreshDrawableState();
20762            dispatchSetSelected(selected);
20763            if (selected) {
20764                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
20765            } else {
20766                notifyViewAccessibilityStateChangedIfNeeded(
20767                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
20768            }
20769        }
20770    }
20771
20772    /**
20773     * Dispatch setSelected to all of this View's children.
20774     *
20775     * @see #setSelected(boolean)
20776     *
20777     * @param selected The new selected state
20778     */
20779    protected void dispatchSetSelected(boolean selected) {
20780    }
20781
20782    /**
20783     * Indicates the selection state of this view.
20784     *
20785     * @return true if the view is selected, false otherwise
20786     */
20787    @ViewDebug.ExportedProperty
20788    public boolean isSelected() {
20789        return (mPrivateFlags & PFLAG_SELECTED) != 0;
20790    }
20791
20792    /**
20793     * Changes the activated state of this view. A view can be activated or not.
20794     * Note that activation is not the same as selection.  Selection is
20795     * a transient property, representing the view (hierarchy) the user is
20796     * currently interacting with.  Activation is a longer-term state that the
20797     * user can move views in and out of.  For example, in a list view with
20798     * single or multiple selection enabled, the views in the current selection
20799     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
20800     * here.)  The activated state is propagated down to children of the view it
20801     * is set on.
20802     *
20803     * @param activated true if the view must be activated, false otherwise
20804     */
20805    public void setActivated(boolean activated) {
20806        //noinspection DoubleNegation
20807        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
20808            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
20809            invalidate(true);
20810            refreshDrawableState();
20811            dispatchSetActivated(activated);
20812        }
20813    }
20814
20815    /**
20816     * Dispatch setActivated to all of this View's children.
20817     *
20818     * @see #setActivated(boolean)
20819     *
20820     * @param activated The new activated state
20821     */
20822    protected void dispatchSetActivated(boolean activated) {
20823    }
20824
20825    /**
20826     * Indicates the activation state of this view.
20827     *
20828     * @return true if the view is activated, false otherwise
20829     */
20830    @ViewDebug.ExportedProperty
20831    public boolean isActivated() {
20832        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
20833    }
20834
20835    /**
20836     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
20837     * observer can be used to get notifications when global events, like
20838     * layout, happen.
20839     *
20840     * The returned ViewTreeObserver observer is not guaranteed to remain
20841     * valid for the lifetime of this View. If the caller of this method keeps
20842     * a long-lived reference to ViewTreeObserver, it should always check for
20843     * the return value of {@link ViewTreeObserver#isAlive()}.
20844     *
20845     * @return The ViewTreeObserver for this view's hierarchy.
20846     */
20847    public ViewTreeObserver getViewTreeObserver() {
20848        if (mAttachInfo != null) {
20849            return mAttachInfo.mTreeObserver;
20850        }
20851        if (mFloatingTreeObserver == null) {
20852            mFloatingTreeObserver = new ViewTreeObserver(mContext);
20853        }
20854        return mFloatingTreeObserver;
20855    }
20856
20857    /**
20858     * <p>Finds the topmost view in the current view hierarchy.</p>
20859     *
20860     * @return the topmost view containing this view
20861     */
20862    public View getRootView() {
20863        if (mAttachInfo != null) {
20864            final View v = mAttachInfo.mRootView;
20865            if (v != null) {
20866                return v;
20867            }
20868        }
20869
20870        View parent = this;
20871
20872        while (parent.mParent != null && parent.mParent instanceof View) {
20873            parent = (View) parent.mParent;
20874        }
20875
20876        return parent;
20877    }
20878
20879    /**
20880     * Transforms a motion event from view-local coordinates to on-screen
20881     * coordinates.
20882     *
20883     * @param ev the view-local motion event
20884     * @return false if the transformation could not be applied
20885     * @hide
20886     */
20887    public boolean toGlobalMotionEvent(MotionEvent ev) {
20888        final AttachInfo info = mAttachInfo;
20889        if (info == null) {
20890            return false;
20891        }
20892
20893        final Matrix m = info.mTmpMatrix;
20894        m.set(Matrix.IDENTITY_MATRIX);
20895        transformMatrixToGlobal(m);
20896        ev.transform(m);
20897        return true;
20898    }
20899
20900    /**
20901     * Transforms a motion event from on-screen coordinates to view-local
20902     * coordinates.
20903     *
20904     * @param ev the on-screen motion event
20905     * @return false if the transformation could not be applied
20906     * @hide
20907     */
20908    public boolean toLocalMotionEvent(MotionEvent ev) {
20909        final AttachInfo info = mAttachInfo;
20910        if (info == null) {
20911            return false;
20912        }
20913
20914        final Matrix m = info.mTmpMatrix;
20915        m.set(Matrix.IDENTITY_MATRIX);
20916        transformMatrixToLocal(m);
20917        ev.transform(m);
20918        return true;
20919    }
20920
20921    /**
20922     * Modifies the input matrix such that it maps view-local coordinates to
20923     * on-screen coordinates.
20924     *
20925     * @param m input matrix to modify
20926     * @hide
20927     */
20928    public void transformMatrixToGlobal(Matrix m) {
20929        final ViewParent parent = mParent;
20930        if (parent instanceof View) {
20931            final View vp = (View) parent;
20932            vp.transformMatrixToGlobal(m);
20933            m.preTranslate(-vp.mScrollX, -vp.mScrollY);
20934        } else if (parent instanceof ViewRootImpl) {
20935            final ViewRootImpl vr = (ViewRootImpl) parent;
20936            vr.transformMatrixToGlobal(m);
20937            m.preTranslate(0, -vr.mCurScrollY);
20938        }
20939
20940        m.preTranslate(mLeft, mTop);
20941
20942        if (!hasIdentityMatrix()) {
20943            m.preConcat(getMatrix());
20944        }
20945    }
20946
20947    /**
20948     * Modifies the input matrix such that it maps on-screen coordinates to
20949     * view-local coordinates.
20950     *
20951     * @param m input matrix to modify
20952     * @hide
20953     */
20954    public void transformMatrixToLocal(Matrix m) {
20955        final ViewParent parent = mParent;
20956        if (parent instanceof View) {
20957            final View vp = (View) parent;
20958            vp.transformMatrixToLocal(m);
20959            m.postTranslate(vp.mScrollX, vp.mScrollY);
20960        } else if (parent instanceof ViewRootImpl) {
20961            final ViewRootImpl vr = (ViewRootImpl) parent;
20962            vr.transformMatrixToLocal(m);
20963            m.postTranslate(0, vr.mCurScrollY);
20964        }
20965
20966        m.postTranslate(-mLeft, -mTop);
20967
20968        if (!hasIdentityMatrix()) {
20969            m.postConcat(getInverseMatrix());
20970        }
20971    }
20972
20973    /**
20974     * @hide
20975     */
20976    @ViewDebug.ExportedProperty(category = "layout", indexMapping = {
20977            @ViewDebug.IntToString(from = 0, to = "x"),
20978            @ViewDebug.IntToString(from = 1, to = "y")
20979    })
20980    public int[] getLocationOnScreen() {
20981        int[] location = new int[2];
20982        getLocationOnScreen(location);
20983        return location;
20984    }
20985
20986    /**
20987     * <p>Computes the coordinates of this view on the screen. The argument
20988     * must be an array of two integers. After the method returns, the array
20989     * contains the x and y location in that order.</p>
20990     *
20991     * @param outLocation an array of two integers in which to hold the coordinates
20992     */
20993    public void getLocationOnScreen(@Size(2) int[] outLocation) {
20994        getLocationInWindow(outLocation);
20995
20996        final AttachInfo info = mAttachInfo;
20997        if (info != null) {
20998            outLocation[0] += info.mWindowLeft;
20999            outLocation[1] += info.mWindowTop;
21000        }
21001    }
21002
21003    /**
21004     * <p>Computes the coordinates of this view in its window. The argument
21005     * must be an array of two integers. After the method returns, the array
21006     * contains the x and y location in that order.</p>
21007     *
21008     * @param outLocation an array of two integers in which to hold the coordinates
21009     */
21010    public void getLocationInWindow(@Size(2) int[] outLocation) {
21011        if (outLocation == null || outLocation.length < 2) {
21012            throw new IllegalArgumentException("outLocation must be an array of two integers");
21013        }
21014
21015        outLocation[0] = 0;
21016        outLocation[1] = 0;
21017
21018        transformFromViewToWindowSpace(outLocation);
21019    }
21020
21021    /** @hide */
21022    public void transformFromViewToWindowSpace(@Size(2) int[] inOutLocation) {
21023        if (inOutLocation == null || inOutLocation.length < 2) {
21024            throw new IllegalArgumentException("inOutLocation must be an array of two integers");
21025        }
21026
21027        if (mAttachInfo == null) {
21028            // When the view is not attached to a window, this method does not make sense
21029            inOutLocation[0] = inOutLocation[1] = 0;
21030            return;
21031        }
21032
21033        float position[] = mAttachInfo.mTmpTransformLocation;
21034        position[0] = inOutLocation[0];
21035        position[1] = inOutLocation[1];
21036
21037        if (!hasIdentityMatrix()) {
21038            getMatrix().mapPoints(position);
21039        }
21040
21041        position[0] += mLeft;
21042        position[1] += mTop;
21043
21044        ViewParent viewParent = mParent;
21045        while (viewParent instanceof View) {
21046            final View view = (View) viewParent;
21047
21048            position[0] -= view.mScrollX;
21049            position[1] -= view.mScrollY;
21050
21051            if (!view.hasIdentityMatrix()) {
21052                view.getMatrix().mapPoints(position);
21053            }
21054
21055            position[0] += view.mLeft;
21056            position[1] += view.mTop;
21057
21058            viewParent = view.mParent;
21059         }
21060
21061        if (viewParent instanceof ViewRootImpl) {
21062            // *cough*
21063            final ViewRootImpl vr = (ViewRootImpl) viewParent;
21064            position[1] -= vr.mCurScrollY;
21065        }
21066
21067        inOutLocation[0] = Math.round(position[0]);
21068        inOutLocation[1] = Math.round(position[1]);
21069    }
21070
21071    /**
21072     * @param id the id of the view to be found
21073     * @return the view of the specified id, null if cannot be found
21074     * @hide
21075     */
21076    protected <T extends View> T findViewTraversal(@IdRes int id) {
21077        if (id == mID) {
21078            return (T) this;
21079        }
21080        return null;
21081    }
21082
21083    /**
21084     * @param tag the tag of the view to be found
21085     * @return the view of specified tag, null if cannot be found
21086     * @hide
21087     */
21088    protected <T extends View> T findViewWithTagTraversal(Object tag) {
21089        if (tag != null && tag.equals(mTag)) {
21090            return (T) this;
21091        }
21092        return null;
21093    }
21094
21095    /**
21096     * @param predicate The predicate to evaluate.
21097     * @param childToSkip If not null, ignores this child during the recursive traversal.
21098     * @return The first view that matches the predicate or null.
21099     * @hide
21100     */
21101    protected <T extends View> T findViewByPredicateTraversal(Predicate<View> predicate,
21102            View childToSkip) {
21103        if (predicate.test(this)) {
21104            return (T) this;
21105        }
21106        return null;
21107    }
21108
21109    /**
21110     * Finds the first descendant view with the given ID, the view itself if
21111     * the ID matches {@link #getId()}, or {@code null} if the ID is invalid
21112     * (< 0) or there is no matching view in the hierarchy.
21113     * <p>
21114     * <strong>Note:</strong> In most cases -- depending on compiler support --
21115     * the resulting view is automatically cast to the target class type. If
21116     * the target class type is unconstrained, an explicit cast may be
21117     * necessary.
21118     *
21119     * @param id the ID to search for
21120     * @return a view with given ID if found, or {@code null} otherwise
21121     * @see View#findViewById(int)
21122     */
21123    @Nullable
21124    public final <T extends View> T findViewById(@IdRes int id) {
21125        if (id < 0) {
21126            return null;
21127        }
21128        return findViewTraversal(id);
21129    }
21130
21131    /**
21132     * Finds a view by its unuque and stable accessibility id.
21133     *
21134     * @param accessibilityId The searched accessibility id.
21135     * @return The found view.
21136     */
21137    final <T extends View> T  findViewByAccessibilityId(int accessibilityId) {
21138        if (accessibilityId < 0) {
21139            return null;
21140        }
21141        T view = findViewByAccessibilityIdTraversal(accessibilityId);
21142        if (view != null) {
21143            return view.includeForAccessibility() ? view : null;
21144        }
21145        return null;
21146    }
21147
21148    /**
21149     * Performs the traversal to find a view by its unuque and stable accessibility id.
21150     *
21151     * <strong>Note:</strong>This method does not stop at the root namespace
21152     * boundary since the user can touch the screen at an arbitrary location
21153     * potentially crossing the root namespace bounday which will send an
21154     * accessibility event to accessibility services and they should be able
21155     * to obtain the event source. Also accessibility ids are guaranteed to be
21156     * unique in the window.
21157     *
21158     * @param accessibilityId The accessibility id.
21159     * @return The found view.
21160     * @hide
21161     */
21162    public <T extends View> T findViewByAccessibilityIdTraversal(int accessibilityId) {
21163        if (getAccessibilityViewId() == accessibilityId) {
21164            return (T) this;
21165        }
21166        return null;
21167    }
21168
21169    /**
21170     * Look for a child view with the given tag.  If this view has the given
21171     * tag, return this view.
21172     *
21173     * @param tag The tag to search for, using "tag.equals(getTag())".
21174     * @return The View that has the given tag in the hierarchy or null
21175     */
21176    public final <T extends View> T findViewWithTag(Object tag) {
21177        if (tag == null) {
21178            return null;
21179        }
21180        return findViewWithTagTraversal(tag);
21181    }
21182
21183    /**
21184     * Look for a child view that matches the specified predicate.
21185     * If this view matches the predicate, return this view.
21186     *
21187     * @param predicate The predicate to evaluate.
21188     * @return The first view that matches the predicate or null.
21189     * @hide
21190     */
21191    public final <T extends View> T findViewByPredicate(Predicate<View> predicate) {
21192        return findViewByPredicateTraversal(predicate, null);
21193    }
21194
21195    /**
21196     * Look for a child view that matches the specified predicate,
21197     * starting with the specified view and its descendents and then
21198     * recusively searching the ancestors and siblings of that view
21199     * until this view is reached.
21200     *
21201     * This method is useful in cases where the predicate does not match
21202     * a single unique view (perhaps multiple views use the same id)
21203     * and we are trying to find the view that is "closest" in scope to the
21204     * starting view.
21205     *
21206     * @param start The view to start from.
21207     * @param predicate The predicate to evaluate.
21208     * @return The first view that matches the predicate or null.
21209     * @hide
21210     */
21211    public final <T extends View> T findViewByPredicateInsideOut(
21212            View start, Predicate<View> predicate) {
21213        View childToSkip = null;
21214        for (;;) {
21215            T view = start.findViewByPredicateTraversal(predicate, childToSkip);
21216            if (view != null || start == this) {
21217                return view;
21218            }
21219
21220            ViewParent parent = start.getParent();
21221            if (parent == null || !(parent instanceof View)) {
21222                return null;
21223            }
21224
21225            childToSkip = start;
21226            start = (View) parent;
21227        }
21228    }
21229
21230    /**
21231     * Sets the identifier for this view. The identifier does not have to be
21232     * unique in this view's hierarchy. The identifier should be a positive
21233     * number.
21234     *
21235     * @see #NO_ID
21236     * @see #getId()
21237     * @see #findViewById(int)
21238     *
21239     * @param id a number used to identify the view
21240     *
21241     * @attr ref android.R.styleable#View_id
21242     */
21243    public void setId(@IdRes int id) {
21244        mID = id;
21245        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
21246            mID = generateViewId();
21247        }
21248    }
21249
21250    /**
21251     * {@hide}
21252     *
21253     * @param isRoot true if the view belongs to the root namespace, false
21254     *        otherwise
21255     */
21256    public void setIsRootNamespace(boolean isRoot) {
21257        if (isRoot) {
21258            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
21259        } else {
21260            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
21261        }
21262    }
21263
21264    /**
21265     * {@hide}
21266     *
21267     * @return true if the view belongs to the root namespace, false otherwise
21268     */
21269    public boolean isRootNamespace() {
21270        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
21271    }
21272
21273    /**
21274     * Returns this view's identifier.
21275     *
21276     * @return a positive integer used to identify the view or {@link #NO_ID}
21277     *         if the view has no ID
21278     *
21279     * @see #setId(int)
21280     * @see #findViewById(int)
21281     * @attr ref android.R.styleable#View_id
21282     */
21283    @IdRes
21284    @ViewDebug.CapturedViewProperty
21285    public int getId() {
21286        return mID;
21287    }
21288
21289    /**
21290     * Returns this view's tag.
21291     *
21292     * @return the Object stored in this view as a tag, or {@code null} if not
21293     *         set
21294     *
21295     * @see #setTag(Object)
21296     * @see #getTag(int)
21297     */
21298    @ViewDebug.ExportedProperty
21299    public Object getTag() {
21300        return mTag;
21301    }
21302
21303    /**
21304     * Sets the tag associated with this view. A tag can be used to mark
21305     * a view in its hierarchy and does not have to be unique within the
21306     * hierarchy. Tags can also be used to store data within a view without
21307     * resorting to another data structure.
21308     *
21309     * @param tag an Object to tag the view with
21310     *
21311     * @see #getTag()
21312     * @see #setTag(int, Object)
21313     */
21314    public void setTag(final Object tag) {
21315        mTag = tag;
21316    }
21317
21318    /**
21319     * Returns the tag associated with this view and the specified key.
21320     *
21321     * @param key The key identifying the tag
21322     *
21323     * @return the Object stored in this view as a tag, or {@code null} if not
21324     *         set
21325     *
21326     * @see #setTag(int, Object)
21327     * @see #getTag()
21328     */
21329    public Object getTag(int key) {
21330        if (mKeyedTags != null) return mKeyedTags.get(key);
21331        return null;
21332    }
21333
21334    /**
21335     * Sets a tag associated with this view and a key. A tag can be used
21336     * to mark a view in its hierarchy and does not have to be unique within
21337     * the hierarchy. Tags can also be used to store data within a view
21338     * without resorting to another data structure.
21339     *
21340     * The specified key should be an id declared in the resources of the
21341     * application to ensure it is unique (see the <a
21342     * href="{@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
21343     * Keys identified as belonging to
21344     * the Android framework or not associated with any package will cause
21345     * an {@link IllegalArgumentException} to be thrown.
21346     *
21347     * @param key The key identifying the tag
21348     * @param tag An Object to tag the view with
21349     *
21350     * @throws IllegalArgumentException If they specified key is not valid
21351     *
21352     * @see #setTag(Object)
21353     * @see #getTag(int)
21354     */
21355    public void setTag(int key, final Object tag) {
21356        // If the package id is 0x00 or 0x01, it's either an undefined package
21357        // or a framework id
21358        if ((key >>> 24) < 2) {
21359            throw new IllegalArgumentException("The key must be an application-specific "
21360                    + "resource id.");
21361        }
21362
21363        setKeyedTag(key, tag);
21364    }
21365
21366    /**
21367     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
21368     * framework id.
21369     *
21370     * @hide
21371     */
21372    public void setTagInternal(int key, Object tag) {
21373        if ((key >>> 24) != 0x1) {
21374            throw new IllegalArgumentException("The key must be a framework-specific "
21375                    + "resource id.");
21376        }
21377
21378        setKeyedTag(key, tag);
21379    }
21380
21381    private void setKeyedTag(int key, Object tag) {
21382        if (mKeyedTags == null) {
21383            mKeyedTags = new SparseArray<Object>(2);
21384        }
21385
21386        mKeyedTags.put(key, tag);
21387    }
21388
21389    /**
21390     * Prints information about this view in the log output, with the tag
21391     * {@link #VIEW_LOG_TAG}.
21392     *
21393     * @hide
21394     */
21395    public void debug() {
21396        debug(0);
21397    }
21398
21399    /**
21400     * Prints information about this view in the log output, with the tag
21401     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
21402     * indentation defined by the <code>depth</code>.
21403     *
21404     * @param depth the indentation level
21405     *
21406     * @hide
21407     */
21408    protected void debug(int depth) {
21409        String output = debugIndent(depth - 1);
21410
21411        output += "+ " + this;
21412        int id = getId();
21413        if (id != -1) {
21414            output += " (id=" + id + ")";
21415        }
21416        Object tag = getTag();
21417        if (tag != null) {
21418            output += " (tag=" + tag + ")";
21419        }
21420        Log.d(VIEW_LOG_TAG, output);
21421
21422        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
21423            output = debugIndent(depth) + " FOCUSED";
21424            Log.d(VIEW_LOG_TAG, output);
21425        }
21426
21427        output = debugIndent(depth);
21428        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
21429                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
21430                + "} ";
21431        Log.d(VIEW_LOG_TAG, output);
21432
21433        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
21434                || mPaddingBottom != 0) {
21435            output = debugIndent(depth);
21436            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
21437                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
21438            Log.d(VIEW_LOG_TAG, output);
21439        }
21440
21441        output = debugIndent(depth);
21442        output += "mMeasureWidth=" + mMeasuredWidth +
21443                " mMeasureHeight=" + mMeasuredHeight;
21444        Log.d(VIEW_LOG_TAG, output);
21445
21446        output = debugIndent(depth);
21447        if (mLayoutParams == null) {
21448            output += "BAD! no layout params";
21449        } else {
21450            output = mLayoutParams.debug(output);
21451        }
21452        Log.d(VIEW_LOG_TAG, output);
21453
21454        output = debugIndent(depth);
21455        output += "flags={";
21456        output += View.printFlags(mViewFlags);
21457        output += "}";
21458        Log.d(VIEW_LOG_TAG, output);
21459
21460        output = debugIndent(depth);
21461        output += "privateFlags={";
21462        output += View.printPrivateFlags(mPrivateFlags);
21463        output += "}";
21464        Log.d(VIEW_LOG_TAG, output);
21465    }
21466
21467    /**
21468     * Creates a string of whitespaces used for indentation.
21469     *
21470     * @param depth the indentation level
21471     * @return a String containing (depth * 2 + 3) * 2 white spaces
21472     *
21473     * @hide
21474     */
21475    protected static String debugIndent(int depth) {
21476        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
21477        for (int i = 0; i < (depth * 2) + 3; i++) {
21478            spaces.append(' ').append(' ');
21479        }
21480        return spaces.toString();
21481    }
21482
21483    /**
21484     * <p>Return the offset of the widget's text baseline from the widget's top
21485     * boundary. If this widget does not support baseline alignment, this
21486     * method returns -1. </p>
21487     *
21488     * @return the offset of the baseline within the widget's bounds or -1
21489     *         if baseline alignment is not supported
21490     */
21491    @ViewDebug.ExportedProperty(category = "layout")
21492    public int getBaseline() {
21493        return -1;
21494    }
21495
21496    /**
21497     * Returns whether the view hierarchy is currently undergoing a layout pass. This
21498     * information is useful to avoid situations such as calling {@link #requestLayout()} during
21499     * a layout pass.
21500     *
21501     * @return whether the view hierarchy is currently undergoing a layout pass
21502     */
21503    public boolean isInLayout() {
21504        ViewRootImpl viewRoot = getViewRootImpl();
21505        return (viewRoot != null && viewRoot.isInLayout());
21506    }
21507
21508    /**
21509     * Call this when something has changed which has invalidated the
21510     * layout of this view. This will schedule a layout pass of the view
21511     * tree. This should not be called while the view hierarchy is currently in a layout
21512     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
21513     * end of the current layout pass (and then layout will run again) or after the current
21514     * frame is drawn and the next layout occurs.
21515     *
21516     * <p>Subclasses which override this method should call the superclass method to
21517     * handle possible request-during-layout errors correctly.</p>
21518     */
21519    @CallSuper
21520    public void requestLayout() {
21521        if (mMeasureCache != null) mMeasureCache.clear();
21522
21523        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
21524            // Only trigger request-during-layout logic if this is the view requesting it,
21525            // not the views in its parent hierarchy
21526            ViewRootImpl viewRoot = getViewRootImpl();
21527            if (viewRoot != null && viewRoot.isInLayout()) {
21528                if (!viewRoot.requestLayoutDuringLayout(this)) {
21529                    return;
21530                }
21531            }
21532            mAttachInfo.mViewRequestingLayout = this;
21533        }
21534
21535        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
21536        mPrivateFlags |= PFLAG_INVALIDATED;
21537
21538        if (mParent != null && !mParent.isLayoutRequested()) {
21539            mParent.requestLayout();
21540        }
21541        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
21542            mAttachInfo.mViewRequestingLayout = null;
21543        }
21544    }
21545
21546    /**
21547     * Forces this view to be laid out during the next layout pass.
21548     * This method does not call requestLayout() or forceLayout()
21549     * on the parent.
21550     */
21551    public void forceLayout() {
21552        if (mMeasureCache != null) mMeasureCache.clear();
21553
21554        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
21555        mPrivateFlags |= PFLAG_INVALIDATED;
21556    }
21557
21558    /**
21559     * <p>
21560     * This is called to find out how big a view should be. The parent
21561     * supplies constraint information in the width and height parameters.
21562     * </p>
21563     *
21564     * <p>
21565     * The actual measurement work of a view is performed in
21566     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
21567     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
21568     * </p>
21569     *
21570     *
21571     * @param widthMeasureSpec Horizontal space requirements as imposed by the
21572     *        parent
21573     * @param heightMeasureSpec Vertical space requirements as imposed by the
21574     *        parent
21575     *
21576     * @see #onMeasure(int, int)
21577     */
21578    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
21579        boolean optical = isLayoutModeOptical(this);
21580        if (optical != isLayoutModeOptical(mParent)) {
21581            Insets insets = getOpticalInsets();
21582            int oWidth  = insets.left + insets.right;
21583            int oHeight = insets.top  + insets.bottom;
21584            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
21585            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
21586        }
21587
21588        // Suppress sign extension for the low bytes
21589        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
21590        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
21591
21592        final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
21593
21594        // Optimize layout by avoiding an extra EXACTLY pass when the view is
21595        // already measured as the correct size. In API 23 and below, this
21596        // extra pass is required to make LinearLayout re-distribute weight.
21597        final boolean specChanged = widthMeasureSpec != mOldWidthMeasureSpec
21598                || heightMeasureSpec != mOldHeightMeasureSpec;
21599        final boolean isSpecExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY
21600                && MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY;
21601        final boolean matchesSpecSize = getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec)
21602                && getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec);
21603        final boolean needsLayout = specChanged
21604                && (sAlwaysRemeasureExactly || !isSpecExactly || !matchesSpecSize);
21605
21606        if (forceLayout || needsLayout) {
21607            // first clears the measured dimension flag
21608            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
21609
21610            resolveRtlPropertiesIfNeeded();
21611
21612            int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key);
21613            if (cacheIndex < 0 || sIgnoreMeasureCache) {
21614                // measure ourselves, this should set the measured dimension flag back
21615                onMeasure(widthMeasureSpec, heightMeasureSpec);
21616                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
21617            } else {
21618                long value = mMeasureCache.valueAt(cacheIndex);
21619                // Casting a long to int drops the high 32 bits, no mask needed
21620                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
21621                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
21622            }
21623
21624            // flag not set, setMeasuredDimension() was not invoked, we raise
21625            // an exception to warn the developer
21626            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
21627                throw new IllegalStateException("View with id " + getId() + ": "
21628                        + getClass().getName() + "#onMeasure() did not set the"
21629                        + " measured dimension by calling"
21630                        + " setMeasuredDimension()");
21631            }
21632
21633            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
21634        }
21635
21636        mOldWidthMeasureSpec = widthMeasureSpec;
21637        mOldHeightMeasureSpec = heightMeasureSpec;
21638
21639        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
21640                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
21641    }
21642
21643    /**
21644     * <p>
21645     * Measure the view and its content to determine the measured width and the
21646     * measured height. This method is invoked by {@link #measure(int, int)} and
21647     * should be overridden by subclasses to provide accurate and efficient
21648     * measurement of their contents.
21649     * </p>
21650     *
21651     * <p>
21652     * <strong>CONTRACT:</strong> When overriding this method, you
21653     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
21654     * measured width and height of this view. Failure to do so will trigger an
21655     * <code>IllegalStateException</code>, thrown by
21656     * {@link #measure(int, int)}. Calling the superclass'
21657     * {@link #onMeasure(int, int)} is a valid use.
21658     * </p>
21659     *
21660     * <p>
21661     * The base class implementation of measure defaults to the background size,
21662     * unless a larger size is allowed by the MeasureSpec. Subclasses should
21663     * override {@link #onMeasure(int, int)} to provide better measurements of
21664     * their content.
21665     * </p>
21666     *
21667     * <p>
21668     * If this method is overridden, it is the subclass's responsibility to make
21669     * sure the measured height and width are at least the view's minimum height
21670     * and width ({@link #getSuggestedMinimumHeight()} and
21671     * {@link #getSuggestedMinimumWidth()}).
21672     * </p>
21673     *
21674     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
21675     *                         The requirements are encoded with
21676     *                         {@link android.view.View.MeasureSpec}.
21677     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
21678     *                         The requirements are encoded with
21679     *                         {@link android.view.View.MeasureSpec}.
21680     *
21681     * @see #getMeasuredWidth()
21682     * @see #getMeasuredHeight()
21683     * @see #setMeasuredDimension(int, int)
21684     * @see #getSuggestedMinimumHeight()
21685     * @see #getSuggestedMinimumWidth()
21686     * @see android.view.View.MeasureSpec#getMode(int)
21687     * @see android.view.View.MeasureSpec#getSize(int)
21688     */
21689    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
21690        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
21691                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
21692    }
21693
21694    /**
21695     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
21696     * measured width and measured height. Failing to do so will trigger an
21697     * exception at measurement time.</p>
21698     *
21699     * @param measuredWidth The measured width of this view.  May be a complex
21700     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
21701     * {@link #MEASURED_STATE_TOO_SMALL}.
21702     * @param measuredHeight The measured height of this view.  May be a complex
21703     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
21704     * {@link #MEASURED_STATE_TOO_SMALL}.
21705     */
21706    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
21707        boolean optical = isLayoutModeOptical(this);
21708        if (optical != isLayoutModeOptical(mParent)) {
21709            Insets insets = getOpticalInsets();
21710            int opticalWidth  = insets.left + insets.right;
21711            int opticalHeight = insets.top  + insets.bottom;
21712
21713            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
21714            measuredHeight += optical ? opticalHeight : -opticalHeight;
21715        }
21716        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
21717    }
21718
21719    /**
21720     * Sets the measured dimension without extra processing for things like optical bounds.
21721     * Useful for reapplying consistent values that have already been cooked with adjustments
21722     * for optical bounds, etc. such as those from the measurement cache.
21723     *
21724     * @param measuredWidth The measured width of this view.  May be a complex
21725     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
21726     * {@link #MEASURED_STATE_TOO_SMALL}.
21727     * @param measuredHeight The measured height of this view.  May be a complex
21728     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
21729     * {@link #MEASURED_STATE_TOO_SMALL}.
21730     */
21731    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
21732        mMeasuredWidth = measuredWidth;
21733        mMeasuredHeight = measuredHeight;
21734
21735        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
21736    }
21737
21738    /**
21739     * Merge two states as returned by {@link #getMeasuredState()}.
21740     * @param curState The current state as returned from a view or the result
21741     * of combining multiple views.
21742     * @param newState The new view state to combine.
21743     * @return Returns a new integer reflecting the combination of the two
21744     * states.
21745     */
21746    public static int combineMeasuredStates(int curState, int newState) {
21747        return curState | newState;
21748    }
21749
21750    /**
21751     * Version of {@link #resolveSizeAndState(int, int, int)}
21752     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
21753     */
21754    public static int resolveSize(int size, int measureSpec) {
21755        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
21756    }
21757
21758    /**
21759     * Utility to reconcile a desired size and state, with constraints imposed
21760     * by a MeasureSpec. Will take the desired size, unless a different size
21761     * is imposed by the constraints. The returned value is a compound integer,
21762     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
21763     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the
21764     * resulting size is smaller than the size the view wants to be.
21765     *
21766     * @param size How big the view wants to be.
21767     * @param measureSpec Constraints imposed by the parent.
21768     * @param childMeasuredState Size information bit mask for the view's
21769     *                           children.
21770     * @return Size information bit mask as defined by
21771     *         {@link #MEASURED_SIZE_MASK} and
21772     *         {@link #MEASURED_STATE_TOO_SMALL}.
21773     */
21774    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
21775        final int specMode = MeasureSpec.getMode(measureSpec);
21776        final int specSize = MeasureSpec.getSize(measureSpec);
21777        final int result;
21778        switch (specMode) {
21779            case MeasureSpec.AT_MOST:
21780                if (specSize < size) {
21781                    result = specSize | MEASURED_STATE_TOO_SMALL;
21782                } else {
21783                    result = size;
21784                }
21785                break;
21786            case MeasureSpec.EXACTLY:
21787                result = specSize;
21788                break;
21789            case MeasureSpec.UNSPECIFIED:
21790            default:
21791                result = size;
21792        }
21793        return result | (childMeasuredState & MEASURED_STATE_MASK);
21794    }
21795
21796    /**
21797     * Utility to return a default size. Uses the supplied size if the
21798     * MeasureSpec imposed no constraints. Will get larger if allowed
21799     * by the MeasureSpec.
21800     *
21801     * @param size Default size for this view
21802     * @param measureSpec Constraints imposed by the parent
21803     * @return The size this view should be.
21804     */
21805    public static int getDefaultSize(int size, int measureSpec) {
21806        int result = size;
21807        int specMode = MeasureSpec.getMode(measureSpec);
21808        int specSize = MeasureSpec.getSize(measureSpec);
21809
21810        switch (specMode) {
21811        case MeasureSpec.UNSPECIFIED:
21812            result = size;
21813            break;
21814        case MeasureSpec.AT_MOST:
21815        case MeasureSpec.EXACTLY:
21816            result = specSize;
21817            break;
21818        }
21819        return result;
21820    }
21821
21822    /**
21823     * Returns the suggested minimum height that the view should use. This
21824     * returns the maximum of the view's minimum height
21825     * and the background's minimum height
21826     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
21827     * <p>
21828     * When being used in {@link #onMeasure(int, int)}, the caller should still
21829     * ensure the returned height is within the requirements of the parent.
21830     *
21831     * @return The suggested minimum height of the view.
21832     */
21833    protected int getSuggestedMinimumHeight() {
21834        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
21835
21836    }
21837
21838    /**
21839     * Returns the suggested minimum width that the view should use. This
21840     * returns the maximum of the view's minimum width
21841     * and the background's minimum width
21842     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
21843     * <p>
21844     * When being used in {@link #onMeasure(int, int)}, the caller should still
21845     * ensure the returned width is within the requirements of the parent.
21846     *
21847     * @return The suggested minimum width of the view.
21848     */
21849    protected int getSuggestedMinimumWidth() {
21850        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
21851    }
21852
21853    /**
21854     * Returns the minimum height of the view.
21855     *
21856     * @return the minimum height the view will try to be, in pixels
21857     *
21858     * @see #setMinimumHeight(int)
21859     *
21860     * @attr ref android.R.styleable#View_minHeight
21861     */
21862    public int getMinimumHeight() {
21863        return mMinHeight;
21864    }
21865
21866    /**
21867     * Sets the minimum height of the view. It is not guaranteed the view will
21868     * be able to achieve this minimum height (for example, if its parent layout
21869     * constrains it with less available height).
21870     *
21871     * @param minHeight The minimum height the view will try to be, in pixels
21872     *
21873     * @see #getMinimumHeight()
21874     *
21875     * @attr ref android.R.styleable#View_minHeight
21876     */
21877    @RemotableViewMethod
21878    public void setMinimumHeight(int minHeight) {
21879        mMinHeight = minHeight;
21880        requestLayout();
21881    }
21882
21883    /**
21884     * Returns the minimum width of the view.
21885     *
21886     * @return the minimum width the view will try to be, in pixels
21887     *
21888     * @see #setMinimumWidth(int)
21889     *
21890     * @attr ref android.R.styleable#View_minWidth
21891     */
21892    public int getMinimumWidth() {
21893        return mMinWidth;
21894    }
21895
21896    /**
21897     * Sets the minimum width of the view. It is not guaranteed the view will
21898     * be able to achieve this minimum width (for example, if its parent layout
21899     * constrains it with less available width).
21900     *
21901     * @param minWidth The minimum width the view will try to be, in pixels
21902     *
21903     * @see #getMinimumWidth()
21904     *
21905     * @attr ref android.R.styleable#View_minWidth
21906     */
21907    public void setMinimumWidth(int minWidth) {
21908        mMinWidth = minWidth;
21909        requestLayout();
21910
21911    }
21912
21913    /**
21914     * Get the animation currently associated with this view.
21915     *
21916     * @return The animation that is currently playing or
21917     *         scheduled to play for this view.
21918     */
21919    public Animation getAnimation() {
21920        return mCurrentAnimation;
21921    }
21922
21923    /**
21924     * Start the specified animation now.
21925     *
21926     * @param animation the animation to start now
21927     */
21928    public void startAnimation(Animation animation) {
21929        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
21930        setAnimation(animation);
21931        invalidateParentCaches();
21932        invalidate(true);
21933    }
21934
21935    /**
21936     * Cancels any animations for this view.
21937     */
21938    public void clearAnimation() {
21939        if (mCurrentAnimation != null) {
21940            mCurrentAnimation.detach();
21941        }
21942        mCurrentAnimation = null;
21943        invalidateParentIfNeeded();
21944    }
21945
21946    /**
21947     * Sets the next animation to play for this view.
21948     * If you want the animation to play immediately, use
21949     * {@link #startAnimation(android.view.animation.Animation)} instead.
21950     * This method provides allows fine-grained
21951     * control over the start time and invalidation, but you
21952     * must make sure that 1) the animation has a start time set, and
21953     * 2) the view's parent (which controls animations on its children)
21954     * will be invalidated when the animation is supposed to
21955     * start.
21956     *
21957     * @param animation The next animation, or null.
21958     */
21959    public void setAnimation(Animation animation) {
21960        mCurrentAnimation = animation;
21961
21962        if (animation != null) {
21963            // If the screen is off assume the animation start time is now instead of
21964            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
21965            // would cause the animation to start when the screen turns back on
21966            if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF
21967                    && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
21968                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
21969            }
21970            animation.reset();
21971        }
21972    }
21973
21974    /**
21975     * Invoked by a parent ViewGroup to notify the start of the animation
21976     * currently associated with this view. If you override this method,
21977     * always call super.onAnimationStart();
21978     *
21979     * @see #setAnimation(android.view.animation.Animation)
21980     * @see #getAnimation()
21981     */
21982    @CallSuper
21983    protected void onAnimationStart() {
21984        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
21985    }
21986
21987    /**
21988     * Invoked by a parent ViewGroup to notify the end of the animation
21989     * currently associated with this view. If you override this method,
21990     * always call super.onAnimationEnd();
21991     *
21992     * @see #setAnimation(android.view.animation.Animation)
21993     * @see #getAnimation()
21994     */
21995    @CallSuper
21996    protected void onAnimationEnd() {
21997        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
21998    }
21999
22000    /**
22001     * Invoked if there is a Transform that involves alpha. Subclass that can
22002     * draw themselves with the specified alpha should return true, and then
22003     * respect that alpha when their onDraw() is called. If this returns false
22004     * then the view may be redirected to draw into an offscreen buffer to
22005     * fulfill the request, which will look fine, but may be slower than if the
22006     * subclass handles it internally. The default implementation returns false.
22007     *
22008     * @param alpha The alpha (0..255) to apply to the view's drawing
22009     * @return true if the view can draw with the specified alpha.
22010     */
22011    protected boolean onSetAlpha(int alpha) {
22012        return false;
22013    }
22014
22015    /**
22016     * This is used by the RootView to perform an optimization when
22017     * the view hierarchy contains one or several SurfaceView.
22018     * SurfaceView is always considered transparent, but its children are not,
22019     * therefore all View objects remove themselves from the global transparent
22020     * region (passed as a parameter to this function).
22021     *
22022     * @param region The transparent region for this ViewAncestor (window).
22023     *
22024     * @return Returns true if the effective visibility of the view at this
22025     * point is opaque, regardless of the transparent region; returns false
22026     * if it is possible for underlying windows to be seen behind the view.
22027     *
22028     * {@hide}
22029     */
22030    public boolean gatherTransparentRegion(Region region) {
22031        final AttachInfo attachInfo = mAttachInfo;
22032        if (region != null && attachInfo != null) {
22033            final int pflags = mPrivateFlags;
22034            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
22035                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
22036                // remove it from the transparent region.
22037                final int[] location = attachInfo.mTransparentLocation;
22038                getLocationInWindow(location);
22039                // When a view has Z value, then it will be better to leave some area below the view
22040                // for drawing shadow. The shadow outset is proportional to the Z value. Note that
22041                // the bottom part needs more offset than the left, top and right parts due to the
22042                // spot light effects.
22043                int shadowOffset = getZ() > 0 ? (int) getZ() : 0;
22044                region.op(location[0] - shadowOffset, location[1] - shadowOffset,
22045                        location[0] + mRight - mLeft + shadowOffset,
22046                        location[1] + mBottom - mTop + (shadowOffset * 3), Region.Op.DIFFERENCE);
22047            } else {
22048                if (mBackground != null && mBackground.getOpacity() != PixelFormat.TRANSPARENT) {
22049                    // The SKIP_DRAW flag IS set and the background drawable exists, we remove
22050                    // the background drawable's non-transparent parts from this transparent region.
22051                    applyDrawableToTransparentRegion(mBackground, region);
22052                }
22053                if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
22054                        && mForegroundInfo.mDrawable.getOpacity() != PixelFormat.TRANSPARENT) {
22055                    // Similarly, we remove the foreground drawable's non-transparent parts.
22056                    applyDrawableToTransparentRegion(mForegroundInfo.mDrawable, region);
22057                }
22058                if (mDefaultFocusHighlight != null
22059                        && mDefaultFocusHighlight.getOpacity() != PixelFormat.TRANSPARENT) {
22060                    // Similarly, we remove the default focus highlight's non-transparent parts.
22061                    applyDrawableToTransparentRegion(mDefaultFocusHighlight, region);
22062                }
22063            }
22064        }
22065        return true;
22066    }
22067
22068    /**
22069     * Play a sound effect for this view.
22070     *
22071     * <p>The framework will play sound effects for some built in actions, such as
22072     * clicking, but you may wish to play these effects in your widget,
22073     * for instance, for internal navigation.
22074     *
22075     * <p>The sound effect will only be played if sound effects are enabled by the user, and
22076     * {@link #isSoundEffectsEnabled()} is true.
22077     *
22078     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
22079     */
22080    public void playSoundEffect(int soundConstant) {
22081        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
22082            return;
22083        }
22084        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
22085    }
22086
22087    /**
22088     * BZZZTT!!1!
22089     *
22090     * <p>Provide haptic feedback to the user for this view.
22091     *
22092     * <p>The framework will provide haptic feedback for some built in actions,
22093     * such as long presses, but you may wish to provide feedback for your
22094     * own widget.
22095     *
22096     * <p>The feedback will only be performed if
22097     * {@link #isHapticFeedbackEnabled()} is true.
22098     *
22099     * @param feedbackConstant One of the constants defined in
22100     * {@link HapticFeedbackConstants}
22101     */
22102    public boolean performHapticFeedback(int feedbackConstant) {
22103        return performHapticFeedback(feedbackConstant, 0);
22104    }
22105
22106    /**
22107     * BZZZTT!!1!
22108     *
22109     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
22110     *
22111     * @param feedbackConstant One of the constants defined in
22112     * {@link HapticFeedbackConstants}
22113     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
22114     */
22115    public boolean performHapticFeedback(int feedbackConstant, int flags) {
22116        if (mAttachInfo == null) {
22117            return false;
22118        }
22119        //noinspection SimplifiableIfStatement
22120        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
22121                && !isHapticFeedbackEnabled()) {
22122            return false;
22123        }
22124        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
22125                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
22126    }
22127
22128    /**
22129     * Request that the visibility of the status bar or other screen/window
22130     * decorations be changed.
22131     *
22132     * <p>This method is used to put the over device UI into temporary modes
22133     * where the user's attention is focused more on the application content,
22134     * by dimming or hiding surrounding system affordances.  This is typically
22135     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
22136     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
22137     * to be placed behind the action bar (and with these flags other system
22138     * affordances) so that smooth transitions between hiding and showing them
22139     * can be done.
22140     *
22141     * <p>Two representative examples of the use of system UI visibility is
22142     * implementing a content browsing application (like a magazine reader)
22143     * and a video playing application.
22144     *
22145     * <p>The first code shows a typical implementation of a View in a content
22146     * browsing application.  In this implementation, the application goes
22147     * into a content-oriented mode by hiding the status bar and action bar,
22148     * and putting the navigation elements into lights out mode.  The user can
22149     * then interact with content while in this mode.  Such an application should
22150     * provide an easy way for the user to toggle out of the mode (such as to
22151     * check information in the status bar or access notifications).  In the
22152     * implementation here, this is done simply by tapping on the content.
22153     *
22154     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
22155     *      content}
22156     *
22157     * <p>This second code sample shows a typical implementation of a View
22158     * in a video playing application.  In this situation, while the video is
22159     * playing the application would like to go into a complete full-screen mode,
22160     * to use as much of the display as possible for the video.  When in this state
22161     * the user can not interact with the application; the system intercepts
22162     * touching on the screen to pop the UI out of full screen mode.  See
22163     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
22164     *
22165     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
22166     *      content}
22167     *
22168     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
22169     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
22170     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
22171     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
22172     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
22173     */
22174    public void setSystemUiVisibility(int visibility) {
22175        if (visibility != mSystemUiVisibility) {
22176            mSystemUiVisibility = visibility;
22177            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
22178                mParent.recomputeViewAttributes(this);
22179            }
22180        }
22181    }
22182
22183    /**
22184     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
22185     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
22186     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
22187     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
22188     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
22189     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
22190     */
22191    public int getSystemUiVisibility() {
22192        return mSystemUiVisibility;
22193    }
22194
22195    /**
22196     * Returns the current system UI visibility that is currently set for
22197     * the entire window.  This is the combination of the
22198     * {@link #setSystemUiVisibility(int)} values supplied by all of the
22199     * views in the window.
22200     */
22201    public int getWindowSystemUiVisibility() {
22202        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
22203    }
22204
22205    /**
22206     * Override to find out when the window's requested system UI visibility
22207     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
22208     * This is different from the callbacks received through
22209     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
22210     * in that this is only telling you about the local request of the window,
22211     * not the actual values applied by the system.
22212     */
22213    public void onWindowSystemUiVisibilityChanged(int visible) {
22214    }
22215
22216    /**
22217     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
22218     * the view hierarchy.
22219     */
22220    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
22221        onWindowSystemUiVisibilityChanged(visible);
22222    }
22223
22224    /**
22225     * Set a listener to receive callbacks when the visibility of the system bar changes.
22226     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
22227     */
22228    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
22229        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
22230        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
22231            mParent.recomputeViewAttributes(this);
22232        }
22233    }
22234
22235    /**
22236     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
22237     * the view hierarchy.
22238     */
22239    public void dispatchSystemUiVisibilityChanged(int visibility) {
22240        ListenerInfo li = mListenerInfo;
22241        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
22242            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
22243                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
22244        }
22245    }
22246
22247    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
22248        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
22249        if (val != mSystemUiVisibility) {
22250            setSystemUiVisibility(val);
22251            return true;
22252        }
22253        return false;
22254    }
22255
22256    /** @hide */
22257    public void setDisabledSystemUiVisibility(int flags) {
22258        if (mAttachInfo != null) {
22259            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
22260                mAttachInfo.mDisabledSystemUiVisibility = flags;
22261                if (mParent != null) {
22262                    mParent.recomputeViewAttributes(this);
22263                }
22264            }
22265        }
22266    }
22267
22268    /**
22269     * Creates an image that the system displays during the drag and drop
22270     * operation. This is called a &quot;drag shadow&quot;. The default implementation
22271     * for a DragShadowBuilder based on a View returns an image that has exactly the same
22272     * appearance as the given View. The default also positions the center of the drag shadow
22273     * directly under the touch point. If no View is provided (the constructor with no parameters
22274     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
22275     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overridden, then the
22276     * default is an invisible drag shadow.
22277     * <p>
22278     * You are not required to use the View you provide to the constructor as the basis of the
22279     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
22280     * anything you want as the drag shadow.
22281     * </p>
22282     * <p>
22283     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
22284     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
22285     *  size and position of the drag shadow. It uses this data to construct a
22286     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
22287     *  so that your application can draw the shadow image in the Canvas.
22288     * </p>
22289     *
22290     * <div class="special reference">
22291     * <h3>Developer Guides</h3>
22292     * <p>For a guide to implementing drag and drop features, read the
22293     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
22294     * </div>
22295     */
22296    public static class DragShadowBuilder {
22297        private final WeakReference<View> mView;
22298
22299        /**
22300         * Constructs a shadow image builder based on a View. By default, the resulting drag
22301         * shadow will have the same appearance and dimensions as the View, with the touch point
22302         * over the center of the View.
22303         * @param view A View. Any View in scope can be used.
22304         */
22305        public DragShadowBuilder(View view) {
22306            mView = new WeakReference<View>(view);
22307        }
22308
22309        /**
22310         * Construct a shadow builder object with no associated View.  This
22311         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
22312         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
22313         * to supply the drag shadow's dimensions and appearance without
22314         * reference to any View object. If they are not overridden, then the result is an
22315         * invisible drag shadow.
22316         */
22317        public DragShadowBuilder() {
22318            mView = new WeakReference<View>(null);
22319        }
22320
22321        /**
22322         * Returns the View object that had been passed to the
22323         * {@link #View.DragShadowBuilder(View)}
22324         * constructor.  If that View parameter was {@code null} or if the
22325         * {@link #View.DragShadowBuilder()}
22326         * constructor was used to instantiate the builder object, this method will return
22327         * null.
22328         *
22329         * @return The View object associate with this builder object.
22330         */
22331        @SuppressWarnings({"JavadocReference"})
22332        final public View getView() {
22333            return mView.get();
22334        }
22335
22336        /**
22337         * Provides the metrics for the shadow image. These include the dimensions of
22338         * the shadow image, and the point within that shadow that should
22339         * be centered under the touch location while dragging.
22340         * <p>
22341         * The default implementation sets the dimensions of the shadow to be the
22342         * same as the dimensions of the View itself and centers the shadow under
22343         * the touch point.
22344         * </p>
22345         *
22346         * @param outShadowSize A {@link android.graphics.Point} containing the width and height
22347         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
22348         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
22349         * image.
22350         *
22351         * @param outShadowTouchPoint A {@link android.graphics.Point} for the position within the
22352         * shadow image that should be underneath the touch point during the drag and drop
22353         * operation. Your application must set {@link android.graphics.Point#x} to the
22354         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
22355         */
22356        public void onProvideShadowMetrics(Point outShadowSize, Point outShadowTouchPoint) {
22357            final View view = mView.get();
22358            if (view != null) {
22359                outShadowSize.set(view.getWidth(), view.getHeight());
22360                outShadowTouchPoint.set(outShadowSize.x / 2, outShadowSize.y / 2);
22361            } else {
22362                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
22363            }
22364        }
22365
22366        /**
22367         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
22368         * based on the dimensions it received from the
22369         * {@link #onProvideShadowMetrics(Point, Point)} callback.
22370         *
22371         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
22372         */
22373        public void onDrawShadow(Canvas canvas) {
22374            final View view = mView.get();
22375            if (view != null) {
22376                view.draw(canvas);
22377            } else {
22378                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
22379            }
22380        }
22381    }
22382
22383    /**
22384     * @deprecated Use {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)
22385     * startDragAndDrop()} for newer platform versions.
22386     */
22387    @Deprecated
22388    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
22389                                   Object myLocalState, int flags) {
22390        return startDragAndDrop(data, shadowBuilder, myLocalState, flags);
22391    }
22392
22393    /**
22394     * Starts a drag and drop operation. When your application calls this method, it passes a
22395     * {@link android.view.View.DragShadowBuilder} object to the system. The
22396     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
22397     * to get metrics for the drag shadow, and then calls the object's
22398     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
22399     * <p>
22400     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
22401     *  drag events to all the View objects in your application that are currently visible. It does
22402     *  this either by calling the View object's drag listener (an implementation of
22403     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
22404     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
22405     *  Both are passed a {@link android.view.DragEvent} object that has a
22406     *  {@link android.view.DragEvent#getAction()} value of
22407     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
22408     * </p>
22409     * <p>
22410     * Your application can invoke {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object,
22411     * int) startDragAndDrop()} on any attached View object. The View object does not need to be
22412     * the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to be related
22413     * to the View the user selected for dragging.
22414     * </p>
22415     * @param data A {@link android.content.ClipData} object pointing to the data to be
22416     * transferred by the drag and drop operation.
22417     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
22418     * drag shadow.
22419     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
22420     * drop operation. When dispatching drag events to views in the same activity this object
22421     * will be available through {@link android.view.DragEvent#getLocalState()}. Views in other
22422     * activities will not have access to this data ({@link android.view.DragEvent#getLocalState()}
22423     * will return null).
22424     * <p>
22425     * myLocalState is a lightweight mechanism for the sending information from the dragged View
22426     * to the target Views. For example, it can contain flags that differentiate between a
22427     * a copy operation and a move operation.
22428     * </p>
22429     * @param flags Flags that control the drag and drop operation. This can be set to 0 for no
22430     * flags, or any combination of the following:
22431     *     <ul>
22432     *         <li>{@link #DRAG_FLAG_GLOBAL}</li>
22433     *         <li>{@link #DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION}</li>
22434     *         <li>{@link #DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION}</li>
22435     *         <li>{@link #DRAG_FLAG_GLOBAL_URI_READ}</li>
22436     *         <li>{@link #DRAG_FLAG_GLOBAL_URI_WRITE}</li>
22437     *         <li>{@link #DRAG_FLAG_OPAQUE}</li>
22438     *     </ul>
22439     * @return {@code true} if the method completes successfully, or
22440     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
22441     * do a drag, and so no drag operation is in progress.
22442     */
22443    public final boolean startDragAndDrop(ClipData data, DragShadowBuilder shadowBuilder,
22444            Object myLocalState, int flags) {
22445        if (ViewDebug.DEBUG_DRAG) {
22446            Log.d(VIEW_LOG_TAG, "startDragAndDrop: data=" + data + " flags=" + flags);
22447        }
22448        if (mAttachInfo == null) {
22449            Log.w(VIEW_LOG_TAG, "startDragAndDrop called on a detached view.");
22450            return false;
22451        }
22452
22453        if (data != null) {
22454            data.prepareToLeaveProcess((flags & View.DRAG_FLAG_GLOBAL) != 0);
22455        }
22456
22457        boolean okay = false;
22458
22459        Point shadowSize = new Point();
22460        Point shadowTouchPoint = new Point();
22461        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
22462
22463        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
22464                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
22465            throw new IllegalStateException("Drag shadow dimensions must not be negative");
22466        }
22467
22468        if (ViewDebug.DEBUG_DRAG) {
22469            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
22470                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
22471        }
22472        if (mAttachInfo.mDragSurface != null) {
22473            mAttachInfo.mDragSurface.release();
22474        }
22475        mAttachInfo.mDragSurface = new Surface();
22476        try {
22477            mAttachInfo.mDragToken = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
22478                    flags, shadowSize.x, shadowSize.y, mAttachInfo.mDragSurface);
22479            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token="
22480                    + mAttachInfo.mDragToken + " surface=" + mAttachInfo.mDragSurface);
22481            if (mAttachInfo.mDragToken != null) {
22482                Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null);
22483                try {
22484                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
22485                    shadowBuilder.onDrawShadow(canvas);
22486                } finally {
22487                    mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas);
22488                }
22489
22490                final ViewRootImpl root = getViewRootImpl();
22491
22492                // Cache the local state object for delivery with DragEvents
22493                root.setLocalDragState(myLocalState);
22494
22495                // repurpose 'shadowSize' for the last touch point
22496                root.getLastTouchPoint(shadowSize);
22497
22498                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, mAttachInfo.mDragToken,
22499                        root.getLastTouchSource(), shadowSize.x, shadowSize.y,
22500                        shadowTouchPoint.x, shadowTouchPoint.y, data);
22501                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
22502            }
22503        } catch (Exception e) {
22504            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
22505            mAttachInfo.mDragSurface.destroy();
22506            mAttachInfo.mDragSurface = null;
22507        }
22508
22509        return okay;
22510    }
22511
22512    /**
22513     * Cancels an ongoing drag and drop operation.
22514     * <p>
22515     * A {@link android.view.DragEvent} object with
22516     * {@link android.view.DragEvent#getAction()} value of
22517     * {@link android.view.DragEvent#ACTION_DRAG_ENDED} and
22518     * {@link android.view.DragEvent#getResult()} value of {@code false}
22519     * will be sent to every
22520     * View that received {@link android.view.DragEvent#ACTION_DRAG_STARTED}
22521     * even if they are not currently visible.
22522     * </p>
22523     * <p>
22524     * This method can be called on any View in the same window as the View on which
22525     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int) startDragAndDrop}
22526     * was called.
22527     * </p>
22528     */
22529    public final void cancelDragAndDrop() {
22530        if (ViewDebug.DEBUG_DRAG) {
22531            Log.d(VIEW_LOG_TAG, "cancelDragAndDrop");
22532        }
22533        if (mAttachInfo == null) {
22534            Log.w(VIEW_LOG_TAG, "cancelDragAndDrop called on a detached view.");
22535            return;
22536        }
22537        if (mAttachInfo.mDragToken != null) {
22538            try {
22539                mAttachInfo.mSession.cancelDragAndDrop(mAttachInfo.mDragToken);
22540            } catch (Exception e) {
22541                Log.e(VIEW_LOG_TAG, "Unable to cancel drag", e);
22542            }
22543            mAttachInfo.mDragToken = null;
22544        } else {
22545            Log.e(VIEW_LOG_TAG, "No active drag to cancel");
22546        }
22547    }
22548
22549    /**
22550     * Updates the drag shadow for the ongoing drag and drop operation.
22551     *
22552     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
22553     * new drag shadow.
22554     */
22555    public final void updateDragShadow(DragShadowBuilder shadowBuilder) {
22556        if (ViewDebug.DEBUG_DRAG) {
22557            Log.d(VIEW_LOG_TAG, "updateDragShadow");
22558        }
22559        if (mAttachInfo == null) {
22560            Log.w(VIEW_LOG_TAG, "updateDragShadow called on a detached view.");
22561            return;
22562        }
22563        if (mAttachInfo.mDragToken != null) {
22564            try {
22565                Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null);
22566                try {
22567                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
22568                    shadowBuilder.onDrawShadow(canvas);
22569                } finally {
22570                    mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas);
22571                }
22572            } catch (Exception e) {
22573                Log.e(VIEW_LOG_TAG, "Unable to update drag shadow", e);
22574            }
22575        } else {
22576            Log.e(VIEW_LOG_TAG, "No active drag");
22577        }
22578    }
22579
22580    /**
22581     * Starts a move from {startX, startY}, the amount of the movement will be the offset
22582     * between {startX, startY} and the new cursor positon.
22583     * @param startX horizontal coordinate where the move started.
22584     * @param startY vertical coordinate where the move started.
22585     * @return whether moving was started successfully.
22586     * @hide
22587     */
22588    public final boolean startMovingTask(float startX, float startY) {
22589        if (ViewDebug.DEBUG_POSITIONING) {
22590            Log.d(VIEW_LOG_TAG, "startMovingTask: {" + startX + "," + startY + "}");
22591        }
22592        try {
22593            return mAttachInfo.mSession.startMovingTask(mAttachInfo.mWindow, startX, startY);
22594        } catch (RemoteException e) {
22595            Log.e(VIEW_LOG_TAG, "Unable to start moving", e);
22596        }
22597        return false;
22598    }
22599
22600    /**
22601     * Handles drag events sent by the system following a call to
22602     * {@link android.view.View#startDragAndDrop(ClipData,DragShadowBuilder,Object,int)
22603     * startDragAndDrop()}.
22604     *<p>
22605     * When the system calls this method, it passes a
22606     * {@link android.view.DragEvent} object. A call to
22607     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
22608     * in DragEvent. The method uses these to determine what is happening in the drag and drop
22609     * operation.
22610     * @param event The {@link android.view.DragEvent} sent by the system.
22611     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
22612     * in DragEvent, indicating the type of drag event represented by this object.
22613     * @return {@code true} if the method was successful, otherwise {@code false}.
22614     * <p>
22615     *  The method should return {@code true} in response to an action type of
22616     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
22617     *  operation.
22618     * </p>
22619     * <p>
22620     *  The method should also return {@code true} in response to an action type of
22621     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
22622     *  {@code false} if it didn't.
22623     * </p>
22624     * <p>
22625     *  For all other events, the return value is ignored.
22626     * </p>
22627     */
22628    public boolean onDragEvent(DragEvent event) {
22629        return false;
22630    }
22631
22632    // Dispatches ACTION_DRAG_ENTERED and ACTION_DRAG_EXITED events for pre-Nougat apps.
22633    boolean dispatchDragEnterExitInPreN(DragEvent event) {
22634        return callDragEventHandler(event);
22635    }
22636
22637    /**
22638     * Detects if this View is enabled and has a drag event listener.
22639     * If both are true, then it calls the drag event listener with the
22640     * {@link android.view.DragEvent} it received. If the drag event listener returns
22641     * {@code true}, then dispatchDragEvent() returns {@code true}.
22642     * <p>
22643     * For all other cases, the method calls the
22644     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
22645     * method and returns its result.
22646     * </p>
22647     * <p>
22648     * This ensures that a drag event is always consumed, even if the View does not have a drag
22649     * event listener. However, if the View has a listener and the listener returns true, then
22650     * onDragEvent() is not called.
22651     * </p>
22652     */
22653    public boolean dispatchDragEvent(DragEvent event) {
22654        event.mEventHandlerWasCalled = true;
22655        if (event.mAction == DragEvent.ACTION_DRAG_LOCATION ||
22656            event.mAction == DragEvent.ACTION_DROP) {
22657            // About to deliver an event with coordinates to this view. Notify that now this view
22658            // has drag focus. This will send exit/enter events as needed.
22659            getViewRootImpl().setDragFocus(this, event);
22660        }
22661        return callDragEventHandler(event);
22662    }
22663
22664    final boolean callDragEventHandler(DragEvent event) {
22665        final boolean result;
22666
22667        ListenerInfo li = mListenerInfo;
22668        //noinspection SimplifiableIfStatement
22669        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
22670                && li.mOnDragListener.onDrag(this, event)) {
22671            result = true;
22672        } else {
22673            result = onDragEvent(event);
22674        }
22675
22676        switch (event.mAction) {
22677            case DragEvent.ACTION_DRAG_ENTERED: {
22678                mPrivateFlags2 |= View.PFLAG2_DRAG_HOVERED;
22679                refreshDrawableState();
22680            } break;
22681            case DragEvent.ACTION_DRAG_EXITED: {
22682                mPrivateFlags2 &= ~View.PFLAG2_DRAG_HOVERED;
22683                refreshDrawableState();
22684            } break;
22685            case DragEvent.ACTION_DRAG_ENDED: {
22686                mPrivateFlags2 &= ~View.DRAG_MASK;
22687                refreshDrawableState();
22688            } break;
22689        }
22690
22691        return result;
22692    }
22693
22694    boolean canAcceptDrag() {
22695        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
22696    }
22697
22698    /**
22699     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
22700     * it is ever exposed at all.
22701     * @hide
22702     */
22703    public void onCloseSystemDialogs(String reason) {
22704    }
22705
22706    /**
22707     * Given a Drawable whose bounds have been set to draw into this view,
22708     * update a Region being computed for
22709     * {@link #gatherTransparentRegion(android.graphics.Region)} so
22710     * that any non-transparent parts of the Drawable are removed from the
22711     * given transparent region.
22712     *
22713     * @param dr The Drawable whose transparency is to be applied to the region.
22714     * @param region A Region holding the current transparency information,
22715     * where any parts of the region that are set are considered to be
22716     * transparent.  On return, this region will be modified to have the
22717     * transparency information reduced by the corresponding parts of the
22718     * Drawable that are not transparent.
22719     * {@hide}
22720     */
22721    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
22722        if (DBG) {
22723            Log.i("View", "Getting transparent region for: " + this);
22724        }
22725        final Region r = dr.getTransparentRegion();
22726        final Rect db = dr.getBounds();
22727        final AttachInfo attachInfo = mAttachInfo;
22728        if (r != null && attachInfo != null) {
22729            final int w = getRight()-getLeft();
22730            final int h = getBottom()-getTop();
22731            if (db.left > 0) {
22732                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
22733                r.op(0, 0, db.left, h, Region.Op.UNION);
22734            }
22735            if (db.right < w) {
22736                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
22737                r.op(db.right, 0, w, h, Region.Op.UNION);
22738            }
22739            if (db.top > 0) {
22740                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
22741                r.op(0, 0, w, db.top, Region.Op.UNION);
22742            }
22743            if (db.bottom < h) {
22744                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
22745                r.op(0, db.bottom, w, h, Region.Op.UNION);
22746            }
22747            final int[] location = attachInfo.mTransparentLocation;
22748            getLocationInWindow(location);
22749            r.translate(location[0], location[1]);
22750            region.op(r, Region.Op.INTERSECT);
22751        } else {
22752            region.op(db, Region.Op.DIFFERENCE);
22753        }
22754    }
22755
22756    private void checkForLongClick(int delayOffset, float x, float y) {
22757        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE || (mViewFlags & TOOLTIP) == TOOLTIP) {
22758            mHasPerformedLongPress = false;
22759
22760            if (mPendingCheckForLongPress == null) {
22761                mPendingCheckForLongPress = new CheckForLongPress();
22762            }
22763            mPendingCheckForLongPress.setAnchor(x, y);
22764            mPendingCheckForLongPress.rememberWindowAttachCount();
22765            mPendingCheckForLongPress.rememberPressedState();
22766            postDelayed(mPendingCheckForLongPress,
22767                    ViewConfiguration.getLongPressTimeout() - delayOffset);
22768        }
22769    }
22770
22771    /**
22772     * Inflate a view from an XML resource.  This convenience method wraps the {@link
22773     * LayoutInflater} class, which provides a full range of options for view inflation.
22774     *
22775     * @param context The Context object for your activity or application.
22776     * @param resource The resource ID to inflate
22777     * @param root A view group that will be the parent.  Used to properly inflate the
22778     * layout_* parameters.
22779     * @see LayoutInflater
22780     */
22781    public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
22782        LayoutInflater factory = LayoutInflater.from(context);
22783        return factory.inflate(resource, root);
22784    }
22785
22786    /**
22787     * Scroll the view with standard behavior for scrolling beyond the normal
22788     * content boundaries. Views that call this method should override
22789     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
22790     * results of an over-scroll operation.
22791     *
22792     * Views can use this method to handle any touch or fling-based scrolling.
22793     *
22794     * @param deltaX Change in X in pixels
22795     * @param deltaY Change in Y in pixels
22796     * @param scrollX Current X scroll value in pixels before applying deltaX
22797     * @param scrollY Current Y scroll value in pixels before applying deltaY
22798     * @param scrollRangeX Maximum content scroll range along the X axis
22799     * @param scrollRangeY Maximum content scroll range along the Y axis
22800     * @param maxOverScrollX Number of pixels to overscroll by in either direction
22801     *          along the X axis.
22802     * @param maxOverScrollY Number of pixels to overscroll by in either direction
22803     *          along the Y axis.
22804     * @param isTouchEvent true if this scroll operation is the result of a touch event.
22805     * @return true if scrolling was clamped to an over-scroll boundary along either
22806     *          axis, false otherwise.
22807     */
22808    @SuppressWarnings({"UnusedParameters"})
22809    protected boolean overScrollBy(int deltaX, int deltaY,
22810            int scrollX, int scrollY,
22811            int scrollRangeX, int scrollRangeY,
22812            int maxOverScrollX, int maxOverScrollY,
22813            boolean isTouchEvent) {
22814        final int overScrollMode = mOverScrollMode;
22815        final boolean canScrollHorizontal =
22816                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
22817        final boolean canScrollVertical =
22818                computeVerticalScrollRange() > computeVerticalScrollExtent();
22819        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
22820                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
22821        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
22822                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
22823
22824        int newScrollX = scrollX + deltaX;
22825        if (!overScrollHorizontal) {
22826            maxOverScrollX = 0;
22827        }
22828
22829        int newScrollY = scrollY + deltaY;
22830        if (!overScrollVertical) {
22831            maxOverScrollY = 0;
22832        }
22833
22834        // Clamp values if at the limits and record
22835        final int left = -maxOverScrollX;
22836        final int right = maxOverScrollX + scrollRangeX;
22837        final int top = -maxOverScrollY;
22838        final int bottom = maxOverScrollY + scrollRangeY;
22839
22840        boolean clampedX = false;
22841        if (newScrollX > right) {
22842            newScrollX = right;
22843            clampedX = true;
22844        } else if (newScrollX < left) {
22845            newScrollX = left;
22846            clampedX = true;
22847        }
22848
22849        boolean clampedY = false;
22850        if (newScrollY > bottom) {
22851            newScrollY = bottom;
22852            clampedY = true;
22853        } else if (newScrollY < top) {
22854            newScrollY = top;
22855            clampedY = true;
22856        }
22857
22858        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
22859
22860        return clampedX || clampedY;
22861    }
22862
22863    /**
22864     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
22865     * respond to the results of an over-scroll operation.
22866     *
22867     * @param scrollX New X scroll value in pixels
22868     * @param scrollY New Y scroll value in pixels
22869     * @param clampedX True if scrollX was clamped to an over-scroll boundary
22870     * @param clampedY True if scrollY was clamped to an over-scroll boundary
22871     */
22872    protected void onOverScrolled(int scrollX, int scrollY,
22873            boolean clampedX, boolean clampedY) {
22874        // Intentionally empty.
22875    }
22876
22877    /**
22878     * Returns the over-scroll mode for this view. The result will be
22879     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
22880     * (allow over-scrolling only if the view content is larger than the container),
22881     * or {@link #OVER_SCROLL_NEVER}.
22882     *
22883     * @return This view's over-scroll mode.
22884     */
22885    public int getOverScrollMode() {
22886        return mOverScrollMode;
22887    }
22888
22889    /**
22890     * Set the over-scroll mode for this view. Valid over-scroll modes are
22891     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
22892     * (allow over-scrolling only if the view content is larger than the container),
22893     * or {@link #OVER_SCROLL_NEVER}.
22894     *
22895     * Setting the over-scroll mode of a view will have an effect only if the
22896     * view is capable of scrolling.
22897     *
22898     * @param overScrollMode The new over-scroll mode for this view.
22899     */
22900    public void setOverScrollMode(int overScrollMode) {
22901        if (overScrollMode != OVER_SCROLL_ALWAYS &&
22902                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
22903                overScrollMode != OVER_SCROLL_NEVER) {
22904            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
22905        }
22906        mOverScrollMode = overScrollMode;
22907    }
22908
22909    /**
22910     * Enable or disable nested scrolling for this view.
22911     *
22912     * <p>If this property is set to true the view will be permitted to initiate nested
22913     * scrolling operations with a compatible parent view in the current hierarchy. If this
22914     * view does not implement nested scrolling this will have no effect. Disabling nested scrolling
22915     * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping}
22916     * the nested scroll.</p>
22917     *
22918     * @param enabled true to enable nested scrolling, false to disable
22919     *
22920     * @see #isNestedScrollingEnabled()
22921     */
22922    public void setNestedScrollingEnabled(boolean enabled) {
22923        if (enabled) {
22924            mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED;
22925        } else {
22926            stopNestedScroll();
22927            mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED;
22928        }
22929    }
22930
22931    /**
22932     * Returns true if nested scrolling is enabled for this view.
22933     *
22934     * <p>If nested scrolling is enabled and this View class implementation supports it,
22935     * this view will act as a nested scrolling child view when applicable, forwarding data
22936     * about the scroll operation in progress to a compatible and cooperating nested scrolling
22937     * parent.</p>
22938     *
22939     * @return true if nested scrolling is enabled
22940     *
22941     * @see #setNestedScrollingEnabled(boolean)
22942     */
22943    public boolean isNestedScrollingEnabled() {
22944        return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) ==
22945                PFLAG3_NESTED_SCROLLING_ENABLED;
22946    }
22947
22948    /**
22949     * Begin a nestable scroll operation along the given axes.
22950     *
22951     * <p>A view starting a nested scroll promises to abide by the following contract:</p>
22952     *
22953     * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case
22954     * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}.
22955     * In the case of touch scrolling the nested scroll will be terminated automatically in
22956     * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}.
22957     * In the event of programmatic scrolling the caller must explicitly call
22958     * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p>
22959     *
22960     * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found.
22961     * If it returns false the caller may ignore the rest of this contract until the next scroll.
22962     * Calling startNestedScroll while a nested scroll is already in progress will return true.</p>
22963     *
22964     * <p>At each incremental step of the scroll the caller should invoke
22965     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll}
22966     * once it has calculated the requested scrolling delta. If it returns true the nested scrolling
22967     * parent at least partially consumed the scroll and the caller should adjust the amount it
22968     * scrolls by.</p>
22969     *
22970     * <p>After applying the remainder of the scroll delta the caller should invoke
22971     * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing
22972     * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat
22973     * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}.
22974     * </p>
22975     *
22976     * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or
22977     *             {@link #SCROLL_AXIS_VERTICAL}.
22978     * @return true if a cooperative parent was found and nested scrolling has been enabled for
22979     *         the current gesture.
22980     *
22981     * @see #stopNestedScroll()
22982     * @see #dispatchNestedPreScroll(int, int, int[], int[])
22983     * @see #dispatchNestedScroll(int, int, int, int, int[])
22984     */
22985    public boolean startNestedScroll(int axes) {
22986        if (hasNestedScrollingParent()) {
22987            // Already in progress
22988            return true;
22989        }
22990        if (isNestedScrollingEnabled()) {
22991            ViewParent p = getParent();
22992            View child = this;
22993            while (p != null) {
22994                try {
22995                    if (p.onStartNestedScroll(child, this, axes)) {
22996                        mNestedScrollingParent = p;
22997                        p.onNestedScrollAccepted(child, this, axes);
22998                        return true;
22999                    }
23000                } catch (AbstractMethodError e) {
23001                    Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " +
23002                            "method onStartNestedScroll", e);
23003                    // Allow the search upward to continue
23004                }
23005                if (p instanceof View) {
23006                    child = (View) p;
23007                }
23008                p = p.getParent();
23009            }
23010        }
23011        return false;
23012    }
23013
23014    /**
23015     * Stop a nested scroll in progress.
23016     *
23017     * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p>
23018     *
23019     * @see #startNestedScroll(int)
23020     */
23021    public void stopNestedScroll() {
23022        if (mNestedScrollingParent != null) {
23023            mNestedScrollingParent.onStopNestedScroll(this);
23024            mNestedScrollingParent = null;
23025        }
23026    }
23027
23028    /**
23029     * Returns true if this view has a nested scrolling parent.
23030     *
23031     * <p>The presence of a nested scrolling parent indicates that this view has initiated
23032     * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p>
23033     *
23034     * @return whether this view has a nested scrolling parent
23035     */
23036    public boolean hasNestedScrollingParent() {
23037        return mNestedScrollingParent != null;
23038    }
23039
23040    /**
23041     * Dispatch one step of a nested scroll in progress.
23042     *
23043     * <p>Implementations of views that support nested scrolling should call this to report
23044     * info about a scroll in progress to the current nested scrolling parent. If a nested scroll
23045     * is not currently in progress or nested scrolling is not
23046     * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p>
23047     *
23048     * <p>Compatible View implementations should also call
23049     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before
23050     * consuming a component of the scroll event themselves.</p>
23051     *
23052     * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step
23053     * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step
23054     * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view
23055     * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view
23056     * @param offsetInWindow Optional. If not null, on return this will contain the offset
23057     *                       in local view coordinates of this view from before this operation
23058     *                       to after it completes. View implementations may use this to adjust
23059     *                       expected input coordinate tracking.
23060     * @return true if the event was dispatched, false if it could not be dispatched.
23061     * @see #dispatchNestedPreScroll(int, int, int[], int[])
23062     */
23063    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed,
23064            int dxUnconsumed, int dyUnconsumed, @Nullable @Size(2) int[] offsetInWindow) {
23065        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
23066            if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) {
23067                int startX = 0;
23068                int startY = 0;
23069                if (offsetInWindow != null) {
23070                    getLocationInWindow(offsetInWindow);
23071                    startX = offsetInWindow[0];
23072                    startY = offsetInWindow[1];
23073                }
23074
23075                mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed,
23076                        dxUnconsumed, dyUnconsumed);
23077
23078                if (offsetInWindow != null) {
23079                    getLocationInWindow(offsetInWindow);
23080                    offsetInWindow[0] -= startX;
23081                    offsetInWindow[1] -= startY;
23082                }
23083                return true;
23084            } else if (offsetInWindow != null) {
23085                // No motion, no dispatch. Keep offsetInWindow up to date.
23086                offsetInWindow[0] = 0;
23087                offsetInWindow[1] = 0;
23088            }
23089        }
23090        return false;
23091    }
23092
23093    /**
23094     * Dispatch one step of a nested scroll in progress before this view consumes any portion of it.
23095     *
23096     * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch.
23097     * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested
23098     * scrolling operation to consume some or all of the scroll operation before the child view
23099     * consumes it.</p>
23100     *
23101     * @param dx Horizontal scroll distance in pixels
23102     * @param dy Vertical scroll distance in pixels
23103     * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx
23104     *                 and consumed[1] the consumed dy.
23105     * @param offsetInWindow Optional. If not null, on return this will contain the offset
23106     *                       in local view coordinates of this view from before this operation
23107     *                       to after it completes. View implementations may use this to adjust
23108     *                       expected input coordinate tracking.
23109     * @return true if the parent consumed some or all of the scroll delta
23110     * @see #dispatchNestedScroll(int, int, int, int, int[])
23111     */
23112    public boolean dispatchNestedPreScroll(int dx, int dy,
23113            @Nullable @Size(2) int[] consumed, @Nullable @Size(2) int[] offsetInWindow) {
23114        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
23115            if (dx != 0 || dy != 0) {
23116                int startX = 0;
23117                int startY = 0;
23118                if (offsetInWindow != null) {
23119                    getLocationInWindow(offsetInWindow);
23120                    startX = offsetInWindow[0];
23121                    startY = offsetInWindow[1];
23122                }
23123
23124                if (consumed == null) {
23125                    if (mTempNestedScrollConsumed == null) {
23126                        mTempNestedScrollConsumed = new int[2];
23127                    }
23128                    consumed = mTempNestedScrollConsumed;
23129                }
23130                consumed[0] = 0;
23131                consumed[1] = 0;
23132                mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed);
23133
23134                if (offsetInWindow != null) {
23135                    getLocationInWindow(offsetInWindow);
23136                    offsetInWindow[0] -= startX;
23137                    offsetInWindow[1] -= startY;
23138                }
23139                return consumed[0] != 0 || consumed[1] != 0;
23140            } else if (offsetInWindow != null) {
23141                offsetInWindow[0] = 0;
23142                offsetInWindow[1] = 0;
23143            }
23144        }
23145        return false;
23146    }
23147
23148    /**
23149     * Dispatch a fling to a nested scrolling parent.
23150     *
23151     * <p>This method should be used to indicate that a nested scrolling child has detected
23152     * suitable conditions for a fling. Generally this means that a touch scroll has ended with a
23153     * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds
23154     * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity}
23155     * along a scrollable axis.</p>
23156     *
23157     * <p>If a nested scrolling child view would normally fling but it is at the edge of
23158     * its own content, it can use this method to delegate the fling to its nested scrolling
23159     * parent instead. The parent may optionally consume the fling or observe a child fling.</p>
23160     *
23161     * @param velocityX Horizontal fling velocity in pixels per second
23162     * @param velocityY Vertical fling velocity in pixels per second
23163     * @param consumed true if the child consumed the fling, false otherwise
23164     * @return true if the nested scrolling parent consumed or otherwise reacted to the fling
23165     */
23166    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
23167        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
23168            return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed);
23169        }
23170        return false;
23171    }
23172
23173    /**
23174     * Dispatch a fling to a nested scrolling parent before it is processed by this view.
23175     *
23176     * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch
23177     * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code>
23178     * offsets an opportunity for the parent view in a nested fling to fully consume the fling
23179     * before the child view consumes it. If this method returns <code>true</code>, a nested
23180     * parent view consumed the fling and this view should not scroll as a result.</p>
23181     *
23182     * <p>For a better user experience, only one view in a nested scrolling chain should consume
23183     * the fling at a time. If a parent view consumed the fling this method will return false.
23184     * Custom view implementations should account for this in two ways:</p>
23185     *
23186     * <ul>
23187     *     <li>If a custom view is paged and needs to settle to a fixed page-point, do not
23188     *     call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid
23189     *     position regardless.</li>
23190     *     <li>If a nested parent does consume the fling, this view should not scroll at all,
23191     *     even to settle back to a valid idle position.</li>
23192     * </ul>
23193     *
23194     * <p>Views should also not offer fling velocities to nested parent views along an axis
23195     * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView}
23196     * should not offer a horizontal fling velocity to its parents since scrolling along that
23197     * axis is not permitted and carrying velocity along that motion does not make sense.</p>
23198     *
23199     * @param velocityX Horizontal fling velocity in pixels per second
23200     * @param velocityY Vertical fling velocity in pixels per second
23201     * @return true if a nested scrolling parent consumed the fling
23202     */
23203    public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
23204        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
23205            return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY);
23206        }
23207        return false;
23208    }
23209
23210    /**
23211     * Gets a scale factor that determines the distance the view should scroll
23212     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
23213     * @return The vertical scroll scale factor.
23214     * @hide
23215     */
23216    protected float getVerticalScrollFactor() {
23217        if (mVerticalScrollFactor == 0) {
23218            TypedValue outValue = new TypedValue();
23219            if (!mContext.getTheme().resolveAttribute(
23220                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
23221                throw new IllegalStateException(
23222                        "Expected theme to define listPreferredItemHeight.");
23223            }
23224            mVerticalScrollFactor = outValue.getDimension(
23225                    mContext.getResources().getDisplayMetrics());
23226        }
23227        return mVerticalScrollFactor;
23228    }
23229
23230    /**
23231     * Gets a scale factor that determines the distance the view should scroll
23232     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
23233     * @return The horizontal scroll scale factor.
23234     * @hide
23235     */
23236    protected float getHorizontalScrollFactor() {
23237        // TODO: Should use something else.
23238        return getVerticalScrollFactor();
23239    }
23240
23241    /**
23242     * Return the value specifying the text direction or policy that was set with
23243     * {@link #setTextDirection(int)}.
23244     *
23245     * @return the defined text direction. It can be one of:
23246     *
23247     * {@link #TEXT_DIRECTION_INHERIT},
23248     * {@link #TEXT_DIRECTION_FIRST_STRONG},
23249     * {@link #TEXT_DIRECTION_ANY_RTL},
23250     * {@link #TEXT_DIRECTION_LTR},
23251     * {@link #TEXT_DIRECTION_RTL},
23252     * {@link #TEXT_DIRECTION_LOCALE},
23253     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
23254     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
23255     *
23256     * @attr ref android.R.styleable#View_textDirection
23257     *
23258     * @hide
23259     */
23260    @ViewDebug.ExportedProperty(category = "text", mapping = {
23261            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
23262            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
23263            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
23264            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
23265            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
23266            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
23267            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
23268            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
23269    })
23270    public int getRawTextDirection() {
23271        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
23272    }
23273
23274    /**
23275     * Set the text direction.
23276     *
23277     * @param textDirection the direction to set. Should be one of:
23278     *
23279     * {@link #TEXT_DIRECTION_INHERIT},
23280     * {@link #TEXT_DIRECTION_FIRST_STRONG},
23281     * {@link #TEXT_DIRECTION_ANY_RTL},
23282     * {@link #TEXT_DIRECTION_LTR},
23283     * {@link #TEXT_DIRECTION_RTL},
23284     * {@link #TEXT_DIRECTION_LOCALE}
23285     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
23286     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL},
23287     *
23288     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
23289     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
23290     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
23291     *
23292     * @attr ref android.R.styleable#View_textDirection
23293     */
23294    public void setTextDirection(int textDirection) {
23295        if (getRawTextDirection() != textDirection) {
23296            // Reset the current text direction and the resolved one
23297            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
23298            resetResolvedTextDirection();
23299            // Set the new text direction
23300            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
23301            // Do resolution
23302            resolveTextDirection();
23303            // Notify change
23304            onRtlPropertiesChanged(getLayoutDirection());
23305            // Refresh
23306            requestLayout();
23307            invalidate(true);
23308        }
23309    }
23310
23311    /**
23312     * Return the resolved text direction.
23313     *
23314     * @return the resolved text direction. Returns one of:
23315     *
23316     * {@link #TEXT_DIRECTION_FIRST_STRONG},
23317     * {@link #TEXT_DIRECTION_ANY_RTL},
23318     * {@link #TEXT_DIRECTION_LTR},
23319     * {@link #TEXT_DIRECTION_RTL},
23320     * {@link #TEXT_DIRECTION_LOCALE},
23321     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
23322     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
23323     *
23324     * @attr ref android.R.styleable#View_textDirection
23325     */
23326    @ViewDebug.ExportedProperty(category = "text", mapping = {
23327            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
23328            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
23329            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
23330            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
23331            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
23332            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
23333            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
23334            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
23335    })
23336    public int getTextDirection() {
23337        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
23338    }
23339
23340    /**
23341     * Resolve the text direction.
23342     *
23343     * @return true if resolution has been done, false otherwise.
23344     *
23345     * @hide
23346     */
23347    public boolean resolveTextDirection() {
23348        // Reset any previous text direction resolution
23349        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
23350
23351        if (hasRtlSupport()) {
23352            // Set resolved text direction flag depending on text direction flag
23353            final int textDirection = getRawTextDirection();
23354            switch(textDirection) {
23355                case TEXT_DIRECTION_INHERIT:
23356                    if (!canResolveTextDirection()) {
23357                        // We cannot do the resolution if there is no parent, so use the default one
23358                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
23359                        // Resolution will need to happen again later
23360                        return false;
23361                    }
23362
23363                    // Parent has not yet resolved, so we still return the default
23364                    try {
23365                        if (!mParent.isTextDirectionResolved()) {
23366                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
23367                            // Resolution will need to happen again later
23368                            return false;
23369                        }
23370                    } catch (AbstractMethodError e) {
23371                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
23372                                " does not fully implement ViewParent", e);
23373                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
23374                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
23375                        return true;
23376                    }
23377
23378                    // Set current resolved direction to the same value as the parent's one
23379                    int parentResolvedDirection;
23380                    try {
23381                        parentResolvedDirection = mParent.getTextDirection();
23382                    } catch (AbstractMethodError e) {
23383                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
23384                                " does not fully implement ViewParent", e);
23385                        parentResolvedDirection = TEXT_DIRECTION_LTR;
23386                    }
23387                    switch (parentResolvedDirection) {
23388                        case TEXT_DIRECTION_FIRST_STRONG:
23389                        case TEXT_DIRECTION_ANY_RTL:
23390                        case TEXT_DIRECTION_LTR:
23391                        case TEXT_DIRECTION_RTL:
23392                        case TEXT_DIRECTION_LOCALE:
23393                        case TEXT_DIRECTION_FIRST_STRONG_LTR:
23394                        case TEXT_DIRECTION_FIRST_STRONG_RTL:
23395                            mPrivateFlags2 |=
23396                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
23397                            break;
23398                        default:
23399                            // Default resolved direction is "first strong" heuristic
23400                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
23401                    }
23402                    break;
23403                case TEXT_DIRECTION_FIRST_STRONG:
23404                case TEXT_DIRECTION_ANY_RTL:
23405                case TEXT_DIRECTION_LTR:
23406                case TEXT_DIRECTION_RTL:
23407                case TEXT_DIRECTION_LOCALE:
23408                case TEXT_DIRECTION_FIRST_STRONG_LTR:
23409                case TEXT_DIRECTION_FIRST_STRONG_RTL:
23410                    // Resolved direction is the same as text direction
23411                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
23412                    break;
23413                default:
23414                    // Default resolved direction is "first strong" heuristic
23415                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
23416            }
23417        } else {
23418            // Default resolved direction is "first strong" heuristic
23419            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
23420        }
23421
23422        // Set to resolved
23423        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
23424        return true;
23425    }
23426
23427    /**
23428     * Check if text direction resolution can be done.
23429     *
23430     * @return true if text direction resolution can be done otherwise return false.
23431     */
23432    public boolean canResolveTextDirection() {
23433        switch (getRawTextDirection()) {
23434            case TEXT_DIRECTION_INHERIT:
23435                if (mParent != null) {
23436                    try {
23437                        return mParent.canResolveTextDirection();
23438                    } catch (AbstractMethodError e) {
23439                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
23440                                " does not fully implement ViewParent", e);
23441                    }
23442                }
23443                return false;
23444
23445            default:
23446                return true;
23447        }
23448    }
23449
23450    /**
23451     * Reset resolved text direction. Text direction will be resolved during a call to
23452     * {@link #onMeasure(int, int)}.
23453     *
23454     * @hide
23455     */
23456    public void resetResolvedTextDirection() {
23457        // Reset any previous text direction resolution
23458        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
23459        // Set to default value
23460        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
23461    }
23462
23463    /**
23464     * @return true if text direction is inherited.
23465     *
23466     * @hide
23467     */
23468    public boolean isTextDirectionInherited() {
23469        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
23470    }
23471
23472    /**
23473     * @return true if text direction is resolved.
23474     */
23475    public boolean isTextDirectionResolved() {
23476        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
23477    }
23478
23479    /**
23480     * Return the value specifying the text alignment or policy that was set with
23481     * {@link #setTextAlignment(int)}.
23482     *
23483     * @return the defined text alignment. It can be one of:
23484     *
23485     * {@link #TEXT_ALIGNMENT_INHERIT},
23486     * {@link #TEXT_ALIGNMENT_GRAVITY},
23487     * {@link #TEXT_ALIGNMENT_CENTER},
23488     * {@link #TEXT_ALIGNMENT_TEXT_START},
23489     * {@link #TEXT_ALIGNMENT_TEXT_END},
23490     * {@link #TEXT_ALIGNMENT_VIEW_START},
23491     * {@link #TEXT_ALIGNMENT_VIEW_END}
23492     *
23493     * @attr ref android.R.styleable#View_textAlignment
23494     *
23495     * @hide
23496     */
23497    @ViewDebug.ExportedProperty(category = "text", mapping = {
23498            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
23499            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
23500            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
23501            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
23502            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
23503            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
23504            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
23505    })
23506    @TextAlignment
23507    public int getRawTextAlignment() {
23508        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
23509    }
23510
23511    /**
23512     * Set the text alignment.
23513     *
23514     * @param textAlignment The text alignment to set. Should be one of
23515     *
23516     * {@link #TEXT_ALIGNMENT_INHERIT},
23517     * {@link #TEXT_ALIGNMENT_GRAVITY},
23518     * {@link #TEXT_ALIGNMENT_CENTER},
23519     * {@link #TEXT_ALIGNMENT_TEXT_START},
23520     * {@link #TEXT_ALIGNMENT_TEXT_END},
23521     * {@link #TEXT_ALIGNMENT_VIEW_START},
23522     * {@link #TEXT_ALIGNMENT_VIEW_END}
23523     *
23524     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
23525     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
23526     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
23527     *
23528     * @attr ref android.R.styleable#View_textAlignment
23529     */
23530    public void setTextAlignment(@TextAlignment int textAlignment) {
23531        if (textAlignment != getRawTextAlignment()) {
23532            // Reset the current and resolved text alignment
23533            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
23534            resetResolvedTextAlignment();
23535            // Set the new text alignment
23536            mPrivateFlags2 |=
23537                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
23538            // Do resolution
23539            resolveTextAlignment();
23540            // Notify change
23541            onRtlPropertiesChanged(getLayoutDirection());
23542            // Refresh
23543            requestLayout();
23544            invalidate(true);
23545        }
23546    }
23547
23548    /**
23549     * Return the resolved text alignment.
23550     *
23551     * @return the resolved text alignment. Returns one of:
23552     *
23553     * {@link #TEXT_ALIGNMENT_GRAVITY},
23554     * {@link #TEXT_ALIGNMENT_CENTER},
23555     * {@link #TEXT_ALIGNMENT_TEXT_START},
23556     * {@link #TEXT_ALIGNMENT_TEXT_END},
23557     * {@link #TEXT_ALIGNMENT_VIEW_START},
23558     * {@link #TEXT_ALIGNMENT_VIEW_END}
23559     *
23560     * @attr ref android.R.styleable#View_textAlignment
23561     */
23562    @ViewDebug.ExportedProperty(category = "text", mapping = {
23563            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
23564            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
23565            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
23566            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
23567            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
23568            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
23569            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
23570    })
23571    @TextAlignment
23572    public int getTextAlignment() {
23573        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
23574                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
23575    }
23576
23577    /**
23578     * Resolve the text alignment.
23579     *
23580     * @return true if resolution has been done, false otherwise.
23581     *
23582     * @hide
23583     */
23584    public boolean resolveTextAlignment() {
23585        // Reset any previous text alignment resolution
23586        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
23587
23588        if (hasRtlSupport()) {
23589            // Set resolved text alignment flag depending on text alignment flag
23590            final int textAlignment = getRawTextAlignment();
23591            switch (textAlignment) {
23592                case TEXT_ALIGNMENT_INHERIT:
23593                    // Check if we can resolve the text alignment
23594                    if (!canResolveTextAlignment()) {
23595                        // We cannot do the resolution if there is no parent so use the default
23596                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
23597                        // Resolution will need to happen again later
23598                        return false;
23599                    }
23600
23601                    // Parent has not yet resolved, so we still return the default
23602                    try {
23603                        if (!mParent.isTextAlignmentResolved()) {
23604                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
23605                            // Resolution will need to happen again later
23606                            return false;
23607                        }
23608                    } catch (AbstractMethodError e) {
23609                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
23610                                " does not fully implement ViewParent", e);
23611                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
23612                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
23613                        return true;
23614                    }
23615
23616                    int parentResolvedTextAlignment;
23617                    try {
23618                        parentResolvedTextAlignment = mParent.getTextAlignment();
23619                    } catch (AbstractMethodError e) {
23620                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
23621                                " does not fully implement ViewParent", e);
23622                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
23623                    }
23624                    switch (parentResolvedTextAlignment) {
23625                        case TEXT_ALIGNMENT_GRAVITY:
23626                        case TEXT_ALIGNMENT_TEXT_START:
23627                        case TEXT_ALIGNMENT_TEXT_END:
23628                        case TEXT_ALIGNMENT_CENTER:
23629                        case TEXT_ALIGNMENT_VIEW_START:
23630                        case TEXT_ALIGNMENT_VIEW_END:
23631                            // Resolved text alignment is the same as the parent resolved
23632                            // text alignment
23633                            mPrivateFlags2 |=
23634                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
23635                            break;
23636                        default:
23637                            // Use default resolved text alignment
23638                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
23639                    }
23640                    break;
23641                case TEXT_ALIGNMENT_GRAVITY:
23642                case TEXT_ALIGNMENT_TEXT_START:
23643                case TEXT_ALIGNMENT_TEXT_END:
23644                case TEXT_ALIGNMENT_CENTER:
23645                case TEXT_ALIGNMENT_VIEW_START:
23646                case TEXT_ALIGNMENT_VIEW_END:
23647                    // Resolved text alignment is the same as text alignment
23648                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
23649                    break;
23650                default:
23651                    // Use default resolved text alignment
23652                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
23653            }
23654        } else {
23655            // Use default resolved text alignment
23656            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
23657        }
23658
23659        // Set the resolved
23660        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
23661        return true;
23662    }
23663
23664    /**
23665     * Check if text alignment resolution can be done.
23666     *
23667     * @return true if text alignment resolution can be done otherwise return false.
23668     */
23669    public boolean canResolveTextAlignment() {
23670        switch (getRawTextAlignment()) {
23671            case TEXT_DIRECTION_INHERIT:
23672                if (mParent != null) {
23673                    try {
23674                        return mParent.canResolveTextAlignment();
23675                    } catch (AbstractMethodError e) {
23676                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
23677                                " does not fully implement ViewParent", e);
23678                    }
23679                }
23680                return false;
23681
23682            default:
23683                return true;
23684        }
23685    }
23686
23687    /**
23688     * Reset resolved text alignment. Text alignment will be resolved during a call to
23689     * {@link #onMeasure(int, int)}.
23690     *
23691     * @hide
23692     */
23693    public void resetResolvedTextAlignment() {
23694        // Reset any previous text alignment resolution
23695        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
23696        // Set to default
23697        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
23698    }
23699
23700    /**
23701     * @return true if text alignment is inherited.
23702     *
23703     * @hide
23704     */
23705    public boolean isTextAlignmentInherited() {
23706        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
23707    }
23708
23709    /**
23710     * @return true if text alignment is resolved.
23711     */
23712    public boolean isTextAlignmentResolved() {
23713        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
23714    }
23715
23716    /**
23717     * Generate a value suitable for use in {@link #setId(int)}.
23718     * This value will not collide with ID values generated at build time by aapt for R.id.
23719     *
23720     * @return a generated ID value
23721     */
23722    public static int generateViewId() {
23723        for (;;) {
23724            final int result = sNextGeneratedId.get();
23725            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
23726            int newValue = result + 1;
23727            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
23728            if (sNextGeneratedId.compareAndSet(result, newValue)) {
23729                return result;
23730            }
23731        }
23732    }
23733
23734    private static boolean isViewIdGenerated(int id) {
23735        return (id & 0xFF000000) == 0 && (id & 0x00FFFFFF) != 0;
23736    }
23737
23738    /**
23739     * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions.
23740     * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and
23741     *                           a normal View or a ViewGroup with
23742     *                           {@link android.view.ViewGroup#isTransitionGroup()} true.
23743     * @hide
23744     */
23745    public void captureTransitioningViews(List<View> transitioningViews) {
23746        if (getVisibility() == View.VISIBLE) {
23747            transitioningViews.add(this);
23748        }
23749    }
23750
23751    /**
23752     * Adds all Views that have {@link #getTransitionName()} non-null to namedElements.
23753     * @param namedElements Will contain all Views in the hierarchy having a transitionName.
23754     * @hide
23755     */
23756    public void findNamedViews(Map<String, View> namedElements) {
23757        if (getVisibility() == VISIBLE || mGhostView != null) {
23758            String transitionName = getTransitionName();
23759            if (transitionName != null) {
23760                namedElements.put(transitionName, this);
23761            }
23762        }
23763    }
23764
23765    /**
23766     * Returns the pointer icon for the motion event, or null if it doesn't specify the icon.
23767     * The default implementation does not care the location or event types, but some subclasses
23768     * may use it (such as WebViews).
23769     * @param event The MotionEvent from a mouse
23770     * @param pointerIndex The index of the pointer for which to retrieve the {@link PointerIcon}.
23771     *                     This will be between 0 and {@link MotionEvent#getPointerCount()}.
23772     * @see PointerIcon
23773     */
23774    public PointerIcon onResolvePointerIcon(MotionEvent event, int pointerIndex) {
23775        final float x = event.getX(pointerIndex);
23776        final float y = event.getY(pointerIndex);
23777        if (isDraggingScrollBar() || isOnScrollbarThumb(x, y)) {
23778            return PointerIcon.getSystemIcon(mContext, PointerIcon.TYPE_ARROW);
23779        }
23780        return mPointerIcon;
23781    }
23782
23783    /**
23784     * Set the pointer icon for the current view.
23785     * Passing {@code null} will restore the pointer icon to its default value.
23786     * @param pointerIcon A PointerIcon instance which will be shown when the mouse hovers.
23787     */
23788    public void setPointerIcon(PointerIcon pointerIcon) {
23789        mPointerIcon = pointerIcon;
23790        if (mAttachInfo == null || mAttachInfo.mHandlingPointerEvent) {
23791            return;
23792        }
23793        try {
23794            mAttachInfo.mSession.updatePointerIcon(mAttachInfo.mWindow);
23795        } catch (RemoteException e) {
23796        }
23797    }
23798
23799    /**
23800     * Gets the pointer icon for the current view.
23801     */
23802    public PointerIcon getPointerIcon() {
23803        return mPointerIcon;
23804    }
23805
23806    /**
23807     * Checks pointer capture status.
23808     *
23809     * @return true if the view has pointer capture.
23810     * @see #requestPointerCapture()
23811     * @see #hasPointerCapture()
23812     */
23813    public boolean hasPointerCapture() {
23814        final ViewRootImpl viewRootImpl = getViewRootImpl();
23815        if (viewRootImpl == null) {
23816            return false;
23817        }
23818        return viewRootImpl.hasPointerCapture();
23819    }
23820
23821    /**
23822     * Requests pointer capture mode.
23823     * <p>
23824     * When the window has pointer capture, the mouse pointer icon will disappear and will not
23825     * change its position. Further mouse will be dispatched with the source
23826     * {@link InputDevice#SOURCE_MOUSE_RELATIVE}, and relative position changes will be available
23827     * through {@link MotionEvent#getX} and {@link MotionEvent#getY}. Non-mouse events
23828     * (touchscreens, or stylus) will not be affected.
23829     * <p>
23830     * If the window already has pointer capture, this call does nothing.
23831     * <p>
23832     * The capture may be released through {@link #releasePointerCapture()}, or will be lost
23833     * automatically when the window loses focus.
23834     *
23835     * @see #releasePointerCapture()
23836     * @see #hasPointerCapture()
23837     */
23838    public void requestPointerCapture() {
23839        final ViewRootImpl viewRootImpl = getViewRootImpl();
23840        if (viewRootImpl != null) {
23841            viewRootImpl.requestPointerCapture(true);
23842        }
23843    }
23844
23845
23846    /**
23847     * Releases the pointer capture.
23848     * <p>
23849     * If the window does not have pointer capture, this call will do nothing.
23850     * @see #requestPointerCapture()
23851     * @see #hasPointerCapture()
23852     */
23853    public void releasePointerCapture() {
23854        final ViewRootImpl viewRootImpl = getViewRootImpl();
23855        if (viewRootImpl != null) {
23856            viewRootImpl.requestPointerCapture(false);
23857        }
23858    }
23859
23860    /**
23861     * Called when the window has just acquired or lost pointer capture.
23862     *
23863     * @param hasCapture True if the view now has pointerCapture, false otherwise.
23864     */
23865    @CallSuper
23866    public void onPointerCaptureChange(boolean hasCapture) {
23867    }
23868
23869    /**
23870     * @see #onPointerCaptureChange
23871     */
23872    public void dispatchPointerCaptureChanged(boolean hasCapture) {
23873        onPointerCaptureChange(hasCapture);
23874    }
23875
23876    /**
23877     * Implement this method to handle captured pointer events
23878     *
23879     * @param event The captured pointer event.
23880     * @return True if the event was handled, false otherwise.
23881     * @see #requestPointerCapture()
23882     */
23883    public boolean onCapturedPointerEvent(MotionEvent event) {
23884        return false;
23885    }
23886
23887    /**
23888     * Interface definition for a callback to be invoked when a captured pointer event
23889     * is being dispatched this view. The callback will be invoked before the event is
23890     * given to the view.
23891     */
23892    public interface OnCapturedPointerListener {
23893        /**
23894         * Called when a captured pointer event is dispatched to a view.
23895         * @param view The view this event has been dispatched to.
23896         * @param event The captured event.
23897         * @return True if the listener has consumed the event, false otherwise.
23898         */
23899        boolean onCapturedPointer(View view, MotionEvent event);
23900    }
23901
23902    /**
23903     * Set a listener to receive callbacks when the pointer capture state of a view changes.
23904     * @param l  The {@link OnCapturedPointerListener} to receive callbacks.
23905     */
23906    public void setOnCapturedPointerListener(OnCapturedPointerListener l) {
23907        getListenerInfo().mOnCapturedPointerListener = l;
23908    }
23909
23910    // Properties
23911    //
23912    /**
23913     * A Property wrapper around the <code>alpha</code> functionality handled by the
23914     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
23915     */
23916    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
23917        @Override
23918        public void setValue(View object, float value) {
23919            object.setAlpha(value);
23920        }
23921
23922        @Override
23923        public Float get(View object) {
23924            return object.getAlpha();
23925        }
23926    };
23927
23928    /**
23929     * A Property wrapper around the <code>translationX</code> functionality handled by the
23930     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
23931     */
23932    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
23933        @Override
23934        public void setValue(View object, float value) {
23935            object.setTranslationX(value);
23936        }
23937
23938                @Override
23939        public Float get(View object) {
23940            return object.getTranslationX();
23941        }
23942    };
23943
23944    /**
23945     * A Property wrapper around the <code>translationY</code> functionality handled by the
23946     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
23947     */
23948    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
23949        @Override
23950        public void setValue(View object, float value) {
23951            object.setTranslationY(value);
23952        }
23953
23954        @Override
23955        public Float get(View object) {
23956            return object.getTranslationY();
23957        }
23958    };
23959
23960    /**
23961     * A Property wrapper around the <code>translationZ</code> functionality handled by the
23962     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
23963     */
23964    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
23965        @Override
23966        public void setValue(View object, float value) {
23967            object.setTranslationZ(value);
23968        }
23969
23970        @Override
23971        public Float get(View object) {
23972            return object.getTranslationZ();
23973        }
23974    };
23975
23976    /**
23977     * A Property wrapper around the <code>x</code> functionality handled by the
23978     * {@link View#setX(float)} and {@link View#getX()} methods.
23979     */
23980    public static final Property<View, Float> X = new FloatProperty<View>("x") {
23981        @Override
23982        public void setValue(View object, float value) {
23983            object.setX(value);
23984        }
23985
23986        @Override
23987        public Float get(View object) {
23988            return object.getX();
23989        }
23990    };
23991
23992    /**
23993     * A Property wrapper around the <code>y</code> functionality handled by the
23994     * {@link View#setY(float)} and {@link View#getY()} methods.
23995     */
23996    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
23997        @Override
23998        public void setValue(View object, float value) {
23999            object.setY(value);
24000        }
24001
24002        @Override
24003        public Float get(View object) {
24004            return object.getY();
24005        }
24006    };
24007
24008    /**
24009     * A Property wrapper around the <code>z</code> functionality handled by the
24010     * {@link View#setZ(float)} and {@link View#getZ()} methods.
24011     */
24012    public static final Property<View, Float> Z = new FloatProperty<View>("z") {
24013        @Override
24014        public void setValue(View object, float value) {
24015            object.setZ(value);
24016        }
24017
24018        @Override
24019        public Float get(View object) {
24020            return object.getZ();
24021        }
24022    };
24023
24024    /**
24025     * A Property wrapper around the <code>rotation</code> functionality handled by the
24026     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
24027     */
24028    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
24029        @Override
24030        public void setValue(View object, float value) {
24031            object.setRotation(value);
24032        }
24033
24034        @Override
24035        public Float get(View object) {
24036            return object.getRotation();
24037        }
24038    };
24039
24040    /**
24041     * A Property wrapper around the <code>rotationX</code> functionality handled by the
24042     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
24043     */
24044    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
24045        @Override
24046        public void setValue(View object, float value) {
24047            object.setRotationX(value);
24048        }
24049
24050        @Override
24051        public Float get(View object) {
24052            return object.getRotationX();
24053        }
24054    };
24055
24056    /**
24057     * A Property wrapper around the <code>rotationY</code> functionality handled by the
24058     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
24059     */
24060    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
24061        @Override
24062        public void setValue(View object, float value) {
24063            object.setRotationY(value);
24064        }
24065
24066        @Override
24067        public Float get(View object) {
24068            return object.getRotationY();
24069        }
24070    };
24071
24072    /**
24073     * A Property wrapper around the <code>scaleX</code> functionality handled by the
24074     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
24075     */
24076    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
24077        @Override
24078        public void setValue(View object, float value) {
24079            object.setScaleX(value);
24080        }
24081
24082        @Override
24083        public Float get(View object) {
24084            return object.getScaleX();
24085        }
24086    };
24087
24088    /**
24089     * A Property wrapper around the <code>scaleY</code> functionality handled by the
24090     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
24091     */
24092    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
24093        @Override
24094        public void setValue(View object, float value) {
24095            object.setScaleY(value);
24096        }
24097
24098        @Override
24099        public Float get(View object) {
24100            return object.getScaleY();
24101        }
24102    };
24103
24104    /**
24105     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
24106     * Each MeasureSpec represents a requirement for either the width or the height.
24107     * A MeasureSpec is comprised of a size and a mode. There are three possible
24108     * modes:
24109     * <dl>
24110     * <dt>UNSPECIFIED</dt>
24111     * <dd>
24112     * The parent has not imposed any constraint on the child. It can be whatever size
24113     * it wants.
24114     * </dd>
24115     *
24116     * <dt>EXACTLY</dt>
24117     * <dd>
24118     * The parent has determined an exact size for the child. The child is going to be
24119     * given those bounds regardless of how big it wants to be.
24120     * </dd>
24121     *
24122     * <dt>AT_MOST</dt>
24123     * <dd>
24124     * The child can be as large as it wants up to the specified size.
24125     * </dd>
24126     * </dl>
24127     *
24128     * MeasureSpecs are implemented as ints to reduce object allocation. This class
24129     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
24130     */
24131    public static class MeasureSpec {
24132        private static final int MODE_SHIFT = 30;
24133        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
24134
24135        /** @hide */
24136        @IntDef({UNSPECIFIED, EXACTLY, AT_MOST})
24137        @Retention(RetentionPolicy.SOURCE)
24138        public @interface MeasureSpecMode {}
24139
24140        /**
24141         * Measure specification mode: The parent has not imposed any constraint
24142         * on the child. It can be whatever size it wants.
24143         */
24144        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
24145
24146        /**
24147         * Measure specification mode: The parent has determined an exact size
24148         * for the child. The child is going to be given those bounds regardless
24149         * of how big it wants to be.
24150         */
24151        public static final int EXACTLY     = 1 << MODE_SHIFT;
24152
24153        /**
24154         * Measure specification mode: The child can be as large as it wants up
24155         * to the specified size.
24156         */
24157        public static final int AT_MOST     = 2 << MODE_SHIFT;
24158
24159        /**
24160         * Creates a measure specification based on the supplied size and mode.
24161         *
24162         * The mode must always be one of the following:
24163         * <ul>
24164         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
24165         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
24166         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
24167         * </ul>
24168         *
24169         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
24170         * implementation was such that the order of arguments did not matter
24171         * and overflow in either value could impact the resulting MeasureSpec.
24172         * {@link android.widget.RelativeLayout} was affected by this bug.
24173         * Apps targeting API levels greater than 17 will get the fixed, more strict
24174         * behavior.</p>
24175         *
24176         * @param size the size of the measure specification
24177         * @param mode the mode of the measure specification
24178         * @return the measure specification based on size and mode
24179         */
24180        public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size,
24181                                          @MeasureSpecMode int mode) {
24182            if (sUseBrokenMakeMeasureSpec) {
24183                return size + mode;
24184            } else {
24185                return (size & ~MODE_MASK) | (mode & MODE_MASK);
24186            }
24187        }
24188
24189        /**
24190         * Like {@link #makeMeasureSpec(int, int)}, but any spec with a mode of UNSPECIFIED
24191         * will automatically get a size of 0. Older apps expect this.
24192         *
24193         * @hide internal use only for compatibility with system widgets and older apps
24194         */
24195        public static int makeSafeMeasureSpec(int size, int mode) {
24196            if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) {
24197                return 0;
24198            }
24199            return makeMeasureSpec(size, mode);
24200        }
24201
24202        /**
24203         * Extracts the mode from the supplied measure specification.
24204         *
24205         * @param measureSpec the measure specification to extract the mode from
24206         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
24207         *         {@link android.view.View.MeasureSpec#AT_MOST} or
24208         *         {@link android.view.View.MeasureSpec#EXACTLY}
24209         */
24210        @MeasureSpecMode
24211        public static int getMode(int measureSpec) {
24212            //noinspection ResourceType
24213            return (measureSpec & MODE_MASK);
24214        }
24215
24216        /**
24217         * Extracts the size from the supplied measure specification.
24218         *
24219         * @param measureSpec the measure specification to extract the size from
24220         * @return the size in pixels defined in the supplied measure specification
24221         */
24222        public static int getSize(int measureSpec) {
24223            return (measureSpec & ~MODE_MASK);
24224        }
24225
24226        static int adjust(int measureSpec, int delta) {
24227            final int mode = getMode(measureSpec);
24228            int size = getSize(measureSpec);
24229            if (mode == UNSPECIFIED) {
24230                // No need to adjust size for UNSPECIFIED mode.
24231                return makeMeasureSpec(size, UNSPECIFIED);
24232            }
24233            size += delta;
24234            if (size < 0) {
24235                Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
24236                        ") spec: " + toString(measureSpec) + " delta: " + delta);
24237                size = 0;
24238            }
24239            return makeMeasureSpec(size, mode);
24240        }
24241
24242        /**
24243         * Returns a String representation of the specified measure
24244         * specification.
24245         *
24246         * @param measureSpec the measure specification to convert to a String
24247         * @return a String with the following format: "MeasureSpec: MODE SIZE"
24248         */
24249        public static String toString(int measureSpec) {
24250            int mode = getMode(measureSpec);
24251            int size = getSize(measureSpec);
24252
24253            StringBuilder sb = new StringBuilder("MeasureSpec: ");
24254
24255            if (mode == UNSPECIFIED)
24256                sb.append("UNSPECIFIED ");
24257            else if (mode == EXACTLY)
24258                sb.append("EXACTLY ");
24259            else if (mode == AT_MOST)
24260                sb.append("AT_MOST ");
24261            else
24262                sb.append(mode).append(" ");
24263
24264            sb.append(size);
24265            return sb.toString();
24266        }
24267    }
24268
24269    private final class CheckForLongPress implements Runnable {
24270        private int mOriginalWindowAttachCount;
24271        private float mX;
24272        private float mY;
24273        private boolean mOriginalPressedState;
24274
24275        @Override
24276        public void run() {
24277            if ((mOriginalPressedState == isPressed()) && (mParent != null)
24278                    && mOriginalWindowAttachCount == mWindowAttachCount) {
24279                if (performLongClick(mX, mY)) {
24280                    mHasPerformedLongPress = true;
24281                }
24282            }
24283        }
24284
24285        public void setAnchor(float x, float y) {
24286            mX = x;
24287            mY = y;
24288        }
24289
24290        public void rememberWindowAttachCount() {
24291            mOriginalWindowAttachCount = mWindowAttachCount;
24292        }
24293
24294        public void rememberPressedState() {
24295            mOriginalPressedState = isPressed();
24296        }
24297    }
24298
24299    private final class CheckForTap implements Runnable {
24300        public float x;
24301        public float y;
24302
24303        @Override
24304        public void run() {
24305            mPrivateFlags &= ~PFLAG_PREPRESSED;
24306            setPressed(true, x, y);
24307            checkForLongClick(ViewConfiguration.getTapTimeout(), x, y);
24308        }
24309    }
24310
24311    private final class PerformClick implements Runnable {
24312        @Override
24313        public void run() {
24314            performClick();
24315        }
24316    }
24317
24318    /**
24319     * This method returns a ViewPropertyAnimator object, which can be used to animate
24320     * specific properties on this View.
24321     *
24322     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
24323     */
24324    public ViewPropertyAnimator animate() {
24325        if (mAnimator == null) {
24326            mAnimator = new ViewPropertyAnimator(this);
24327        }
24328        return mAnimator;
24329    }
24330
24331    /**
24332     * Sets the name of the View to be used to identify Views in Transitions.
24333     * Names should be unique in the View hierarchy.
24334     *
24335     * @param transitionName The name of the View to uniquely identify it for Transitions.
24336     */
24337    public final void setTransitionName(String transitionName) {
24338        mTransitionName = transitionName;
24339    }
24340
24341    /**
24342     * Returns the name of the View to be used to identify Views in Transitions.
24343     * Names should be unique in the View hierarchy.
24344     *
24345     * <p>This returns null if the View has not been given a name.</p>
24346     *
24347     * @return The name used of the View to be used to identify Views in Transitions or null
24348     * if no name has been given.
24349     */
24350    @ViewDebug.ExportedProperty
24351    public String getTransitionName() {
24352        return mTransitionName;
24353    }
24354
24355    /**
24356     * @hide
24357     */
24358    public void requestKeyboardShortcuts(List<KeyboardShortcutGroup> data, int deviceId) {
24359        // Do nothing.
24360    }
24361
24362    /**
24363     * Interface definition for a callback to be invoked when a hardware key event is
24364     * dispatched to this view. The callback will be invoked before the key event is
24365     * given to the view. This is only useful for hardware keyboards; a software input
24366     * method has no obligation to trigger this listener.
24367     */
24368    public interface OnKeyListener {
24369        /**
24370         * Called when a hardware key is dispatched to a view. This allows listeners to
24371         * get a chance to respond before the target view.
24372         * <p>Key presses in software keyboards will generally NOT trigger this method,
24373         * although some may elect to do so in some situations. Do not assume a
24374         * software input method has to be key-based; even if it is, it may use key presses
24375         * in a different way than you expect, so there is no way to reliably catch soft
24376         * input key presses.
24377         *
24378         * @param v The view the key has been dispatched to.
24379         * @param keyCode The code for the physical key that was pressed
24380         * @param event The KeyEvent object containing full information about
24381         *        the event.
24382         * @return True if the listener has consumed the event, false otherwise.
24383         */
24384        boolean onKey(View v, int keyCode, KeyEvent event);
24385    }
24386
24387    /**
24388     * Interface definition for a callback to be invoked when a touch event is
24389     * dispatched to this view. The callback will be invoked before the touch
24390     * event is given to the view.
24391     */
24392    public interface OnTouchListener {
24393        /**
24394         * Called when a touch event is dispatched to a view. This allows listeners to
24395         * get a chance to respond before the target view.
24396         *
24397         * @param v The view the touch event has been dispatched to.
24398         * @param event The MotionEvent object containing full information about
24399         *        the event.
24400         * @return True if the listener has consumed the event, false otherwise.
24401         */
24402        boolean onTouch(View v, MotionEvent event);
24403    }
24404
24405    /**
24406     * Interface definition for a callback to be invoked when a hover event is
24407     * dispatched to this view. The callback will be invoked before the hover
24408     * event is given to the view.
24409     */
24410    public interface OnHoverListener {
24411        /**
24412         * Called when a hover event is dispatched to a view. This allows listeners to
24413         * get a chance to respond before the target view.
24414         *
24415         * @param v The view the hover event has been dispatched to.
24416         * @param event The MotionEvent object containing full information about
24417         *        the event.
24418         * @return True if the listener has consumed the event, false otherwise.
24419         */
24420        boolean onHover(View v, MotionEvent event);
24421    }
24422
24423    /**
24424     * Interface definition for a callback to be invoked when a generic motion event is
24425     * dispatched to this view. The callback will be invoked before the generic motion
24426     * event is given to the view.
24427     */
24428    public interface OnGenericMotionListener {
24429        /**
24430         * Called when a generic motion event is dispatched to a view. This allows listeners to
24431         * get a chance to respond before the target view.
24432         *
24433         * @param v The view the generic motion event has been dispatched to.
24434         * @param event The MotionEvent object containing full information about
24435         *        the event.
24436         * @return True if the listener has consumed the event, false otherwise.
24437         */
24438        boolean onGenericMotion(View v, MotionEvent event);
24439    }
24440
24441    /**
24442     * Interface definition for a callback to be invoked when a view has been clicked and held.
24443     */
24444    public interface OnLongClickListener {
24445        /**
24446         * Called when a view has been clicked and held.
24447         *
24448         * @param v The view that was clicked and held.
24449         *
24450         * @return true if the callback consumed the long click, false otherwise.
24451         */
24452        boolean onLongClick(View v);
24453    }
24454
24455    /**
24456     * Interface definition for a callback to be invoked when a drag is being dispatched
24457     * to this view.  The callback will be invoked before the hosting view's own
24458     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
24459     * onDrag(event) behavior, it should return 'false' from this callback.
24460     *
24461     * <div class="special reference">
24462     * <h3>Developer Guides</h3>
24463     * <p>For a guide to implementing drag and drop features, read the
24464     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
24465     * </div>
24466     */
24467    public interface OnDragListener {
24468        /**
24469         * Called when a drag event is dispatched to a view. This allows listeners
24470         * to get a chance to override base View behavior.
24471         *
24472         * @param v The View that received the drag event.
24473         * @param event The {@link android.view.DragEvent} object for the drag event.
24474         * @return {@code true} if the drag event was handled successfully, or {@code false}
24475         * if the drag event was not handled. Note that {@code false} will trigger the View
24476         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
24477         */
24478        boolean onDrag(View v, DragEvent event);
24479    }
24480
24481    /**
24482     * Interface definition for a callback to be invoked when the focus state of
24483     * a view changed.
24484     */
24485    public interface OnFocusChangeListener {
24486        /**
24487         * Called when the focus state of a view has changed.
24488         *
24489         * @param v The view whose state has changed.
24490         * @param hasFocus The new focus state of v.
24491         */
24492        void onFocusChange(View v, boolean hasFocus);
24493    }
24494
24495    /**
24496     * Interface definition for a callback to be invoked when a view is clicked.
24497     */
24498    public interface OnClickListener {
24499        /**
24500         * Called when a view has been clicked.
24501         *
24502         * @param v The view that was clicked.
24503         */
24504        void onClick(View v);
24505    }
24506
24507    /**
24508     * Interface definition for a callback to be invoked when a view is context clicked.
24509     */
24510    public interface OnContextClickListener {
24511        /**
24512         * Called when a view is context clicked.
24513         *
24514         * @param v The view that has been context clicked.
24515         * @return true if the callback consumed the context click, false otherwise.
24516         */
24517        boolean onContextClick(View v);
24518    }
24519
24520    /**
24521     * Interface definition for a callback to be invoked when the context menu
24522     * for this view is being built.
24523     */
24524    public interface OnCreateContextMenuListener {
24525        /**
24526         * Called when the context menu for this view is being built. It is not
24527         * safe to hold onto the menu after this method returns.
24528         *
24529         * @param menu The context menu that is being built
24530         * @param v The view for which the context menu is being built
24531         * @param menuInfo Extra information about the item for which the
24532         *            context menu should be shown. This information will vary
24533         *            depending on the class of v.
24534         */
24535        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
24536    }
24537
24538    /**
24539     * Interface definition for a callback to be invoked when the status bar changes
24540     * visibility.  This reports <strong>global</strong> changes to the system UI
24541     * state, not what the application is requesting.
24542     *
24543     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
24544     */
24545    public interface OnSystemUiVisibilityChangeListener {
24546        /**
24547         * Called when the status bar changes visibility because of a call to
24548         * {@link View#setSystemUiVisibility(int)}.
24549         *
24550         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
24551         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
24552         * This tells you the <strong>global</strong> state of these UI visibility
24553         * flags, not what your app is currently applying.
24554         */
24555        public void onSystemUiVisibilityChange(int visibility);
24556    }
24557
24558    /**
24559     * Interface definition for a callback to be invoked when this view is attached
24560     * or detached from its window.
24561     */
24562    public interface OnAttachStateChangeListener {
24563        /**
24564         * Called when the view is attached to a window.
24565         * @param v The view that was attached
24566         */
24567        public void onViewAttachedToWindow(View v);
24568        /**
24569         * Called when the view is detached from a window.
24570         * @param v The view that was detached
24571         */
24572        public void onViewDetachedFromWindow(View v);
24573    }
24574
24575    /**
24576     * Listener for applying window insets on a view in a custom way.
24577     *
24578     * <p>Apps may choose to implement this interface if they want to apply custom policy
24579     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
24580     * is set, its
24581     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
24582     * method will be called instead of the View's own
24583     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
24584     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
24585     * the View's normal behavior as part of its own.</p>
24586     */
24587    public interface OnApplyWindowInsetsListener {
24588        /**
24589         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
24590         * on a View, this listener method will be called instead of the view's own
24591         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
24592         *
24593         * @param v The view applying window insets
24594         * @param insets The insets to apply
24595         * @return The insets supplied, minus any insets that were consumed
24596         */
24597        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
24598    }
24599
24600    private final class UnsetPressedState implements Runnable {
24601        @Override
24602        public void run() {
24603            setPressed(false);
24604        }
24605    }
24606
24607    /**
24608     * Base class for derived classes that want to save and restore their own
24609     * state in {@link android.view.View#onSaveInstanceState()}.
24610     */
24611    public static class BaseSavedState extends AbsSavedState {
24612        static final int START_ACTIVITY_REQUESTED_WHO_SAVED = 0b1;
24613        static final int IS_AUTOFILLED = 0b10;
24614        static final int ACCESSIBILITY_ID = 0b100;
24615
24616        // Flags that describe what data in this state is valid
24617        int mSavedData;
24618        String mStartActivityRequestWhoSaved;
24619        boolean mIsAutofilled;
24620        int mAccessibilityViewId;
24621
24622        /**
24623         * Constructor used when reading from a parcel. Reads the state of the superclass.
24624         *
24625         * @param source parcel to read from
24626         */
24627        public BaseSavedState(Parcel source) {
24628            this(source, null);
24629        }
24630
24631        /**
24632         * Constructor used when reading from a parcel using a given class loader.
24633         * Reads the state of the superclass.
24634         *
24635         * @param source parcel to read from
24636         * @param loader ClassLoader to use for reading
24637         */
24638        public BaseSavedState(Parcel source, ClassLoader loader) {
24639            super(source, loader);
24640            mSavedData = source.readInt();
24641            mStartActivityRequestWhoSaved = source.readString();
24642            mIsAutofilled = source.readBoolean();
24643            mAccessibilityViewId = source.readInt();
24644        }
24645
24646        /**
24647         * Constructor called by derived classes when creating their SavedState objects
24648         *
24649         * @param superState The state of the superclass of this view
24650         */
24651        public BaseSavedState(Parcelable superState) {
24652            super(superState);
24653        }
24654
24655        @Override
24656        public void writeToParcel(Parcel out, int flags) {
24657            super.writeToParcel(out, flags);
24658
24659            out.writeInt(mSavedData);
24660            out.writeString(mStartActivityRequestWhoSaved);
24661            out.writeBoolean(mIsAutofilled);
24662            out.writeInt(mAccessibilityViewId);
24663        }
24664
24665        public static final Parcelable.Creator<BaseSavedState> CREATOR
24666                = new Parcelable.ClassLoaderCreator<BaseSavedState>() {
24667            @Override
24668            public BaseSavedState createFromParcel(Parcel in) {
24669                return new BaseSavedState(in);
24670            }
24671
24672            @Override
24673            public BaseSavedState createFromParcel(Parcel in, ClassLoader loader) {
24674                return new BaseSavedState(in, loader);
24675            }
24676
24677            @Override
24678            public BaseSavedState[] newArray(int size) {
24679                return new BaseSavedState[size];
24680            }
24681        };
24682    }
24683
24684    /**
24685     * A set of information given to a view when it is attached to its parent
24686     * window.
24687     */
24688    final static class AttachInfo {
24689        interface Callbacks {
24690            void playSoundEffect(int effectId);
24691            boolean performHapticFeedback(int effectId, boolean always);
24692        }
24693
24694        /**
24695         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
24696         * to a Handler. This class contains the target (View) to invalidate and
24697         * the coordinates of the dirty rectangle.
24698         *
24699         * For performance purposes, this class also implements a pool of up to
24700         * POOL_LIMIT objects that get reused. This reduces memory allocations
24701         * whenever possible.
24702         */
24703        static class InvalidateInfo {
24704            private static final int POOL_LIMIT = 10;
24705
24706            private static final SynchronizedPool<InvalidateInfo> sPool =
24707                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
24708
24709            View target;
24710
24711            int left;
24712            int top;
24713            int right;
24714            int bottom;
24715
24716            public static InvalidateInfo obtain() {
24717                InvalidateInfo instance = sPool.acquire();
24718                return (instance != null) ? instance : new InvalidateInfo();
24719            }
24720
24721            public void recycle() {
24722                target = null;
24723                sPool.release(this);
24724            }
24725        }
24726
24727        final IWindowSession mSession;
24728
24729        final IWindow mWindow;
24730
24731        final IBinder mWindowToken;
24732
24733        Display mDisplay;
24734
24735        final Callbacks mRootCallbacks;
24736
24737        IWindowId mIWindowId;
24738        WindowId mWindowId;
24739
24740        /**
24741         * The top view of the hierarchy.
24742         */
24743        View mRootView;
24744
24745        IBinder mPanelParentWindowToken;
24746
24747        boolean mHardwareAccelerated;
24748        boolean mHardwareAccelerationRequested;
24749        ThreadedRenderer mThreadedRenderer;
24750        List<RenderNode> mPendingAnimatingRenderNodes;
24751
24752        /**
24753         * The state of the display to which the window is attached, as reported
24754         * by {@link Display#getState()}.  Note that the display state constants
24755         * declared by {@link Display} do not exactly line up with the screen state
24756         * constants declared by {@link View} (there are more display states than
24757         * screen states).
24758         */
24759        int mDisplayState = Display.STATE_UNKNOWN;
24760
24761        /**
24762         * Scale factor used by the compatibility mode
24763         */
24764        float mApplicationScale;
24765
24766        /**
24767         * Indicates whether the application is in compatibility mode
24768         */
24769        boolean mScalingRequired;
24770
24771        /**
24772         * Left position of this view's window
24773         */
24774        int mWindowLeft;
24775
24776        /**
24777         * Top position of this view's window
24778         */
24779        int mWindowTop;
24780
24781        /**
24782         * Indicates whether views need to use 32-bit drawing caches
24783         */
24784        boolean mUse32BitDrawingCache;
24785
24786        /**
24787         * For windows that are full-screen but using insets to layout inside
24788         * of the screen areas, these are the current insets to appear inside
24789         * the overscan area of the display.
24790         */
24791        final Rect mOverscanInsets = new Rect();
24792
24793        /**
24794         * For windows that are full-screen but using insets to layout inside
24795         * of the screen decorations, these are the current insets for the
24796         * content of the window.
24797         */
24798        final Rect mContentInsets = new Rect();
24799
24800        /**
24801         * For windows that are full-screen but using insets to layout inside
24802         * of the screen decorations, these are the current insets for the
24803         * actual visible parts of the window.
24804         */
24805        final Rect mVisibleInsets = new Rect();
24806
24807        /**
24808         * For windows that are full-screen but using insets to layout inside
24809         * of the screen decorations, these are the current insets for the
24810         * stable system windows.
24811         */
24812        final Rect mStableInsets = new Rect();
24813
24814        /**
24815         * For windows that include areas that are not covered by real surface these are the outsets
24816         * for real surface.
24817         */
24818        final Rect mOutsets = new Rect();
24819
24820        /**
24821         * In multi-window we force show the navigation bar. Because we don't want that the surface
24822         * size changes in this mode, we instead have a flag whether the navigation bar size should
24823         * always be consumed, so the app is treated like there is no virtual navigation bar at all.
24824         */
24825        boolean mAlwaysConsumeNavBar;
24826
24827        /**
24828         * The internal insets given by this window.  This value is
24829         * supplied by the client (through
24830         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
24831         * be given to the window manager when changed to be used in laying
24832         * out windows behind it.
24833         */
24834        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
24835                = new ViewTreeObserver.InternalInsetsInfo();
24836
24837        /**
24838         * Set to true when mGivenInternalInsets is non-empty.
24839         */
24840        boolean mHasNonEmptyGivenInternalInsets;
24841
24842        /**
24843         * All views in the window's hierarchy that serve as scroll containers,
24844         * used to determine if the window can be resized or must be panned
24845         * to adjust for a soft input area.
24846         */
24847        final ArrayList<View> mScrollContainers = new ArrayList<View>();
24848
24849        final KeyEvent.DispatcherState mKeyDispatchState
24850                = new KeyEvent.DispatcherState();
24851
24852        /**
24853         * Indicates whether the view's window currently has the focus.
24854         */
24855        boolean mHasWindowFocus;
24856
24857        /**
24858         * The current visibility of the window.
24859         */
24860        int mWindowVisibility;
24861
24862        /**
24863         * Indicates the time at which drawing started to occur.
24864         */
24865        long mDrawingTime;
24866
24867        /**
24868         * Indicates whether or not ignoring the DIRTY_MASK flags.
24869         */
24870        boolean mIgnoreDirtyState;
24871
24872        /**
24873         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
24874         * to avoid clearing that flag prematurely.
24875         */
24876        boolean mSetIgnoreDirtyState = false;
24877
24878        /**
24879         * Indicates whether the view's window is currently in touch mode.
24880         */
24881        boolean mInTouchMode;
24882
24883        /**
24884         * Indicates whether the view has requested unbuffered input dispatching for the current
24885         * event stream.
24886         */
24887        boolean mUnbufferedDispatchRequested;
24888
24889        /**
24890         * Indicates that ViewAncestor should trigger a global layout change
24891         * the next time it performs a traversal
24892         */
24893        boolean mRecomputeGlobalAttributes;
24894
24895        /**
24896         * Always report new attributes at next traversal.
24897         */
24898        boolean mForceReportNewAttributes;
24899
24900        /**
24901         * Set during a traveral if any views want to keep the screen on.
24902         */
24903        boolean mKeepScreenOn;
24904
24905        /**
24906         * Set during a traveral if the light center needs to be updated.
24907         */
24908        boolean mNeedsUpdateLightCenter;
24909
24910        /**
24911         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
24912         */
24913        int mSystemUiVisibility;
24914
24915        /**
24916         * Hack to force certain system UI visibility flags to be cleared.
24917         */
24918        int mDisabledSystemUiVisibility;
24919
24920        /**
24921         * Last global system UI visibility reported by the window manager.
24922         */
24923        int mGlobalSystemUiVisibility = -1;
24924
24925        /**
24926         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
24927         * attached.
24928         */
24929        boolean mHasSystemUiListeners;
24930
24931        /**
24932         * Set if the window has requested to extend into the overscan region
24933         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
24934         */
24935        boolean mOverscanRequested;
24936
24937        /**
24938         * Set if the visibility of any views has changed.
24939         */
24940        boolean mViewVisibilityChanged;
24941
24942        /**
24943         * Set to true if a view has been scrolled.
24944         */
24945        boolean mViewScrollChanged;
24946
24947        /**
24948         * Set to true if high contrast mode enabled
24949         */
24950        boolean mHighContrastText;
24951
24952        /**
24953         * Set to true if a pointer event is currently being handled.
24954         */
24955        boolean mHandlingPointerEvent;
24956
24957        /**
24958         * Global to the view hierarchy used as a temporary for dealing with
24959         * x/y points in the transparent region computations.
24960         */
24961        final int[] mTransparentLocation = new int[2];
24962
24963        /**
24964         * Global to the view hierarchy used as a temporary for dealing with
24965         * x/y points in the ViewGroup.invalidateChild implementation.
24966         */
24967        final int[] mInvalidateChildLocation = new int[2];
24968
24969        /**
24970         * Global to the view hierarchy used as a temporary for dealing with
24971         * computing absolute on-screen location.
24972         */
24973        final int[] mTmpLocation = new int[2];
24974
24975        /**
24976         * Global to the view hierarchy used as a temporary for dealing with
24977         * x/y location when view is transformed.
24978         */
24979        final float[] mTmpTransformLocation = new float[2];
24980
24981        /**
24982         * The view tree observer used to dispatch global events like
24983         * layout, pre-draw, touch mode change, etc.
24984         */
24985        final ViewTreeObserver mTreeObserver;
24986
24987        /**
24988         * A Canvas used by the view hierarchy to perform bitmap caching.
24989         */
24990        Canvas mCanvas;
24991
24992        /**
24993         * The view root impl.
24994         */
24995        final ViewRootImpl mViewRootImpl;
24996
24997        /**
24998         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
24999         * handler can be used to pump events in the UI events queue.
25000         */
25001        final Handler mHandler;
25002
25003        /**
25004         * Temporary for use in computing invalidate rectangles while
25005         * calling up the hierarchy.
25006         */
25007        final Rect mTmpInvalRect = new Rect();
25008
25009        /**
25010         * Temporary for use in computing hit areas with transformed views
25011         */
25012        final RectF mTmpTransformRect = new RectF();
25013
25014        /**
25015         * Temporary for use in computing hit areas with transformed views
25016         */
25017        final RectF mTmpTransformRect1 = new RectF();
25018
25019        /**
25020         * Temporary list of rectanges.
25021         */
25022        final List<RectF> mTmpRectList = new ArrayList<>();
25023
25024        /**
25025         * Temporary for use in transforming invalidation rect
25026         */
25027        final Matrix mTmpMatrix = new Matrix();
25028
25029        /**
25030         * Temporary for use in transforming invalidation rect
25031         */
25032        final Transformation mTmpTransformation = new Transformation();
25033
25034        /**
25035         * Temporary for use in querying outlines from OutlineProviders
25036         */
25037        final Outline mTmpOutline = new Outline();
25038
25039        /**
25040         * Temporary list for use in collecting focusable descendents of a view.
25041         */
25042        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
25043
25044        /**
25045         * The id of the window for accessibility purposes.
25046         */
25047        int mAccessibilityWindowId = AccessibilityWindowInfo.UNDEFINED_WINDOW_ID;
25048
25049        /**
25050         * Flags related to accessibility processing.
25051         *
25052         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
25053         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
25054         */
25055        int mAccessibilityFetchFlags;
25056
25057        /**
25058         * The drawable for highlighting accessibility focus.
25059         */
25060        Drawable mAccessibilityFocusDrawable;
25061
25062        /**
25063         * The drawable for highlighting autofilled views.
25064         *
25065         * @see #isAutofilled()
25066         */
25067        Drawable mAutofilledDrawable;
25068
25069        /**
25070         * Show where the margins, bounds and layout bounds are for each view.
25071         */
25072        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
25073
25074        /**
25075         * Point used to compute visible regions.
25076         */
25077        final Point mPoint = new Point();
25078
25079        /**
25080         * Used to track which View originated a requestLayout() call, used when
25081         * requestLayout() is called during layout.
25082         */
25083        View mViewRequestingLayout;
25084
25085        /**
25086         * Used to track views that need (at least) a partial relayout at their current size
25087         * during the next traversal.
25088         */
25089        List<View> mPartialLayoutViews = new ArrayList<>();
25090
25091        /**
25092         * Swapped with mPartialLayoutViews during layout to avoid concurrent
25093         * modification. Lazily assigned during ViewRootImpl layout.
25094         */
25095        List<View> mEmptyPartialLayoutViews;
25096
25097        /**
25098         * Used to track the identity of the current drag operation.
25099         */
25100        IBinder mDragToken;
25101
25102        /**
25103         * The drag shadow surface for the current drag operation.
25104         */
25105        public Surface mDragSurface;
25106
25107
25108        /**
25109         * The view that currently has a tooltip displayed.
25110         */
25111        View mTooltipHost;
25112
25113        /**
25114         * Creates a new set of attachment information with the specified
25115         * events handler and thread.
25116         *
25117         * @param handler the events handler the view must use
25118         */
25119        AttachInfo(IWindowSession session, IWindow window, Display display,
25120                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer,
25121                Context context) {
25122            mSession = session;
25123            mWindow = window;
25124            mWindowToken = window.asBinder();
25125            mDisplay = display;
25126            mViewRootImpl = viewRootImpl;
25127            mHandler = handler;
25128            mRootCallbacks = effectPlayer;
25129            mTreeObserver = new ViewTreeObserver(context);
25130        }
25131    }
25132
25133    /**
25134     * <p>ScrollabilityCache holds various fields used by a View when scrolling
25135     * is supported. This avoids keeping too many unused fields in most
25136     * instances of View.</p>
25137     */
25138    private static class ScrollabilityCache implements Runnable {
25139
25140        /**
25141         * Scrollbars are not visible
25142         */
25143        public static final int OFF = 0;
25144
25145        /**
25146         * Scrollbars are visible
25147         */
25148        public static final int ON = 1;
25149
25150        /**
25151         * Scrollbars are fading away
25152         */
25153        public static final int FADING = 2;
25154
25155        public boolean fadeScrollBars;
25156
25157        public int fadingEdgeLength;
25158        public int scrollBarDefaultDelayBeforeFade;
25159        public int scrollBarFadeDuration;
25160
25161        public int scrollBarSize;
25162        public int scrollBarMinTouchTarget;
25163        public ScrollBarDrawable scrollBar;
25164        public float[] interpolatorValues;
25165        public View host;
25166
25167        public final Paint paint;
25168        public final Matrix matrix;
25169        public Shader shader;
25170
25171        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
25172
25173        private static final float[] OPAQUE = { 255 };
25174        private static final float[] TRANSPARENT = { 0.0f };
25175
25176        /**
25177         * When fading should start. This time moves into the future every time
25178         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
25179         */
25180        public long fadeStartTime;
25181
25182
25183        /**
25184         * The current state of the scrollbars: ON, OFF, or FADING
25185         */
25186        public int state = OFF;
25187
25188        private int mLastColor;
25189
25190        public final Rect mScrollBarBounds = new Rect();
25191        public final Rect mScrollBarTouchBounds = new Rect();
25192
25193        public static final int NOT_DRAGGING = 0;
25194        public static final int DRAGGING_VERTICAL_SCROLL_BAR = 1;
25195        public static final int DRAGGING_HORIZONTAL_SCROLL_BAR = 2;
25196        public int mScrollBarDraggingState = NOT_DRAGGING;
25197
25198        public float mScrollBarDraggingPos = 0;
25199
25200        public ScrollabilityCache(ViewConfiguration configuration, View host) {
25201            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
25202            scrollBarSize = configuration.getScaledScrollBarSize();
25203            scrollBarMinTouchTarget = configuration.getScaledMinScrollbarTouchTarget();
25204            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
25205            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
25206
25207            paint = new Paint();
25208            matrix = new Matrix();
25209            // use use a height of 1, and then wack the matrix each time we
25210            // actually use it.
25211            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
25212            paint.setShader(shader);
25213            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
25214
25215            this.host = host;
25216        }
25217
25218        public void setFadeColor(int color) {
25219            if (color != mLastColor) {
25220                mLastColor = color;
25221
25222                if (color != 0) {
25223                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
25224                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
25225                    paint.setShader(shader);
25226                    // Restore the default transfer mode (src_over)
25227                    paint.setXfermode(null);
25228                } else {
25229                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
25230                    paint.setShader(shader);
25231                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
25232                }
25233            }
25234        }
25235
25236        public void run() {
25237            long now = AnimationUtils.currentAnimationTimeMillis();
25238            if (now >= fadeStartTime) {
25239
25240                // the animation fades the scrollbars out by changing
25241                // the opacity (alpha) from fully opaque to fully
25242                // transparent
25243                int nextFrame = (int) now;
25244                int framesCount = 0;
25245
25246                Interpolator interpolator = scrollBarInterpolator;
25247
25248                // Start opaque
25249                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
25250
25251                // End transparent
25252                nextFrame += scrollBarFadeDuration;
25253                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
25254
25255                state = FADING;
25256
25257                // Kick off the fade animation
25258                host.invalidate(true);
25259            }
25260        }
25261    }
25262
25263    /**
25264     * Resuable callback for sending
25265     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
25266     */
25267    private class SendViewScrolledAccessibilityEvent implements Runnable {
25268        public volatile boolean mIsPending;
25269
25270        public void run() {
25271            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
25272            mIsPending = false;
25273        }
25274    }
25275
25276    /**
25277     * <p>
25278     * This class represents a delegate that can be registered in a {@link View}
25279     * to enhance accessibility support via composition rather via inheritance.
25280     * It is specifically targeted to widget developers that extend basic View
25281     * classes i.e. classes in package android.view, that would like their
25282     * applications to be backwards compatible.
25283     * </p>
25284     * <div class="special reference">
25285     * <h3>Developer Guides</h3>
25286     * <p>For more information about making applications accessible, read the
25287     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
25288     * developer guide.</p>
25289     * </div>
25290     * <p>
25291     * A scenario in which a developer would like to use an accessibility delegate
25292     * is overriding a method introduced in a later API version than the minimal API
25293     * version supported by the application. For example, the method
25294     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
25295     * in API version 4 when the accessibility APIs were first introduced. If a
25296     * developer would like his application to run on API version 4 devices (assuming
25297     * all other APIs used by the application are version 4 or lower) and take advantage
25298     * of this method, instead of overriding the method which would break the application's
25299     * backwards compatibility, he can override the corresponding method in this
25300     * delegate and register the delegate in the target View if the API version of
25301     * the system is high enough, i.e. the API version is the same as or higher than the API
25302     * version that introduced
25303     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
25304     * </p>
25305     * <p>
25306     * Here is an example implementation:
25307     * </p>
25308     * <code><pre><p>
25309     * if (Build.VERSION.SDK_INT >= 14) {
25310     *     // If the API version is equal of higher than the version in
25311     *     // which onInitializeAccessibilityNodeInfo was introduced we
25312     *     // register a delegate with a customized implementation.
25313     *     View view = findViewById(R.id.view_id);
25314     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
25315     *         public void onInitializeAccessibilityNodeInfo(View host,
25316     *                 AccessibilityNodeInfo info) {
25317     *             // Let the default implementation populate the info.
25318     *             super.onInitializeAccessibilityNodeInfo(host, info);
25319     *             // Set some other information.
25320     *             info.setEnabled(host.isEnabled());
25321     *         }
25322     *     });
25323     * }
25324     * </code></pre></p>
25325     * <p>
25326     * This delegate contains methods that correspond to the accessibility methods
25327     * in View. If a delegate has been specified the implementation in View hands
25328     * off handling to the corresponding method in this delegate. The default
25329     * implementation the delegate methods behaves exactly as the corresponding
25330     * method in View for the case of no accessibility delegate been set. Hence,
25331     * to customize the behavior of a View method, clients can override only the
25332     * corresponding delegate method without altering the behavior of the rest
25333     * accessibility related methods of the host view.
25334     * </p>
25335     * <p>
25336     * <strong>Note:</strong> On platform versions prior to
25337     * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on
25338     * views in the {@code android.widget.*} package are called <i>before</i>
25339     * host methods. This prevents certain properties such as class name from
25340     * being modified by overriding
25341     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)},
25342     * as any changes will be overwritten by the host class.
25343     * <p>
25344     * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate
25345     * methods are called <i>after</i> host methods, which all properties to be
25346     * modified without being overwritten by the host class.
25347     */
25348    public static class AccessibilityDelegate {
25349
25350        /**
25351         * Sends an accessibility event of the given type. If accessibility is not
25352         * enabled this method has no effect.
25353         * <p>
25354         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
25355         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
25356         * been set.
25357         * </p>
25358         *
25359         * @param host The View hosting the delegate.
25360         * @param eventType The type of the event to send.
25361         *
25362         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
25363         */
25364        public void sendAccessibilityEvent(View host, int eventType) {
25365            host.sendAccessibilityEventInternal(eventType);
25366        }
25367
25368        /**
25369         * Performs the specified accessibility action on the view. For
25370         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
25371         * <p>
25372         * The default implementation behaves as
25373         * {@link View#performAccessibilityAction(int, Bundle)
25374         *  View#performAccessibilityAction(int, Bundle)} for the case of
25375         *  no accessibility delegate been set.
25376         * </p>
25377         *
25378         * @param action The action to perform.
25379         * @return Whether the action was performed.
25380         *
25381         * @see View#performAccessibilityAction(int, Bundle)
25382         *      View#performAccessibilityAction(int, Bundle)
25383         */
25384        public boolean performAccessibilityAction(View host, int action, Bundle args) {
25385            return host.performAccessibilityActionInternal(action, args);
25386        }
25387
25388        /**
25389         * Sends an accessibility event. This method behaves exactly as
25390         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
25391         * empty {@link AccessibilityEvent} and does not perform a check whether
25392         * accessibility is enabled.
25393         * <p>
25394         * The default implementation behaves as
25395         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
25396         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
25397         * the case of no accessibility delegate been set.
25398         * </p>
25399         *
25400         * @param host The View hosting the delegate.
25401         * @param event The event to send.
25402         *
25403         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
25404         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
25405         */
25406        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
25407            host.sendAccessibilityEventUncheckedInternal(event);
25408        }
25409
25410        /**
25411         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
25412         * to its children for adding their text content to the event.
25413         * <p>
25414         * The default implementation behaves as
25415         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
25416         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
25417         * the case of no accessibility delegate been set.
25418         * </p>
25419         *
25420         * @param host The View hosting the delegate.
25421         * @param event The event.
25422         * @return True if the event population was completed.
25423         *
25424         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
25425         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
25426         */
25427        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
25428            return host.dispatchPopulateAccessibilityEventInternal(event);
25429        }
25430
25431        /**
25432         * Gives a chance to the host View to populate the accessibility event with its
25433         * text content.
25434         * <p>
25435         * The default implementation behaves as
25436         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
25437         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
25438         * the case of no accessibility delegate been set.
25439         * </p>
25440         *
25441         * @param host The View hosting the delegate.
25442         * @param event The accessibility event which to populate.
25443         *
25444         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
25445         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
25446         */
25447        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
25448            host.onPopulateAccessibilityEventInternal(event);
25449        }
25450
25451        /**
25452         * Initializes an {@link AccessibilityEvent} with information about the
25453         * the host View which is the event source.
25454         * <p>
25455         * The default implementation behaves as
25456         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
25457         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
25458         * the case of no accessibility delegate been set.
25459         * </p>
25460         *
25461         * @param host The View hosting the delegate.
25462         * @param event The event to initialize.
25463         *
25464         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
25465         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
25466         */
25467        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
25468            host.onInitializeAccessibilityEventInternal(event);
25469        }
25470
25471        /**
25472         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
25473         * <p>
25474         * The default implementation behaves as
25475         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
25476         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
25477         * the case of no accessibility delegate been set.
25478         * </p>
25479         *
25480         * @param host The View hosting the delegate.
25481         * @param info The instance to initialize.
25482         *
25483         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
25484         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
25485         */
25486        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
25487            host.onInitializeAccessibilityNodeInfoInternal(info);
25488        }
25489
25490        /**
25491         * Adds extra data to an {@link AccessibilityNodeInfo} based on an explicit request for the
25492         * additional data.
25493         * <p>
25494         * This method only needs to be implemented if the View offers to provide additional data.
25495         * </p>
25496         * <p>
25497         * The default implementation behaves as
25498         * {@link View#addExtraDataToAccessibilityNodeInfo(AccessibilityNodeInfo, int) for
25499         * the case where no accessibility delegate is set.
25500         * </p>
25501         *
25502         * @param host The View hosting the delegate. Never {@code null}.
25503         * @param info The info to which to add the extra data. Never {@code null}.
25504         * @param extraDataKey A key specifying the type of extra data to add to the info. The
25505         *                     extra data should be added to the {@link Bundle} returned by
25506         *                     the info's {@link AccessibilityNodeInfo#getExtras} method.  Never
25507         *                     {@code null}.
25508         * @param arguments A {@link Bundle} holding any arguments relevant for this request.
25509         *                  May be {@code null} if the if the service provided no arguments.
25510         *
25511         * @see AccessibilityNodeInfo#setExtraAvailableData
25512         */
25513        public void addExtraDataToAccessibilityNodeInfo(@NonNull View host,
25514                @NonNull AccessibilityNodeInfo info, @NonNull String extraDataKey,
25515                @Nullable Bundle arguments) {
25516            host.addExtraDataToAccessibilityNodeInfo(info, extraDataKey, arguments);
25517        }
25518
25519        /**
25520         * Called when a child of the host View has requested sending an
25521         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
25522         * to augment the event.
25523         * <p>
25524         * The default implementation behaves as
25525         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
25526         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
25527         * the case of no accessibility delegate been set.
25528         * </p>
25529         *
25530         * @param host The View hosting the delegate.
25531         * @param child The child which requests sending the event.
25532         * @param event The event to be sent.
25533         * @return True if the event should be sent
25534         *
25535         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
25536         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
25537         */
25538        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
25539                AccessibilityEvent event) {
25540            return host.onRequestSendAccessibilityEventInternal(child, event);
25541        }
25542
25543        /**
25544         * Gets the provider for managing a virtual view hierarchy rooted at this View
25545         * and reported to {@link android.accessibilityservice.AccessibilityService}s
25546         * that explore the window content.
25547         * <p>
25548         * The default implementation behaves as
25549         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
25550         * the case of no accessibility delegate been set.
25551         * </p>
25552         *
25553         * @return The provider.
25554         *
25555         * @see AccessibilityNodeProvider
25556         */
25557        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
25558            return null;
25559        }
25560
25561        /**
25562         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
25563         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
25564         * This method is responsible for obtaining an accessibility node info from a
25565         * pool of reusable instances and calling
25566         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
25567         * view to initialize the former.
25568         * <p>
25569         * <strong>Note:</strong> The client is responsible for recycling the obtained
25570         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
25571         * creation.
25572         * </p>
25573         * <p>
25574         * The default implementation behaves as
25575         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
25576         * the case of no accessibility delegate been set.
25577         * </p>
25578         * @return A populated {@link AccessibilityNodeInfo}.
25579         *
25580         * @see AccessibilityNodeInfo
25581         *
25582         * @hide
25583         */
25584        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
25585            return host.createAccessibilityNodeInfoInternal();
25586        }
25587    }
25588
25589    private static class MatchIdPredicate implements Predicate<View> {
25590        public int mId;
25591
25592        @Override
25593        public boolean test(View view) {
25594            return (view.mID == mId);
25595        }
25596    }
25597
25598    private static class MatchLabelForPredicate implements Predicate<View> {
25599        private int mLabeledId;
25600
25601        @Override
25602        public boolean test(View view) {
25603            return (view.mLabelForId == mLabeledId);
25604        }
25605    }
25606
25607    private class SendViewStateChangedAccessibilityEvent implements Runnable {
25608        private int mChangeTypes = 0;
25609        private boolean mPosted;
25610        private boolean mPostedWithDelay;
25611        private long mLastEventTimeMillis;
25612
25613        @Override
25614        public void run() {
25615            mPosted = false;
25616            mPostedWithDelay = false;
25617            mLastEventTimeMillis = SystemClock.uptimeMillis();
25618            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
25619                final AccessibilityEvent event = AccessibilityEvent.obtain();
25620                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
25621                event.setContentChangeTypes(mChangeTypes);
25622                sendAccessibilityEventUnchecked(event);
25623            }
25624            mChangeTypes = 0;
25625        }
25626
25627        public void runOrPost(int changeType) {
25628            mChangeTypes |= changeType;
25629
25630            // If this is a live region or the child of a live region, collect
25631            // all events from this frame and send them on the next frame.
25632            if (inLiveRegion()) {
25633                // If we're already posted with a delay, remove that.
25634                if (mPostedWithDelay) {
25635                    removeCallbacks(this);
25636                    mPostedWithDelay = false;
25637                }
25638                // Only post if we're not already posted.
25639                if (!mPosted) {
25640                    post(this);
25641                    mPosted = true;
25642                }
25643                return;
25644            }
25645
25646            if (mPosted) {
25647                return;
25648            }
25649
25650            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
25651            final long minEventIntevalMillis =
25652                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
25653            if (timeSinceLastMillis >= minEventIntevalMillis) {
25654                removeCallbacks(this);
25655                run();
25656            } else {
25657                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
25658                mPostedWithDelay = true;
25659            }
25660        }
25661    }
25662
25663    private boolean inLiveRegion() {
25664        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
25665            return true;
25666        }
25667
25668        ViewParent parent = getParent();
25669        while (parent instanceof View) {
25670            if (((View) parent).getAccessibilityLiveRegion()
25671                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
25672                return true;
25673            }
25674            parent = parent.getParent();
25675        }
25676
25677        return false;
25678    }
25679
25680    /**
25681     * Dump all private flags in readable format, useful for documentation and
25682     * sanity checking.
25683     */
25684    private static void dumpFlags() {
25685        final HashMap<String, String> found = Maps.newHashMap();
25686        try {
25687            for (Field field : View.class.getDeclaredFields()) {
25688                final int modifiers = field.getModifiers();
25689                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
25690                    if (field.getType().equals(int.class)) {
25691                        final int value = field.getInt(null);
25692                        dumpFlag(found, field.getName(), value);
25693                    } else if (field.getType().equals(int[].class)) {
25694                        final int[] values = (int[]) field.get(null);
25695                        for (int i = 0; i < values.length; i++) {
25696                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
25697                        }
25698                    }
25699                }
25700            }
25701        } catch (IllegalAccessException e) {
25702            throw new RuntimeException(e);
25703        }
25704
25705        final ArrayList<String> keys = Lists.newArrayList();
25706        keys.addAll(found.keySet());
25707        Collections.sort(keys);
25708        for (String key : keys) {
25709            Log.d(VIEW_LOG_TAG, found.get(key));
25710        }
25711    }
25712
25713    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
25714        // Sort flags by prefix, then by bits, always keeping unique keys
25715        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
25716        final int prefix = name.indexOf('_');
25717        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
25718        final String output = bits + " " + name;
25719        found.put(key, output);
25720    }
25721
25722    /** {@hide} */
25723    public void encode(@NonNull ViewHierarchyEncoder stream) {
25724        stream.beginObject(this);
25725        encodeProperties(stream);
25726        stream.endObject();
25727    }
25728
25729    /** {@hide} */
25730    @CallSuper
25731    protected void encodeProperties(@NonNull ViewHierarchyEncoder stream) {
25732        Object resolveId = ViewDebug.resolveId(getContext(), mID);
25733        if (resolveId instanceof String) {
25734            stream.addProperty("id", (String) resolveId);
25735        } else {
25736            stream.addProperty("id", mID);
25737        }
25738
25739        stream.addProperty("misc:transformation.alpha",
25740                mTransformationInfo != null ? mTransformationInfo.mAlpha : 0);
25741        stream.addProperty("misc:transitionName", getTransitionName());
25742
25743        // layout
25744        stream.addProperty("layout:left", mLeft);
25745        stream.addProperty("layout:right", mRight);
25746        stream.addProperty("layout:top", mTop);
25747        stream.addProperty("layout:bottom", mBottom);
25748        stream.addProperty("layout:width", getWidth());
25749        stream.addProperty("layout:height", getHeight());
25750        stream.addProperty("layout:layoutDirection", getLayoutDirection());
25751        stream.addProperty("layout:layoutRtl", isLayoutRtl());
25752        stream.addProperty("layout:hasTransientState", hasTransientState());
25753        stream.addProperty("layout:baseline", getBaseline());
25754
25755        // layout params
25756        ViewGroup.LayoutParams layoutParams = getLayoutParams();
25757        if (layoutParams != null) {
25758            stream.addPropertyKey("layoutParams");
25759            layoutParams.encode(stream);
25760        }
25761
25762        // scrolling
25763        stream.addProperty("scrolling:scrollX", mScrollX);
25764        stream.addProperty("scrolling:scrollY", mScrollY);
25765
25766        // padding
25767        stream.addProperty("padding:paddingLeft", mPaddingLeft);
25768        stream.addProperty("padding:paddingRight", mPaddingRight);
25769        stream.addProperty("padding:paddingTop", mPaddingTop);
25770        stream.addProperty("padding:paddingBottom", mPaddingBottom);
25771        stream.addProperty("padding:userPaddingRight", mUserPaddingRight);
25772        stream.addProperty("padding:userPaddingLeft", mUserPaddingLeft);
25773        stream.addProperty("padding:userPaddingBottom", mUserPaddingBottom);
25774        stream.addProperty("padding:userPaddingStart", mUserPaddingStart);
25775        stream.addProperty("padding:userPaddingEnd", mUserPaddingEnd);
25776
25777        // measurement
25778        stream.addProperty("measurement:minHeight", mMinHeight);
25779        stream.addProperty("measurement:minWidth", mMinWidth);
25780        stream.addProperty("measurement:measuredWidth", mMeasuredWidth);
25781        stream.addProperty("measurement:measuredHeight", mMeasuredHeight);
25782
25783        // drawing
25784        stream.addProperty("drawing:elevation", getElevation());
25785        stream.addProperty("drawing:translationX", getTranslationX());
25786        stream.addProperty("drawing:translationY", getTranslationY());
25787        stream.addProperty("drawing:translationZ", getTranslationZ());
25788        stream.addProperty("drawing:rotation", getRotation());
25789        stream.addProperty("drawing:rotationX", getRotationX());
25790        stream.addProperty("drawing:rotationY", getRotationY());
25791        stream.addProperty("drawing:scaleX", getScaleX());
25792        stream.addProperty("drawing:scaleY", getScaleY());
25793        stream.addProperty("drawing:pivotX", getPivotX());
25794        stream.addProperty("drawing:pivotY", getPivotY());
25795        stream.addProperty("drawing:opaque", isOpaque());
25796        stream.addProperty("drawing:alpha", getAlpha());
25797        stream.addProperty("drawing:transitionAlpha", getTransitionAlpha());
25798        stream.addProperty("drawing:shadow", hasShadow());
25799        stream.addProperty("drawing:solidColor", getSolidColor());
25800        stream.addProperty("drawing:layerType", mLayerType);
25801        stream.addProperty("drawing:willNotDraw", willNotDraw());
25802        stream.addProperty("drawing:hardwareAccelerated", isHardwareAccelerated());
25803        stream.addProperty("drawing:willNotCacheDrawing", willNotCacheDrawing());
25804        stream.addProperty("drawing:drawingCacheEnabled", isDrawingCacheEnabled());
25805        stream.addProperty("drawing:overlappingRendering", hasOverlappingRendering());
25806
25807        // focus
25808        stream.addProperty("focus:hasFocus", hasFocus());
25809        stream.addProperty("focus:isFocused", isFocused());
25810        stream.addProperty("focus:isFocusable", isFocusable());
25811        stream.addProperty("focus:isFocusableInTouchMode", isFocusableInTouchMode());
25812
25813        stream.addProperty("misc:clickable", isClickable());
25814        stream.addProperty("misc:pressed", isPressed());
25815        stream.addProperty("misc:selected", isSelected());
25816        stream.addProperty("misc:touchMode", isInTouchMode());
25817        stream.addProperty("misc:hovered", isHovered());
25818        stream.addProperty("misc:activated", isActivated());
25819
25820        stream.addProperty("misc:visibility", getVisibility());
25821        stream.addProperty("misc:fitsSystemWindows", getFitsSystemWindows());
25822        stream.addProperty("misc:filterTouchesWhenObscured", getFilterTouchesWhenObscured());
25823
25824        stream.addProperty("misc:enabled", isEnabled());
25825        stream.addProperty("misc:soundEffectsEnabled", isSoundEffectsEnabled());
25826        stream.addProperty("misc:hapticFeedbackEnabled", isHapticFeedbackEnabled());
25827
25828        // theme attributes
25829        Resources.Theme theme = getContext().getTheme();
25830        if (theme != null) {
25831            stream.addPropertyKey("theme");
25832            theme.encode(stream);
25833        }
25834
25835        // view attribute information
25836        int n = mAttributes != null ? mAttributes.length : 0;
25837        stream.addProperty("meta:__attrCount__", n/2);
25838        for (int i = 0; i < n; i += 2) {
25839            stream.addProperty("meta:__attr__" + mAttributes[i], mAttributes[i+1]);
25840        }
25841
25842        stream.addProperty("misc:scrollBarStyle", getScrollBarStyle());
25843
25844        // text
25845        stream.addProperty("text:textDirection", getTextDirection());
25846        stream.addProperty("text:textAlignment", getTextAlignment());
25847
25848        // accessibility
25849        CharSequence contentDescription = getContentDescription();
25850        stream.addProperty("accessibility:contentDescription",
25851                contentDescription == null ? "" : contentDescription.toString());
25852        stream.addProperty("accessibility:labelFor", getLabelFor());
25853        stream.addProperty("accessibility:importantForAccessibility", getImportantForAccessibility());
25854    }
25855
25856    /**
25857     * Determine if this view is rendered on a round wearable device and is the main view
25858     * on the screen.
25859     */
25860    boolean shouldDrawRoundScrollbar() {
25861        if (!mResources.getConfiguration().isScreenRound() || mAttachInfo == null) {
25862            return false;
25863        }
25864
25865        final View rootView = getRootView();
25866        final WindowInsets insets = getRootWindowInsets();
25867
25868        int height = getHeight();
25869        int width = getWidth();
25870        int displayHeight = rootView.getHeight();
25871        int displayWidth = rootView.getWidth();
25872
25873        if (height != displayHeight || width != displayWidth) {
25874            return false;
25875        }
25876
25877        getLocationInWindow(mAttachInfo.mTmpLocation);
25878        return mAttachInfo.mTmpLocation[0] == insets.getStableInsetLeft()
25879                && mAttachInfo.mTmpLocation[1] == insets.getStableInsetTop();
25880    }
25881
25882    /**
25883     * Sets the tooltip text which will be displayed in a small popup next to the view.
25884     * <p>
25885     * The tooltip will be displayed:
25886     * <ul>
25887     * <li>On long click, unless it is handled otherwise (by OnLongClickListener or a context
25888     * menu). </li>
25889     * <li>On hover, after a brief delay since the pointer has stopped moving </li>
25890     * </ul>
25891     * <p>
25892     * <strong>Note:</strong> Do not override this method, as it will have no
25893     * effect on the text displayed in the tooltip.
25894     *
25895     * @param tooltipText the tooltip text, or null if no tooltip is required
25896     * @see #getTooltipText()
25897     * @attr ref android.R.styleable#View_tooltipText
25898     */
25899    public void setTooltipText(@Nullable CharSequence tooltipText) {
25900        if (TextUtils.isEmpty(tooltipText)) {
25901            setFlags(0, TOOLTIP);
25902            hideTooltip();
25903            mTooltipInfo = null;
25904        } else {
25905            setFlags(TOOLTIP, TOOLTIP);
25906            if (mTooltipInfo == null) {
25907                mTooltipInfo = new TooltipInfo();
25908                mTooltipInfo.mShowTooltipRunnable = this::showHoverTooltip;
25909                mTooltipInfo.mHideTooltipRunnable = this::hideTooltip;
25910            }
25911            mTooltipInfo.mTooltipText = tooltipText;
25912            if (mTooltipInfo.mTooltipPopup != null && mTooltipInfo.mTooltipPopup.isShowing()) {
25913                mTooltipInfo.mTooltipPopup.updateContent(mTooltipInfo.mTooltipText);
25914            }
25915        }
25916    }
25917
25918    /**
25919     * @hide Binary compatibility stub. To be removed when we finalize O APIs.
25920     */
25921    public void setTooltip(@Nullable CharSequence tooltipText) {
25922        setTooltipText(tooltipText);
25923    }
25924
25925    /**
25926     * Returns the view's tooltip text.
25927     *
25928     * <strong>Note:</strong> Do not override this method, as it will have no
25929     * effect on the text displayed in the tooltip. You must call
25930     * {@link #setTooltipText(CharSequence)} to modify the tooltip text.
25931     *
25932     * @return the tooltip text
25933     * @see #setTooltipText(CharSequence)
25934     * @attr ref android.R.styleable#View_tooltipText
25935     */
25936    @Nullable
25937    public CharSequence getTooltipText() {
25938        return mTooltipInfo != null ? mTooltipInfo.mTooltipText : null;
25939    }
25940
25941    /**
25942     * @hide Binary compatibility stub. To be removed when we finalize O APIs.
25943     */
25944    @Nullable
25945    public CharSequence getTooltip() {
25946        return getTooltipText();
25947    }
25948
25949    private boolean showTooltip(int x, int y, boolean fromLongClick) {
25950        if (mAttachInfo == null || mTooltipInfo == null) {
25951            return false;
25952        }
25953        if ((mViewFlags & ENABLED_MASK) != ENABLED) {
25954            return false;
25955        }
25956        if (TextUtils.isEmpty(mTooltipInfo.mTooltipText)) {
25957            return false;
25958        }
25959        hideTooltip();
25960        mTooltipInfo.mTooltipFromLongClick = fromLongClick;
25961        mTooltipInfo.mTooltipPopup = new TooltipPopup(getContext());
25962        final boolean fromTouch = (mPrivateFlags3 & PFLAG3_FINGER_DOWN) == PFLAG3_FINGER_DOWN;
25963        mTooltipInfo.mTooltipPopup.show(this, x, y, fromTouch, mTooltipInfo.mTooltipText);
25964        mAttachInfo.mTooltipHost = this;
25965        return true;
25966    }
25967
25968    void hideTooltip() {
25969        if (mTooltipInfo == null) {
25970            return;
25971        }
25972        removeCallbacks(mTooltipInfo.mShowTooltipRunnable);
25973        if (mTooltipInfo.mTooltipPopup == null) {
25974            return;
25975        }
25976        mTooltipInfo.mTooltipPopup.hide();
25977        mTooltipInfo.mTooltipPopup = null;
25978        mTooltipInfo.mTooltipFromLongClick = false;
25979        if (mAttachInfo != null) {
25980            mAttachInfo.mTooltipHost = null;
25981        }
25982    }
25983
25984    private boolean showLongClickTooltip(int x, int y) {
25985        removeCallbacks(mTooltipInfo.mShowTooltipRunnable);
25986        removeCallbacks(mTooltipInfo.mHideTooltipRunnable);
25987        return showTooltip(x, y, true);
25988    }
25989
25990    private void showHoverTooltip() {
25991        showTooltip(mTooltipInfo.mAnchorX, mTooltipInfo.mAnchorY, false);
25992    }
25993
25994    boolean dispatchTooltipHoverEvent(MotionEvent event) {
25995        if (mTooltipInfo == null) {
25996            return false;
25997        }
25998        switch(event.getAction()) {
25999            case MotionEvent.ACTION_HOVER_MOVE:
26000                if ((mViewFlags & TOOLTIP) != TOOLTIP || (mViewFlags & ENABLED_MASK) != ENABLED) {
26001                    break;
26002                }
26003                if (!mTooltipInfo.mTooltipFromLongClick) {
26004                    if (mTooltipInfo.mTooltipPopup == null) {
26005                        // Schedule showing the tooltip after a timeout.
26006                        mTooltipInfo.mAnchorX = (int) event.getX();
26007                        mTooltipInfo.mAnchorY = (int) event.getY();
26008                        removeCallbacks(mTooltipInfo.mShowTooltipRunnable);
26009                        postDelayed(mTooltipInfo.mShowTooltipRunnable,
26010                                ViewConfiguration.getHoverTooltipShowTimeout());
26011                    }
26012
26013                    // Hide hover-triggered tooltip after a period of inactivity.
26014                    // Match the timeout used by NativeInputManager to hide the mouse pointer
26015                    // (depends on SYSTEM_UI_FLAG_LOW_PROFILE being set).
26016                    final int timeout;
26017                    if ((getWindowSystemUiVisibility() & SYSTEM_UI_FLAG_LOW_PROFILE)
26018                            == SYSTEM_UI_FLAG_LOW_PROFILE) {
26019                        timeout = ViewConfiguration.getHoverTooltipHideShortTimeout();
26020                    } else {
26021                        timeout = ViewConfiguration.getHoverTooltipHideTimeout();
26022                    }
26023                    removeCallbacks(mTooltipInfo.mHideTooltipRunnable);
26024                    postDelayed(mTooltipInfo.mHideTooltipRunnable, timeout);
26025                }
26026                return true;
26027
26028            case MotionEvent.ACTION_HOVER_EXIT:
26029                if (!mTooltipInfo.mTooltipFromLongClick) {
26030                    hideTooltip();
26031                }
26032                break;
26033        }
26034        return false;
26035    }
26036
26037    void handleTooltipKey(KeyEvent event) {
26038        switch (event.getAction()) {
26039            case KeyEvent.ACTION_DOWN:
26040                if (event.getRepeatCount() == 0) {
26041                    hideTooltip();
26042                }
26043                break;
26044
26045            case KeyEvent.ACTION_UP:
26046                handleTooltipUp();
26047                break;
26048        }
26049    }
26050
26051    private void handleTooltipUp() {
26052        if (mTooltipInfo == null || mTooltipInfo.mTooltipPopup == null) {
26053            return;
26054        }
26055        removeCallbacks(mTooltipInfo.mHideTooltipRunnable);
26056        postDelayed(mTooltipInfo.mHideTooltipRunnable,
26057                ViewConfiguration.getLongPressTooltipHideTimeout());
26058    }
26059
26060    private int getFocusableAttribute(TypedArray attributes) {
26061        TypedValue val = new TypedValue();
26062        if (attributes.getValue(com.android.internal.R.styleable.View_focusable, val)) {
26063            if (val.type == TypedValue.TYPE_INT_BOOLEAN) {
26064                return (val.data == 0 ? NOT_FOCUSABLE : FOCUSABLE);
26065            } else {
26066                return val.data;
26067            }
26068        } else {
26069            return FOCUSABLE_AUTO;
26070        }
26071    }
26072
26073    /**
26074     * @return The content view of the tooltip popup currently being shown, or null if the tooltip
26075     * is not showing.
26076     * @hide
26077     */
26078    @TestApi
26079    public View getTooltipView() {
26080        if (mTooltipInfo == null || mTooltipInfo.mTooltipPopup == null) {
26081            return null;
26082        }
26083        return mTooltipInfo.mTooltipPopup.getContentView();
26084    }
26085}
26086