View.java revision b42d133c8b7f4af04d3a4349c952d437769f14e1
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     * Signals that compatibility booleans have been initialized according to
801     * target SDK versions.
802     */
803    private static boolean sCompatibilityDone = false;
804
805    /**
806     * Use the old (broken) way of building MeasureSpecs.
807     */
808    private static boolean sUseBrokenMakeMeasureSpec = false;
809
810    /**
811     * Always return a size of 0 for MeasureSpec values with a mode of UNSPECIFIED
812     */
813    static boolean sUseZeroUnspecifiedMeasureSpec = false;
814
815    /**
816     * Ignore any optimizations using the measure cache.
817     */
818    private static boolean sIgnoreMeasureCache = false;
819
820    /**
821     * Ignore an optimization that skips unnecessary EXACTLY layout passes.
822     */
823    private static boolean sAlwaysRemeasureExactly = false;
824
825    /**
826     * Relax constraints around whether setLayoutParams() must be called after
827     * modifying the layout params.
828     */
829    private static boolean sLayoutParamsAlwaysChanged = false;
830
831    /**
832     * Allow setForeground/setBackground to be called (and ignored) on a textureview,
833     * without throwing
834     */
835    static boolean sTextureViewIgnoresDrawableSetters = false;
836
837    /**
838     * Prior to N, some ViewGroups would not convert LayoutParams properly even though both extend
839     * MarginLayoutParams. For instance, converting LinearLayout.LayoutParams to
840     * RelativeLayout.LayoutParams would lose margin information. This is fixed on N but target API
841     * check is implemented for backwards compatibility.
842     *
843     * {@hide}
844     */
845    protected static boolean sPreserveMarginParamsInLayoutParamConversion;
846
847    /**
848     * Prior to N, when drag enters into child of a view that has already received an
849     * ACTION_DRAG_ENTERED event, the parent doesn't get a ACTION_DRAG_EXITED event.
850     * ACTION_DRAG_LOCATION and ACTION_DROP were delivered to the parent of a view that returned
851     * false from its event handler for these events.
852     * Starting from N, the parent will get ACTION_DRAG_EXITED event before the child gets its
853     * ACTION_DRAG_ENTERED. ACTION_DRAG_LOCATION and ACTION_DROP are never propagated to the parent.
854     * sCascadedDragDrop is true for pre-N apps for backwards compatibility implementation.
855     */
856    static boolean sCascadedDragDrop;
857
858    /**
859     * Prior to O, auto-focusable didn't exist and widgets such as ListView use hasFocusable
860     * to determine things like whether or not to permit item click events. We can't break
861     * apps that do this just because more things (clickable things) are now auto-focusable
862     * and they would get different results, so give old behavior to old apps.
863     */
864    static boolean sHasFocusableExcludeAutoFocusable;
865
866    /**
867     * Prior to O, auto-focusable didn't exist and views marked as clickable weren't implicitly
868     * made focusable by default. As a result, apps could (incorrectly) change the clickable
869     * setting of views off the UI thread. Now that clickable can effect the focusable state,
870     * changing the clickable attribute off the UI thread will cause an exception (since changing
871     * the focusable state checks). In order to prevent apps from crashing, we will handle this
872     * specific case and just not notify parents on new focusables resulting from marking views
873     * clickable from outside the UI thread.
874     */
875    private static boolean sAutoFocusableOffUIThreadWontNotifyParents;
876
877    /** @hide */
878    @IntDef({NOT_FOCUSABLE, FOCUSABLE, FOCUSABLE_AUTO})
879    @Retention(RetentionPolicy.SOURCE)
880    public @interface Focusable {}
881
882    /**
883     * This view does not want keystrokes.
884     * <p>
885     * Use with {@link #setFocusable(int)} and <a href="#attr_android:focusable">{@code
886     * android:focusable}.
887     */
888    public static final int NOT_FOCUSABLE = 0x00000000;
889
890    /**
891     * This view wants keystrokes.
892     * <p>
893     * Use with {@link #setFocusable(int)} and <a href="#attr_android:focusable">{@code
894     * android:focusable}.
895     */
896    public static final int FOCUSABLE = 0x00000001;
897
898    /**
899     * This view determines focusability automatically. This is the default.
900     * <p>
901     * Use with {@link #setFocusable(int)} and <a href="#attr_android:focusable">{@code
902     * android:focusable}.
903     */
904    public static final int FOCUSABLE_AUTO = 0x00000010;
905
906    /**
907     * Mask for use with setFlags indicating bits used for focus.
908     */
909    private static final int FOCUSABLE_MASK = 0x00000011;
910
911    /**
912     * This view will adjust its padding to fit sytem windows (e.g. status bar)
913     */
914    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
915
916    /** @hide */
917    @IntDef({VISIBLE, INVISIBLE, GONE})
918    @Retention(RetentionPolicy.SOURCE)
919    public @interface Visibility {}
920
921    /**
922     * This view is visible.
923     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
924     * android:visibility}.
925     */
926    public static final int VISIBLE = 0x00000000;
927
928    /**
929     * This view is invisible, but it still takes up space for layout purposes.
930     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
931     * android:visibility}.
932     */
933    public static final int INVISIBLE = 0x00000004;
934
935    /**
936     * This view is invisible, and it doesn't take any space for layout
937     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
938     * android:visibility}.
939     */
940    public static final int GONE = 0x00000008;
941
942    /**
943     * Mask for use with setFlags indicating bits used for visibility.
944     * {@hide}
945     */
946    static final int VISIBILITY_MASK = 0x0000000C;
947
948    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
949
950    /** @hide */
951    @IntDef({
952            AUTOFILL_MODE_INHERIT,
953            AUTOFILL_MODE_AUTO,
954            AUTOFILL_MODE_MANUAL
955    })
956    @Retention(RetentionPolicy.SOURCE)
957    public @interface AutofillMode {}
958
959    /**
960     * This view inherits the autofill state from it's parent. If there is no parent it is
961     * {@link #AUTOFILL_MODE_AUTO}.
962     * Use with {@link #setAutofillMode(int)} and <a href="#attr_android:autofillMode">
963     * {@code android:autofillMode}.
964     */
965    public static final int AUTOFILL_MODE_INHERIT = 0;
966
967    /**
968     * Allows this view to automatically trigger an autofill request when it get focus.
969     * Use with {@link #setAutofillMode(int)} and <a href="#attr_android:autofillMode">
970     * {@code android:autofillMode}.
971     */
972    public static final int AUTOFILL_MODE_AUTO = 1;
973
974    /**
975     * Do not trigger an autofill request if this view is focused. The user can still force
976     * an autofill request.
977     * <p>This does not prevent this field from being autofilled if an autofill operation is
978     * triggered from a different view.</p>
979     *
980     * Use with {@link #setAutofillMode(int)} and <a href="#attr_android:autofillMode">{@code
981     * android:autofillMode}.
982     */
983    public static final int AUTOFILL_MODE_MANUAL = 2;
984
985    /**
986     * This view contains an email address.
987     *
988     * Use with {@link #setAutofillHints(String[])}, or set "{@value #AUTOFILL_HINT_EMAIL_ADDRESS}"
989     * to <a href="#attr_android:autofillHint"> {@code android:autofillHint}.
990     */
991    public static final String AUTOFILL_HINT_EMAIL_ADDRESS = "emailAddress";
992
993    /**
994     * The view contains a real name.
995     *
996     * Use with {@link #setAutofillHints(String[])}, or set "{@value #AUTOFILL_HINT_NAME}" to
997     * <a href="#attr_android:autofillHint"> {@code android:autofillHint}.
998     */
999    public static final String AUTOFILL_HINT_NAME = "name";
1000
1001    /**
1002     * The view contains a user name.
1003     *
1004     * Use with {@link #setAutofillHints(String[])}, or set "{@value #AUTOFILL_HINT_USERNAME}" to
1005     * <a href="#attr_android:autofillHint"> {@code android:autofillHint}.
1006     */
1007    public static final String AUTOFILL_HINT_USERNAME = "username";
1008
1009    /**
1010     * The view contains a password.
1011     *
1012     * Use with {@link #setAutofillHints(String[])}, or set "{@value #AUTOFILL_HINT_PASSWORD}" to
1013     * <a href="#attr_android:autofillHint"> {@code android:autofillHint}.
1014     */
1015    public static final String AUTOFILL_HINT_PASSWORD = "password";
1016
1017    /**
1018     * The view contains a phone number.
1019     *
1020     * Use with {@link #setAutofillHints(String[])}, or set "{@value #AUTOFILL_HINT_PHONE}" to
1021     * <a href="#attr_android:autofillHint"> {@code android:autofillHint}.
1022     */
1023    public static final String AUTOFILL_HINT_PHONE = "phone";
1024
1025    /**
1026     * The view contains a postal address.
1027     *
1028     * Use with {@link #setAutofillHints(String[])}, or set "{@value #AUTOFILL_HINT_POSTAL_ADDRESS}"
1029     * to <a href="#attr_android:autofillHint"> {@code android:autofillHint}.
1030     */
1031    public static final String AUTOFILL_HINT_POSTAL_ADDRESS = "postalAddress";
1032
1033    /**
1034     * The view contains a postal code.
1035     *
1036     * Use with {@link #setAutofillHints(String[])}, or set "{@value #AUTOFILL_HINT_POSTAL_CODE}" to
1037     * <a href="#attr_android:autofillHint"> {@code android:autofillHint}.
1038     */
1039    public static final String AUTOFILL_HINT_POSTAL_CODE = "postalCode";
1040
1041    /**
1042     * The view contains a credit card number.
1043     *
1044     * Use with {@link #setAutofillHints(String[])}, or set "{@value
1045     * #AUTOFILL_HINT_CREDIT_CARD_NUMBER}" to <a href="#attr_android:autofillHint"> {@code
1046     * android:autofillHint}.
1047     */
1048    public static final String AUTOFILL_HINT_CREDIT_CARD_NUMBER = "creditCardNumber";
1049
1050    /**
1051     * The view contains a credit card security code.
1052     *
1053     * Use with {@link #setAutofillHints(String[])}, or set "{@value
1054     * #AUTOFILL_HINT_CREDIT_CARD_SECURITY_CODE}" to <a href="#attr_android:autofillHint"> {@code
1055     * android:autofillHint}.
1056     */
1057    public static final String AUTOFILL_HINT_CREDIT_CARD_SECURITY_CODE = "creditCardSecurityCode";
1058
1059    /**
1060     * The view contains a credit card expiration date.
1061     *
1062     * Use with {@link #setAutofillHints(String[])}, or set "{@value
1063     * #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DATE}" to <a href="#attr_android:autofillHint"> {@code
1064     * android:autofillHint}.
1065     */
1066    public static final String AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DATE =
1067            "creditCardExpirationDate";
1068
1069    /**
1070     * The view contains the month a credit card expires.
1071     *
1072     * Use with {@link #setAutofillHints(String[])}, or set "{@value
1073     * #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_MONTH}" to <a href="#attr_android:autofillHint"> {@code
1074     * android:autofillHint}.
1075     */
1076    public static final String AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_MONTH =
1077            "creditCardExpirationMonth";
1078
1079    /**
1080     * The view contains the year a credit card expires.
1081     *
1082     * Use with {@link #setAutofillHints(String[])}, or set "{@value
1083     * #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_YEAR}" to <a href="#attr_android:autofillHint"> {@code
1084     * android:autofillHint}.
1085     */
1086    public static final String AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_YEAR =
1087            "creditCardExpirationYear";
1088
1089    /**
1090     * The view contains the day a credit card expires.
1091     *
1092     * Use with {@link #setAutofillHints(String[])}, or set "{@value
1093     * #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DAY}" to <a href="#attr_android:autofillHint"> {@code
1094     * android:autofillHint}.
1095     */
1096    public static final String AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DAY = "creditCardExpirationDay";
1097
1098    /**
1099     * Hintd for the autofill services that describes the content of the view.
1100     */
1101    private @Nullable String[] mAutofillHints;
1102
1103    /** @hide */
1104    @IntDef({
1105            AUTOFILL_TYPE_NONE,
1106            AUTOFILL_TYPE_TEXT,
1107            AUTOFILL_TYPE_TOGGLE,
1108            AUTOFILL_TYPE_LIST,
1109            AUTOFILL_TYPE_DATE
1110    })
1111    @Retention(RetentionPolicy.SOURCE)
1112    public @interface AutofillType {}
1113
1114    /**
1115     * Autofill type for views that cannot be autofilled.
1116     */
1117    public static final int AUTOFILL_TYPE_NONE = 0;
1118
1119    /**
1120     * Autofill type for a text field, which is filled by a {@link CharSequence}.
1121     *
1122     * <p>{@link AutofillValue} instances for autofilling a {@link View} can be obtained through
1123     * {@link AutofillValue#forText(CharSequence)}, and the value passed to autofill a
1124     * {@link View} can be fetched through {@link AutofillValue#getTextValue()}.
1125     */
1126    public static final int AUTOFILL_TYPE_TEXT = 1;
1127
1128    /**
1129     * Autofill type for a togglable field, which is filled by a {@code boolean}.
1130     *
1131     * <p>{@link AutofillValue} instances for autofilling a {@link View} can be obtained through
1132     * {@link AutofillValue#forToggle(boolean)}, and the value passed to autofill a
1133     * {@link View} can be fetched through {@link AutofillValue#getToggleValue()}.
1134     */
1135    public static final int AUTOFILL_TYPE_TOGGLE = 2;
1136
1137    /**
1138     * Autofill type for a selection list field, which is filled by an {@code int}
1139     * representing the element index inside the list (starting at {@code 0}).
1140     *
1141     * <p>{@link AutofillValue} instances for autofilling a {@link View} can be obtained through
1142     * {@link AutofillValue#forList(int)}, and the value passed to autofill a
1143     * {@link View} can be fetched through {@link AutofillValue#getListValue()}.
1144     *
1145     * <p>The available options in the selection list are typically provided by
1146     * {@link android.app.assist.AssistStructure.ViewNode#getAutofillOptions()}.
1147     */
1148    public static final int AUTOFILL_TYPE_LIST = 3;
1149
1150
1151    /**
1152     * Autofill type for a field that contains a date, which is represented by a long representing
1153     * the number of milliseconds since the standard base time known as "the epoch", namely
1154     * January 1, 1970, 00:00:00 GMT (see {@link java.util.Date#getTime()}.
1155     *
1156     * <p>{@link AutofillValue} instances for autofilling a {@link View} can be obtained through
1157     * {@link AutofillValue#forDate(long)}, and the values passed to
1158     * autofill a {@link View} can be fetched through {@link AutofillValue#getDateValue()}.
1159     */
1160    public static final int AUTOFILL_TYPE_DATE = 4;
1161
1162    /** @hide */
1163    @IntDef({
1164            IMPORTANT_FOR_AUTOFILL_AUTO,
1165            IMPORTANT_FOR_AUTOFILL_YES,
1166            IMPORTANT_FOR_AUTOFILL_NO
1167    })
1168    @Retention(RetentionPolicy.SOURCE)
1169    public @interface AutofillImportance {}
1170
1171    /**
1172     * Automatically determine whether a view is important for auto-fill.
1173     */
1174    public static final int IMPORTANT_FOR_AUTOFILL_AUTO = 0x0;
1175
1176    /**
1177     * The view is important for important for auto-fill.
1178     */
1179    public static final int IMPORTANT_FOR_AUTOFILL_YES = 0x1;
1180
1181    /**
1182     * The view is not important for auto-fill.
1183     */
1184    public static final int IMPORTANT_FOR_AUTOFILL_NO = 0x2;
1185
1186    /**
1187     * This view is enabled. Interpretation varies by subclass.
1188     * Use with ENABLED_MASK when calling setFlags.
1189     * {@hide}
1190     */
1191    static final int ENABLED = 0x00000000;
1192
1193    /**
1194     * This view is disabled. Interpretation varies by subclass.
1195     * Use with ENABLED_MASK when calling setFlags.
1196     * {@hide}
1197     */
1198    static final int DISABLED = 0x00000020;
1199
1200   /**
1201    * Mask for use with setFlags indicating bits used for indicating whether
1202    * this view is enabled
1203    * {@hide}
1204    */
1205    static final int ENABLED_MASK = 0x00000020;
1206
1207    /**
1208     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
1209     * called and further optimizations will be performed. It is okay to have
1210     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
1211     * {@hide}
1212     */
1213    static final int WILL_NOT_DRAW = 0x00000080;
1214
1215    /**
1216     * Mask for use with setFlags indicating bits used for indicating whether
1217     * this view is will draw
1218     * {@hide}
1219     */
1220    static final int DRAW_MASK = 0x00000080;
1221
1222    /**
1223     * <p>This view doesn't show scrollbars.</p>
1224     * {@hide}
1225     */
1226    static final int SCROLLBARS_NONE = 0x00000000;
1227
1228    /**
1229     * <p>This view shows horizontal scrollbars.</p>
1230     * {@hide}
1231     */
1232    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
1233
1234    /**
1235     * <p>This view shows vertical scrollbars.</p>
1236     * {@hide}
1237     */
1238    static final int SCROLLBARS_VERTICAL = 0x00000200;
1239
1240    /**
1241     * <p>Mask for use with setFlags indicating bits used for indicating which
1242     * scrollbars are enabled.</p>
1243     * {@hide}
1244     */
1245    static final int SCROLLBARS_MASK = 0x00000300;
1246
1247    /**
1248     * Indicates that the view should filter touches when its window is obscured.
1249     * Refer to the class comments for more information about this security feature.
1250     * {@hide}
1251     */
1252    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
1253
1254    /**
1255     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
1256     * that they are optional and should be skipped if the window has
1257     * requested system UI flags that ignore those insets for layout.
1258     */
1259    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
1260
1261    /**
1262     * <p>This view doesn't show fading edges.</p>
1263     * {@hide}
1264     */
1265    static final int FADING_EDGE_NONE = 0x00000000;
1266
1267    /**
1268     * <p>This view shows horizontal fading edges.</p>
1269     * {@hide}
1270     */
1271    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
1272
1273    /**
1274     * <p>This view shows vertical fading edges.</p>
1275     * {@hide}
1276     */
1277    static final int FADING_EDGE_VERTICAL = 0x00002000;
1278
1279    /**
1280     * <p>Mask for use with setFlags indicating bits used for indicating which
1281     * fading edges are enabled.</p>
1282     * {@hide}
1283     */
1284    static final int FADING_EDGE_MASK = 0x00003000;
1285
1286    /**
1287     * <p>Indicates this view can be clicked. When clickable, a View reacts
1288     * to clicks by notifying the OnClickListener.<p>
1289     * {@hide}
1290     */
1291    static final int CLICKABLE = 0x00004000;
1292
1293    /**
1294     * <p>Indicates this view is caching its drawing into a bitmap.</p>
1295     * {@hide}
1296     */
1297    static final int DRAWING_CACHE_ENABLED = 0x00008000;
1298
1299    /**
1300     * <p>Indicates that no icicle should be saved for this view.<p>
1301     * {@hide}
1302     */
1303    static final int SAVE_DISABLED = 0x000010000;
1304
1305    /**
1306     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
1307     * property.</p>
1308     * {@hide}
1309     */
1310    static final int SAVE_DISABLED_MASK = 0x000010000;
1311
1312    /**
1313     * <p>Indicates that no drawing cache should ever be created for this view.<p>
1314     * {@hide}
1315     */
1316    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
1317
1318    /**
1319     * <p>Indicates this view can take / keep focus when int touch mode.</p>
1320     * {@hide}
1321     */
1322    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
1323
1324    /** @hide */
1325    @Retention(RetentionPolicy.SOURCE)
1326    @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO})
1327    public @interface DrawingCacheQuality {}
1328
1329    /**
1330     * <p>Enables low quality mode for the drawing cache.</p>
1331     */
1332    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
1333
1334    /**
1335     * <p>Enables high quality mode for the drawing cache.</p>
1336     */
1337    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
1338
1339    /**
1340     * <p>Enables automatic quality mode for the drawing cache.</p>
1341     */
1342    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
1343
1344    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
1345            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
1346    };
1347
1348    /**
1349     * <p>Mask for use with setFlags indicating bits used for the cache
1350     * quality property.</p>
1351     * {@hide}
1352     */
1353    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
1354
1355    /**
1356     * <p>
1357     * Indicates this view can be long clicked. When long clickable, a View
1358     * reacts to long clicks by notifying the OnLongClickListener or showing a
1359     * context menu.
1360     * </p>
1361     * {@hide}
1362     */
1363    static final int LONG_CLICKABLE = 0x00200000;
1364
1365    /**
1366     * <p>Indicates that this view gets its drawable states from its direct parent
1367     * and ignores its original internal states.</p>
1368     *
1369     * @hide
1370     */
1371    static final int DUPLICATE_PARENT_STATE = 0x00400000;
1372
1373    /**
1374     * <p>
1375     * Indicates this view can be context clicked. When context clickable, a View reacts to a
1376     * context click (e.g. a primary stylus button press or right mouse click) by notifying the
1377     * OnContextClickListener.
1378     * </p>
1379     * {@hide}
1380     */
1381    static final int CONTEXT_CLICKABLE = 0x00800000;
1382
1383
1384    /** @hide */
1385    @IntDef({
1386        SCROLLBARS_INSIDE_OVERLAY,
1387        SCROLLBARS_INSIDE_INSET,
1388        SCROLLBARS_OUTSIDE_OVERLAY,
1389        SCROLLBARS_OUTSIDE_INSET
1390    })
1391    @Retention(RetentionPolicy.SOURCE)
1392    public @interface ScrollBarStyle {}
1393
1394    /**
1395     * The scrollbar style to display the scrollbars inside the content area,
1396     * without increasing the padding. The scrollbars will be overlaid with
1397     * translucency on the view's content.
1398     */
1399    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
1400
1401    /**
1402     * The scrollbar style to display the scrollbars inside the padded area,
1403     * increasing the padding of the view. The scrollbars will not overlap the
1404     * content area of the view.
1405     */
1406    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
1407
1408    /**
1409     * The scrollbar style to display the scrollbars at the edge of the view,
1410     * without increasing the padding. The scrollbars will be overlaid with
1411     * translucency.
1412     */
1413    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
1414
1415    /**
1416     * The scrollbar style to display the scrollbars at the edge of the view,
1417     * increasing the padding of the view. The scrollbars will only overlap the
1418     * background, if any.
1419     */
1420    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
1421
1422    /**
1423     * Mask to check if the scrollbar style is overlay or inset.
1424     * {@hide}
1425     */
1426    static final int SCROLLBARS_INSET_MASK = 0x01000000;
1427
1428    /**
1429     * Mask to check if the scrollbar style is inside or outside.
1430     * {@hide}
1431     */
1432    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
1433
1434    /**
1435     * Mask for scrollbar style.
1436     * {@hide}
1437     */
1438    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
1439
1440    /**
1441     * View flag indicating that the screen should remain on while the
1442     * window containing this view is visible to the user.  This effectively
1443     * takes care of automatically setting the WindowManager's
1444     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
1445     */
1446    public static final int KEEP_SCREEN_ON = 0x04000000;
1447
1448    /**
1449     * View flag indicating whether this view should have sound effects enabled
1450     * for events such as clicking and touching.
1451     */
1452    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
1453
1454    /**
1455     * View flag indicating whether this view should have haptic feedback
1456     * enabled for events such as long presses.
1457     */
1458    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
1459
1460    /**
1461     * <p>Indicates that the view hierarchy should stop saving state when
1462     * it reaches this view.  If state saving is initiated immediately at
1463     * the view, it will be allowed.
1464     * {@hide}
1465     */
1466    static final int PARENT_SAVE_DISABLED = 0x20000000;
1467
1468    /**
1469     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1470     * {@hide}
1471     */
1472    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1473
1474    private static Paint sDebugPaint;
1475
1476    /**
1477     * <p>Indicates this view can display a tooltip on hover or long press.</p>
1478     * {@hide}
1479     */
1480    static final int TOOLTIP = 0x40000000;
1481
1482    /** @hide */
1483    @IntDef(flag = true,
1484            value = {
1485                FOCUSABLES_ALL,
1486                FOCUSABLES_TOUCH_MODE
1487            })
1488    @Retention(RetentionPolicy.SOURCE)
1489    public @interface FocusableMode {}
1490
1491    /**
1492     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1493     * should add all focusable Views regardless if they are focusable in touch mode.
1494     */
1495    public static final int FOCUSABLES_ALL = 0x00000000;
1496
1497    /**
1498     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1499     * should add only Views focusable in touch mode.
1500     */
1501    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1502
1503    /** @hide */
1504    @IntDef({
1505            FOCUS_BACKWARD,
1506            FOCUS_FORWARD,
1507            FOCUS_LEFT,
1508            FOCUS_UP,
1509            FOCUS_RIGHT,
1510            FOCUS_DOWN
1511    })
1512    @Retention(RetentionPolicy.SOURCE)
1513    public @interface FocusDirection {}
1514
1515    /** @hide */
1516    @IntDef({
1517            FOCUS_LEFT,
1518            FOCUS_UP,
1519            FOCUS_RIGHT,
1520            FOCUS_DOWN
1521    })
1522    @Retention(RetentionPolicy.SOURCE)
1523    public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward
1524
1525    /**
1526     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1527     * item.
1528     */
1529    public static final int FOCUS_BACKWARD = 0x00000001;
1530
1531    /**
1532     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1533     * item.
1534     */
1535    public static final int FOCUS_FORWARD = 0x00000002;
1536
1537    /**
1538     * Use with {@link #focusSearch(int)}. Move focus to the left.
1539     */
1540    public static final int FOCUS_LEFT = 0x00000011;
1541
1542    /**
1543     * Use with {@link #focusSearch(int)}. Move focus up.
1544     */
1545    public static final int FOCUS_UP = 0x00000021;
1546
1547    /**
1548     * Use with {@link #focusSearch(int)}. Move focus to the right.
1549     */
1550    public static final int FOCUS_RIGHT = 0x00000042;
1551
1552    /**
1553     * Use with {@link #focusSearch(int)}. Move focus down.
1554     */
1555    public static final int FOCUS_DOWN = 0x00000082;
1556
1557    /**
1558     * Bits of {@link #getMeasuredWidthAndState()} and
1559     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1560     */
1561    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1562
1563    /**
1564     * Bits of {@link #getMeasuredWidthAndState()} and
1565     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1566     */
1567    public static final int MEASURED_STATE_MASK = 0xff000000;
1568
1569    /**
1570     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1571     * for functions that combine both width and height into a single int,
1572     * such as {@link #getMeasuredState()} and the childState argument of
1573     * {@link #resolveSizeAndState(int, int, int)}.
1574     */
1575    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1576
1577    /**
1578     * Bit of {@link #getMeasuredWidthAndState()} and
1579     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1580     * is smaller that the space the view would like to have.
1581     */
1582    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1583
1584    /**
1585     * Base View state sets
1586     */
1587    // Singles
1588    /**
1589     * Indicates the view has no states set. States are used with
1590     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1591     * view depending on its state.
1592     *
1593     * @see android.graphics.drawable.Drawable
1594     * @see #getDrawableState()
1595     */
1596    protected static final int[] EMPTY_STATE_SET;
1597    /**
1598     * Indicates the view is enabled. States are used with
1599     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1600     * view depending on its state.
1601     *
1602     * @see android.graphics.drawable.Drawable
1603     * @see #getDrawableState()
1604     */
1605    protected static final int[] ENABLED_STATE_SET;
1606    /**
1607     * Indicates the view is focused. States are used with
1608     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1609     * view depending on its state.
1610     *
1611     * @see android.graphics.drawable.Drawable
1612     * @see #getDrawableState()
1613     */
1614    protected static final int[] FOCUSED_STATE_SET;
1615    /**
1616     * Indicates the view is selected. States are used with
1617     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1618     * view depending on its state.
1619     *
1620     * @see android.graphics.drawable.Drawable
1621     * @see #getDrawableState()
1622     */
1623    protected static final int[] SELECTED_STATE_SET;
1624    /**
1625     * Indicates the view is pressed. States are used with
1626     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1627     * view depending on its state.
1628     *
1629     * @see android.graphics.drawable.Drawable
1630     * @see #getDrawableState()
1631     */
1632    protected static final int[] PRESSED_STATE_SET;
1633    /**
1634     * Indicates the view's window has focus. States are used with
1635     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1636     * view depending on its state.
1637     *
1638     * @see android.graphics.drawable.Drawable
1639     * @see #getDrawableState()
1640     */
1641    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1642    // Doubles
1643    /**
1644     * Indicates the view is enabled and has the focus.
1645     *
1646     * @see #ENABLED_STATE_SET
1647     * @see #FOCUSED_STATE_SET
1648     */
1649    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1650    /**
1651     * Indicates the view is enabled and selected.
1652     *
1653     * @see #ENABLED_STATE_SET
1654     * @see #SELECTED_STATE_SET
1655     */
1656    protected static final int[] ENABLED_SELECTED_STATE_SET;
1657    /**
1658     * Indicates the view is enabled and that its window has focus.
1659     *
1660     * @see #ENABLED_STATE_SET
1661     * @see #WINDOW_FOCUSED_STATE_SET
1662     */
1663    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1664    /**
1665     * Indicates the view is focused and selected.
1666     *
1667     * @see #FOCUSED_STATE_SET
1668     * @see #SELECTED_STATE_SET
1669     */
1670    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1671    /**
1672     * Indicates the view has the focus and that its window has the focus.
1673     *
1674     * @see #FOCUSED_STATE_SET
1675     * @see #WINDOW_FOCUSED_STATE_SET
1676     */
1677    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1678    /**
1679     * Indicates the view is selected and that its window has the focus.
1680     *
1681     * @see #SELECTED_STATE_SET
1682     * @see #WINDOW_FOCUSED_STATE_SET
1683     */
1684    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1685    // Triples
1686    /**
1687     * Indicates the view is enabled, focused and selected.
1688     *
1689     * @see #ENABLED_STATE_SET
1690     * @see #FOCUSED_STATE_SET
1691     * @see #SELECTED_STATE_SET
1692     */
1693    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1694    /**
1695     * Indicates the view is enabled, focused and its window has the focus.
1696     *
1697     * @see #ENABLED_STATE_SET
1698     * @see #FOCUSED_STATE_SET
1699     * @see #WINDOW_FOCUSED_STATE_SET
1700     */
1701    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1702    /**
1703     * Indicates the view is enabled, selected and its window has the focus.
1704     *
1705     * @see #ENABLED_STATE_SET
1706     * @see #SELECTED_STATE_SET
1707     * @see #WINDOW_FOCUSED_STATE_SET
1708     */
1709    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1710    /**
1711     * Indicates the view is focused, selected and its window has the focus.
1712     *
1713     * @see #FOCUSED_STATE_SET
1714     * @see #SELECTED_STATE_SET
1715     * @see #WINDOW_FOCUSED_STATE_SET
1716     */
1717    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1718    /**
1719     * Indicates the view is enabled, focused, selected and its window
1720     * has the focus.
1721     *
1722     * @see #ENABLED_STATE_SET
1723     * @see #FOCUSED_STATE_SET
1724     * @see #SELECTED_STATE_SET
1725     * @see #WINDOW_FOCUSED_STATE_SET
1726     */
1727    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1728    /**
1729     * Indicates the view is pressed and its window has the focus.
1730     *
1731     * @see #PRESSED_STATE_SET
1732     * @see #WINDOW_FOCUSED_STATE_SET
1733     */
1734    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1735    /**
1736     * Indicates the view is pressed and selected.
1737     *
1738     * @see #PRESSED_STATE_SET
1739     * @see #SELECTED_STATE_SET
1740     */
1741    protected static final int[] PRESSED_SELECTED_STATE_SET;
1742    /**
1743     * Indicates the view is pressed, selected and its window has the focus.
1744     *
1745     * @see #PRESSED_STATE_SET
1746     * @see #SELECTED_STATE_SET
1747     * @see #WINDOW_FOCUSED_STATE_SET
1748     */
1749    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1750    /**
1751     * Indicates the view is pressed and focused.
1752     *
1753     * @see #PRESSED_STATE_SET
1754     * @see #FOCUSED_STATE_SET
1755     */
1756    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1757    /**
1758     * Indicates the view is pressed, focused and its window has the focus.
1759     *
1760     * @see #PRESSED_STATE_SET
1761     * @see #FOCUSED_STATE_SET
1762     * @see #WINDOW_FOCUSED_STATE_SET
1763     */
1764    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1765    /**
1766     * Indicates the view is pressed, focused and selected.
1767     *
1768     * @see #PRESSED_STATE_SET
1769     * @see #SELECTED_STATE_SET
1770     * @see #FOCUSED_STATE_SET
1771     */
1772    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1773    /**
1774     * Indicates the view is pressed, focused, selected and its window has the focus.
1775     *
1776     * @see #PRESSED_STATE_SET
1777     * @see #FOCUSED_STATE_SET
1778     * @see #SELECTED_STATE_SET
1779     * @see #WINDOW_FOCUSED_STATE_SET
1780     */
1781    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1782    /**
1783     * Indicates the view is pressed and enabled.
1784     *
1785     * @see #PRESSED_STATE_SET
1786     * @see #ENABLED_STATE_SET
1787     */
1788    protected static final int[] PRESSED_ENABLED_STATE_SET;
1789    /**
1790     * Indicates the view is pressed, enabled and its window has the focus.
1791     *
1792     * @see #PRESSED_STATE_SET
1793     * @see #ENABLED_STATE_SET
1794     * @see #WINDOW_FOCUSED_STATE_SET
1795     */
1796    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1797    /**
1798     * Indicates the view is pressed, enabled and selected.
1799     *
1800     * @see #PRESSED_STATE_SET
1801     * @see #ENABLED_STATE_SET
1802     * @see #SELECTED_STATE_SET
1803     */
1804    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1805    /**
1806     * Indicates the view is pressed, enabled, selected and its window has the
1807     * focus.
1808     *
1809     * @see #PRESSED_STATE_SET
1810     * @see #ENABLED_STATE_SET
1811     * @see #SELECTED_STATE_SET
1812     * @see #WINDOW_FOCUSED_STATE_SET
1813     */
1814    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1815    /**
1816     * Indicates the view is pressed, enabled and focused.
1817     *
1818     * @see #PRESSED_STATE_SET
1819     * @see #ENABLED_STATE_SET
1820     * @see #FOCUSED_STATE_SET
1821     */
1822    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1823    /**
1824     * Indicates the view is pressed, enabled, focused and its window has the
1825     * focus.
1826     *
1827     * @see #PRESSED_STATE_SET
1828     * @see #ENABLED_STATE_SET
1829     * @see #FOCUSED_STATE_SET
1830     * @see #WINDOW_FOCUSED_STATE_SET
1831     */
1832    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1833    /**
1834     * Indicates the view is pressed, enabled, focused and selected.
1835     *
1836     * @see #PRESSED_STATE_SET
1837     * @see #ENABLED_STATE_SET
1838     * @see #SELECTED_STATE_SET
1839     * @see #FOCUSED_STATE_SET
1840     */
1841    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1842    /**
1843     * Indicates the view is pressed, enabled, focused, selected and its window
1844     * has the focus.
1845     *
1846     * @see #PRESSED_STATE_SET
1847     * @see #ENABLED_STATE_SET
1848     * @see #SELECTED_STATE_SET
1849     * @see #FOCUSED_STATE_SET
1850     * @see #WINDOW_FOCUSED_STATE_SET
1851     */
1852    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1853
1854    static {
1855        EMPTY_STATE_SET = StateSet.get(0);
1856
1857        WINDOW_FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_WINDOW_FOCUSED);
1858
1859        SELECTED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_SELECTED);
1860        SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1861                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED);
1862
1863        FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_FOCUSED);
1864        FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1865                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED);
1866        FOCUSED_SELECTED_STATE_SET = StateSet.get(
1867                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED);
1868        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1869                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1870                        | StateSet.VIEW_STATE_FOCUSED);
1871
1872        ENABLED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_ENABLED);
1873        ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1874                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED);
1875        ENABLED_SELECTED_STATE_SET = StateSet.get(
1876                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED);
1877        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1878                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1879                        | StateSet.VIEW_STATE_ENABLED);
1880        ENABLED_FOCUSED_STATE_SET = StateSet.get(
1881                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED);
1882        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1883                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1884                        | StateSet.VIEW_STATE_ENABLED);
1885        ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1886                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1887                        | StateSet.VIEW_STATE_ENABLED);
1888        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1889                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1890                        | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED);
1891
1892        PRESSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_PRESSED);
1893        PRESSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1894                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1895        PRESSED_SELECTED_STATE_SET = StateSet.get(
1896                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_PRESSED);
1897        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1898                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1899                        | StateSet.VIEW_STATE_PRESSED);
1900        PRESSED_FOCUSED_STATE_SET = StateSet.get(
1901                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1902        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1903                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1904                        | StateSet.VIEW_STATE_PRESSED);
1905        PRESSED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1906                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1907                        | StateSet.VIEW_STATE_PRESSED);
1908        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1909                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1910                        | StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1911        PRESSED_ENABLED_STATE_SET = StateSet.get(
1912                StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1913        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1914                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED
1915                        | StateSet.VIEW_STATE_PRESSED);
1916        PRESSED_ENABLED_SELECTED_STATE_SET = StateSet.get(
1917                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED
1918                        | StateSet.VIEW_STATE_PRESSED);
1919        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1920                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1921                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1922        PRESSED_ENABLED_FOCUSED_STATE_SET = StateSet.get(
1923                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED
1924                        | StateSet.VIEW_STATE_PRESSED);
1925        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1926                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1927                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1928        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1929                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1930                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1931        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1932                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1933                        | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED
1934                        | StateSet.VIEW_STATE_PRESSED);
1935    }
1936
1937    /**
1938     * Accessibility event types that are dispatched for text population.
1939     */
1940    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1941            AccessibilityEvent.TYPE_VIEW_CLICKED
1942            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1943            | AccessibilityEvent.TYPE_VIEW_SELECTED
1944            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1945            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1946            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1947            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1948            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1949            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1950            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1951            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1952
1953    static final int DEBUG_CORNERS_COLOR = Color.rgb(63, 127, 255);
1954
1955    static final int DEBUG_CORNERS_SIZE_DIP = 8;
1956
1957    /**
1958     * Temporary Rect currently for use in setBackground().  This will probably
1959     * be extended in the future to hold our own class with more than just
1960     * a Rect. :)
1961     */
1962    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1963
1964    /**
1965     * Map used to store views' tags.
1966     */
1967    private SparseArray<Object> mKeyedTags;
1968
1969    /**
1970     * The next available accessibility id.
1971     */
1972    private static int sNextAccessibilityViewId;
1973
1974    /**
1975     * The animation currently associated with this view.
1976     * @hide
1977     */
1978    protected Animation mCurrentAnimation = null;
1979
1980    /**
1981     * Width as measured during measure pass.
1982     * {@hide}
1983     */
1984    @ViewDebug.ExportedProperty(category = "measurement")
1985    int mMeasuredWidth;
1986
1987    /**
1988     * Height as measured during measure pass.
1989     * {@hide}
1990     */
1991    @ViewDebug.ExportedProperty(category = "measurement")
1992    int mMeasuredHeight;
1993
1994    /**
1995     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1996     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1997     * its display list. This flag, used only when hw accelerated, allows us to clear the
1998     * flag while retaining this information until it's needed (at getDisplayList() time and
1999     * in drawChild(), when we decide to draw a view's children's display lists into our own).
2000     *
2001     * {@hide}
2002     */
2003    boolean mRecreateDisplayList = false;
2004
2005    /**
2006     * The view's identifier.
2007     * {@hide}
2008     *
2009     * @see #setId(int)
2010     * @see #getId()
2011     */
2012    @IdRes
2013    @ViewDebug.ExportedProperty(resolveId = true)
2014    int mID = NO_ID;
2015
2016    /**
2017     * The stable ID of this view for accessibility purposes.
2018     */
2019    int mAccessibilityViewId = NO_ID;
2020
2021    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
2022
2023    SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent;
2024
2025    /**
2026     * The view's tag.
2027     * {@hide}
2028     *
2029     * @see #setTag(Object)
2030     * @see #getTag()
2031     */
2032    protected Object mTag = null;
2033
2034    // for mPrivateFlags:
2035    /** {@hide} */
2036    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
2037    /** {@hide} */
2038    static final int PFLAG_FOCUSED                     = 0x00000002;
2039    /** {@hide} */
2040    static final int PFLAG_SELECTED                    = 0x00000004;
2041    /** {@hide} */
2042    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
2043    /** {@hide} */
2044    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
2045    /** {@hide} */
2046    static final int PFLAG_DRAWN                       = 0x00000020;
2047    /**
2048     * When this flag is set, this view is running an animation on behalf of its
2049     * children and should therefore not cancel invalidate requests, even if they
2050     * lie outside of this view's bounds.
2051     *
2052     * {@hide}
2053     */
2054    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
2055    /** {@hide} */
2056    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
2057    /** {@hide} */
2058    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
2059    /** {@hide} */
2060    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
2061    /** {@hide} */
2062    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
2063    /** {@hide} */
2064    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
2065    /** {@hide} */
2066    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
2067
2068    private static final int PFLAG_PRESSED             = 0x00004000;
2069
2070    /** {@hide} */
2071    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
2072    /**
2073     * Flag used to indicate that this view should be drawn once more (and only once
2074     * more) after its animation has completed.
2075     * {@hide}
2076     */
2077    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
2078
2079    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
2080
2081    /**
2082     * Indicates that the View returned true when onSetAlpha() was called and that
2083     * the alpha must be restored.
2084     * {@hide}
2085     */
2086    static final int PFLAG_ALPHA_SET                   = 0x00040000;
2087
2088    /**
2089     * Set by {@link #setScrollContainer(boolean)}.
2090     */
2091    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
2092
2093    /**
2094     * Set by {@link #setScrollContainer(boolean)}.
2095     */
2096    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
2097
2098    /**
2099     * View flag indicating whether this view was invalidated (fully or partially.)
2100     *
2101     * @hide
2102     */
2103    static final int PFLAG_DIRTY                       = 0x00200000;
2104
2105    /**
2106     * View flag indicating whether this view was invalidated by an opaque
2107     * invalidate request.
2108     *
2109     * @hide
2110     */
2111    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
2112
2113    /**
2114     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
2115     *
2116     * @hide
2117     */
2118    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
2119
2120    /**
2121     * Indicates whether the background is opaque.
2122     *
2123     * @hide
2124     */
2125    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
2126
2127    /**
2128     * Indicates whether the scrollbars are opaque.
2129     *
2130     * @hide
2131     */
2132    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
2133
2134    /**
2135     * Indicates whether the view is opaque.
2136     *
2137     * @hide
2138     */
2139    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
2140
2141    /**
2142     * Indicates a prepressed state;
2143     * the short time between ACTION_DOWN and recognizing
2144     * a 'real' press. Prepressed is used to recognize quick taps
2145     * even when they are shorter than ViewConfiguration.getTapTimeout().
2146     *
2147     * @hide
2148     */
2149    private static final int PFLAG_PREPRESSED          = 0x02000000;
2150
2151    /**
2152     * Indicates whether the view is temporarily detached.
2153     *
2154     * @hide
2155     */
2156    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
2157
2158    /**
2159     * Indicates that we should awaken scroll bars once attached
2160     *
2161     * PLEASE NOTE: This flag is now unused as we now send onVisibilityChanged
2162     * during window attachment and it is no longer needed. Feel free to repurpose it.
2163     *
2164     * @hide
2165     */
2166    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
2167
2168    /**
2169     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
2170     * @hide
2171     */
2172    private static final int PFLAG_HOVERED             = 0x10000000;
2173
2174    /**
2175     * no longer needed, should be reused
2176     */
2177    private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000;
2178
2179    /** {@hide} */
2180    static final int PFLAG_ACTIVATED                   = 0x40000000;
2181
2182    /**
2183     * Indicates that this view was specifically invalidated, not just dirtied because some
2184     * child view was invalidated. The flag is used to determine when we need to recreate
2185     * a view's display list (as opposed to just returning a reference to its existing
2186     * display list).
2187     *
2188     * @hide
2189     */
2190    static final int PFLAG_INVALIDATED                 = 0x80000000;
2191
2192    /**
2193     * Masks for mPrivateFlags2, as generated by dumpFlags():
2194     *
2195     * |-------|-------|-------|-------|
2196     *                                 1 PFLAG2_DRAG_CAN_ACCEPT
2197     *                                1  PFLAG2_DRAG_HOVERED
2198     *                              11   PFLAG2_LAYOUT_DIRECTION_MASK
2199     *                             1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
2200     *                            1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
2201     *                            11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
2202     *                           1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
2203     *                          1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
2204     *                          11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
2205     *                         1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
2206     *                         1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
2207     *                         11        PFLAG2_TEXT_DIRECTION_FLAGS[6]
2208     *                         111       PFLAG2_TEXT_DIRECTION_FLAGS[7]
2209     *                         111       PFLAG2_TEXT_DIRECTION_MASK
2210     *                        1          PFLAG2_TEXT_DIRECTION_RESOLVED
2211     *                       1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
2212     *                     111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
2213     *                    1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
2214     *                   1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
2215     *                   11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
2216     *                  1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
2217     *                  1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
2218     *                  11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
2219     *                  111              PFLAG2_TEXT_ALIGNMENT_MASK
2220     *                 1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
2221     *                1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
2222     *              111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
2223     *           111                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
2224     *         11                        PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK
2225     *       1                           PFLAG2_ACCESSIBILITY_FOCUSED
2226     *      1                            PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED
2227     *     1                             PFLAG2_VIEW_QUICK_REJECTED
2228     *    1                              PFLAG2_PADDING_RESOLVED
2229     *   1                               PFLAG2_DRAWABLE_RESOLVED
2230     *  1                                PFLAG2_HAS_TRANSIENT_STATE
2231     * |-------|-------|-------|-------|
2232     */
2233
2234    /**
2235     * Indicates that this view has reported that it can accept the current drag's content.
2236     * Cleared when the drag operation concludes.
2237     * @hide
2238     */
2239    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
2240
2241    /**
2242     * Indicates that this view is currently directly under the drag location in a
2243     * drag-and-drop operation involving content that it can accept.  Cleared when
2244     * the drag exits the view, or when the drag operation concludes.
2245     * @hide
2246     */
2247    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
2248
2249    /** @hide */
2250    @IntDef({
2251        LAYOUT_DIRECTION_LTR,
2252        LAYOUT_DIRECTION_RTL,
2253        LAYOUT_DIRECTION_INHERIT,
2254        LAYOUT_DIRECTION_LOCALE
2255    })
2256    @Retention(RetentionPolicy.SOURCE)
2257    // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection
2258    public @interface LayoutDir {}
2259
2260    /** @hide */
2261    @IntDef({
2262        LAYOUT_DIRECTION_LTR,
2263        LAYOUT_DIRECTION_RTL
2264    })
2265    @Retention(RetentionPolicy.SOURCE)
2266    public @interface ResolvedLayoutDir {}
2267
2268    /**
2269     * A flag to indicate that the layout direction of this view has not been defined yet.
2270     * @hide
2271     */
2272    public static final int LAYOUT_DIRECTION_UNDEFINED = LayoutDirection.UNDEFINED;
2273
2274    /**
2275     * Horizontal layout direction of this view is from Left to Right.
2276     * Use with {@link #setLayoutDirection}.
2277     */
2278    public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR;
2279
2280    /**
2281     * Horizontal layout direction of this view is from Right to Left.
2282     * Use with {@link #setLayoutDirection}.
2283     */
2284    public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL;
2285
2286    /**
2287     * Horizontal layout direction of this view is inherited from its parent.
2288     * Use with {@link #setLayoutDirection}.
2289     */
2290    public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT;
2291
2292    /**
2293     * Horizontal layout direction of this view is from deduced from the default language
2294     * script for the locale. Use with {@link #setLayoutDirection}.
2295     */
2296    public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE;
2297
2298    /**
2299     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2300     * @hide
2301     */
2302    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
2303
2304    /**
2305     * Mask for use with private flags indicating bits used for horizontal layout direction.
2306     * @hide
2307     */
2308    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2309
2310    /**
2311     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
2312     * right-to-left direction.
2313     * @hide
2314     */
2315    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2316
2317    /**
2318     * Indicates whether the view horizontal layout direction has been resolved.
2319     * @hide
2320     */
2321    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2322
2323    /**
2324     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
2325     * @hide
2326     */
2327    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
2328            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2329
2330    /*
2331     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
2332     * flag value.
2333     * @hide
2334     */
2335    private static final int[] LAYOUT_DIRECTION_FLAGS = {
2336            LAYOUT_DIRECTION_LTR,
2337            LAYOUT_DIRECTION_RTL,
2338            LAYOUT_DIRECTION_INHERIT,
2339            LAYOUT_DIRECTION_LOCALE
2340    };
2341
2342    /**
2343     * Default horizontal layout direction.
2344     */
2345    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
2346
2347    /**
2348     * Default horizontal layout direction.
2349     * @hide
2350     */
2351    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
2352
2353    /**
2354     * Text direction is inherited through {@link ViewGroup}
2355     */
2356    public static final int TEXT_DIRECTION_INHERIT = 0;
2357
2358    /**
2359     * Text direction is using "first strong algorithm". The first strong directional character
2360     * determines the paragraph direction. If there is no strong directional character, the
2361     * paragraph direction is the view's resolved layout direction.
2362     */
2363    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
2364
2365    /**
2366     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
2367     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
2368     * If there are neither, the paragraph direction is the view's resolved layout direction.
2369     */
2370    public static final int TEXT_DIRECTION_ANY_RTL = 2;
2371
2372    /**
2373     * Text direction is forced to LTR.
2374     */
2375    public static final int TEXT_DIRECTION_LTR = 3;
2376
2377    /**
2378     * Text direction is forced to RTL.
2379     */
2380    public static final int TEXT_DIRECTION_RTL = 4;
2381
2382    /**
2383     * Text direction is coming from the system Locale.
2384     */
2385    public static final int TEXT_DIRECTION_LOCALE = 5;
2386
2387    /**
2388     * Text direction is using "first strong algorithm". The first strong directional character
2389     * determines the paragraph direction. If there is no strong directional character, the
2390     * paragraph direction is LTR.
2391     */
2392    public static final int TEXT_DIRECTION_FIRST_STRONG_LTR = 6;
2393
2394    /**
2395     * Text direction is using "first strong algorithm". The first strong directional character
2396     * determines the paragraph direction. If there is no strong directional character, the
2397     * paragraph direction is RTL.
2398     */
2399    public static final int TEXT_DIRECTION_FIRST_STRONG_RTL = 7;
2400
2401    /**
2402     * Default text direction is inherited
2403     */
2404    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
2405
2406    /**
2407     * Default resolved text direction
2408     * @hide
2409     */
2410    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
2411
2412    /**
2413     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
2414     * @hide
2415     */
2416    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
2417
2418    /**
2419     * Mask for use with private flags indicating bits used for text direction.
2420     * @hide
2421     */
2422    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
2423            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2424
2425    /**
2426     * Array of text direction flags for mapping attribute "textDirection" to correct
2427     * flag value.
2428     * @hide
2429     */
2430    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
2431            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2432            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2433            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2434            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2435            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2436            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2437            TEXT_DIRECTION_FIRST_STRONG_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2438            TEXT_DIRECTION_FIRST_STRONG_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
2439    };
2440
2441    /**
2442     * Indicates whether the view text direction has been resolved.
2443     * @hide
2444     */
2445    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
2446            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2447
2448    /**
2449     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2450     * @hide
2451     */
2452    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
2453
2454    /**
2455     * Mask for use with private flags indicating bits used for resolved text direction.
2456     * @hide
2457     */
2458    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
2459            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2460
2461    /**
2462     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
2463     * @hide
2464     */
2465    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
2466            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2467
2468    /** @hide */
2469    @IntDef({
2470        TEXT_ALIGNMENT_INHERIT,
2471        TEXT_ALIGNMENT_GRAVITY,
2472        TEXT_ALIGNMENT_CENTER,
2473        TEXT_ALIGNMENT_TEXT_START,
2474        TEXT_ALIGNMENT_TEXT_END,
2475        TEXT_ALIGNMENT_VIEW_START,
2476        TEXT_ALIGNMENT_VIEW_END
2477    })
2478    @Retention(RetentionPolicy.SOURCE)
2479    public @interface TextAlignment {}
2480
2481    /**
2482     * Default text alignment. The text alignment of this View is inherited from its parent.
2483     * Use with {@link #setTextAlignment(int)}
2484     */
2485    public static final int TEXT_ALIGNMENT_INHERIT = 0;
2486
2487    /**
2488     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
2489     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
2490     *
2491     * Use with {@link #setTextAlignment(int)}
2492     */
2493    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
2494
2495    /**
2496     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2497     *
2498     * Use with {@link #setTextAlignment(int)}
2499     */
2500    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2501
2502    /**
2503     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2504     *
2505     * Use with {@link #setTextAlignment(int)}
2506     */
2507    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2508
2509    /**
2510     * Center the paragraph, e.g. ALIGN_CENTER.
2511     *
2512     * Use with {@link #setTextAlignment(int)}
2513     */
2514    public static final int TEXT_ALIGNMENT_CENTER = 4;
2515
2516    /**
2517     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2518     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2519     *
2520     * Use with {@link #setTextAlignment(int)}
2521     */
2522    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2523
2524    /**
2525     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2526     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2527     *
2528     * Use with {@link #setTextAlignment(int)}
2529     */
2530    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2531
2532    /**
2533     * Default text alignment is inherited
2534     */
2535    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2536
2537    /**
2538     * Default resolved text alignment
2539     * @hide
2540     */
2541    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2542
2543    /**
2544      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2545      * @hide
2546      */
2547    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2548
2549    /**
2550      * Mask for use with private flags indicating bits used for text alignment.
2551      * @hide
2552      */
2553    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2554
2555    /**
2556     * Array of text direction flags for mapping attribute "textAlignment" to correct
2557     * flag value.
2558     * @hide
2559     */
2560    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2561            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2562            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2563            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2564            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2565            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2566            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2567            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2568    };
2569
2570    /**
2571     * Indicates whether the view text alignment has been resolved.
2572     * @hide
2573     */
2574    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2575
2576    /**
2577     * Bit shift to get the resolved text alignment.
2578     * @hide
2579     */
2580    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2581
2582    /**
2583     * Mask for use with private flags indicating bits used for text alignment.
2584     * @hide
2585     */
2586    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2587            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2588
2589    /**
2590     * Indicates whether if the view text alignment has been resolved to gravity
2591     */
2592    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2593            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2594
2595    // Accessiblity constants for mPrivateFlags2
2596
2597    /**
2598     * Shift for the bits in {@link #mPrivateFlags2} related to the
2599     * "importantForAccessibility" attribute.
2600     */
2601    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2602
2603    /**
2604     * Automatically determine whether a view is important for accessibility.
2605     */
2606    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2607
2608    /**
2609     * The view is important for accessibility.
2610     */
2611    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2612
2613    /**
2614     * The view is not important for accessibility.
2615     */
2616    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2617
2618    /**
2619     * The view is not important for accessibility, nor are any of its
2620     * descendant views.
2621     */
2622    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004;
2623
2624    /**
2625     * The default whether the view is important for accessibility.
2626     */
2627    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2628
2629    /**
2630     * Mask for obtaining the bits which specify how to determine
2631     * whether a view is important for accessibility.
2632     */
2633    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2634        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO
2635        | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS)
2636        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2637
2638    /**
2639     * Shift for the bits in {@link #mPrivateFlags2} related to the
2640     * "accessibilityLiveRegion" attribute.
2641     */
2642    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23;
2643
2644    /**
2645     * Live region mode specifying that accessibility services should not
2646     * automatically announce changes to this view. This is the default live
2647     * region mode for most views.
2648     * <p>
2649     * Use with {@link #setAccessibilityLiveRegion(int)}.
2650     */
2651    public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000;
2652
2653    /**
2654     * Live region mode specifying that accessibility services should announce
2655     * changes to this view.
2656     * <p>
2657     * Use with {@link #setAccessibilityLiveRegion(int)}.
2658     */
2659    public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001;
2660
2661    /**
2662     * Live region mode specifying that accessibility services should interrupt
2663     * ongoing speech to immediately announce changes to this view.
2664     * <p>
2665     * Use with {@link #setAccessibilityLiveRegion(int)}.
2666     */
2667    public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002;
2668
2669    /**
2670     * The default whether the view is important for accessibility.
2671     */
2672    static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE;
2673
2674    /**
2675     * Mask for obtaining the bits which specify a view's accessibility live
2676     * region mode.
2677     */
2678    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE
2679            | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE)
2680            << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
2681
2682    /**
2683     * Flag indicating whether a view has accessibility focus.
2684     */
2685    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000;
2686
2687    /**
2688     * Flag whether the accessibility state of the subtree rooted at this view changed.
2689     */
2690    static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000;
2691
2692    /**
2693     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2694     * is used to check whether later changes to the view's transform should invalidate the
2695     * view to force the quickReject test to run again.
2696     */
2697    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2698
2699    /**
2700     * Flag indicating that start/end padding has been resolved into left/right padding
2701     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2702     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2703     * during measurement. In some special cases this is required such as when an adapter-based
2704     * view measures prospective children without attaching them to a window.
2705     */
2706    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2707
2708    /**
2709     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2710     */
2711    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2712
2713    /**
2714     * Indicates that the view is tracking some sort of transient state
2715     * that the app should not need to be aware of, but that the framework
2716     * should take special care to preserve.
2717     */
2718    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000;
2719
2720    /**
2721     * Group of bits indicating that RTL properties resolution is done.
2722     */
2723    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2724            PFLAG2_TEXT_DIRECTION_RESOLVED |
2725            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2726            PFLAG2_PADDING_RESOLVED |
2727            PFLAG2_DRAWABLE_RESOLVED;
2728
2729    // There are a couple of flags left in mPrivateFlags2
2730
2731    /* End of masks for mPrivateFlags2 */
2732
2733    /**
2734     * Masks for mPrivateFlags3, as generated by dumpFlags():
2735     *
2736     * |-------|-------|-------|-------|
2737     *                                 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM
2738     *                                1  PFLAG3_VIEW_IS_ANIMATING_ALPHA
2739     *                               1   PFLAG3_IS_LAID_OUT
2740     *                              1    PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT
2741     *                             1     PFLAG3_CALLED_SUPER
2742     *                            1      PFLAG3_APPLYING_INSETS
2743     *                           1       PFLAG3_FITTING_SYSTEM_WINDOWS
2744     *                          1        PFLAG3_NESTED_SCROLLING_ENABLED
2745     *                         1         PFLAG3_SCROLL_INDICATOR_TOP
2746     *                        1          PFLAG3_SCROLL_INDICATOR_BOTTOM
2747     *                       1           PFLAG3_SCROLL_INDICATOR_LEFT
2748     *                      1            PFLAG3_SCROLL_INDICATOR_RIGHT
2749     *                     1             PFLAG3_SCROLL_INDICATOR_START
2750     *                    1              PFLAG3_SCROLL_INDICATOR_END
2751     *                   1               PFLAG3_ASSIST_BLOCKED
2752     *                  1                PFLAG3_CLUSTER
2753     *                 1                 PFLAG3_IS_AUTOFILLED
2754     *                1                  PFLAG3_FINGER_DOWN
2755     *               1                   PFLAG3_FOCUSED_BY_DEFAULT
2756     *             11                    PFLAG3_AUTO_FILL_MODE_MASK
2757     *           11                      PFLAG3_IMPORTANT_FOR_AUTOFILL
2758     *          1                        PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE
2759     *         1                         PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED
2760     *        1                          PFLAG3_TEMPORARY_DETACH
2761     *       1                           PFLAG3_NO_REVEAL_ON_FOCUS
2762     * |-------|-------|-------|-------|
2763     */
2764
2765    /**
2766     * Flag indicating that view has a transform animation set on it. This is used to track whether
2767     * an animation is cleared between successive frames, in order to tell the associated
2768     * DisplayList to clear its animation matrix.
2769     */
2770    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2771
2772    /**
2773     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2774     * animation is cleared between successive frames, in order to tell the associated
2775     * DisplayList to restore its alpha value.
2776     */
2777    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2778
2779    /**
2780     * Flag indicating that the view has been through at least one layout since it
2781     * was last attached to a window.
2782     */
2783    static final int PFLAG3_IS_LAID_OUT = 0x4;
2784
2785    /**
2786     * Flag indicating that a call to measure() was skipped and should be done
2787     * instead when layout() is invoked.
2788     */
2789    static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8;
2790
2791    /**
2792     * Flag indicating that an overridden method correctly called down to
2793     * the superclass implementation as required by the API spec.
2794     */
2795    static final int PFLAG3_CALLED_SUPER = 0x10;
2796
2797    /**
2798     * Flag indicating that we're in the process of applying window insets.
2799     */
2800    static final int PFLAG3_APPLYING_INSETS = 0x20;
2801
2802    /**
2803     * Flag indicating that we're in the process of fitting system windows using the old method.
2804     */
2805    static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40;
2806
2807    /**
2808     * Flag indicating that nested scrolling is enabled for this view.
2809     * The view will optionally cooperate with views up its parent chain to allow for
2810     * integrated nested scrolling along the same axis.
2811     */
2812    static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80;
2813
2814    /**
2815     * Flag indicating that the bottom scroll indicator should be displayed
2816     * when this view can scroll up.
2817     */
2818    static final int PFLAG3_SCROLL_INDICATOR_TOP = 0x0100;
2819
2820    /**
2821     * Flag indicating that the bottom scroll indicator should be displayed
2822     * when this view can scroll down.
2823     */
2824    static final int PFLAG3_SCROLL_INDICATOR_BOTTOM = 0x0200;
2825
2826    /**
2827     * Flag indicating that the left scroll indicator should be displayed
2828     * when this view can scroll left.
2829     */
2830    static final int PFLAG3_SCROLL_INDICATOR_LEFT = 0x0400;
2831
2832    /**
2833     * Flag indicating that the right scroll indicator should be displayed
2834     * when this view can scroll right.
2835     */
2836    static final int PFLAG3_SCROLL_INDICATOR_RIGHT = 0x0800;
2837
2838    /**
2839     * Flag indicating that the start scroll indicator should be displayed
2840     * when this view can scroll in the start direction.
2841     */
2842    static final int PFLAG3_SCROLL_INDICATOR_START = 0x1000;
2843
2844    /**
2845     * Flag indicating that the end scroll indicator should be displayed
2846     * when this view can scroll in the end direction.
2847     */
2848    static final int PFLAG3_SCROLL_INDICATOR_END = 0x2000;
2849
2850    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2851
2852    static final int SCROLL_INDICATORS_NONE = 0x0000;
2853
2854    /**
2855     * Mask for use with setFlags indicating bits used for indicating which
2856     * scroll indicators are enabled.
2857     */
2858    static final int SCROLL_INDICATORS_PFLAG3_MASK = PFLAG3_SCROLL_INDICATOR_TOP
2859            | PFLAG3_SCROLL_INDICATOR_BOTTOM | PFLAG3_SCROLL_INDICATOR_LEFT
2860            | PFLAG3_SCROLL_INDICATOR_RIGHT | PFLAG3_SCROLL_INDICATOR_START
2861            | PFLAG3_SCROLL_INDICATOR_END;
2862
2863    /**
2864     * Left-shift required to translate between public scroll indicator flags
2865     * and internal PFLAGS3 flags. When used as a right-shift, translates
2866     * PFLAGS3 flags to public flags.
2867     */
2868    static final int SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT = 8;
2869
2870    /** @hide */
2871    @Retention(RetentionPolicy.SOURCE)
2872    @IntDef(flag = true,
2873            value = {
2874                    SCROLL_INDICATOR_TOP,
2875                    SCROLL_INDICATOR_BOTTOM,
2876                    SCROLL_INDICATOR_LEFT,
2877                    SCROLL_INDICATOR_RIGHT,
2878                    SCROLL_INDICATOR_START,
2879                    SCROLL_INDICATOR_END,
2880            })
2881    public @interface ScrollIndicators {}
2882
2883    /**
2884     * Scroll indicator direction for the top edge of the view.
2885     *
2886     * @see #setScrollIndicators(int)
2887     * @see #setScrollIndicators(int, int)
2888     * @see #getScrollIndicators()
2889     */
2890    public static final int SCROLL_INDICATOR_TOP =
2891            PFLAG3_SCROLL_INDICATOR_TOP >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2892
2893    /**
2894     * Scroll indicator direction for the bottom edge of the view.
2895     *
2896     * @see #setScrollIndicators(int)
2897     * @see #setScrollIndicators(int, int)
2898     * @see #getScrollIndicators()
2899     */
2900    public static final int SCROLL_INDICATOR_BOTTOM =
2901            PFLAG3_SCROLL_INDICATOR_BOTTOM >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2902
2903    /**
2904     * Scroll indicator direction for the left edge of the view.
2905     *
2906     * @see #setScrollIndicators(int)
2907     * @see #setScrollIndicators(int, int)
2908     * @see #getScrollIndicators()
2909     */
2910    public static final int SCROLL_INDICATOR_LEFT =
2911            PFLAG3_SCROLL_INDICATOR_LEFT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2912
2913    /**
2914     * Scroll indicator direction for the right edge of the view.
2915     *
2916     * @see #setScrollIndicators(int)
2917     * @see #setScrollIndicators(int, int)
2918     * @see #getScrollIndicators()
2919     */
2920    public static final int SCROLL_INDICATOR_RIGHT =
2921            PFLAG3_SCROLL_INDICATOR_RIGHT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2922
2923    /**
2924     * Scroll indicator direction for the starting edge of the view.
2925     * <p>
2926     * Resolved according to the view's layout direction, see
2927     * {@link #getLayoutDirection()} for more information.
2928     *
2929     * @see #setScrollIndicators(int)
2930     * @see #setScrollIndicators(int, int)
2931     * @see #getScrollIndicators()
2932     */
2933    public static final int SCROLL_INDICATOR_START =
2934            PFLAG3_SCROLL_INDICATOR_START >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2935
2936    /**
2937     * Scroll indicator direction for the ending edge of the view.
2938     * <p>
2939     * Resolved according to the view's layout direction, see
2940     * {@link #getLayoutDirection()} for more information.
2941     *
2942     * @see #setScrollIndicators(int)
2943     * @see #setScrollIndicators(int, int)
2944     * @see #getScrollIndicators()
2945     */
2946    public static final int SCROLL_INDICATOR_END =
2947            PFLAG3_SCROLL_INDICATOR_END >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2948
2949    /**
2950     * <p>Indicates that we are allowing {@link ViewStructure} to traverse
2951     * into this view.<p>
2952     */
2953    static final int PFLAG3_ASSIST_BLOCKED = 0x4000;
2954
2955    /**
2956     * Flag indicating that the view is a root of a keyboard navigation cluster.
2957     *
2958     * @see #isKeyboardNavigationCluster()
2959     * @see #setKeyboardNavigationCluster(boolean)
2960     */
2961    private static final int PFLAG3_CLUSTER = 0x8000;
2962
2963    /**
2964     * Flag indicating that the view is autofilled
2965     *
2966     * @see #isAutofilled()
2967     * @see #setAutofilled(boolean)
2968     */
2969    private static final int PFLAG3_IS_AUTOFILLED = 0x10000;
2970
2971    /**
2972     * Indicates that the user is currently touching the screen.
2973     * Currently used for the tooltip positioning only.
2974     */
2975    private static final int PFLAG3_FINGER_DOWN = 0x20000;
2976
2977    /**
2978     * Flag indicating that this view is the default-focus view.
2979     *
2980     * @see #isFocusedByDefault()
2981     * @see #setFocusedByDefault(boolean)
2982     */
2983    private static final int PFLAG3_FOCUSED_BY_DEFAULT = 0x40000;
2984
2985    /**
2986     * Shift for the place where the autofill mode is stored in the pflags
2987     *
2988     * @see #getAutofillMode()
2989     * @see #setAutofillMode(int)
2990     */
2991    private static final int PFLAG3_AUTOFILL_MODE_SHIFT = 19;
2992
2993    /**
2994     * Mask for autofill modes
2995     *
2996     * @see #getAutofillMode()
2997     * @see #setAutofillMode(int)
2998     */
2999    private static final int PFLAG3_AUTOFILL_MODE_MASK = (AUTOFILL_MODE_INHERIT
3000            | AUTOFILL_MODE_AUTO | AUTOFILL_MODE_MANUAL) << PFLAG3_AUTOFILL_MODE_SHIFT;
3001
3002    /**
3003     * Shift for the bits in {@link #mPrivateFlags3} related to the
3004     * "importantForAutofill" attribute.
3005     */
3006    static final int PFLAG3_IMPORTANT_FOR_AUTOFILL_SHIFT = 21;
3007
3008    /**
3009     * Mask for obtaining the bits which specify how to determine
3010     * whether a view is important for autofill.
3011     */
3012    static final int PFLAG3_IMPORTANT_FOR_AUTOFILL_MASK = (IMPORTANT_FOR_AUTOFILL_AUTO
3013            | IMPORTANT_FOR_AUTOFILL_YES | IMPORTANT_FOR_AUTOFILL_NO)
3014            << PFLAG3_IMPORTANT_FOR_AUTOFILL_SHIFT;
3015
3016    /**
3017     * Whether this view has rendered elements that overlap (see {@link
3018     * #hasOverlappingRendering()}, {@link #forceHasOverlappingRendering(boolean)}, and
3019     * {@link #getHasOverlappingRendering()} ). The value in this bit is only valid when
3020     * PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED has been set. Otherwise, the value is
3021     * determined by whatever {@link #hasOverlappingRendering()} returns.
3022     */
3023    private static final int PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE = 0x800000;
3024
3025    /**
3026     * Whether {@link #forceHasOverlappingRendering(boolean)} has been called. When true, value
3027     * in PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE is valid.
3028     */
3029    private static final int PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED = 0x1000000;
3030
3031    /**
3032     * Flag indicating that the view is temporarily detached from the parent view.
3033     *
3034     * @see #onStartTemporaryDetach()
3035     * @see #onFinishTemporaryDetach()
3036     */
3037    static final int PFLAG3_TEMPORARY_DETACH = 0x2000000;
3038
3039    /**
3040     * Flag indicating that the view does not wish to be revealed within its parent
3041     * hierarchy when it gains focus. Expressed in the negative since the historical
3042     * default behavior is to reveal on focus; this flag suppresses that behavior.
3043     *
3044     * @see #setRevealOnFocusHint(boolean)
3045     * @see #getRevealOnFocusHint()
3046     */
3047    private static final int PFLAG3_NO_REVEAL_ON_FOCUS = 0x4000000;
3048
3049    /* End of masks for mPrivateFlags3 */
3050
3051    /**
3052     * Always allow a user to over-scroll this view, provided it is a
3053     * view that can scroll.
3054     *
3055     * @see #getOverScrollMode()
3056     * @see #setOverScrollMode(int)
3057     */
3058    public static final int OVER_SCROLL_ALWAYS = 0;
3059
3060    /**
3061     * Allow a user to over-scroll this view only if the content is large
3062     * enough to meaningfully scroll, provided it is a view that can scroll.
3063     *
3064     * @see #getOverScrollMode()
3065     * @see #setOverScrollMode(int)
3066     */
3067    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
3068
3069    /**
3070     * Never allow a user to over-scroll this view.
3071     *
3072     * @see #getOverScrollMode()
3073     * @see #setOverScrollMode(int)
3074     */
3075    public static final int OVER_SCROLL_NEVER = 2;
3076
3077    /**
3078     * Special constant for {@link #setSystemUiVisibility(int)}: View has
3079     * requested the system UI (status bar) to be visible (the default).
3080     *
3081     * @see #setSystemUiVisibility(int)
3082     */
3083    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
3084
3085    /**
3086     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
3087     * system UI to enter an unobtrusive "low profile" mode.
3088     *
3089     * <p>This is for use in games, book readers, video players, or any other
3090     * "immersive" application where the usual system chrome is deemed too distracting.
3091     *
3092     * <p>In low profile mode, the status bar and/or navigation icons may dim.
3093     *
3094     * @see #setSystemUiVisibility(int)
3095     */
3096    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
3097
3098    /**
3099     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
3100     * system navigation be temporarily hidden.
3101     *
3102     * <p>This is an even less obtrusive state than that called for by
3103     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
3104     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
3105     * those to disappear. This is useful (in conjunction with the
3106     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
3107     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
3108     * window flags) for displaying content using every last pixel on the display.
3109     *
3110     * <p>There is a limitation: because navigation controls are so important, the least user
3111     * interaction will cause them to reappear immediately.  When this happens, both
3112     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
3113     * so that both elements reappear at the same time.
3114     *
3115     * @see #setSystemUiVisibility(int)
3116     */
3117    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
3118
3119    /**
3120     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
3121     * into the normal fullscreen mode so that its content can take over the screen
3122     * while still allowing the user to interact with the application.
3123     *
3124     * <p>This has the same visual effect as
3125     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
3126     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
3127     * meaning that non-critical screen decorations (such as the status bar) will be
3128     * hidden while the user is in the View's window, focusing the experience on
3129     * that content.  Unlike the window flag, if you are using ActionBar in
3130     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
3131     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
3132     * hide the action bar.
3133     *
3134     * <p>This approach to going fullscreen is best used over the window flag when
3135     * it is a transient state -- that is, the application does this at certain
3136     * points in its user interaction where it wants to allow the user to focus
3137     * on content, but not as a continuous state.  For situations where the application
3138     * would like to simply stay full screen the entire time (such as a game that
3139     * wants to take over the screen), the
3140     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
3141     * is usually a better approach.  The state set here will be removed by the system
3142     * in various situations (such as the user moving to another application) like
3143     * the other system UI states.
3144     *
3145     * <p>When using this flag, the application should provide some easy facility
3146     * for the user to go out of it.  A common example would be in an e-book
3147     * reader, where tapping on the screen brings back whatever screen and UI
3148     * decorations that had been hidden while the user was immersed in reading
3149     * the book.
3150     *
3151     * @see #setSystemUiVisibility(int)
3152     */
3153    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
3154
3155    /**
3156     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
3157     * flags, we would like a stable view of the content insets given to
3158     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
3159     * will always represent the worst case that the application can expect
3160     * as a continuous state.  In the stock Android UI this is the space for
3161     * the system bar, nav bar, and status bar, but not more transient elements
3162     * such as an input method.
3163     *
3164     * The stable layout your UI sees is based on the system UI modes you can
3165     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
3166     * then you will get a stable layout for changes of the
3167     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
3168     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
3169     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
3170     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
3171     * with a stable layout.  (Note that you should avoid using
3172     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
3173     *
3174     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
3175     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
3176     * then a hidden status bar will be considered a "stable" state for purposes
3177     * here.  This allows your UI to continually hide the status bar, while still
3178     * using the system UI flags to hide the action bar while still retaining
3179     * a stable layout.  Note that changing the window fullscreen flag will never
3180     * provide a stable layout for a clean transition.
3181     *
3182     * <p>If you are using ActionBar in
3183     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
3184     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
3185     * insets it adds to those given to the application.
3186     */
3187    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
3188
3189    /**
3190     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
3191     * to be laid out as if it has requested
3192     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
3193     * allows it to avoid artifacts when switching in and out of that mode, at
3194     * the expense that some of its user interface may be covered by screen
3195     * decorations when they are shown.  You can perform layout of your inner
3196     * UI elements to account for the navigation system UI through the
3197     * {@link #fitSystemWindows(Rect)} method.
3198     */
3199    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
3200
3201    /**
3202     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
3203     * to be laid out as if it has requested
3204     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
3205     * allows it to avoid artifacts when switching in and out of that mode, at
3206     * the expense that some of its user interface may be covered by screen
3207     * decorations when they are shown.  You can perform layout of your inner
3208     * UI elements to account for non-fullscreen system UI through the
3209     * {@link #fitSystemWindows(Rect)} method.
3210     */
3211    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
3212
3213    /**
3214     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
3215     * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  If this flag is
3216     * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any
3217     * user interaction.
3218     * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only
3219     * has an effect when used in combination with that flag.</p>
3220     */
3221    public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800;
3222
3223    /**
3224     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
3225     * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation
3226     * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  Use this flag to create an immersive
3227     * experience while also hiding the system bars.  If this flag is not set,
3228     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user
3229     * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system
3230     * if the user swipes from the top of the screen.
3231     * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with
3232     * system gestures, such as swiping from the top of the screen.  These transient system bars
3233     * will overlay app’s content, may have some degree of transparency, and will automatically
3234     * hide after a short timeout.
3235     * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and
3236     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination
3237     * with one or both of those flags.</p>
3238     */
3239    public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000;
3240
3241    /**
3242     * Flag for {@link #setSystemUiVisibility(int)}: Requests the status bar to draw in a mode that
3243     * is compatible with light status bar backgrounds.
3244     *
3245     * <p>For this to take effect, the window must request
3246     * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS
3247     *         FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not
3248     * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_STATUS
3249     *         FLAG_TRANSLUCENT_STATUS}.
3250     *
3251     * @see android.R.attr#windowLightStatusBar
3252     */
3253    public static final int SYSTEM_UI_FLAG_LIGHT_STATUS_BAR = 0x00002000;
3254
3255    /**
3256     * This flag was previously used for a private API. DO NOT reuse it for a public API as it might
3257     * trigger undefined behavior on older platforms with apps compiled against a new SDK.
3258     */
3259    private static final int SYSTEM_UI_RESERVED_LEGACY1 = 0x00004000;
3260
3261    /**
3262     * This flag was previously used for a private API. DO NOT reuse it for a public API as it might
3263     * trigger undefined behavior on older platforms with apps compiled against a new SDK.
3264     */
3265    private static final int SYSTEM_UI_RESERVED_LEGACY2 = 0x00010000;
3266
3267    /**
3268     * Flag for {@link #setSystemUiVisibility(int)}: Requests the navigation bar to draw in a mode
3269     * that is compatible with light navigation bar backgrounds.
3270     *
3271     * <p>For this to take effect, the window must request
3272     * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS
3273     *         FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not
3274     * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_NAVIGATION
3275     *         FLAG_TRANSLUCENT_NAVIGATION}.
3276     */
3277    public static final int SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR = 0x00000010;
3278
3279    /**
3280     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
3281     */
3282    @Deprecated
3283    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
3284
3285    /**
3286     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
3287     */
3288    @Deprecated
3289    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
3290
3291    /**
3292     * @hide
3293     *
3294     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3295     * out of the public fields to keep the undefined bits out of the developer's way.
3296     *
3297     * Flag to make the status bar not expandable.  Unless you also
3298     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
3299     */
3300    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
3301
3302    /**
3303     * @hide
3304     *
3305     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3306     * out of the public fields to keep the undefined bits out of the developer's way.
3307     *
3308     * Flag to hide notification icons and scrolling ticker text.
3309     */
3310    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
3311
3312    /**
3313     * @hide
3314     *
3315     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3316     * out of the public fields to keep the undefined bits out of the developer's way.
3317     *
3318     * Flag to disable incoming notification alerts.  This will not block
3319     * icons, but it will block sound, vibrating and other visual or aural notifications.
3320     */
3321    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
3322
3323    /**
3324     * @hide
3325     *
3326     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3327     * out of the public fields to keep the undefined bits out of the developer's way.
3328     *
3329     * Flag to hide only the scrolling ticker.  Note that
3330     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
3331     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
3332     */
3333    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
3334
3335    /**
3336     * @hide
3337     *
3338     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3339     * out of the public fields to keep the undefined bits out of the developer's way.
3340     *
3341     * Flag to hide the center system info area.
3342     */
3343    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
3344
3345    /**
3346     * @hide
3347     *
3348     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3349     * out of the public fields to keep the undefined bits out of the developer's way.
3350     *
3351     * Flag to hide only the home button.  Don't use this
3352     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3353     */
3354    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
3355
3356    /**
3357     * @hide
3358     *
3359     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3360     * out of the public fields to keep the undefined bits out of the developer's way.
3361     *
3362     * Flag to hide only the back button. Don't use this
3363     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3364     */
3365    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
3366
3367    /**
3368     * @hide
3369     *
3370     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3371     * out of the public fields to keep the undefined bits out of the developer's way.
3372     *
3373     * Flag to hide only the clock.  You might use this if your activity has
3374     * its own clock making the status bar's clock redundant.
3375     */
3376    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
3377
3378    /**
3379     * @hide
3380     *
3381     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3382     * out of the public fields to keep the undefined bits out of the developer's way.
3383     *
3384     * Flag to hide only the recent apps button. Don't use this
3385     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3386     */
3387    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
3388
3389    /**
3390     * @hide
3391     *
3392     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3393     * out of the public fields to keep the undefined bits out of the developer's way.
3394     *
3395     * Flag to disable the global search gesture. Don't use this
3396     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3397     */
3398    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
3399
3400    /**
3401     * @hide
3402     *
3403     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3404     * out of the public fields to keep the undefined bits out of the developer's way.
3405     *
3406     * Flag to specify that the status bar is displayed in transient mode.
3407     */
3408    public static final int STATUS_BAR_TRANSIENT = 0x04000000;
3409
3410    /**
3411     * @hide
3412     *
3413     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3414     * out of the public fields to keep the undefined bits out of the developer's way.
3415     *
3416     * Flag to specify that the navigation bar is displayed in transient mode.
3417     */
3418    public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000;
3419
3420    /**
3421     * @hide
3422     *
3423     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3424     * out of the public fields to keep the undefined bits out of the developer's way.
3425     *
3426     * Flag to specify that the hidden status bar would like to be shown.
3427     */
3428    public static final int STATUS_BAR_UNHIDE = 0x10000000;
3429
3430    /**
3431     * @hide
3432     *
3433     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3434     * out of the public fields to keep the undefined bits out of the developer's way.
3435     *
3436     * Flag to specify that the hidden navigation bar would like to be shown.
3437     */
3438    public static final int NAVIGATION_BAR_UNHIDE = 0x20000000;
3439
3440    /**
3441     * @hide
3442     *
3443     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3444     * out of the public fields to keep the undefined bits out of the developer's way.
3445     *
3446     * Flag to specify that the status bar is displayed in translucent mode.
3447     */
3448    public static final int STATUS_BAR_TRANSLUCENT = 0x40000000;
3449
3450    /**
3451     * @hide
3452     *
3453     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3454     * out of the public fields to keep the undefined bits out of the developer's way.
3455     *
3456     * Flag to specify that the navigation bar is displayed in translucent mode.
3457     */
3458    public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000;
3459
3460    /**
3461     * @hide
3462     *
3463     * Makes navigation bar transparent (but not the status bar).
3464     */
3465    public static final int NAVIGATION_BAR_TRANSPARENT = 0x00008000;
3466
3467    /**
3468     * @hide
3469     *
3470     * Makes status bar transparent (but not the navigation bar).
3471     */
3472    public static final int STATUS_BAR_TRANSPARENT = 0x00000008;
3473
3474    /**
3475     * @hide
3476     *
3477     * Makes both status bar and navigation bar transparent.
3478     */
3479    public static final int SYSTEM_UI_TRANSPARENT = NAVIGATION_BAR_TRANSPARENT
3480            | STATUS_BAR_TRANSPARENT;
3481
3482    /**
3483     * @hide
3484     */
3485    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FF7;
3486
3487    /**
3488     * These are the system UI flags that can be cleared by events outside
3489     * of an application.  Currently this is just the ability to tap on the
3490     * screen while hiding the navigation bar to have it return.
3491     * @hide
3492     */
3493    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
3494            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
3495            | SYSTEM_UI_FLAG_FULLSCREEN;
3496
3497    /**
3498     * Flags that can impact the layout in relation to system UI.
3499     */
3500    public static final int SYSTEM_UI_LAYOUT_FLAGS =
3501            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
3502            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
3503
3504    /** @hide */
3505    @IntDef(flag = true,
3506            value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION })
3507    @Retention(RetentionPolicy.SOURCE)
3508    public @interface FindViewFlags {}
3509
3510    /**
3511     * Find views that render the specified text.
3512     *
3513     * @see #findViewsWithText(ArrayList, CharSequence, int)
3514     */
3515    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
3516
3517    /**
3518     * Find find views that contain the specified content description.
3519     *
3520     * @see #findViewsWithText(ArrayList, CharSequence, int)
3521     */
3522    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
3523
3524    /**
3525     * Find views that contain {@link AccessibilityNodeProvider}. Such
3526     * a View is a root of virtual view hierarchy and may contain the searched
3527     * text. If this flag is set Views with providers are automatically
3528     * added and it is a responsibility of the client to call the APIs of
3529     * the provider to determine whether the virtual tree rooted at this View
3530     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
3531     * representing the virtual views with this text.
3532     *
3533     * @see #findViewsWithText(ArrayList, CharSequence, int)
3534     *
3535     * @hide
3536     */
3537    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
3538
3539    /**
3540     * The undefined cursor position.
3541     *
3542     * @hide
3543     */
3544    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
3545
3546    /**
3547     * Indicates that the screen has changed state and is now off.
3548     *
3549     * @see #onScreenStateChanged(int)
3550     */
3551    public static final int SCREEN_STATE_OFF = 0x0;
3552
3553    /**
3554     * Indicates that the screen has changed state and is now on.
3555     *
3556     * @see #onScreenStateChanged(int)
3557     */
3558    public static final int SCREEN_STATE_ON = 0x1;
3559
3560    /**
3561     * Indicates no axis of view scrolling.
3562     */
3563    public static final int SCROLL_AXIS_NONE = 0;
3564
3565    /**
3566     * Indicates scrolling along the horizontal axis.
3567     */
3568    public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0;
3569
3570    /**
3571     * Indicates scrolling along the vertical axis.
3572     */
3573    public static final int SCROLL_AXIS_VERTICAL = 1 << 1;
3574
3575    /**
3576     * Controls the over-scroll mode for this view.
3577     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
3578     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
3579     * and {@link #OVER_SCROLL_NEVER}.
3580     */
3581    private int mOverScrollMode;
3582
3583    /**
3584     * The parent this view is attached to.
3585     * {@hide}
3586     *
3587     * @see #getParent()
3588     */
3589    protected ViewParent mParent;
3590
3591    /**
3592     * {@hide}
3593     */
3594    AttachInfo mAttachInfo;
3595
3596    /**
3597     * {@hide}
3598     */
3599    @ViewDebug.ExportedProperty(flagMapping = {
3600        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
3601                name = "FORCE_LAYOUT"),
3602        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
3603                name = "LAYOUT_REQUIRED"),
3604        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
3605            name = "DRAWING_CACHE_INVALID", outputIf = false),
3606        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
3607        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
3608        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
3609        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
3610    }, formatToHexString = true)
3611
3612    /* @hide */
3613    public int mPrivateFlags;
3614    int mPrivateFlags2;
3615    int mPrivateFlags3;
3616
3617    /**
3618     * This view's request for the visibility of the status bar.
3619     * @hide
3620     */
3621    @ViewDebug.ExportedProperty(flagMapping = {
3622        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
3623                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
3624                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
3625        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
3626                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
3627                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
3628        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
3629                                equals = SYSTEM_UI_FLAG_VISIBLE,
3630                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
3631    }, formatToHexString = true)
3632    int mSystemUiVisibility;
3633
3634    /**
3635     * Reference count for transient state.
3636     * @see #setHasTransientState(boolean)
3637     */
3638    int mTransientStateCount = 0;
3639
3640    /**
3641     * Count of how many windows this view has been attached to.
3642     */
3643    int mWindowAttachCount;
3644
3645    /**
3646     * The layout parameters associated with this view and used by the parent
3647     * {@link android.view.ViewGroup} to determine how this view should be
3648     * laid out.
3649     * {@hide}
3650     */
3651    protected ViewGroup.LayoutParams mLayoutParams;
3652
3653    /**
3654     * The view flags hold various views states.
3655     * {@hide}
3656     */
3657    @ViewDebug.ExportedProperty(formatToHexString = true)
3658    int mViewFlags;
3659
3660    static class TransformationInfo {
3661        /**
3662         * The transform matrix for the View. This transform is calculated internally
3663         * based on the translation, rotation, and scale properties.
3664         *
3665         * Do *not* use this variable directly; instead call getMatrix(), which will
3666         * load the value from the View's RenderNode.
3667         */
3668        private final Matrix mMatrix = new Matrix();
3669
3670        /**
3671         * The inverse transform matrix for the View. This transform is calculated
3672         * internally based on the translation, rotation, and scale properties.
3673         *
3674         * Do *not* use this variable directly; instead call getInverseMatrix(),
3675         * which will load the value from the View's RenderNode.
3676         */
3677        private Matrix mInverseMatrix;
3678
3679        /**
3680         * The opacity of the View. This is a value from 0 to 1, where 0 means
3681         * completely transparent and 1 means completely opaque.
3682         */
3683        @ViewDebug.ExportedProperty
3684        float mAlpha = 1f;
3685
3686        /**
3687         * The opacity of the view as manipulated by the Fade transition. This is a hidden
3688         * property only used by transitions, which is composited with the other alpha
3689         * values to calculate the final visual alpha value.
3690         */
3691        float mTransitionAlpha = 1f;
3692    }
3693
3694    /** @hide */
3695    public TransformationInfo mTransformationInfo;
3696
3697    /**
3698     * Current clip bounds. to which all drawing of this view are constrained.
3699     */
3700    Rect mClipBounds = null;
3701
3702    private boolean mLastIsOpaque;
3703
3704    /**
3705     * The distance in pixels from the left edge of this view's parent
3706     * to the left edge of this view.
3707     * {@hide}
3708     */
3709    @ViewDebug.ExportedProperty(category = "layout")
3710    protected int mLeft;
3711    /**
3712     * The distance in pixels from the left edge of this view's parent
3713     * to the right edge of this view.
3714     * {@hide}
3715     */
3716    @ViewDebug.ExportedProperty(category = "layout")
3717    protected int mRight;
3718    /**
3719     * The distance in pixels from the top edge of this view's parent
3720     * to the top edge of this view.
3721     * {@hide}
3722     */
3723    @ViewDebug.ExportedProperty(category = "layout")
3724    protected int mTop;
3725    /**
3726     * The distance in pixels from the top edge of this view's parent
3727     * to the bottom edge of this view.
3728     * {@hide}
3729     */
3730    @ViewDebug.ExportedProperty(category = "layout")
3731    protected int mBottom;
3732
3733    /**
3734     * The offset, in pixels, by which the content of this view is scrolled
3735     * horizontally.
3736     * {@hide}
3737     */
3738    @ViewDebug.ExportedProperty(category = "scrolling")
3739    protected int mScrollX;
3740    /**
3741     * The offset, in pixels, by which the content of this view is scrolled
3742     * vertically.
3743     * {@hide}
3744     */
3745    @ViewDebug.ExportedProperty(category = "scrolling")
3746    protected int mScrollY;
3747
3748    /**
3749     * The left padding in pixels, that is the distance in pixels between the
3750     * left edge of this view and the left edge of its content.
3751     * {@hide}
3752     */
3753    @ViewDebug.ExportedProperty(category = "padding")
3754    protected int mPaddingLeft = 0;
3755    /**
3756     * The right padding in pixels, that is the distance in pixels between the
3757     * right edge of this view and the right edge of its content.
3758     * {@hide}
3759     */
3760    @ViewDebug.ExportedProperty(category = "padding")
3761    protected int mPaddingRight = 0;
3762    /**
3763     * The top padding in pixels, that is the distance in pixels between the
3764     * top edge of this view and the top edge of its content.
3765     * {@hide}
3766     */
3767    @ViewDebug.ExportedProperty(category = "padding")
3768    protected int mPaddingTop;
3769    /**
3770     * The bottom padding in pixels, that is the distance in pixels between the
3771     * bottom edge of this view and the bottom edge of its content.
3772     * {@hide}
3773     */
3774    @ViewDebug.ExportedProperty(category = "padding")
3775    protected int mPaddingBottom;
3776
3777    /**
3778     * The layout insets in pixels, that is the distance in pixels between the
3779     * visible edges of this view its bounds.
3780     */
3781    private Insets mLayoutInsets;
3782
3783    /**
3784     * Briefly describes the view and is primarily used for accessibility support.
3785     */
3786    private CharSequence mContentDescription;
3787
3788    /**
3789     * Specifies the id of a view for which this view serves as a label for
3790     * accessibility purposes.
3791     */
3792    private int mLabelForId = View.NO_ID;
3793
3794    /**
3795     * Predicate for matching labeled view id with its label for
3796     * accessibility purposes.
3797     */
3798    private MatchLabelForPredicate mMatchLabelForPredicate;
3799
3800    /**
3801     * Specifies a view before which this one is visited in accessibility traversal.
3802     */
3803    private int mAccessibilityTraversalBeforeId = NO_ID;
3804
3805    /**
3806     * Specifies a view after which this one is visited in accessibility traversal.
3807     */
3808    private int mAccessibilityTraversalAfterId = NO_ID;
3809
3810    /**
3811     * Predicate for matching a view by its id.
3812     */
3813    private MatchIdPredicate mMatchIdPredicate;
3814
3815    /**
3816     * Cache the paddingRight set by the user to append to the scrollbar's size.
3817     *
3818     * @hide
3819     */
3820    @ViewDebug.ExportedProperty(category = "padding")
3821    protected int mUserPaddingRight;
3822
3823    /**
3824     * Cache the paddingBottom set by the user to append to the scrollbar's size.
3825     *
3826     * @hide
3827     */
3828    @ViewDebug.ExportedProperty(category = "padding")
3829    protected int mUserPaddingBottom;
3830
3831    /**
3832     * Cache the paddingLeft set by the user to append to the scrollbar's size.
3833     *
3834     * @hide
3835     */
3836    @ViewDebug.ExportedProperty(category = "padding")
3837    protected int mUserPaddingLeft;
3838
3839    /**
3840     * Cache the paddingStart set by the user to append to the scrollbar's size.
3841     *
3842     */
3843    @ViewDebug.ExportedProperty(category = "padding")
3844    int mUserPaddingStart;
3845
3846    /**
3847     * Cache the paddingEnd set by the user to append to the scrollbar's size.
3848     *
3849     */
3850    @ViewDebug.ExportedProperty(category = "padding")
3851    int mUserPaddingEnd;
3852
3853    /**
3854     * Cache initial left padding.
3855     *
3856     * @hide
3857     */
3858    int mUserPaddingLeftInitial;
3859
3860    /**
3861     * Cache initial right padding.
3862     *
3863     * @hide
3864     */
3865    int mUserPaddingRightInitial;
3866
3867    /**
3868     * Default undefined padding
3869     */
3870    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
3871
3872    /**
3873     * Cache if a left padding has been defined
3874     */
3875    private boolean mLeftPaddingDefined = false;
3876
3877    /**
3878     * Cache if a right padding has been defined
3879     */
3880    private boolean mRightPaddingDefined = false;
3881
3882    /**
3883     * @hide
3884     */
3885    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
3886    /**
3887     * @hide
3888     */
3889    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
3890
3891    private LongSparseLongArray mMeasureCache;
3892
3893    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
3894    private Drawable mBackground;
3895    private TintInfo mBackgroundTint;
3896
3897    @ViewDebug.ExportedProperty(deepExport = true, prefix = "fg_")
3898    private ForegroundInfo mForegroundInfo;
3899
3900    private Drawable mScrollIndicatorDrawable;
3901
3902    /**
3903     * RenderNode used for backgrounds.
3904     * <p>
3905     * When non-null and valid, this is expected to contain an up-to-date copy
3906     * of the background drawable. It is cleared on temporary detach, and reset
3907     * on cleanup.
3908     */
3909    private RenderNode mBackgroundRenderNode;
3910
3911    private int mBackgroundResource;
3912    private boolean mBackgroundSizeChanged;
3913
3914    private String mTransitionName;
3915
3916    static class TintInfo {
3917        ColorStateList mTintList;
3918        PorterDuff.Mode mTintMode;
3919        boolean mHasTintMode;
3920        boolean mHasTintList;
3921    }
3922
3923    private static class ForegroundInfo {
3924        private Drawable mDrawable;
3925        private TintInfo mTintInfo;
3926        private int mGravity = Gravity.FILL;
3927        private boolean mInsidePadding = true;
3928        private boolean mBoundsChanged = true;
3929        private final Rect mSelfBounds = new Rect();
3930        private final Rect mOverlayBounds = new Rect();
3931    }
3932
3933    static class ListenerInfo {
3934        /**
3935         * Listener used to dispatch focus change events.
3936         * This field should be made private, so it is hidden from the SDK.
3937         * {@hide}
3938         */
3939        protected OnFocusChangeListener mOnFocusChangeListener;
3940
3941        /**
3942         * Listeners for layout change events.
3943         */
3944        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
3945
3946        protected OnScrollChangeListener mOnScrollChangeListener;
3947
3948        /**
3949         * Listeners for attach events.
3950         */
3951        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
3952
3953        /**
3954         * Listener used to dispatch click events.
3955         * This field should be made private, so it is hidden from the SDK.
3956         * {@hide}
3957         */
3958        public OnClickListener mOnClickListener;
3959
3960        /**
3961         * Listener used to dispatch long click events.
3962         * This field should be made private, so it is hidden from the SDK.
3963         * {@hide}
3964         */
3965        protected OnLongClickListener mOnLongClickListener;
3966
3967        /**
3968         * Listener used to dispatch context click events. This field should be made private, so it
3969         * is hidden from the SDK.
3970         * {@hide}
3971         */
3972        protected OnContextClickListener mOnContextClickListener;
3973
3974        /**
3975         * Listener used to build the context menu.
3976         * This field should be made private, so it is hidden from the SDK.
3977         * {@hide}
3978         */
3979        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
3980
3981        private OnKeyListener mOnKeyListener;
3982
3983        private OnTouchListener mOnTouchListener;
3984
3985        private OnHoverListener mOnHoverListener;
3986
3987        private OnGenericMotionListener mOnGenericMotionListener;
3988
3989        private OnDragListener mOnDragListener;
3990
3991        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
3992
3993        OnApplyWindowInsetsListener mOnApplyWindowInsetsListener;
3994
3995        OnCapturedPointerListener mOnCapturedPointerListener;
3996    }
3997
3998    ListenerInfo mListenerInfo;
3999
4000    private static class TooltipInfo {
4001        /**
4002         * Text to be displayed in a tooltip popup.
4003         */
4004        @Nullable
4005        CharSequence mTooltipText;
4006
4007        /**
4008         * View-relative position of the tooltip anchor point.
4009         */
4010        int mAnchorX;
4011        int mAnchorY;
4012
4013        /**
4014         * The tooltip popup.
4015         */
4016        @Nullable
4017        TooltipPopup mTooltipPopup;
4018
4019        /**
4020         * Set to true if the tooltip was shown as a result of a long click.
4021         */
4022        boolean mTooltipFromLongClick;
4023
4024        /**
4025         * Keep these Runnables so that they can be used to reschedule.
4026         */
4027        Runnable mShowTooltipRunnable;
4028        Runnable mHideTooltipRunnable;
4029    }
4030
4031    TooltipInfo mTooltipInfo;
4032
4033    // Temporary values used to hold (x,y) coordinates when delegating from the
4034    // two-arg performLongClick() method to the legacy no-arg version.
4035    private float mLongClickX = Float.NaN;
4036    private float mLongClickY = Float.NaN;
4037
4038    /**
4039     * The application environment this view lives in.
4040     * This field should be made private, so it is hidden from the SDK.
4041     * {@hide}
4042     */
4043    @ViewDebug.ExportedProperty(deepExport = true)
4044    protected Context mContext;
4045
4046    private final Resources mResources;
4047
4048    private ScrollabilityCache mScrollCache;
4049
4050    private int[] mDrawableState = null;
4051
4052    ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND;
4053
4054    /**
4055     * Animator that automatically runs based on state changes.
4056     */
4057    private StateListAnimator mStateListAnimator;
4058
4059    /**
4060     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
4061     * the user may specify which view to go to next.
4062     */
4063    private int mNextFocusLeftId = View.NO_ID;
4064
4065    /**
4066     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
4067     * the user may specify which view to go to next.
4068     */
4069    private int mNextFocusRightId = View.NO_ID;
4070
4071    /**
4072     * When this view has focus and the next focus is {@link #FOCUS_UP},
4073     * the user may specify which view to go to next.
4074     */
4075    private int mNextFocusUpId = View.NO_ID;
4076
4077    /**
4078     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
4079     * the user may specify which view to go to next.
4080     */
4081    private int mNextFocusDownId = View.NO_ID;
4082
4083    /**
4084     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
4085     * the user may specify which view to go to next.
4086     */
4087    int mNextFocusForwardId = View.NO_ID;
4088
4089    /**
4090     * User-specified next keyboard navigation cluster in the {@link #FOCUS_FORWARD} direction.
4091     *
4092     * @see #findUserSetNextKeyboardNavigationCluster(View, int)
4093     */
4094    int mNextClusterForwardId = View.NO_ID;
4095
4096    private CheckForLongPress mPendingCheckForLongPress;
4097    private CheckForTap mPendingCheckForTap = null;
4098    private PerformClick mPerformClick;
4099    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
4100
4101    private UnsetPressedState mUnsetPressedState;
4102
4103    /**
4104     * Whether the long press's action has been invoked.  The tap's action is invoked on the
4105     * up event while a long press is invoked as soon as the long press duration is reached, so
4106     * a long press could be performed before the tap is checked, in which case the tap's action
4107     * should not be invoked.
4108     */
4109    private boolean mHasPerformedLongPress;
4110
4111    /**
4112     * Whether a context click button is currently pressed down. This is true when the stylus is
4113     * touching the screen and the primary button has been pressed, or if a mouse's right button is
4114     * pressed. This is false once the button is released or if the stylus has been lifted.
4115     */
4116    private boolean mInContextButtonPress;
4117
4118    /**
4119     * Whether the next up event should be ignored for the purposes of gesture recognition. This is
4120     * true after a stylus button press has occured, when the next up event should not be recognized
4121     * as a tap.
4122     */
4123    private boolean mIgnoreNextUpEvent;
4124
4125    /**
4126     * The minimum height of the view. We'll try our best to have the height
4127     * of this view to at least this amount.
4128     */
4129    @ViewDebug.ExportedProperty(category = "measurement")
4130    private int mMinHeight;
4131
4132    /**
4133     * The minimum width of the view. We'll try our best to have the width
4134     * of this view to at least this amount.
4135     */
4136    @ViewDebug.ExportedProperty(category = "measurement")
4137    private int mMinWidth;
4138
4139    /**
4140     * The delegate to handle touch events that are physically in this view
4141     * but should be handled by another view.
4142     */
4143    private TouchDelegate mTouchDelegate = null;
4144
4145    /**
4146     * Solid color to use as a background when creating the drawing cache. Enables
4147     * the cache to use 16 bit bitmaps instead of 32 bit.
4148     */
4149    private int mDrawingCacheBackgroundColor = 0;
4150
4151    /**
4152     * Special tree observer used when mAttachInfo is null.
4153     */
4154    private ViewTreeObserver mFloatingTreeObserver;
4155
4156    /**
4157     * Cache the touch slop from the context that created the view.
4158     */
4159    private int mTouchSlop;
4160
4161    /**
4162     * Object that handles automatic animation of view properties.
4163     */
4164    private ViewPropertyAnimator mAnimator = null;
4165
4166    /**
4167     * List of registered FrameMetricsObservers.
4168     */
4169    private ArrayList<FrameMetricsObserver> mFrameMetricsObservers;
4170
4171    /**
4172     * Flag indicating that a drag can cross window boundaries.  When
4173     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called
4174     * with this flag set, all visible applications with targetSdkVersion >=
4175     * {@link android.os.Build.VERSION_CODES#N API 24} will be able to participate
4176     * in the drag operation and receive the dragged content.
4177     *
4178     * <p>If this is the only flag set, then the drag recipient will only have access to text data
4179     * and intents contained in the {@link ClipData} object. Access to URIs contained in the
4180     * {@link ClipData} is determined by other DRAG_FLAG_GLOBAL_* flags</p>
4181     */
4182    public static final int DRAG_FLAG_GLOBAL = 1 << 8;  // 256
4183
4184    /**
4185     * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to
4186     * request read access to the content URI(s) contained in the {@link ClipData} object.
4187     * @see android.content.Intent#FLAG_GRANT_READ_URI_PERMISSION
4188     */
4189    public static final int DRAG_FLAG_GLOBAL_URI_READ = Intent.FLAG_GRANT_READ_URI_PERMISSION;
4190
4191    /**
4192     * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to
4193     * request write access to the content URI(s) contained in the {@link ClipData} object.
4194     * @see android.content.Intent#FLAG_GRANT_WRITE_URI_PERMISSION
4195     */
4196    public static final int DRAG_FLAG_GLOBAL_URI_WRITE = Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
4197
4198    /**
4199     * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link
4200     * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant can be persisted across device
4201     * reboots until explicitly revoked with
4202     * {@link android.content.Context#revokeUriPermission(Uri, int)} Context.revokeUriPermission}.
4203     * @see android.content.Intent#FLAG_GRANT_PERSISTABLE_URI_PERMISSION
4204     */
4205    public static final int DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION =
4206            Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION;
4207
4208    /**
4209     * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link
4210     * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant applies to any URI that is a prefix
4211     * match against the original granted URI.
4212     * @see android.content.Intent#FLAG_GRANT_PREFIX_URI_PERMISSION
4213     */
4214    public static final int DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION =
4215            Intent.FLAG_GRANT_PREFIX_URI_PERMISSION;
4216
4217    /**
4218     * Flag indicating that the drag shadow will be opaque.  When
4219     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called
4220     * with this flag set, the drag shadow will be opaque, otherwise, it will be semitransparent.
4221     */
4222    public static final int DRAG_FLAG_OPAQUE = 1 << 9;
4223
4224    /**
4225     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
4226     */
4227    private float mVerticalScrollFactor;
4228
4229    /**
4230     * Position of the vertical scroll bar.
4231     */
4232    private int mVerticalScrollbarPosition;
4233
4234    /**
4235     * Position the scroll bar at the default position as determined by the system.
4236     */
4237    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
4238
4239    /**
4240     * Position the scroll bar along the left edge.
4241     */
4242    public static final int SCROLLBAR_POSITION_LEFT = 1;
4243
4244    /**
4245     * Position the scroll bar along the right edge.
4246     */
4247    public static final int SCROLLBAR_POSITION_RIGHT = 2;
4248
4249    /**
4250     * Indicates that the view does not have a layer.
4251     *
4252     * @see #getLayerType()
4253     * @see #setLayerType(int, android.graphics.Paint)
4254     * @see #LAYER_TYPE_SOFTWARE
4255     * @see #LAYER_TYPE_HARDWARE
4256     */
4257    public static final int LAYER_TYPE_NONE = 0;
4258
4259    /**
4260     * <p>Indicates that the view has a software layer. A software layer is backed
4261     * by a bitmap and causes the view to be rendered using Android's software
4262     * rendering pipeline, even if hardware acceleration is enabled.</p>
4263     *
4264     * <p>Software layers have various usages:</p>
4265     * <p>When the application is not using hardware acceleration, a software layer
4266     * is useful to apply a specific color filter and/or blending mode and/or
4267     * translucency to a view and all its children.</p>
4268     * <p>When the application is using hardware acceleration, a software layer
4269     * is useful to render drawing primitives not supported by the hardware
4270     * accelerated pipeline. It can also be used to cache a complex view tree
4271     * into a texture and reduce the complexity of drawing operations. For instance,
4272     * when animating a complex view tree with a translation, a software layer can
4273     * be used to render the view tree only once.</p>
4274     * <p>Software layers should be avoided when the affected view tree updates
4275     * often. Every update will require to re-render the software layer, which can
4276     * potentially be slow (particularly when hardware acceleration is turned on
4277     * since the layer will have to be uploaded into a hardware texture after every
4278     * update.)</p>
4279     *
4280     * @see #getLayerType()
4281     * @see #setLayerType(int, android.graphics.Paint)
4282     * @see #LAYER_TYPE_NONE
4283     * @see #LAYER_TYPE_HARDWARE
4284     */
4285    public static final int LAYER_TYPE_SOFTWARE = 1;
4286
4287    /**
4288     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
4289     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
4290     * OpenGL hardware) and causes the view to be rendered using Android's hardware
4291     * rendering pipeline, but only if hardware acceleration is turned on for the
4292     * view hierarchy. When hardware acceleration is turned off, hardware layers
4293     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
4294     *
4295     * <p>A hardware layer is useful to apply a specific color filter and/or
4296     * blending mode and/or translucency to a view and all its children.</p>
4297     * <p>A hardware layer can be used to cache a complex view tree into a
4298     * texture and reduce the complexity of drawing operations. For instance,
4299     * when animating a complex view tree with a translation, a hardware layer can
4300     * be used to render the view tree only once.</p>
4301     * <p>A hardware layer can also be used to increase the rendering quality when
4302     * rotation transformations are applied on a view. It can also be used to
4303     * prevent potential clipping issues when applying 3D transforms on a view.</p>
4304     *
4305     * @see #getLayerType()
4306     * @see #setLayerType(int, android.graphics.Paint)
4307     * @see #LAYER_TYPE_NONE
4308     * @see #LAYER_TYPE_SOFTWARE
4309     */
4310    public static final int LAYER_TYPE_HARDWARE = 2;
4311
4312    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
4313            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
4314            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
4315            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
4316    })
4317    int mLayerType = LAYER_TYPE_NONE;
4318    Paint mLayerPaint;
4319
4320    /**
4321     * Set to true when drawing cache is enabled and cannot be created.
4322     *
4323     * @hide
4324     */
4325    public boolean mCachingFailed;
4326    private Bitmap mDrawingCache;
4327    private Bitmap mUnscaledDrawingCache;
4328
4329    /**
4330     * RenderNode holding View properties, potentially holding a DisplayList of View content.
4331     * <p>
4332     * When non-null and valid, this is expected to contain an up-to-date copy
4333     * of the View content. Its DisplayList content is cleared on temporary detach and reset on
4334     * cleanup.
4335     */
4336    final RenderNode mRenderNode;
4337
4338    /**
4339     * Set to true when the view is sending hover accessibility events because it
4340     * is the innermost hovered view.
4341     */
4342    private boolean mSendingHoverAccessibilityEvents;
4343
4344    /**
4345     * Delegate for injecting accessibility functionality.
4346     */
4347    AccessibilityDelegate mAccessibilityDelegate;
4348
4349    /**
4350     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
4351     * and add/remove objects to/from the overlay directly through the Overlay methods.
4352     */
4353    ViewOverlay mOverlay;
4354
4355    /**
4356     * The currently active parent view for receiving delegated nested scrolling events.
4357     * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared
4358     * by {@link #stopNestedScroll()} at the same point where we clear
4359     * requestDisallowInterceptTouchEvent.
4360     */
4361    private ViewParent mNestedScrollingParent;
4362
4363    /**
4364     * Consistency verifier for debugging purposes.
4365     * @hide
4366     */
4367    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
4368            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
4369                    new InputEventConsistencyVerifier(this, 0) : null;
4370
4371    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
4372
4373    private int[] mTempNestedScrollConsumed;
4374
4375    /**
4376     * An overlay is going to draw this View instead of being drawn as part of this
4377     * View's parent. mGhostView is the View in the Overlay that must be invalidated
4378     * when this view is invalidated.
4379     */
4380    GhostView mGhostView;
4381
4382    /**
4383     * Holds pairs of adjacent attribute data: attribute name followed by its value.
4384     * @hide
4385     */
4386    @ViewDebug.ExportedProperty(category = "attributes", hasAdjacentMapping = true)
4387    public String[] mAttributes;
4388
4389    /**
4390     * Maps a Resource id to its name.
4391     */
4392    private static SparseArray<String> mAttributeMap;
4393
4394    /**
4395     * Queue of pending runnables. Used to postpone calls to post() until this
4396     * view is attached and has a handler.
4397     */
4398    private HandlerActionQueue mRunQueue;
4399
4400    /**
4401     * The pointer icon when the mouse hovers on this view. The default is null.
4402     */
4403    private PointerIcon mPointerIcon;
4404
4405    /**
4406     * @hide
4407     */
4408    String mStartActivityRequestWho;
4409
4410    @Nullable
4411    private RoundScrollbarRenderer mRoundScrollbarRenderer;
4412
4413    /**
4414     * Simple constructor to use when creating a view from code.
4415     *
4416     * @param context The Context the view is running in, through which it can
4417     *        access the current theme, resources, etc.
4418     */
4419    public View(Context context) {
4420        mContext = context;
4421        mResources = context != null ? context.getResources() : null;
4422        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED | FOCUSABLE_AUTO;
4423        // Set some flags defaults
4424        mPrivateFlags2 =
4425                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
4426                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
4427                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
4428                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
4429                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
4430                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
4431        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
4432        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
4433        mUserPaddingStart = UNDEFINED_PADDING;
4434        mUserPaddingEnd = UNDEFINED_PADDING;
4435        mRenderNode = RenderNode.create(getClass().getName(), this);
4436
4437        if (!sCompatibilityDone && context != null) {
4438            final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
4439
4440            // Older apps may need this compatibility hack for measurement.
4441            sUseBrokenMakeMeasureSpec = targetSdkVersion <= Build.VERSION_CODES.JELLY_BEAN_MR1;
4442
4443            // Older apps expect onMeasure() to always be called on a layout pass, regardless
4444            // of whether a layout was requested on that View.
4445            sIgnoreMeasureCache = targetSdkVersion < Build.VERSION_CODES.KITKAT;
4446
4447            Canvas.sCompatibilityRestore = targetSdkVersion < Build.VERSION_CODES.M;
4448
4449            // In M and newer, our widgets can pass a "hint" value in the size
4450            // for UNSPECIFIED MeasureSpecs. This lets child views of scrolling containers
4451            // know what the expected parent size is going to be, so e.g. list items can size
4452            // themselves at 1/3 the size of their container. It breaks older apps though,
4453            // specifically apps that use some popular open source libraries.
4454            sUseZeroUnspecifiedMeasureSpec = targetSdkVersion < Build.VERSION_CODES.M;
4455
4456            // Old versions of the platform would give different results from
4457            // LinearLayout measurement passes using EXACTLY and non-EXACTLY
4458            // modes, so we always need to run an additional EXACTLY pass.
4459            sAlwaysRemeasureExactly = targetSdkVersion <= Build.VERSION_CODES.M;
4460
4461            // Prior to N, layout params could change without requiring a
4462            // subsequent call to setLayoutParams() and they would usually
4463            // work. Partial layout breaks this assumption.
4464            sLayoutParamsAlwaysChanged = targetSdkVersion <= Build.VERSION_CODES.M;
4465
4466            // Prior to N, TextureView would silently ignore calls to setBackground/setForeground.
4467            // On N+, we throw, but that breaks compatibility with apps that use these methods.
4468            sTextureViewIgnoresDrawableSetters = targetSdkVersion <= Build.VERSION_CODES.M;
4469
4470            // Prior to N, we would drop margins in LayoutParam conversions. The fix triggers bugs
4471            // in apps so we target check it to avoid breaking existing apps.
4472            sPreserveMarginParamsInLayoutParamConversion =
4473                    targetSdkVersion >= Build.VERSION_CODES.N;
4474
4475            sCascadedDragDrop = targetSdkVersion < Build.VERSION_CODES.N;
4476
4477            sHasFocusableExcludeAutoFocusable = targetSdkVersion < Build.VERSION_CODES.O;
4478
4479            sAutoFocusableOffUIThreadWontNotifyParents = targetSdkVersion < Build.VERSION_CODES.O;
4480
4481            sCompatibilityDone = true;
4482        }
4483    }
4484
4485    /**
4486     * Constructor that is called when inflating a view from XML. This is called
4487     * when a view is being constructed from an XML file, supplying attributes
4488     * that were specified in the XML file. This version uses a default style of
4489     * 0, so the only attribute values applied are those in the Context's Theme
4490     * and the given AttributeSet.
4491     *
4492     * <p>
4493     * The method onFinishInflate() will be called after all children have been
4494     * added.
4495     *
4496     * @param context The Context the view is running in, through which it can
4497     *        access the current theme, resources, etc.
4498     * @param attrs The attributes of the XML tag that is inflating the view.
4499     * @see #View(Context, AttributeSet, int)
4500     */
4501    public View(Context context, @Nullable AttributeSet attrs) {
4502        this(context, attrs, 0);
4503    }
4504
4505    /**
4506     * Perform inflation from XML and apply a class-specific base style from a
4507     * theme attribute. This constructor of View allows subclasses to use their
4508     * own base style when they are inflating. For example, a Button class's
4509     * constructor would call this version of the super class constructor and
4510     * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this
4511     * allows the theme's button style to modify all of the base view attributes
4512     * (in particular its background) as well as the Button class's attributes.
4513     *
4514     * @param context The Context the view is running in, through which it can
4515     *        access the current theme, resources, etc.
4516     * @param attrs The attributes of the XML tag that is inflating the view.
4517     * @param defStyleAttr An attribute in the current theme that contains a
4518     *        reference to a style resource that supplies default values for
4519     *        the view. Can be 0 to not look for defaults.
4520     * @see #View(Context, AttributeSet)
4521     */
4522    public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
4523        this(context, attrs, defStyleAttr, 0);
4524    }
4525
4526    /**
4527     * Perform inflation from XML and apply a class-specific base style from a
4528     * theme attribute or style resource. This constructor of View allows
4529     * subclasses to use their own base style when they are inflating.
4530     * <p>
4531     * When determining the final value of a particular attribute, there are
4532     * four inputs that come into play:
4533     * <ol>
4534     * <li>Any attribute values in the given AttributeSet.
4535     * <li>The style resource specified in the AttributeSet (named "style").
4536     * <li>The default style specified by <var>defStyleAttr</var>.
4537     * <li>The default style specified by <var>defStyleRes</var>.
4538     * <li>The base values in this theme.
4539     * </ol>
4540     * <p>
4541     * Each of these inputs is considered in-order, with the first listed taking
4542     * precedence over the following ones. In other words, if in the
4543     * AttributeSet you have supplied <code>&lt;Button * textColor="#ff000000"&gt;</code>
4544     * , then the button's text will <em>always</em> be black, regardless of
4545     * what is specified in any of the styles.
4546     *
4547     * @param context The Context the view is running in, through which it can
4548     *        access the current theme, resources, etc.
4549     * @param attrs The attributes of the XML tag that is inflating the view.
4550     * @param defStyleAttr An attribute in the current theme that contains a
4551     *        reference to a style resource that supplies default values for
4552     *        the view. Can be 0 to not look for defaults.
4553     * @param defStyleRes A resource identifier of a style resource that
4554     *        supplies default values for the view, used only if
4555     *        defStyleAttr is 0 or can not be found in the theme. Can be 0
4556     *        to not look for defaults.
4557     * @see #View(Context, AttributeSet, int)
4558     */
4559    public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
4560        this(context);
4561
4562        final TypedArray a = context.obtainStyledAttributes(
4563                attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes);
4564
4565        if (mDebugViewAttributes) {
4566            saveAttributeData(attrs, a);
4567        }
4568
4569        Drawable background = null;
4570
4571        int leftPadding = -1;
4572        int topPadding = -1;
4573        int rightPadding = -1;
4574        int bottomPadding = -1;
4575        int startPadding = UNDEFINED_PADDING;
4576        int endPadding = UNDEFINED_PADDING;
4577
4578        int padding = -1;
4579        int paddingHorizontal = -1;
4580        int paddingVertical = -1;
4581
4582        int viewFlagValues = 0;
4583        int viewFlagMasks = 0;
4584
4585        boolean setScrollContainer = false;
4586
4587        int x = 0;
4588        int y = 0;
4589
4590        float tx = 0;
4591        float ty = 0;
4592        float tz = 0;
4593        float elevation = 0;
4594        float rotation = 0;
4595        float rotationX = 0;
4596        float rotationY = 0;
4597        float sx = 1f;
4598        float sy = 1f;
4599        boolean transformSet = false;
4600
4601        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
4602        int overScrollMode = mOverScrollMode;
4603        boolean initializeScrollbars = false;
4604        boolean initializeScrollIndicators = false;
4605
4606        boolean startPaddingDefined = false;
4607        boolean endPaddingDefined = false;
4608        boolean leftPaddingDefined = false;
4609        boolean rightPaddingDefined = false;
4610
4611        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
4612
4613        // Set default values.
4614        viewFlagValues |= FOCUSABLE_AUTO;
4615        viewFlagMasks |= FOCUSABLE_AUTO;
4616
4617        final int N = a.getIndexCount();
4618        for (int i = 0; i < N; i++) {
4619            int attr = a.getIndex(i);
4620            switch (attr) {
4621                case com.android.internal.R.styleable.View_background:
4622                    background = a.getDrawable(attr);
4623                    break;
4624                case com.android.internal.R.styleable.View_padding:
4625                    padding = a.getDimensionPixelSize(attr, -1);
4626                    mUserPaddingLeftInitial = padding;
4627                    mUserPaddingRightInitial = padding;
4628                    leftPaddingDefined = true;
4629                    rightPaddingDefined = true;
4630                    break;
4631                case com.android.internal.R.styleable.View_paddingHorizontal:
4632                    paddingHorizontal = a.getDimensionPixelSize(attr, -1);
4633                    mUserPaddingLeftInitial = paddingHorizontal;
4634                    mUserPaddingRightInitial = paddingHorizontal;
4635                    leftPaddingDefined = true;
4636                    rightPaddingDefined = true;
4637                    break;
4638                case com.android.internal.R.styleable.View_paddingVertical:
4639                    paddingVertical = a.getDimensionPixelSize(attr, -1);
4640                    break;
4641                 case com.android.internal.R.styleable.View_paddingLeft:
4642                    leftPadding = a.getDimensionPixelSize(attr, -1);
4643                    mUserPaddingLeftInitial = leftPadding;
4644                    leftPaddingDefined = true;
4645                    break;
4646                case com.android.internal.R.styleable.View_paddingTop:
4647                    topPadding = a.getDimensionPixelSize(attr, -1);
4648                    break;
4649                case com.android.internal.R.styleable.View_paddingRight:
4650                    rightPadding = a.getDimensionPixelSize(attr, -1);
4651                    mUserPaddingRightInitial = rightPadding;
4652                    rightPaddingDefined = true;
4653                    break;
4654                case com.android.internal.R.styleable.View_paddingBottom:
4655                    bottomPadding = a.getDimensionPixelSize(attr, -1);
4656                    break;
4657                case com.android.internal.R.styleable.View_paddingStart:
4658                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
4659                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
4660                    break;
4661                case com.android.internal.R.styleable.View_paddingEnd:
4662                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
4663                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
4664                    break;
4665                case com.android.internal.R.styleable.View_scrollX:
4666                    x = a.getDimensionPixelOffset(attr, 0);
4667                    break;
4668                case com.android.internal.R.styleable.View_scrollY:
4669                    y = a.getDimensionPixelOffset(attr, 0);
4670                    break;
4671                case com.android.internal.R.styleable.View_alpha:
4672                    setAlpha(a.getFloat(attr, 1f));
4673                    break;
4674                case com.android.internal.R.styleable.View_transformPivotX:
4675                    setPivotX(a.getDimension(attr, 0));
4676                    break;
4677                case com.android.internal.R.styleable.View_transformPivotY:
4678                    setPivotY(a.getDimension(attr, 0));
4679                    break;
4680                case com.android.internal.R.styleable.View_translationX:
4681                    tx = a.getDimension(attr, 0);
4682                    transformSet = true;
4683                    break;
4684                case com.android.internal.R.styleable.View_translationY:
4685                    ty = a.getDimension(attr, 0);
4686                    transformSet = true;
4687                    break;
4688                case com.android.internal.R.styleable.View_translationZ:
4689                    tz = a.getDimension(attr, 0);
4690                    transformSet = true;
4691                    break;
4692                case com.android.internal.R.styleable.View_elevation:
4693                    elevation = a.getDimension(attr, 0);
4694                    transformSet = true;
4695                    break;
4696                case com.android.internal.R.styleable.View_rotation:
4697                    rotation = a.getFloat(attr, 0);
4698                    transformSet = true;
4699                    break;
4700                case com.android.internal.R.styleable.View_rotationX:
4701                    rotationX = a.getFloat(attr, 0);
4702                    transformSet = true;
4703                    break;
4704                case com.android.internal.R.styleable.View_rotationY:
4705                    rotationY = a.getFloat(attr, 0);
4706                    transformSet = true;
4707                    break;
4708                case com.android.internal.R.styleable.View_scaleX:
4709                    sx = a.getFloat(attr, 1f);
4710                    transformSet = true;
4711                    break;
4712                case com.android.internal.R.styleable.View_scaleY:
4713                    sy = a.getFloat(attr, 1f);
4714                    transformSet = true;
4715                    break;
4716                case com.android.internal.R.styleable.View_id:
4717                    mID = a.getResourceId(attr, NO_ID);
4718                    break;
4719                case com.android.internal.R.styleable.View_tag:
4720                    mTag = a.getText(attr);
4721                    break;
4722                case com.android.internal.R.styleable.View_fitsSystemWindows:
4723                    if (a.getBoolean(attr, false)) {
4724                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
4725                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
4726                    }
4727                    break;
4728                case com.android.internal.R.styleable.View_focusable:
4729                    viewFlagValues = (viewFlagValues & ~FOCUSABLE_MASK) | getFocusableAttribute(a);
4730                    if ((viewFlagValues & FOCUSABLE_AUTO) == 0) {
4731                        viewFlagMasks |= FOCUSABLE_MASK;
4732                    }
4733                    break;
4734                case com.android.internal.R.styleable.View_focusableInTouchMode:
4735                    if (a.getBoolean(attr, false)) {
4736                        // unset auto focus since focusableInTouchMode implies explicit focusable
4737                        viewFlagValues &= ~FOCUSABLE_AUTO;
4738                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
4739                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
4740                    }
4741                    break;
4742                case com.android.internal.R.styleable.View_clickable:
4743                    if (a.getBoolean(attr, false)) {
4744                        viewFlagValues |= CLICKABLE;
4745                        viewFlagMasks |= CLICKABLE;
4746                    }
4747                    break;
4748                case com.android.internal.R.styleable.View_longClickable:
4749                    if (a.getBoolean(attr, false)) {
4750                        viewFlagValues |= LONG_CLICKABLE;
4751                        viewFlagMasks |= LONG_CLICKABLE;
4752                    }
4753                    break;
4754                case com.android.internal.R.styleable.View_contextClickable:
4755                    if (a.getBoolean(attr, false)) {
4756                        viewFlagValues |= CONTEXT_CLICKABLE;
4757                        viewFlagMasks |= CONTEXT_CLICKABLE;
4758                    }
4759                    break;
4760                case com.android.internal.R.styleable.View_saveEnabled:
4761                    if (!a.getBoolean(attr, true)) {
4762                        viewFlagValues |= SAVE_DISABLED;
4763                        viewFlagMasks |= SAVE_DISABLED_MASK;
4764                    }
4765                    break;
4766                case com.android.internal.R.styleable.View_duplicateParentState:
4767                    if (a.getBoolean(attr, false)) {
4768                        viewFlagValues |= DUPLICATE_PARENT_STATE;
4769                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
4770                    }
4771                    break;
4772                case com.android.internal.R.styleable.View_visibility:
4773                    final int visibility = a.getInt(attr, 0);
4774                    if (visibility != 0) {
4775                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
4776                        viewFlagMasks |= VISIBILITY_MASK;
4777                    }
4778                    break;
4779                case com.android.internal.R.styleable.View_layoutDirection:
4780                    // Clear any layout direction flags (included resolved bits) already set
4781                    mPrivateFlags2 &=
4782                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
4783                    // Set the layout direction flags depending on the value of the attribute
4784                    final int layoutDirection = a.getInt(attr, -1);
4785                    final int value = (layoutDirection != -1) ?
4786                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
4787                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
4788                    break;
4789                case com.android.internal.R.styleable.View_drawingCacheQuality:
4790                    final int cacheQuality = a.getInt(attr, 0);
4791                    if (cacheQuality != 0) {
4792                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
4793                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
4794                    }
4795                    break;
4796                case com.android.internal.R.styleable.View_contentDescription:
4797                    setContentDescription(a.getString(attr));
4798                    break;
4799                case com.android.internal.R.styleable.View_accessibilityTraversalBefore:
4800                    setAccessibilityTraversalBefore(a.getResourceId(attr, NO_ID));
4801                    break;
4802                case com.android.internal.R.styleable.View_accessibilityTraversalAfter:
4803                    setAccessibilityTraversalAfter(a.getResourceId(attr, NO_ID));
4804                    break;
4805                case com.android.internal.R.styleable.View_labelFor:
4806                    setLabelFor(a.getResourceId(attr, NO_ID));
4807                    break;
4808                case com.android.internal.R.styleable.View_soundEffectsEnabled:
4809                    if (!a.getBoolean(attr, true)) {
4810                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
4811                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
4812                    }
4813                    break;
4814                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
4815                    if (!a.getBoolean(attr, true)) {
4816                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
4817                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
4818                    }
4819                    break;
4820                case R.styleable.View_scrollbars:
4821                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
4822                    if (scrollbars != SCROLLBARS_NONE) {
4823                        viewFlagValues |= scrollbars;
4824                        viewFlagMasks |= SCROLLBARS_MASK;
4825                        initializeScrollbars = true;
4826                    }
4827                    break;
4828                //noinspection deprecation
4829                case R.styleable.View_fadingEdge:
4830                    if (targetSdkVersion >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
4831                        // Ignore the attribute starting with ICS
4832                        break;
4833                    }
4834                    // With builds < ICS, fall through and apply fading edges
4835                case R.styleable.View_requiresFadingEdge:
4836                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
4837                    if (fadingEdge != FADING_EDGE_NONE) {
4838                        viewFlagValues |= fadingEdge;
4839                        viewFlagMasks |= FADING_EDGE_MASK;
4840                        initializeFadingEdgeInternal(a);
4841                    }
4842                    break;
4843                case R.styleable.View_scrollbarStyle:
4844                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
4845                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4846                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
4847                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
4848                    }
4849                    break;
4850                case R.styleable.View_isScrollContainer:
4851                    setScrollContainer = true;
4852                    if (a.getBoolean(attr, false)) {
4853                        setScrollContainer(true);
4854                    }
4855                    break;
4856                case com.android.internal.R.styleable.View_keepScreenOn:
4857                    if (a.getBoolean(attr, false)) {
4858                        viewFlagValues |= KEEP_SCREEN_ON;
4859                        viewFlagMasks |= KEEP_SCREEN_ON;
4860                    }
4861                    break;
4862                case R.styleable.View_filterTouchesWhenObscured:
4863                    if (a.getBoolean(attr, false)) {
4864                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
4865                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
4866                    }
4867                    break;
4868                case R.styleable.View_nextFocusLeft:
4869                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
4870                    break;
4871                case R.styleable.View_nextFocusRight:
4872                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
4873                    break;
4874                case R.styleable.View_nextFocusUp:
4875                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
4876                    break;
4877                case R.styleable.View_nextFocusDown:
4878                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
4879                    break;
4880                case R.styleable.View_nextFocusForward:
4881                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
4882                    break;
4883                case R.styleable.View_nextClusterForward:
4884                    mNextClusterForwardId = a.getResourceId(attr, View.NO_ID);
4885                    break;
4886                case R.styleable.View_minWidth:
4887                    mMinWidth = a.getDimensionPixelSize(attr, 0);
4888                    break;
4889                case R.styleable.View_minHeight:
4890                    mMinHeight = a.getDimensionPixelSize(attr, 0);
4891                    break;
4892                case R.styleable.View_onClick:
4893                    if (context.isRestricted()) {
4894                        throw new IllegalStateException("The android:onClick attribute cannot "
4895                                + "be used within a restricted context");
4896                    }
4897
4898                    final String handlerName = a.getString(attr);
4899                    if (handlerName != null) {
4900                        setOnClickListener(new DeclaredOnClickListener(this, handlerName));
4901                    }
4902                    break;
4903                case R.styleable.View_overScrollMode:
4904                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
4905                    break;
4906                case R.styleable.View_verticalScrollbarPosition:
4907                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
4908                    break;
4909                case R.styleable.View_layerType:
4910                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
4911                    break;
4912                case R.styleable.View_textDirection:
4913                    // Clear any text direction flag already set
4914                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
4915                    // Set the text direction flags depending on the value of the attribute
4916                    final int textDirection = a.getInt(attr, -1);
4917                    if (textDirection != -1) {
4918                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
4919                    }
4920                    break;
4921                case R.styleable.View_textAlignment:
4922                    // Clear any text alignment flag already set
4923                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
4924                    // Set the text alignment flag depending on the value of the attribute
4925                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
4926                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
4927                    break;
4928                case R.styleable.View_importantForAccessibility:
4929                    setImportantForAccessibility(a.getInt(attr,
4930                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
4931                    break;
4932                case R.styleable.View_accessibilityLiveRegion:
4933                    setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT));
4934                    break;
4935                case R.styleable.View_transitionName:
4936                    setTransitionName(a.getString(attr));
4937                    break;
4938                case R.styleable.View_nestedScrollingEnabled:
4939                    setNestedScrollingEnabled(a.getBoolean(attr, false));
4940                    break;
4941                case R.styleable.View_stateListAnimator:
4942                    setStateListAnimator(AnimatorInflater.loadStateListAnimator(context,
4943                            a.getResourceId(attr, 0)));
4944                    break;
4945                case R.styleable.View_backgroundTint:
4946                    // This will get applied later during setBackground().
4947                    if (mBackgroundTint == null) {
4948                        mBackgroundTint = new TintInfo();
4949                    }
4950                    mBackgroundTint.mTintList = a.getColorStateList(
4951                            R.styleable.View_backgroundTint);
4952                    mBackgroundTint.mHasTintList = true;
4953                    break;
4954                case R.styleable.View_backgroundTintMode:
4955                    // This will get applied later during setBackground().
4956                    if (mBackgroundTint == null) {
4957                        mBackgroundTint = new TintInfo();
4958                    }
4959                    mBackgroundTint.mTintMode = Drawable.parseTintMode(a.getInt(
4960                            R.styleable.View_backgroundTintMode, -1), null);
4961                    mBackgroundTint.mHasTintMode = true;
4962                    break;
4963                case R.styleable.View_outlineProvider:
4964                    setOutlineProviderFromAttribute(a.getInt(R.styleable.View_outlineProvider,
4965                            PROVIDER_BACKGROUND));
4966                    break;
4967                case R.styleable.View_foreground:
4968                    if (targetSdkVersion >= Build.VERSION_CODES.M || this instanceof FrameLayout) {
4969                        setForeground(a.getDrawable(attr));
4970                    }
4971                    break;
4972                case R.styleable.View_foregroundGravity:
4973                    if (targetSdkVersion >= Build.VERSION_CODES.M || this instanceof FrameLayout) {
4974                        setForegroundGravity(a.getInt(attr, Gravity.NO_GRAVITY));
4975                    }
4976                    break;
4977                case R.styleable.View_foregroundTintMode:
4978                    if (targetSdkVersion >= Build.VERSION_CODES.M || this instanceof FrameLayout) {
4979                        setForegroundTintMode(Drawable.parseTintMode(a.getInt(attr, -1), null));
4980                    }
4981                    break;
4982                case R.styleable.View_foregroundTint:
4983                    if (targetSdkVersion >= Build.VERSION_CODES.M || this instanceof FrameLayout) {
4984                        setForegroundTintList(a.getColorStateList(attr));
4985                    }
4986                    break;
4987                case R.styleable.View_foregroundInsidePadding:
4988                    if (targetSdkVersion >= Build.VERSION_CODES.M || this instanceof FrameLayout) {
4989                        if (mForegroundInfo == null) {
4990                            mForegroundInfo = new ForegroundInfo();
4991                        }
4992                        mForegroundInfo.mInsidePadding = a.getBoolean(attr,
4993                                mForegroundInfo.mInsidePadding);
4994                    }
4995                    break;
4996                case R.styleable.View_scrollIndicators:
4997                    final int scrollIndicators =
4998                            (a.getInt(attr, 0) << SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT)
4999                                    & SCROLL_INDICATORS_PFLAG3_MASK;
5000                    if (scrollIndicators != 0) {
5001                        mPrivateFlags3 |= scrollIndicators;
5002                        initializeScrollIndicators = true;
5003                    }
5004                    break;
5005                case R.styleable.View_pointerIcon:
5006                    final int resourceId = a.getResourceId(attr, 0);
5007                    if (resourceId != 0) {
5008                        setPointerIcon(PointerIcon.load(
5009                                context.getResources(), resourceId));
5010                    } else {
5011                        final int pointerType = a.getInt(attr, PointerIcon.TYPE_NOT_SPECIFIED);
5012                        if (pointerType != PointerIcon.TYPE_NOT_SPECIFIED) {
5013                            setPointerIcon(PointerIcon.getSystemIcon(context, pointerType));
5014                        }
5015                    }
5016                    break;
5017                case R.styleable.View_forceHasOverlappingRendering:
5018                    if (a.peekValue(attr) != null) {
5019                        forceHasOverlappingRendering(a.getBoolean(attr, true));
5020                    }
5021                    break;
5022                case R.styleable.View_tooltipText:
5023                    setTooltipText(a.getText(attr));
5024                    break;
5025                case R.styleable.View_keyboardNavigationCluster:
5026                    if (a.peekValue(attr) != null) {
5027                        setKeyboardNavigationCluster(a.getBoolean(attr, true));
5028                    }
5029                    break;
5030                case R.styleable.View_focusedByDefault:
5031                    if (a.peekValue(attr) != null) {
5032                        setFocusedByDefault(a.getBoolean(attr, true));
5033                    }
5034                    break;
5035                case R.styleable.View_autofillMode:
5036                    if (a.peekValue(attr) != null) {
5037                        setAutofillMode(a.getInt(attr, AUTOFILL_MODE_INHERIT));
5038                    }
5039                    break;
5040                case R.styleable.View_autofillHints:
5041                    if (a.peekValue(attr) != null) {
5042                        CharSequence[] rawHints = null;
5043                        String rawString = null;
5044
5045                        if (a.getType(attr) == TypedValue.TYPE_REFERENCE) {
5046                            int resId = a.getResourceId(attr, 0);
5047
5048                            try {
5049                                rawHints = a.getTextArray(attr);
5050                            } catch (Resources.NotFoundException e) {
5051                                rawString = getResources().getString(resId);
5052                            }
5053                        } else {
5054                            rawString = a.getString(attr);
5055                        }
5056
5057                        if (rawHints == null) {
5058                            if (rawString == null) {
5059                                throw new IllegalArgumentException(
5060                                        "Could not resolve autofillHints");
5061                            } else {
5062                                rawHints = rawString.split(",");
5063                            }
5064                        }
5065
5066                        String[] hints = new String[rawHints.length];
5067
5068                        int numHints = rawHints.length;
5069                        for (int rawHintNum = 0; rawHintNum < numHints; rawHintNum++) {
5070                            hints[rawHintNum] = rawHints[rawHintNum].toString().trim();
5071                        }
5072                        setAutofillHints(hints);
5073                    }
5074                    break;
5075                case R.styleable.View_importantForAutofill:
5076                    if (a.peekValue(attr) != null) {
5077                        setImportantForAutofill(a.getInt(attr, IMPORTANT_FOR_AUTOFILL_AUTO));
5078                    }
5079                    break;
5080            }
5081        }
5082
5083        setOverScrollMode(overScrollMode);
5084
5085        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
5086        // the resolved layout direction). Those cached values will be used later during padding
5087        // resolution.
5088        mUserPaddingStart = startPadding;
5089        mUserPaddingEnd = endPadding;
5090
5091        if (background != null) {
5092            setBackground(background);
5093        }
5094
5095        // setBackground above will record that padding is currently provided by the background.
5096        // If we have padding specified via xml, record that here instead and use it.
5097        mLeftPaddingDefined = leftPaddingDefined;
5098        mRightPaddingDefined = rightPaddingDefined;
5099
5100        if (padding >= 0) {
5101            leftPadding = padding;
5102            topPadding = padding;
5103            rightPadding = padding;
5104            bottomPadding = padding;
5105            mUserPaddingLeftInitial = padding;
5106            mUserPaddingRightInitial = padding;
5107        } else {
5108            if (paddingHorizontal >= 0) {
5109                leftPadding = paddingHorizontal;
5110                rightPadding = paddingHorizontal;
5111                mUserPaddingLeftInitial = paddingHorizontal;
5112                mUserPaddingRightInitial = paddingHorizontal;
5113            }
5114            if (paddingVertical >= 0) {
5115                topPadding = paddingVertical;
5116                bottomPadding = paddingVertical;
5117            }
5118        }
5119
5120        if (isRtlCompatibilityMode()) {
5121            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
5122            // left / right padding are used if defined (meaning here nothing to do). If they are not
5123            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
5124            // start / end and resolve them as left / right (layout direction is not taken into account).
5125            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
5126            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
5127            // defined.
5128            if (!mLeftPaddingDefined && startPaddingDefined) {
5129                leftPadding = startPadding;
5130            }
5131            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
5132            if (!mRightPaddingDefined && endPaddingDefined) {
5133                rightPadding = endPadding;
5134            }
5135            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
5136        } else {
5137            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
5138            // values defined. Otherwise, left /right values are used.
5139            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
5140            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
5141            // defined.
5142            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
5143
5144            if (mLeftPaddingDefined && !hasRelativePadding) {
5145                mUserPaddingLeftInitial = leftPadding;
5146            }
5147            if (mRightPaddingDefined && !hasRelativePadding) {
5148                mUserPaddingRightInitial = rightPadding;
5149            }
5150        }
5151
5152        internalSetPadding(
5153                mUserPaddingLeftInitial,
5154                topPadding >= 0 ? topPadding : mPaddingTop,
5155                mUserPaddingRightInitial,
5156                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
5157
5158        if (viewFlagMasks != 0) {
5159            setFlags(viewFlagValues, viewFlagMasks);
5160        }
5161
5162        if (initializeScrollbars) {
5163            initializeScrollbarsInternal(a);
5164        }
5165
5166        if (initializeScrollIndicators) {
5167            initializeScrollIndicatorsInternal();
5168        }
5169
5170        a.recycle();
5171
5172        // Needs to be called after mViewFlags is set
5173        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
5174            recomputePadding();
5175        }
5176
5177        if (x != 0 || y != 0) {
5178            scrollTo(x, y);
5179        }
5180
5181        if (transformSet) {
5182            setTranslationX(tx);
5183            setTranslationY(ty);
5184            setTranslationZ(tz);
5185            setElevation(elevation);
5186            setRotation(rotation);
5187            setRotationX(rotationX);
5188            setRotationY(rotationY);
5189            setScaleX(sx);
5190            setScaleY(sy);
5191        }
5192
5193        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
5194            setScrollContainer(true);
5195        }
5196
5197        computeOpaqueFlags();
5198    }
5199
5200    /**
5201     * An implementation of OnClickListener that attempts to lazily load a
5202     * named click handling method from a parent or ancestor context.
5203     */
5204    private static class DeclaredOnClickListener implements OnClickListener {
5205        private final View mHostView;
5206        private final String mMethodName;
5207
5208        private Method mResolvedMethod;
5209        private Context mResolvedContext;
5210
5211        public DeclaredOnClickListener(@NonNull View hostView, @NonNull String methodName) {
5212            mHostView = hostView;
5213            mMethodName = methodName;
5214        }
5215
5216        @Override
5217        public void onClick(@NonNull View v) {
5218            if (mResolvedMethod == null) {
5219                resolveMethod(mHostView.getContext(), mMethodName);
5220            }
5221
5222            try {
5223                mResolvedMethod.invoke(mResolvedContext, v);
5224            } catch (IllegalAccessException e) {
5225                throw new IllegalStateException(
5226                        "Could not execute non-public method for android:onClick", e);
5227            } catch (InvocationTargetException e) {
5228                throw new IllegalStateException(
5229                        "Could not execute method for android:onClick", e);
5230            }
5231        }
5232
5233        @NonNull
5234        private void resolveMethod(@Nullable Context context, @NonNull String name) {
5235            while (context != null) {
5236                try {
5237                    if (!context.isRestricted()) {
5238                        final Method method = context.getClass().getMethod(mMethodName, View.class);
5239                        if (method != null) {
5240                            mResolvedMethod = method;
5241                            mResolvedContext = context;
5242                            return;
5243                        }
5244                    }
5245                } catch (NoSuchMethodException e) {
5246                    // Failed to find method, keep searching up the hierarchy.
5247                }
5248
5249                if (context instanceof ContextWrapper) {
5250                    context = ((ContextWrapper) context).getBaseContext();
5251                } else {
5252                    // Can't search up the hierarchy, null out and fail.
5253                    context = null;
5254                }
5255            }
5256
5257            final int id = mHostView.getId();
5258            final String idText = id == NO_ID ? "" : " with id '"
5259                    + mHostView.getContext().getResources().getResourceEntryName(id) + "'";
5260            throw new IllegalStateException("Could not find method " + mMethodName
5261                    + "(View) in a parent or ancestor Context for android:onClick "
5262                    + "attribute defined on view " + mHostView.getClass() + idText);
5263        }
5264    }
5265
5266    /**
5267     * Non-public constructor for use in testing
5268     */
5269    View() {
5270        mResources = null;
5271        mRenderNode = RenderNode.create(getClass().getName(), this);
5272    }
5273
5274    final boolean debugDraw() {
5275        return DEBUG_DRAW || mAttachInfo != null && mAttachInfo.mDebugLayout;
5276    }
5277
5278    private static SparseArray<String> getAttributeMap() {
5279        if (mAttributeMap == null) {
5280            mAttributeMap = new SparseArray<>();
5281        }
5282        return mAttributeMap;
5283    }
5284
5285    private void saveAttributeData(@Nullable AttributeSet attrs, @NonNull TypedArray t) {
5286        final int attrsCount = attrs == null ? 0 : attrs.getAttributeCount();
5287        final int indexCount = t.getIndexCount();
5288        final String[] attributes = new String[(attrsCount + indexCount) * 2];
5289
5290        int i = 0;
5291
5292        // Store raw XML attributes.
5293        for (int j = 0; j < attrsCount; ++j) {
5294            attributes[i] = attrs.getAttributeName(j);
5295            attributes[i + 1] = attrs.getAttributeValue(j);
5296            i += 2;
5297        }
5298
5299        // Store resolved styleable attributes.
5300        final Resources res = t.getResources();
5301        final SparseArray<String> attributeMap = getAttributeMap();
5302        for (int j = 0; j < indexCount; ++j) {
5303            final int index = t.getIndex(j);
5304            if (!t.hasValueOrEmpty(index)) {
5305                // Value is undefined. Skip it.
5306                continue;
5307            }
5308
5309            final int resourceId = t.getResourceId(index, 0);
5310            if (resourceId == 0) {
5311                // Value is not a reference. Skip it.
5312                continue;
5313            }
5314
5315            String resourceName = attributeMap.get(resourceId);
5316            if (resourceName == null) {
5317                try {
5318                    resourceName = res.getResourceName(resourceId);
5319                } catch (Resources.NotFoundException e) {
5320                    resourceName = "0x" + Integer.toHexString(resourceId);
5321                }
5322                attributeMap.put(resourceId, resourceName);
5323            }
5324
5325            attributes[i] = resourceName;
5326            attributes[i + 1] = t.getString(index);
5327            i += 2;
5328        }
5329
5330        // Trim to fit contents.
5331        final String[] trimmed = new String[i];
5332        System.arraycopy(attributes, 0, trimmed, 0, i);
5333        mAttributes = trimmed;
5334    }
5335
5336    public String toString() {
5337        StringBuilder out = new StringBuilder(128);
5338        out.append(getClass().getName());
5339        out.append('{');
5340        out.append(Integer.toHexString(System.identityHashCode(this)));
5341        out.append(' ');
5342        switch (mViewFlags&VISIBILITY_MASK) {
5343            case VISIBLE: out.append('V'); break;
5344            case INVISIBLE: out.append('I'); break;
5345            case GONE: out.append('G'); break;
5346            default: out.append('.'); break;
5347        }
5348        out.append((mViewFlags & FOCUSABLE) == FOCUSABLE ? 'F' : '.');
5349        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
5350        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
5351        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
5352        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
5353        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
5354        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
5355        out.append((mViewFlags&CONTEXT_CLICKABLE) != 0 ? 'X' : '.');
5356        out.append(' ');
5357        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
5358        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
5359        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
5360        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
5361            out.append('p');
5362        } else {
5363            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
5364        }
5365        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
5366        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
5367        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
5368        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
5369        out.append(' ');
5370        out.append(mLeft);
5371        out.append(',');
5372        out.append(mTop);
5373        out.append('-');
5374        out.append(mRight);
5375        out.append(',');
5376        out.append(mBottom);
5377        final int id = getId();
5378        if (id != NO_ID) {
5379            out.append(" #");
5380            out.append(Integer.toHexString(id));
5381            final Resources r = mResources;
5382            if (id > 0 && Resources.resourceHasPackage(id) && r != null) {
5383                try {
5384                    String pkgname;
5385                    switch (id&0xff000000) {
5386                        case 0x7f000000:
5387                            pkgname="app";
5388                            break;
5389                        case 0x01000000:
5390                            pkgname="android";
5391                            break;
5392                        default:
5393                            pkgname = r.getResourcePackageName(id);
5394                            break;
5395                    }
5396                    String typename = r.getResourceTypeName(id);
5397                    String entryname = r.getResourceEntryName(id);
5398                    out.append(" ");
5399                    out.append(pkgname);
5400                    out.append(":");
5401                    out.append(typename);
5402                    out.append("/");
5403                    out.append(entryname);
5404                } catch (Resources.NotFoundException e) {
5405                }
5406            }
5407        }
5408        out.append("}");
5409        return out.toString();
5410    }
5411
5412    /**
5413     * <p>
5414     * Initializes the fading edges from a given set of styled attributes. This
5415     * method should be called by subclasses that need fading edges and when an
5416     * instance of these subclasses is created programmatically rather than
5417     * being inflated from XML. This method is automatically called when the XML
5418     * is inflated.
5419     * </p>
5420     *
5421     * @param a the styled attributes set to initialize the fading edges from
5422     *
5423     * @removed
5424     */
5425    protected void initializeFadingEdge(TypedArray a) {
5426        // This method probably shouldn't have been included in the SDK to begin with.
5427        // It relies on 'a' having been initialized using an attribute filter array that is
5428        // not publicly available to the SDK. The old method has been renamed
5429        // to initializeFadingEdgeInternal and hidden for framework use only;
5430        // this one initializes using defaults to make it safe to call for apps.
5431
5432        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
5433
5434        initializeFadingEdgeInternal(arr);
5435
5436        arr.recycle();
5437    }
5438
5439    /**
5440     * <p>
5441     * Initializes the fading edges from a given set of styled attributes. This
5442     * method should be called by subclasses that need fading edges and when an
5443     * instance of these subclasses is created programmatically rather than
5444     * being inflated from XML. This method is automatically called when the XML
5445     * is inflated.
5446     * </p>
5447     *
5448     * @param a the styled attributes set to initialize the fading edges from
5449     * @hide This is the real method; the public one is shimmed to be safe to call from apps.
5450     */
5451    protected void initializeFadingEdgeInternal(TypedArray a) {
5452        initScrollCache();
5453
5454        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
5455                R.styleable.View_fadingEdgeLength,
5456                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
5457    }
5458
5459    /**
5460     * Returns the size of the vertical faded edges used to indicate that more
5461     * content in this view is visible.
5462     *
5463     * @return The size in pixels of the vertical faded edge or 0 if vertical
5464     *         faded edges are not enabled for this view.
5465     * @attr ref android.R.styleable#View_fadingEdgeLength
5466     */
5467    public int getVerticalFadingEdgeLength() {
5468        if (isVerticalFadingEdgeEnabled()) {
5469            ScrollabilityCache cache = mScrollCache;
5470            if (cache != null) {
5471                return cache.fadingEdgeLength;
5472            }
5473        }
5474        return 0;
5475    }
5476
5477    /**
5478     * Set the size of the faded edge used to indicate that more content in this
5479     * view is available.  Will not change whether the fading edge is enabled; use
5480     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
5481     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
5482     * for the vertical or horizontal fading edges.
5483     *
5484     * @param length The size in pixels of the faded edge used to indicate that more
5485     *        content in this view is visible.
5486     */
5487    public void setFadingEdgeLength(int length) {
5488        initScrollCache();
5489        mScrollCache.fadingEdgeLength = length;
5490    }
5491
5492    /**
5493     * Returns the size of the horizontal faded edges used to indicate that more
5494     * content in this view is visible.
5495     *
5496     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
5497     *         faded edges are not enabled for this view.
5498     * @attr ref android.R.styleable#View_fadingEdgeLength
5499     */
5500    public int getHorizontalFadingEdgeLength() {
5501        if (isHorizontalFadingEdgeEnabled()) {
5502            ScrollabilityCache cache = mScrollCache;
5503            if (cache != null) {
5504                return cache.fadingEdgeLength;
5505            }
5506        }
5507        return 0;
5508    }
5509
5510    /**
5511     * Returns the width of the vertical scrollbar.
5512     *
5513     * @return The width in pixels of the vertical scrollbar or 0 if there
5514     *         is no vertical scrollbar.
5515     */
5516    public int getVerticalScrollbarWidth() {
5517        ScrollabilityCache cache = mScrollCache;
5518        if (cache != null) {
5519            ScrollBarDrawable scrollBar = cache.scrollBar;
5520            if (scrollBar != null) {
5521                int size = scrollBar.getSize(true);
5522                if (size <= 0) {
5523                    size = cache.scrollBarSize;
5524                }
5525                return size;
5526            }
5527            return 0;
5528        }
5529        return 0;
5530    }
5531
5532    /**
5533     * Returns the height of the horizontal scrollbar.
5534     *
5535     * @return The height in pixels of the horizontal scrollbar or 0 if
5536     *         there is no horizontal scrollbar.
5537     */
5538    protected int getHorizontalScrollbarHeight() {
5539        ScrollabilityCache cache = mScrollCache;
5540        if (cache != null) {
5541            ScrollBarDrawable scrollBar = cache.scrollBar;
5542            if (scrollBar != null) {
5543                int size = scrollBar.getSize(false);
5544                if (size <= 0) {
5545                    size = cache.scrollBarSize;
5546                }
5547                return size;
5548            }
5549            return 0;
5550        }
5551        return 0;
5552    }
5553
5554    /**
5555     * <p>
5556     * Initializes the scrollbars from a given set of styled attributes. This
5557     * method should be called by subclasses that need scrollbars and when an
5558     * instance of these subclasses is created programmatically rather than
5559     * being inflated from XML. This method is automatically called when the XML
5560     * is inflated.
5561     * </p>
5562     *
5563     * @param a the styled attributes set to initialize the scrollbars from
5564     *
5565     * @removed
5566     */
5567    protected void initializeScrollbars(TypedArray a) {
5568        // It's not safe to use this method from apps. The parameter 'a' must have been obtained
5569        // using the View filter array which is not available to the SDK. As such, internal
5570        // framework usage now uses initializeScrollbarsInternal and we grab a default
5571        // TypedArray with the right filter instead here.
5572        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
5573
5574        initializeScrollbarsInternal(arr);
5575
5576        // We ignored the method parameter. Recycle the one we actually did use.
5577        arr.recycle();
5578    }
5579
5580    /**
5581     * <p>
5582     * Initializes the scrollbars from a given set of styled attributes. This
5583     * method should be called by subclasses that need scrollbars and when an
5584     * instance of these subclasses is created programmatically rather than
5585     * being inflated from XML. This method is automatically called when the XML
5586     * is inflated.
5587     * </p>
5588     *
5589     * @param a the styled attributes set to initialize the scrollbars from
5590     * @hide
5591     */
5592    protected void initializeScrollbarsInternal(TypedArray a) {
5593        initScrollCache();
5594
5595        final ScrollabilityCache scrollabilityCache = mScrollCache;
5596
5597        if (scrollabilityCache.scrollBar == null) {
5598            scrollabilityCache.scrollBar = new ScrollBarDrawable();
5599            scrollabilityCache.scrollBar.setState(getDrawableState());
5600            scrollabilityCache.scrollBar.setCallback(this);
5601        }
5602
5603        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
5604
5605        if (!fadeScrollbars) {
5606            scrollabilityCache.state = ScrollabilityCache.ON;
5607        }
5608        scrollabilityCache.fadeScrollBars = fadeScrollbars;
5609
5610
5611        scrollabilityCache.scrollBarFadeDuration = a.getInt(
5612                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
5613                        .getScrollBarFadeDuration());
5614        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
5615                R.styleable.View_scrollbarDefaultDelayBeforeFade,
5616                ViewConfiguration.getScrollDefaultDelay());
5617
5618
5619        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
5620                com.android.internal.R.styleable.View_scrollbarSize,
5621                ViewConfiguration.get(mContext).getScaledScrollBarSize());
5622
5623        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
5624        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
5625
5626        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
5627        if (thumb != null) {
5628            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
5629        }
5630
5631        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
5632                false);
5633        if (alwaysDraw) {
5634            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
5635        }
5636
5637        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
5638        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
5639
5640        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
5641        if (thumb != null) {
5642            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
5643        }
5644
5645        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
5646                false);
5647        if (alwaysDraw) {
5648            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
5649        }
5650
5651        // Apply layout direction to the new Drawables if needed
5652        final int layoutDirection = getLayoutDirection();
5653        if (track != null) {
5654            track.setLayoutDirection(layoutDirection);
5655        }
5656        if (thumb != null) {
5657            thumb.setLayoutDirection(layoutDirection);
5658        }
5659
5660        // Re-apply user/background padding so that scrollbar(s) get added
5661        resolvePadding();
5662    }
5663
5664    private void initializeScrollIndicatorsInternal() {
5665        // Some day maybe we'll break this into top/left/start/etc. and let the
5666        // client control it. Until then, you can have any scroll indicator you
5667        // want as long as it's a 1dp foreground-colored rectangle.
5668        if (mScrollIndicatorDrawable == null) {
5669            mScrollIndicatorDrawable = mContext.getDrawable(R.drawable.scroll_indicator_material);
5670        }
5671    }
5672
5673    /**
5674     * <p>
5675     * Initalizes the scrollability cache if necessary.
5676     * </p>
5677     */
5678    private void initScrollCache() {
5679        if (mScrollCache == null) {
5680            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
5681        }
5682    }
5683
5684    private ScrollabilityCache getScrollCache() {
5685        initScrollCache();
5686        return mScrollCache;
5687    }
5688
5689    /**
5690     * Set the position of the vertical scroll bar. Should be one of
5691     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
5692     * {@link #SCROLLBAR_POSITION_RIGHT}.
5693     *
5694     * @param position Where the vertical scroll bar should be positioned.
5695     */
5696    public void setVerticalScrollbarPosition(int position) {
5697        if (mVerticalScrollbarPosition != position) {
5698            mVerticalScrollbarPosition = position;
5699            computeOpaqueFlags();
5700            resolvePadding();
5701        }
5702    }
5703
5704    /**
5705     * @return The position where the vertical scroll bar will show, if applicable.
5706     * @see #setVerticalScrollbarPosition(int)
5707     */
5708    public int getVerticalScrollbarPosition() {
5709        return mVerticalScrollbarPosition;
5710    }
5711
5712    boolean isOnScrollbar(float x, float y) {
5713        if (mScrollCache == null) {
5714            return false;
5715        }
5716        x += getScrollX();
5717        y += getScrollY();
5718        if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) {
5719            final Rect touchBounds = mScrollCache.mScrollBarTouchBounds;
5720            getVerticalScrollBarBounds(null, touchBounds);
5721            if (touchBounds.contains((int) x, (int) y)) {
5722                return true;
5723            }
5724        }
5725        if (isHorizontalScrollBarEnabled()) {
5726            final Rect touchBounds = mScrollCache.mScrollBarTouchBounds;
5727            getHorizontalScrollBarBounds(null, touchBounds);
5728            if (touchBounds.contains((int) x, (int) y)) {
5729                return true;
5730            }
5731        }
5732        return false;
5733    }
5734
5735    boolean isOnScrollbarThumb(float x, float y) {
5736        return isOnVerticalScrollbarThumb(x, y) || isOnHorizontalScrollbarThumb(x, y);
5737    }
5738
5739    private boolean isOnVerticalScrollbarThumb(float x, float y) {
5740        if (mScrollCache == null) {
5741            return false;
5742        }
5743        if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) {
5744            x += getScrollX();
5745            y += getScrollY();
5746            final Rect bounds = mScrollCache.mScrollBarBounds;
5747            final Rect touchBounds = mScrollCache.mScrollBarTouchBounds;
5748            getVerticalScrollBarBounds(bounds, touchBounds);
5749            final int range = computeVerticalScrollRange();
5750            final int offset = computeVerticalScrollOffset();
5751            final int extent = computeVerticalScrollExtent();
5752            final int thumbLength = ScrollBarUtils.getThumbLength(bounds.height(), bounds.width(),
5753                    extent, range);
5754            final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.height(), thumbLength,
5755                    extent, range, offset);
5756            final int thumbTop = bounds.top + thumbOffset;
5757            final int adjust = Math.max(mScrollCache.scrollBarMinTouchTarget - thumbLength, 0) / 2;
5758            if (x >= touchBounds.left && x <= touchBounds.right
5759                    && y >= thumbTop - adjust && y <= thumbTop + thumbLength + adjust) {
5760                return true;
5761            }
5762        }
5763        return false;
5764    }
5765
5766    private boolean isOnHorizontalScrollbarThumb(float x, float y) {
5767        if (mScrollCache == null) {
5768            return false;
5769        }
5770        if (isHorizontalScrollBarEnabled()) {
5771            x += getScrollX();
5772            y += getScrollY();
5773            final Rect bounds = mScrollCache.mScrollBarBounds;
5774            final Rect touchBounds = mScrollCache.mScrollBarTouchBounds;
5775            getHorizontalScrollBarBounds(bounds, touchBounds);
5776            final int range = computeHorizontalScrollRange();
5777            final int offset = computeHorizontalScrollOffset();
5778            final int extent = computeHorizontalScrollExtent();
5779            final int thumbLength = ScrollBarUtils.getThumbLength(bounds.width(), bounds.height(),
5780                    extent, range);
5781            final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.width(), thumbLength,
5782                    extent, range, offset);
5783            final int thumbLeft = bounds.left + thumbOffset;
5784            final int adjust = Math.max(mScrollCache.scrollBarMinTouchTarget - thumbLength, 0) / 2;
5785            if (x >= thumbLeft - adjust && x <= thumbLeft + thumbLength + adjust
5786                    && y >= touchBounds.top && y <= touchBounds.bottom) {
5787                return true;
5788            }
5789        }
5790        return false;
5791    }
5792
5793    boolean isDraggingScrollBar() {
5794        return mScrollCache != null
5795                && mScrollCache.mScrollBarDraggingState != ScrollabilityCache.NOT_DRAGGING;
5796    }
5797
5798    /**
5799     * Sets the state of all scroll indicators.
5800     * <p>
5801     * See {@link #setScrollIndicators(int, int)} for usage information.
5802     *
5803     * @param indicators a bitmask of indicators that should be enabled, or
5804     *                   {@code 0} to disable all indicators
5805     * @see #setScrollIndicators(int, int)
5806     * @see #getScrollIndicators()
5807     * @attr ref android.R.styleable#View_scrollIndicators
5808     */
5809    public void setScrollIndicators(@ScrollIndicators int indicators) {
5810        setScrollIndicators(indicators,
5811                SCROLL_INDICATORS_PFLAG3_MASK >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT);
5812    }
5813
5814    /**
5815     * Sets the state of the scroll indicators specified by the mask. To change
5816     * all scroll indicators at once, see {@link #setScrollIndicators(int)}.
5817     * <p>
5818     * When a scroll indicator is enabled, it will be displayed if the view
5819     * can scroll in the direction of the indicator.
5820     * <p>
5821     * Multiple indicator types may be enabled or disabled by passing the
5822     * logical OR of the desired types. If multiple types are specified, they
5823     * will all be set to the same enabled state.
5824     * <p>
5825     * For example, to enable the top scroll indicatorExample: {@code setScrollIndicators
5826     *
5827     * @param indicators the indicator direction, or the logical OR of multiple
5828     *             indicator directions. One or more of:
5829     *             <ul>
5830     *               <li>{@link #SCROLL_INDICATOR_TOP}</li>
5831     *               <li>{@link #SCROLL_INDICATOR_BOTTOM}</li>
5832     *               <li>{@link #SCROLL_INDICATOR_LEFT}</li>
5833     *               <li>{@link #SCROLL_INDICATOR_RIGHT}</li>
5834     *               <li>{@link #SCROLL_INDICATOR_START}</li>
5835     *               <li>{@link #SCROLL_INDICATOR_END}</li>
5836     *             </ul>
5837     * @see #setScrollIndicators(int)
5838     * @see #getScrollIndicators()
5839     * @attr ref android.R.styleable#View_scrollIndicators
5840     */
5841    public void setScrollIndicators(@ScrollIndicators int indicators, @ScrollIndicators int mask) {
5842        // Shift and sanitize mask.
5843        mask <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5844        mask &= SCROLL_INDICATORS_PFLAG3_MASK;
5845
5846        // Shift and mask indicators.
5847        indicators <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5848        indicators &= mask;
5849
5850        // Merge with non-masked flags.
5851        final int updatedFlags = indicators | (mPrivateFlags3 & ~mask);
5852
5853        if (mPrivateFlags3 != updatedFlags) {
5854            mPrivateFlags3 = updatedFlags;
5855
5856            if (indicators != 0) {
5857                initializeScrollIndicatorsInternal();
5858            }
5859            invalidate();
5860        }
5861    }
5862
5863    /**
5864     * Returns a bitmask representing the enabled scroll indicators.
5865     * <p>
5866     * For example, if the top and left scroll indicators are enabled and all
5867     * other indicators are disabled, the return value will be
5868     * {@code View.SCROLL_INDICATOR_TOP | View.SCROLL_INDICATOR_LEFT}.
5869     * <p>
5870     * To check whether the bottom scroll indicator is enabled, use the value
5871     * of {@code (getScrollIndicators() & View.SCROLL_INDICATOR_BOTTOM) != 0}.
5872     *
5873     * @return a bitmask representing the enabled scroll indicators
5874     */
5875    @ScrollIndicators
5876    public int getScrollIndicators() {
5877        return (mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK)
5878                >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5879    }
5880
5881    ListenerInfo getListenerInfo() {
5882        if (mListenerInfo != null) {
5883            return mListenerInfo;
5884        }
5885        mListenerInfo = new ListenerInfo();
5886        return mListenerInfo;
5887    }
5888
5889    /**
5890     * Register a callback to be invoked when the scroll X or Y positions of
5891     * this view change.
5892     * <p>
5893     * <b>Note:</b> Some views handle scrolling independently from View and may
5894     * have their own separate listeners for scroll-type events. For example,
5895     * {@link android.widget.ListView ListView} allows clients to register an
5896     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
5897     * to listen for changes in list scroll position.
5898     *
5899     * @param l The listener to notify when the scroll X or Y position changes.
5900     * @see android.view.View#getScrollX()
5901     * @see android.view.View#getScrollY()
5902     */
5903    public void setOnScrollChangeListener(OnScrollChangeListener l) {
5904        getListenerInfo().mOnScrollChangeListener = l;
5905    }
5906
5907    /**
5908     * Register a callback to be invoked when focus of this view changed.
5909     *
5910     * @param l The callback that will run.
5911     */
5912    public void setOnFocusChangeListener(OnFocusChangeListener l) {
5913        getListenerInfo().mOnFocusChangeListener = l;
5914    }
5915
5916    /**
5917     * Add a listener that will be called when the bounds of the view change due to
5918     * layout processing.
5919     *
5920     * @param listener The listener that will be called when layout bounds change.
5921     */
5922    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
5923        ListenerInfo li = getListenerInfo();
5924        if (li.mOnLayoutChangeListeners == null) {
5925            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
5926        }
5927        if (!li.mOnLayoutChangeListeners.contains(listener)) {
5928            li.mOnLayoutChangeListeners.add(listener);
5929        }
5930    }
5931
5932    /**
5933     * Remove a listener for layout changes.
5934     *
5935     * @param listener The listener for layout bounds change.
5936     */
5937    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
5938        ListenerInfo li = mListenerInfo;
5939        if (li == null || li.mOnLayoutChangeListeners == null) {
5940            return;
5941        }
5942        li.mOnLayoutChangeListeners.remove(listener);
5943    }
5944
5945    /**
5946     * Add a listener for attach state changes.
5947     *
5948     * This listener will be called whenever this view is attached or detached
5949     * from a window. Remove the listener using
5950     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
5951     *
5952     * @param listener Listener to attach
5953     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
5954     */
5955    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
5956        ListenerInfo li = getListenerInfo();
5957        if (li.mOnAttachStateChangeListeners == null) {
5958            li.mOnAttachStateChangeListeners
5959                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
5960        }
5961        li.mOnAttachStateChangeListeners.add(listener);
5962    }
5963
5964    /**
5965     * Remove a listener for attach state changes. The listener will receive no further
5966     * notification of window attach/detach events.
5967     *
5968     * @param listener Listener to remove
5969     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
5970     */
5971    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
5972        ListenerInfo li = mListenerInfo;
5973        if (li == null || li.mOnAttachStateChangeListeners == null) {
5974            return;
5975        }
5976        li.mOnAttachStateChangeListeners.remove(listener);
5977    }
5978
5979    /**
5980     * Returns the focus-change callback registered for this view.
5981     *
5982     * @return The callback, or null if one is not registered.
5983     */
5984    public OnFocusChangeListener getOnFocusChangeListener() {
5985        ListenerInfo li = mListenerInfo;
5986        return li != null ? li.mOnFocusChangeListener : null;
5987    }
5988
5989    /**
5990     * Register a callback to be invoked when this view is clicked. If this view is not
5991     * clickable, it becomes clickable.
5992     *
5993     * @param l The callback that will run
5994     *
5995     * @see #setClickable(boolean)
5996     */
5997    public void setOnClickListener(@Nullable OnClickListener l) {
5998        if (!isClickable()) {
5999            setClickable(true);
6000        }
6001        getListenerInfo().mOnClickListener = l;
6002    }
6003
6004    /**
6005     * Return whether this view has an attached OnClickListener.  Returns
6006     * true if there is a listener, false if there is none.
6007     */
6008    public boolean hasOnClickListeners() {
6009        ListenerInfo li = mListenerInfo;
6010        return (li != null && li.mOnClickListener != null);
6011    }
6012
6013    /**
6014     * Register a callback to be invoked when this view is clicked and held. If this view is not
6015     * long clickable, it becomes long clickable.
6016     *
6017     * @param l The callback that will run
6018     *
6019     * @see #setLongClickable(boolean)
6020     */
6021    public void setOnLongClickListener(@Nullable OnLongClickListener l) {
6022        if (!isLongClickable()) {
6023            setLongClickable(true);
6024        }
6025        getListenerInfo().mOnLongClickListener = l;
6026    }
6027
6028    /**
6029     * Register a callback to be invoked when this view is context clicked. If the view is not
6030     * context clickable, it becomes context clickable.
6031     *
6032     * @param l The callback that will run
6033     * @see #setContextClickable(boolean)
6034     */
6035    public void setOnContextClickListener(@Nullable OnContextClickListener l) {
6036        if (!isContextClickable()) {
6037            setContextClickable(true);
6038        }
6039        getListenerInfo().mOnContextClickListener = l;
6040    }
6041
6042    /**
6043     * Register a callback to be invoked when the context menu for this view is
6044     * being built. If this view is not long clickable, it becomes long clickable.
6045     *
6046     * @param l The callback that will run
6047     *
6048     */
6049    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
6050        if (!isLongClickable()) {
6051            setLongClickable(true);
6052        }
6053        getListenerInfo().mOnCreateContextMenuListener = l;
6054    }
6055
6056    /**
6057     * Set an observer to collect stats for each frame rendered for this view.
6058     *
6059     * @hide
6060     */
6061    public void addFrameMetricsListener(Window window,
6062            Window.OnFrameMetricsAvailableListener listener,
6063            Handler handler) {
6064        if (mAttachInfo != null) {
6065            if (mAttachInfo.mThreadedRenderer != null) {
6066                if (mFrameMetricsObservers == null) {
6067                    mFrameMetricsObservers = new ArrayList<>();
6068                }
6069
6070                FrameMetricsObserver fmo = new FrameMetricsObserver(window,
6071                        handler.getLooper(), listener);
6072                mFrameMetricsObservers.add(fmo);
6073                mAttachInfo.mThreadedRenderer.addFrameMetricsObserver(fmo);
6074            } else {
6075                Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats");
6076            }
6077        } else {
6078            if (mFrameMetricsObservers == null) {
6079                mFrameMetricsObservers = new ArrayList<>();
6080            }
6081
6082            FrameMetricsObserver fmo = new FrameMetricsObserver(window,
6083                    handler.getLooper(), listener);
6084            mFrameMetricsObservers.add(fmo);
6085        }
6086    }
6087
6088    /**
6089     * Remove observer configured to collect frame stats for this view.
6090     *
6091     * @hide
6092     */
6093    public void removeFrameMetricsListener(
6094            Window.OnFrameMetricsAvailableListener listener) {
6095        ThreadedRenderer renderer = getThreadedRenderer();
6096        FrameMetricsObserver fmo = findFrameMetricsObserver(listener);
6097        if (fmo == null) {
6098            throw new IllegalArgumentException(
6099                    "attempt to remove OnFrameMetricsAvailableListener that was never added");
6100        }
6101
6102        if (mFrameMetricsObservers != null) {
6103            mFrameMetricsObservers.remove(fmo);
6104            if (renderer != null) {
6105                renderer.removeFrameMetricsObserver(fmo);
6106            }
6107        }
6108    }
6109
6110    private void registerPendingFrameMetricsObservers() {
6111        if (mFrameMetricsObservers != null) {
6112            ThreadedRenderer renderer = getThreadedRenderer();
6113            if (renderer != null) {
6114                for (FrameMetricsObserver fmo : mFrameMetricsObservers) {
6115                    renderer.addFrameMetricsObserver(fmo);
6116                }
6117            } else {
6118                Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats");
6119            }
6120        }
6121    }
6122
6123    private FrameMetricsObserver findFrameMetricsObserver(
6124            Window.OnFrameMetricsAvailableListener listener) {
6125        for (int i = 0; i < mFrameMetricsObservers.size(); i++) {
6126            FrameMetricsObserver observer = mFrameMetricsObservers.get(i);
6127            if (observer.mListener == listener) {
6128                return observer;
6129            }
6130        }
6131
6132        return null;
6133    }
6134
6135    /**
6136     * Call this view's OnClickListener, if it is defined.  Performs all normal
6137     * actions associated with clicking: reporting accessibility event, playing
6138     * a sound, etc.
6139     *
6140     * @return True there was an assigned OnClickListener that was called, false
6141     *         otherwise is returned.
6142     */
6143    public boolean performClick() {
6144        final boolean result;
6145        final ListenerInfo li = mListenerInfo;
6146        if (li != null && li.mOnClickListener != null) {
6147            playSoundEffect(SoundEffectConstants.CLICK);
6148            li.mOnClickListener.onClick(this);
6149            result = true;
6150        } else {
6151            result = false;
6152        }
6153
6154        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
6155
6156        notifyEnterOrExitForAutoFillIfNeeded(true);
6157
6158        return result;
6159    }
6160
6161    /**
6162     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
6163     * this only calls the listener, and does not do any associated clicking
6164     * actions like reporting an accessibility event.
6165     *
6166     * @return True there was an assigned OnClickListener that was called, false
6167     *         otherwise is returned.
6168     */
6169    public boolean callOnClick() {
6170        ListenerInfo li = mListenerInfo;
6171        if (li != null && li.mOnClickListener != null) {
6172            li.mOnClickListener.onClick(this);
6173            return true;
6174        }
6175        return false;
6176    }
6177
6178    /**
6179     * Calls this view's OnLongClickListener, if it is defined. Invokes the
6180     * context menu if the OnLongClickListener did not consume the event.
6181     *
6182     * @return {@code true} if one of the above receivers consumed the event,
6183     *         {@code false} otherwise
6184     */
6185    public boolean performLongClick() {
6186        return performLongClickInternal(mLongClickX, mLongClickY);
6187    }
6188
6189    /**
6190     * Calls this view's OnLongClickListener, if it is defined. Invokes the
6191     * context menu if the OnLongClickListener did not consume the event,
6192     * anchoring it to an (x,y) coordinate.
6193     *
6194     * @param x x coordinate of the anchoring touch event, or {@link Float#NaN}
6195     *          to disable anchoring
6196     * @param y y coordinate of the anchoring touch event, or {@link Float#NaN}
6197     *          to disable anchoring
6198     * @return {@code true} if one of the above receivers consumed the event,
6199     *         {@code false} otherwise
6200     */
6201    public boolean performLongClick(float x, float y) {
6202        mLongClickX = x;
6203        mLongClickY = y;
6204        final boolean handled = performLongClick();
6205        mLongClickX = Float.NaN;
6206        mLongClickY = Float.NaN;
6207        return handled;
6208    }
6209
6210    /**
6211     * Calls this view's OnLongClickListener, if it is defined. Invokes the
6212     * context menu if the OnLongClickListener did not consume the event,
6213     * optionally anchoring it to an (x,y) coordinate.
6214     *
6215     * @param x x coordinate of the anchoring touch event, or {@link Float#NaN}
6216     *          to disable anchoring
6217     * @param y y coordinate of the anchoring touch event, or {@link Float#NaN}
6218     *          to disable anchoring
6219     * @return {@code true} if one of the above receivers consumed the event,
6220     *         {@code false} otherwise
6221     */
6222    private boolean performLongClickInternal(float x, float y) {
6223        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
6224
6225        boolean handled = false;
6226        final ListenerInfo li = mListenerInfo;
6227        if (li != null && li.mOnLongClickListener != null) {
6228            handled = li.mOnLongClickListener.onLongClick(View.this);
6229        }
6230        if (!handled) {
6231            final boolean isAnchored = !Float.isNaN(x) && !Float.isNaN(y);
6232            handled = isAnchored ? showContextMenu(x, y) : showContextMenu();
6233        }
6234        if ((mViewFlags & TOOLTIP) == TOOLTIP) {
6235            if (!handled) {
6236                handled = showLongClickTooltip((int) x, (int) y);
6237            }
6238        }
6239        if (handled) {
6240            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
6241        }
6242        return handled;
6243    }
6244
6245    /**
6246     * Call this view's OnContextClickListener, if it is defined.
6247     *
6248     * @param x the x coordinate of the context click
6249     * @param y the y coordinate of the context click
6250     * @return True if there was an assigned OnContextClickListener that consumed the event, false
6251     *         otherwise.
6252     */
6253    public boolean performContextClick(float x, float y) {
6254        return performContextClick();
6255    }
6256
6257    /**
6258     * Call this view's OnContextClickListener, if it is defined.
6259     *
6260     * @return True if there was an assigned OnContextClickListener that consumed the event, false
6261     *         otherwise.
6262     */
6263    public boolean performContextClick() {
6264        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CONTEXT_CLICKED);
6265
6266        boolean handled = false;
6267        ListenerInfo li = mListenerInfo;
6268        if (li != null && li.mOnContextClickListener != null) {
6269            handled = li.mOnContextClickListener.onContextClick(View.this);
6270        }
6271        if (handled) {
6272            performHapticFeedback(HapticFeedbackConstants.CONTEXT_CLICK);
6273        }
6274        return handled;
6275    }
6276
6277    /**
6278     * Performs button-related actions during a touch down event.
6279     *
6280     * @param event The event.
6281     * @return True if the down was consumed.
6282     *
6283     * @hide
6284     */
6285    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
6286        if (event.isFromSource(InputDevice.SOURCE_MOUSE) &&
6287            (event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
6288            showContextMenu(event.getX(), event.getY());
6289            mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
6290            return true;
6291        }
6292        return false;
6293    }
6294
6295    /**
6296     * Shows the context menu for this view.
6297     *
6298     * @return {@code true} if the context menu was shown, {@code false}
6299     *         otherwise
6300     * @see #showContextMenu(float, float)
6301     */
6302    public boolean showContextMenu() {
6303        return getParent().showContextMenuForChild(this);
6304    }
6305
6306    /**
6307     * Shows the context menu for this view anchored to the specified
6308     * view-relative coordinate.
6309     *
6310     * @param x the X coordinate in pixels relative to the view to which the
6311     *          menu should be anchored, or {@link Float#NaN} to disable anchoring
6312     * @param y the Y coordinate in pixels relative to the view to which the
6313     *          menu should be anchored, or {@link Float#NaN} to disable anchoring
6314     * @return {@code true} if the context menu was shown, {@code false}
6315     *         otherwise
6316     */
6317    public boolean showContextMenu(float x, float y) {
6318        return getParent().showContextMenuForChild(this, x, y);
6319    }
6320
6321    /**
6322     * Start an action mode with the default type {@link ActionMode#TYPE_PRIMARY}.
6323     *
6324     * @param callback Callback that will control the lifecycle of the action mode
6325     * @return The new action mode if it is started, null otherwise
6326     *
6327     * @see ActionMode
6328     * @see #startActionMode(android.view.ActionMode.Callback, int)
6329     */
6330    public ActionMode startActionMode(ActionMode.Callback callback) {
6331        return startActionMode(callback, ActionMode.TYPE_PRIMARY);
6332    }
6333
6334    /**
6335     * Start an action mode with the given type.
6336     *
6337     * @param callback Callback that will control the lifecycle of the action mode
6338     * @param type One of {@link ActionMode#TYPE_PRIMARY} or {@link ActionMode#TYPE_FLOATING}.
6339     * @return The new action mode if it is started, null otherwise
6340     *
6341     * @see ActionMode
6342     */
6343    public ActionMode startActionMode(ActionMode.Callback callback, int type) {
6344        ViewParent parent = getParent();
6345        if (parent == null) return null;
6346        try {
6347            return parent.startActionModeForChild(this, callback, type);
6348        } catch (AbstractMethodError ame) {
6349            // Older implementations of custom views might not implement this.
6350            return parent.startActionModeForChild(this, callback);
6351        }
6352    }
6353
6354    /**
6355     * Call {@link Context#startActivityForResult(String, Intent, int, Bundle)} for the View's
6356     * Context, creating a unique View identifier to retrieve the result.
6357     *
6358     * @param intent The Intent to be started.
6359     * @param requestCode The request code to use.
6360     * @hide
6361     */
6362    public void startActivityForResult(Intent intent, int requestCode) {
6363        mStartActivityRequestWho = "@android:view:" + System.identityHashCode(this);
6364        getContext().startActivityForResult(mStartActivityRequestWho, intent, requestCode, null);
6365    }
6366
6367    /**
6368     * If this View corresponds to the calling who, dispatches the activity result.
6369     * @param who The identifier for the targeted View to receive the result.
6370     * @param requestCode The integer request code originally supplied to
6371     *                    startActivityForResult(), allowing you to identify who this
6372     *                    result came from.
6373     * @param resultCode The integer result code returned by the child activity
6374     *                   through its setResult().
6375     * @param data An Intent, which can return result data to the caller
6376     *               (various data can be attached to Intent "extras").
6377     * @return {@code true} if the activity result was dispatched.
6378     * @hide
6379     */
6380    public boolean dispatchActivityResult(
6381            String who, int requestCode, int resultCode, Intent data) {
6382        if (mStartActivityRequestWho != null && mStartActivityRequestWho.equals(who)) {
6383            onActivityResult(requestCode, resultCode, data);
6384            mStartActivityRequestWho = null;
6385            return true;
6386        }
6387        return false;
6388    }
6389
6390    /**
6391     * Receive the result from a previous call to {@link #startActivityForResult(Intent, int)}.
6392     *
6393     * @param requestCode The integer request code originally supplied to
6394     *                    startActivityForResult(), allowing you to identify who this
6395     *                    result came from.
6396     * @param resultCode The integer result code returned by the child activity
6397     *                   through its setResult().
6398     * @param data An Intent, which can return result data to the caller
6399     *               (various data can be attached to Intent "extras").
6400     * @hide
6401     */
6402    public void onActivityResult(int requestCode, int resultCode, Intent data) {
6403        // Do nothing.
6404    }
6405
6406    /**
6407     * Register a callback to be invoked when a hardware key is pressed in this view.
6408     * Key presses in software input methods will generally not trigger the methods of
6409     * this listener.
6410     * @param l the key listener to attach to this view
6411     */
6412    public void setOnKeyListener(OnKeyListener l) {
6413        getListenerInfo().mOnKeyListener = l;
6414    }
6415
6416    /**
6417     * Register a callback to be invoked when a touch event is sent to this view.
6418     * @param l the touch listener to attach to this view
6419     */
6420    public void setOnTouchListener(OnTouchListener l) {
6421        getListenerInfo().mOnTouchListener = l;
6422    }
6423
6424    /**
6425     * Register a callback to be invoked when a generic motion event is sent to this view.
6426     * @param l the generic motion listener to attach to this view
6427     */
6428    public void setOnGenericMotionListener(OnGenericMotionListener l) {
6429        getListenerInfo().mOnGenericMotionListener = l;
6430    }
6431
6432    /**
6433     * Register a callback to be invoked when a hover event is sent to this view.
6434     * @param l the hover listener to attach to this view
6435     */
6436    public void setOnHoverListener(OnHoverListener l) {
6437        getListenerInfo().mOnHoverListener = l;
6438    }
6439
6440    /**
6441     * Register a drag event listener callback object for this View. The parameter is
6442     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
6443     * View, the system calls the
6444     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
6445     * @param l An implementation of {@link android.view.View.OnDragListener}.
6446     */
6447    public void setOnDragListener(OnDragListener l) {
6448        getListenerInfo().mOnDragListener = l;
6449    }
6450
6451    /**
6452     * Give this view focus. This will cause
6453     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
6454     *
6455     * Note: this does not check whether this {@link View} should get focus, it just
6456     * gives it focus no matter what.  It should only be called internally by framework
6457     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
6458     *
6459     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
6460     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
6461     *        focus moved when requestFocus() is called. It may not always
6462     *        apply, in which case use the default View.FOCUS_DOWN.
6463     * @param previouslyFocusedRect The rectangle of the view that had focus
6464     *        prior in this View's coordinate system.
6465     */
6466    void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) {
6467        if (DBG) {
6468            System.out.println(this + " requestFocus()");
6469        }
6470
6471        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
6472            mPrivateFlags |= PFLAG_FOCUSED;
6473
6474            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
6475
6476            if (mParent != null) {
6477                mParent.requestChildFocus(this, this);
6478                setFocusedInCluster();
6479            }
6480
6481            if (mAttachInfo != null) {
6482                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
6483            }
6484
6485            onFocusChanged(true, direction, previouslyFocusedRect);
6486            refreshDrawableState();
6487        }
6488    }
6489
6490    /**
6491     * Sets this view's preference for reveal behavior when it gains focus.
6492     *
6493     * <p>When set to true, this is a signal to ancestor views in the hierarchy that
6494     * this view would prefer to be brought fully into view when it gains focus.
6495     * For example, a text field that a user is meant to type into. Other views such
6496     * as scrolling containers may prefer to opt-out of this behavior.</p>
6497     *
6498     * <p>The default value for views is true, though subclasses may change this
6499     * based on their preferred behavior.</p>
6500     *
6501     * @param revealOnFocus true to request reveal on focus in ancestors, false otherwise
6502     *
6503     * @see #getRevealOnFocusHint()
6504     */
6505    public final void setRevealOnFocusHint(boolean revealOnFocus) {
6506        if (revealOnFocus) {
6507            mPrivateFlags3 &= ~PFLAG3_NO_REVEAL_ON_FOCUS;
6508        } else {
6509            mPrivateFlags3 |= PFLAG3_NO_REVEAL_ON_FOCUS;
6510        }
6511    }
6512
6513    /**
6514     * Returns this view's preference for reveal behavior when it gains focus.
6515     *
6516     * <p>When this method returns true for a child view requesting focus, ancestor
6517     * views responding to a focus change in {@link ViewParent#requestChildFocus(View, View)}
6518     * should make a best effort to make the newly focused child fully visible to the user.
6519     * When it returns false, ancestor views should preferably not disrupt scroll positioning or
6520     * other properties affecting visibility to the user as part of the focus change.</p>
6521     *
6522     * @return true if this view would prefer to become fully visible when it gains focus,
6523     *         false if it would prefer not to disrupt scroll positioning
6524     *
6525     * @see #setRevealOnFocusHint(boolean)
6526     */
6527    public final boolean getRevealOnFocusHint() {
6528        return (mPrivateFlags3 & PFLAG3_NO_REVEAL_ON_FOCUS) == 0;
6529    }
6530
6531    /**
6532     * Populates <code>outRect</code> with the hotspot bounds. By default,
6533     * the hotspot bounds are identical to the screen bounds.
6534     *
6535     * @param outRect rect to populate with hotspot bounds
6536     * @hide Only for internal use by views and widgets.
6537     */
6538    public void getHotspotBounds(Rect outRect) {
6539        final Drawable background = getBackground();
6540        if (background != null) {
6541            background.getHotspotBounds(outRect);
6542        } else {
6543            getBoundsOnScreen(outRect);
6544        }
6545    }
6546
6547    /**
6548     * Request that a rectangle of this view be visible on the screen,
6549     * scrolling if necessary just enough.
6550     *
6551     * <p>A View should call this if it maintains some notion of which part
6552     * of its content is interesting.  For example, a text editing view
6553     * should call this when its cursor moves.
6554     * <p>The Rectangle passed into this method should be in the View's content coordinate space.
6555     * It should not be affected by which part of the View is currently visible or its scroll
6556     * position.
6557     *
6558     * @param rectangle The rectangle in the View's content coordinate space
6559     * @return Whether any parent scrolled.
6560     */
6561    public boolean requestRectangleOnScreen(Rect rectangle) {
6562        return requestRectangleOnScreen(rectangle, false);
6563    }
6564
6565    /**
6566     * Request that a rectangle of this view be visible on the screen,
6567     * scrolling if necessary just enough.
6568     *
6569     * <p>A View should call this if it maintains some notion of which part
6570     * of its content is interesting.  For example, a text editing view
6571     * should call this when its cursor moves.
6572     * <p>The Rectangle passed into this method should be in the View's content coordinate space.
6573     * It should not be affected by which part of the View is currently visible or its scroll
6574     * position.
6575     * <p>When <code>immediate</code> is set to true, scrolling will not be
6576     * animated.
6577     *
6578     * @param rectangle The rectangle in the View's content coordinate space
6579     * @param immediate True to forbid animated scrolling, false otherwise
6580     * @return Whether any parent scrolled.
6581     */
6582    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
6583        if (mParent == null) {
6584            return false;
6585        }
6586
6587        View child = this;
6588
6589        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
6590        position.set(rectangle);
6591
6592        ViewParent parent = mParent;
6593        boolean scrolled = false;
6594        while (parent != null) {
6595            rectangle.set((int) position.left, (int) position.top,
6596                    (int) position.right, (int) position.bottom);
6597
6598            scrolled |= parent.requestChildRectangleOnScreen(child, rectangle, immediate);
6599
6600            if (!(parent instanceof View)) {
6601                break;
6602            }
6603
6604            // move it from child's content coordinate space to parent's content coordinate space
6605            position.offset(child.mLeft - child.getScrollX(), child.mTop -child.getScrollY());
6606
6607            child = (View) parent;
6608            parent = child.getParent();
6609        }
6610
6611        return scrolled;
6612    }
6613
6614    /**
6615     * Called when this view wants to give up focus. If focus is cleared
6616     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
6617     * <p>
6618     * <strong>Note:</strong> When a View clears focus the framework is trying
6619     * to give focus to the first focusable View from the top. Hence, if this
6620     * View is the first from the top that can take focus, then all callbacks
6621     * related to clearing focus will be invoked after which the framework will
6622     * give focus to this view.
6623     * </p>
6624     */
6625    public void clearFocus() {
6626        if (DBG) {
6627            System.out.println(this + " clearFocus()");
6628        }
6629
6630        clearFocusInternal(null, true, true);
6631    }
6632
6633    /**
6634     * Clears focus from the view, optionally propagating the change up through
6635     * the parent hierarchy and requesting that the root view place new focus.
6636     *
6637     * @param propagate whether to propagate the change up through the parent
6638     *            hierarchy
6639     * @param refocus when propagate is true, specifies whether to request the
6640     *            root view place new focus
6641     */
6642    void clearFocusInternal(View focused, boolean propagate, boolean refocus) {
6643        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
6644            mPrivateFlags &= ~PFLAG_FOCUSED;
6645
6646            if (propagate && mParent != null) {
6647                mParent.clearChildFocus(this);
6648            }
6649
6650            onFocusChanged(false, 0, null);
6651            refreshDrawableState();
6652
6653            if (propagate && (!refocus || !rootViewRequestFocus())) {
6654                notifyGlobalFocusCleared(this);
6655            }
6656        }
6657    }
6658
6659    void notifyGlobalFocusCleared(View oldFocus) {
6660        if (oldFocus != null && mAttachInfo != null) {
6661            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
6662        }
6663    }
6664
6665    boolean rootViewRequestFocus() {
6666        final View root = getRootView();
6667        return root != null && root.requestFocus();
6668    }
6669
6670    /**
6671     * Called internally by the view system when a new view is getting focus.
6672     * This is what clears the old focus.
6673     * <p>
6674     * <b>NOTE:</b> The parent view's focused child must be updated manually
6675     * after calling this method. Otherwise, the view hierarchy may be left in
6676     * an inconstent state.
6677     */
6678    void unFocus(View focused) {
6679        if (DBG) {
6680            System.out.println(this + " unFocus()");
6681        }
6682
6683        clearFocusInternal(focused, false, false);
6684    }
6685
6686    /**
6687     * Returns true if this view has focus itself, or is the ancestor of the
6688     * view that has focus.
6689     *
6690     * @return True if this view has or contains focus, false otherwise.
6691     */
6692    @ViewDebug.ExportedProperty(category = "focus")
6693    public boolean hasFocus() {
6694        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
6695    }
6696
6697    /**
6698     * Returns true if this view is focusable or if it contains a reachable View
6699     * for which {@link #hasFocusable()} returns {@code true}. A "reachable hasFocusable()"
6700     * is a view whose parents do not block descendants focus.
6701     * Only {@link #VISIBLE} views are considered focusable.
6702     *
6703     * <p>As of {@link Build.VERSION_CODES#O} views that are determined to be focusable
6704     * through {@link #FOCUSABLE_AUTO} will also cause this method to return {@code true}.
6705     * Apps that declare a {@link android.content.pm.ApplicationInfo#targetSdkVersion} of
6706     * earlier than {@link Build.VERSION_CODES#O} will continue to see this method return
6707     * {@code false} for views not explicitly marked as focusable.
6708     * Use {@link #hasExplicitFocusable()} if you require the pre-{@link Build.VERSION_CODES#O}
6709     * behavior.</p>
6710     *
6711     * @return {@code true} if the view is focusable or if the view contains a focusable
6712     *         view, {@code false} otherwise
6713     *
6714     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
6715     * @see ViewGroup#getTouchscreenBlocksFocus()
6716     * @see #hasExplicitFocusable()
6717     */
6718    public boolean hasFocusable() {
6719        return hasFocusable(!sHasFocusableExcludeAutoFocusable, false);
6720    }
6721
6722    /**
6723     * Returns true if this view is focusable or if it contains a reachable View
6724     * for which {@link #hasExplicitFocusable()} returns {@code true}.
6725     * A "reachable hasExplicitFocusable()" is a view whose parents do not block descendants focus.
6726     * Only {@link #VISIBLE} views for which {@link #getFocusable()} would return
6727     * {@link #FOCUSABLE} are considered focusable.
6728     *
6729     * <p>This method preserves the pre-{@link Build.VERSION_CODES#O} behavior of
6730     * {@link #hasFocusable()} in that only views explicitly set focusable will cause
6731     * this method to return true. A view set to {@link #FOCUSABLE_AUTO} that resolves
6732     * to focusable will not.</p>
6733     *
6734     * @return {@code true} if the view is focusable or if the view contains a focusable
6735     *         view, {@code false} otherwise
6736     *
6737     * @see #hasFocusable()
6738     */
6739    public boolean hasExplicitFocusable() {
6740        return hasFocusable(false, true);
6741    }
6742
6743    boolean hasFocusable(boolean allowAutoFocus, boolean dispatchExplicit) {
6744        if (!isFocusableInTouchMode()) {
6745            for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) {
6746                final ViewGroup g = (ViewGroup) p;
6747                if (g.shouldBlockFocusForTouchscreen()) {
6748                    return false;
6749                }
6750            }
6751        }
6752
6753        // Invisible and gone views are never focusable.
6754        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6755            return false;
6756        }
6757
6758        // Only use effective focusable value when allowed.
6759        if ((allowAutoFocus || getFocusable() != FOCUSABLE_AUTO) && isFocusable()) {
6760            return true;
6761        }
6762
6763        return false;
6764    }
6765
6766    /**
6767     * Called by the view system when the focus state of this view changes.
6768     * When the focus change event is caused by directional navigation, direction
6769     * and previouslyFocusedRect provide insight into where the focus is coming from.
6770     * When overriding, be sure to call up through to the super class so that
6771     * the standard focus handling will occur.
6772     *
6773     * @param gainFocus True if the View has focus; false otherwise.
6774     * @param direction The direction focus has moved when requestFocus()
6775     *                  is called to give this view focus. Values are
6776     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
6777     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
6778     *                  It may not always apply, in which case use the default.
6779     * @param previouslyFocusedRect The rectangle, in this view's coordinate
6780     *        system, of the previously focused view.  If applicable, this will be
6781     *        passed in as finer grained information about where the focus is coming
6782     *        from (in addition to direction).  Will be <code>null</code> otherwise.
6783     */
6784    @CallSuper
6785    protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction,
6786            @Nullable Rect previouslyFocusedRect) {
6787        if (gainFocus) {
6788            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
6789        } else {
6790            notifyViewAccessibilityStateChangedIfNeeded(
6791                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
6792        }
6793
6794        InputMethodManager imm = InputMethodManager.peekInstance();
6795        if (!gainFocus) {
6796            if (isPressed()) {
6797                setPressed(false);
6798            }
6799            if (imm != null && mAttachInfo != null && mAttachInfo.mHasWindowFocus) {
6800                imm.focusOut(this);
6801            }
6802            onFocusLost();
6803        } else if (imm != null && mAttachInfo != null && mAttachInfo.mHasWindowFocus) {
6804            imm.focusIn(this);
6805        }
6806
6807        invalidate(true);
6808        ListenerInfo li = mListenerInfo;
6809        if (li != null && li.mOnFocusChangeListener != null) {
6810            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
6811        }
6812
6813        if (mAttachInfo != null) {
6814            mAttachInfo.mKeyDispatchState.reset(this);
6815        }
6816
6817        notifyEnterOrExitForAutoFillIfNeeded(gainFocus);
6818    }
6819
6820    private void notifyEnterOrExitForAutoFillIfNeeded(boolean enter) {
6821        if (isAutofillable() && isAttachedToWindow()
6822                && getResolvedAutofillMode() == AUTOFILL_MODE_AUTO) {
6823            AutofillManager afm = getAutofillManager();
6824            if (afm != null) {
6825                if (enter && hasWindowFocus() && isFocused()) {
6826                    afm.notifyViewEntered(this);
6827                } else if (!hasWindowFocus() || !isFocused()) {
6828                    afm.notifyViewExited(this);
6829                }
6830            }
6831        }
6832    }
6833
6834    /**
6835     * Sends an accessibility event of the given type. If accessibility is
6836     * not enabled this method has no effect. The default implementation calls
6837     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
6838     * to populate information about the event source (this View), then calls
6839     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
6840     * populate the text content of the event source including its descendants,
6841     * and last calls
6842     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
6843     * on its parent to request sending of the event to interested parties.
6844     * <p>
6845     * If an {@link AccessibilityDelegate} has been specified via calling
6846     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6847     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
6848     * responsible for handling this call.
6849     * </p>
6850     *
6851     * @param eventType The type of the event to send, as defined by several types from
6852     * {@link android.view.accessibility.AccessibilityEvent}, such as
6853     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
6854     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
6855     *
6856     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
6857     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6858     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
6859     * @see AccessibilityDelegate
6860     */
6861    public void sendAccessibilityEvent(int eventType) {
6862        if (mAccessibilityDelegate != null) {
6863            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
6864        } else {
6865            sendAccessibilityEventInternal(eventType);
6866        }
6867    }
6868
6869    /**
6870     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
6871     * {@link AccessibilityEvent} to make an announcement which is related to some
6872     * sort of a context change for which none of the events representing UI transitions
6873     * is a good fit. For example, announcing a new page in a book. If accessibility
6874     * is not enabled this method does nothing.
6875     *
6876     * @param text The announcement text.
6877     */
6878    public void announceForAccessibility(CharSequence text) {
6879        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
6880            AccessibilityEvent event = AccessibilityEvent.obtain(
6881                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
6882            onInitializeAccessibilityEvent(event);
6883            event.getText().add(text);
6884            event.setContentDescription(null);
6885            mParent.requestSendAccessibilityEvent(this, event);
6886        }
6887    }
6888
6889    /**
6890     * @see #sendAccessibilityEvent(int)
6891     *
6892     * Note: Called from the default {@link AccessibilityDelegate}.
6893     *
6894     * @hide
6895     */
6896    public void sendAccessibilityEventInternal(int eventType) {
6897        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
6898            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
6899        }
6900    }
6901
6902    /**
6903     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
6904     * takes as an argument an empty {@link AccessibilityEvent} and does not
6905     * perform a check whether accessibility is enabled.
6906     * <p>
6907     * If an {@link AccessibilityDelegate} has been specified via calling
6908     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6909     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
6910     * is responsible for handling this call.
6911     * </p>
6912     *
6913     * @param event The event to send.
6914     *
6915     * @see #sendAccessibilityEvent(int)
6916     */
6917    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
6918        if (mAccessibilityDelegate != null) {
6919            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
6920        } else {
6921            sendAccessibilityEventUncheckedInternal(event);
6922        }
6923    }
6924
6925    /**
6926     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
6927     *
6928     * Note: Called from the default {@link AccessibilityDelegate}.
6929     *
6930     * @hide
6931     */
6932    public void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
6933        if (!isShown()) {
6934            return;
6935        }
6936        onInitializeAccessibilityEvent(event);
6937        // Only a subset of accessibility events populates text content.
6938        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
6939            dispatchPopulateAccessibilityEvent(event);
6940        }
6941        // In the beginning we called #isShown(), so we know that getParent() is not null.
6942        getParent().requestSendAccessibilityEvent(this, event);
6943    }
6944
6945    /**
6946     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
6947     * to its children for adding their text content to the event. Note that the
6948     * event text is populated in a separate dispatch path since we add to the
6949     * event not only the text of the source but also the text of all its descendants.
6950     * A typical implementation will call
6951     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
6952     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
6953     * on each child. Override this method if custom population of the event text
6954     * content is required.
6955     * <p>
6956     * If an {@link AccessibilityDelegate} has been specified via calling
6957     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6958     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
6959     * is responsible for handling this call.
6960     * </p>
6961     * <p>
6962     * <em>Note:</em> Accessibility events of certain types are not dispatched for
6963     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
6964     * </p>
6965     *
6966     * @param event The event.
6967     *
6968     * @return True if the event population was completed.
6969     */
6970    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
6971        if (mAccessibilityDelegate != null) {
6972            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
6973        } else {
6974            return dispatchPopulateAccessibilityEventInternal(event);
6975        }
6976    }
6977
6978    /**
6979     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6980     *
6981     * Note: Called from the default {@link AccessibilityDelegate}.
6982     *
6983     * @hide
6984     */
6985    public boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
6986        onPopulateAccessibilityEvent(event);
6987        return false;
6988    }
6989
6990    /**
6991     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
6992     * giving a chance to this View to populate the accessibility event with its
6993     * text content. While this method is free to modify event
6994     * attributes other than text content, doing so should normally be performed in
6995     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
6996     * <p>
6997     * Example: Adding formatted date string to an accessibility event in addition
6998     *          to the text added by the super implementation:
6999     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
7000     *     super.onPopulateAccessibilityEvent(event);
7001     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
7002     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
7003     *         mCurrentDate.getTimeInMillis(), flags);
7004     *     event.getText().add(selectedDateUtterance);
7005     * }</pre>
7006     * <p>
7007     * If an {@link AccessibilityDelegate} has been specified via calling
7008     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7009     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
7010     * is responsible for handling this call.
7011     * </p>
7012     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
7013     * information to the event, in case the default implementation has basic information to add.
7014     * </p>
7015     *
7016     * @param event The accessibility event which to populate.
7017     *
7018     * @see #sendAccessibilityEvent(int)
7019     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
7020     */
7021    @CallSuper
7022    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
7023        if (mAccessibilityDelegate != null) {
7024            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
7025        } else {
7026            onPopulateAccessibilityEventInternal(event);
7027        }
7028    }
7029
7030    /**
7031     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
7032     *
7033     * Note: Called from the default {@link AccessibilityDelegate}.
7034     *
7035     * @hide
7036     */
7037    public void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
7038    }
7039
7040    /**
7041     * Initializes an {@link AccessibilityEvent} with information about
7042     * this View which is the event source. In other words, the source of
7043     * an accessibility event is the view whose state change triggered firing
7044     * the event.
7045     * <p>
7046     * Example: Setting the password property of an event in addition
7047     *          to properties set by the super implementation:
7048     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
7049     *     super.onInitializeAccessibilityEvent(event);
7050     *     event.setPassword(true);
7051     * }</pre>
7052     * <p>
7053     * If an {@link AccessibilityDelegate} has been specified via calling
7054     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7055     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
7056     * is responsible for handling this call.
7057     * </p>
7058     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
7059     * information to the event, in case the default implementation has basic information to add.
7060     * </p>
7061     * @param event The event to initialize.
7062     *
7063     * @see #sendAccessibilityEvent(int)
7064     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
7065     */
7066    @CallSuper
7067    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
7068        if (mAccessibilityDelegate != null) {
7069            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
7070        } else {
7071            onInitializeAccessibilityEventInternal(event);
7072        }
7073    }
7074
7075    /**
7076     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
7077     *
7078     * Note: Called from the default {@link AccessibilityDelegate}.
7079     *
7080     * @hide
7081     */
7082    public void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
7083        event.setSource(this);
7084        event.setClassName(getAccessibilityClassName());
7085        event.setPackageName(getContext().getPackageName());
7086        event.setEnabled(isEnabled());
7087        event.setContentDescription(mContentDescription);
7088
7089        switch (event.getEventType()) {
7090            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
7091                ArrayList<View> focusablesTempList = (mAttachInfo != null)
7092                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
7093                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
7094                event.setItemCount(focusablesTempList.size());
7095                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
7096                if (mAttachInfo != null) {
7097                    focusablesTempList.clear();
7098                }
7099            } break;
7100            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
7101                CharSequence text = getIterableTextForAccessibility();
7102                if (text != null && text.length() > 0) {
7103                    event.setFromIndex(getAccessibilitySelectionStart());
7104                    event.setToIndex(getAccessibilitySelectionEnd());
7105                    event.setItemCount(text.length());
7106                }
7107            } break;
7108        }
7109    }
7110
7111    /**
7112     * Returns an {@link AccessibilityNodeInfo} representing this view from the
7113     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
7114     * This method is responsible for obtaining an accessibility node info from a
7115     * pool of reusable instances and calling
7116     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
7117     * initialize the former.
7118     * <p>
7119     * Note: The client is responsible for recycling the obtained instance by calling
7120     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
7121     * </p>
7122     *
7123     * @return A populated {@link AccessibilityNodeInfo}.
7124     *
7125     * @see AccessibilityNodeInfo
7126     */
7127    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
7128        if (mAccessibilityDelegate != null) {
7129            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
7130        } else {
7131            return createAccessibilityNodeInfoInternal();
7132        }
7133    }
7134
7135    /**
7136     * @see #createAccessibilityNodeInfo()
7137     *
7138     * @hide
7139     */
7140    public AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
7141        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
7142        if (provider != null) {
7143            return provider.createAccessibilityNodeInfo(AccessibilityNodeProvider.HOST_VIEW_ID);
7144        } else {
7145            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
7146            onInitializeAccessibilityNodeInfo(info);
7147            return info;
7148        }
7149    }
7150
7151    /**
7152     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
7153     * The base implementation sets:
7154     * <ul>
7155     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
7156     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
7157     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
7158     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
7159     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
7160     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
7161     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
7162     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
7163     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
7164     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
7165     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
7166     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
7167     *   <li>{@link AccessibilityNodeInfo#setContextClickable(boolean)}</li>
7168     * </ul>
7169     * <p>
7170     * Subclasses should override this method, call the super implementation,
7171     * and set additional attributes.
7172     * </p>
7173     * <p>
7174     * If an {@link AccessibilityDelegate} has been specified via calling
7175     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7176     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
7177     * is responsible for handling this call.
7178     * </p>
7179     *
7180     * @param info The instance to initialize.
7181     */
7182    @CallSuper
7183    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
7184        if (mAccessibilityDelegate != null) {
7185            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
7186        } else {
7187            onInitializeAccessibilityNodeInfoInternal(info);
7188        }
7189    }
7190
7191    /**
7192     * Gets the location of this view in screen coordinates.
7193     *
7194     * @param outRect The output location
7195     * @hide
7196     */
7197    public void getBoundsOnScreen(Rect outRect) {
7198        getBoundsOnScreen(outRect, false);
7199    }
7200
7201    /**
7202     * Gets the location of this view in screen coordinates.
7203     *
7204     * @param outRect The output location
7205     * @param clipToParent Whether to clip child bounds to the parent ones.
7206     * @hide
7207     */
7208    public void getBoundsOnScreen(Rect outRect, boolean clipToParent) {
7209        if (mAttachInfo == null) {
7210            return;
7211        }
7212
7213        RectF position = mAttachInfo.mTmpTransformRect;
7214        position.set(0, 0, mRight - mLeft, mBottom - mTop);
7215
7216        if (!hasIdentityMatrix()) {
7217            getMatrix().mapRect(position);
7218        }
7219
7220        position.offset(mLeft, mTop);
7221
7222        ViewParent parent = mParent;
7223        while (parent instanceof View) {
7224            View parentView = (View) parent;
7225
7226            position.offset(-parentView.mScrollX, -parentView.mScrollY);
7227
7228            if (clipToParent) {
7229                position.left = Math.max(position.left, 0);
7230                position.top = Math.max(position.top, 0);
7231                position.right = Math.min(position.right, parentView.getWidth());
7232                position.bottom = Math.min(position.bottom, parentView.getHeight());
7233            }
7234
7235            if (!parentView.hasIdentityMatrix()) {
7236                parentView.getMatrix().mapRect(position);
7237            }
7238
7239            position.offset(parentView.mLeft, parentView.mTop);
7240
7241            parent = parentView.mParent;
7242        }
7243
7244        if (parent instanceof ViewRootImpl) {
7245            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
7246            position.offset(0, -viewRootImpl.mCurScrollY);
7247        }
7248
7249        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
7250
7251        outRect.set(Math.round(position.left), Math.round(position.top),
7252                Math.round(position.right), Math.round(position.bottom));
7253    }
7254
7255    /**
7256     * Return the class name of this object to be used for accessibility purposes.
7257     * Subclasses should only override this if they are implementing something that
7258     * should be seen as a completely new class of view when used by accessibility,
7259     * unrelated to the class it is deriving from.  This is used to fill in
7260     * {@link AccessibilityNodeInfo#setClassName AccessibilityNodeInfo.setClassName}.
7261     */
7262    public CharSequence getAccessibilityClassName() {
7263        return View.class.getName();
7264    }
7265
7266    /**
7267     * Called when assist structure is being retrieved from a view as part of
7268     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData}.
7269     * @param structure Fill in with structured view data.  The default implementation
7270     * fills in all data that can be inferred from the view itself.
7271     */
7272    public void onProvideStructure(ViewStructure structure) {
7273        onProvideStructureForAssistOrAutofill(structure, false);
7274    }
7275
7276    /**
7277     * Called when assist structure is being retrieved from a view as part of an autofill request.
7278     *
7279     * <p>This method already provides most of what's needed for autofill, but should be overridden
7280     * when:
7281     * <ol>
7282     * <li>The view contents does not include PII (Personally Identifiable Information), so it
7283     * can call {@link ViewStructure#setDataIsSensitive(boolean)} passing {@code false}.
7284     * <li>It must set fields such {@link ViewStructure#setText(CharSequence)},
7285     * {@link ViewStructure#setAutofillOptions(String[])}, or {@link ViewStructure#setUrl(String)}.
7286     * </ol>
7287     *
7288     * @param structure Fill in with structured view data. The default implementation
7289     * fills in all data that can be inferred from the view itself.
7290     * @param flags optional flags (currently {@code 0}).
7291     */
7292    public void onProvideAutofillStructure(ViewStructure structure, int flags) {
7293        onProvideStructureForAssistOrAutofill(structure, true);
7294    }
7295
7296    private void setAutofillId(ViewStructure structure) {
7297        // The autofill id needs to be unique, but its value doesn't matter,
7298        // so it's better to reuse the accessibility id to save space.
7299        structure.setAutofillId(getAccessibilityViewId());
7300    }
7301
7302    private void onProvideStructureForAssistOrAutofill(ViewStructure structure,
7303            boolean forAutofill) {
7304        final int id = mID;
7305        if (id != NO_ID && !isViewIdGenerated(id)) {
7306            String pkg, type, entry;
7307            try {
7308                final Resources res = getResources();
7309                entry = res.getResourceEntryName(id);
7310                type = res.getResourceTypeName(id);
7311                pkg = res.getResourcePackageName(id);
7312            } catch (Resources.NotFoundException e) {
7313                entry = type = pkg = null;
7314            }
7315            structure.setId(id, pkg, type, entry);
7316        } else {
7317            structure.setId(id, null, null, null);
7318        }
7319
7320        if (forAutofill) {
7321            setAutofillId(structure);
7322            final @AutofillType int autofillType = getAutofillType();
7323            // Don't need to fill autofill info if view does not support it.
7324            // For example, only TextViews that are editable support autofill
7325            if (autofillType != AUTOFILL_TYPE_NONE) {
7326                structure.setAutofillType(autofillType);
7327                structure.setAutofillHints(getAutofillHints());
7328                structure.setAutofillValue(getAutofillValue());
7329            }
7330        }
7331
7332        structure.setDimens(mLeft, mTop, mScrollX, mScrollY, mRight - mLeft, mBottom - mTop);
7333        if (!hasIdentityMatrix()) {
7334            structure.setTransformation(getMatrix());
7335        }
7336        structure.setElevation(getZ());
7337        structure.setVisibility(getVisibility());
7338        structure.setEnabled(isEnabled());
7339        if (isClickable()) {
7340            structure.setClickable(true);
7341        }
7342        if (isFocusable()) {
7343            structure.setFocusable(true);
7344        }
7345        if (isFocused()) {
7346            structure.setFocused(true);
7347        }
7348        if (isAccessibilityFocused()) {
7349            structure.setAccessibilityFocused(true);
7350        }
7351        if (isSelected()) {
7352            structure.setSelected(true);
7353        }
7354        if (isActivated()) {
7355            structure.setActivated(true);
7356        }
7357        if (isLongClickable()) {
7358            structure.setLongClickable(true);
7359        }
7360        if (this instanceof Checkable) {
7361            structure.setCheckable(true);
7362            if (((Checkable)this).isChecked()) {
7363                structure.setChecked(true);
7364            }
7365        }
7366        if (isOpaque()) {
7367            structure.setOpaque(true);
7368        }
7369        if (isContextClickable()) {
7370            structure.setContextClickable(true);
7371        }
7372        structure.setClassName(getAccessibilityClassName().toString());
7373        structure.setContentDescription(getContentDescription());
7374    }
7375
7376    /**
7377     * Called when assist structure is being retrieved from a view as part of
7378     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData} to
7379     * generate additional virtual structure under this view.  The defaullt implementation
7380     * uses {@link #getAccessibilityNodeProvider()} to try to generate this from the
7381     * view's virtual accessibility nodes, if any.  You can override this for a more
7382     * optimal implementation providing this data.
7383     */
7384    public void onProvideVirtualStructure(ViewStructure structure) {
7385        onProvideVirtualStructureForAssistOrAutofill(structure, false);
7386    }
7387
7388    /**
7389     * Called when assist structure is being retrieved from a view as part of an autofill request
7390     * to generate additional virtual structure under this view.
7391     *
7392     * <p>The default implementation uses {@link #getAccessibilityNodeProvider()} to try to
7393     * generate this from the view's virtual accessibility nodes, if any. You can override this
7394     * for a more optimal implementation providing this data.
7395     *
7396     * <p>When implementing this method, subclasses must follow the rules below:
7397     *
7398     * <ol>
7399     * <li>Also implement {@link #autofill(SparseArray)} to autofill the virtual
7400     * children.
7401     * <li>Call
7402     * {@link android.view.autofill.AutofillManager#notifyViewEntered} and
7403     * {@link android.view.autofill.AutofillManager#notifyViewExited(View, int)}
7404     * when the focus inside the view changed.
7405     * <li>Call {@link android.view.autofill.AutofillManager#notifyValueChanged(View, int,
7406     * AutofillValue)} when the value of a child changed.
7407     * <li>Call {@link AutofillManager#commit()} when the autofill context
7408     * of the view structure changed and you want the current autofill interaction if such
7409     * to be commited.
7410     * <li>Call {@link AutofillManager#cancel()} ()} when the autofill context
7411     * of the view structure changed and you want the current autofill interaction if such
7412     * to be cancelled.
7413     * </ol>
7414     *
7415     * @param structure Fill in with structured view data.
7416     * @param flags optional flags (currently {@code 0}).
7417     */
7418    public void onProvideAutofillVirtualStructure(ViewStructure structure, int flags) {
7419        onProvideVirtualStructureForAssistOrAutofill(structure, true);
7420    }
7421
7422    private void onProvideVirtualStructureForAssistOrAutofill(ViewStructure structure,
7423            boolean forAutofill) {
7424        if (forAutofill) {
7425            setAutofillId(structure);
7426        }
7427        // NOTE: currently flags are only used for AutoFill; if they're used for Assist as well,
7428        // this method should take a boolean with the type of request.
7429        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
7430        if (provider != null) {
7431            AccessibilityNodeInfo info = createAccessibilityNodeInfo();
7432            structure.setChildCount(1);
7433            ViewStructure root = structure.newChild(0);
7434            populateVirtualStructure(root, provider, info, forAutofill);
7435            info.recycle();
7436        }
7437    }
7438
7439    /**
7440     * Automatically fills the content of this view with the {@code value}.
7441     *
7442     * <p>By default does nothing, but views should override it (and {@link #getAutofillType()},
7443     * {@link #getAutofillValue()}, and {@link #onProvideAutofillStructure(ViewStructure, int)}
7444     * to support the Autofill Framework.
7445     *
7446     * <p>Typically, it is implemented by:
7447     *
7448     * <ol>
7449     * <li>Calling the proper getter method on {@link AutofillValue} to fetch the actual value.
7450     * <li>Passing the actual value to the equivalent setter in the view.
7451     * </ol>
7452     *
7453     * <p>For example, a text-field view would call:
7454     * <pre class="prettyprint">
7455     * CharSequence text = value.getTextValue();
7456     * if (text != null) {
7457     *     setText(text);
7458     * }
7459     * </pre>
7460     *
7461     * <p>If the value is updated asyncronously the next call to
7462     * {@link AutofillManager#notifyValueChanged(View)} must happen <u>after</u> the value was
7463     * changed to the autofilled value. If not, the view will not be considered autofilled.
7464     *
7465     * @param value value to be autofilled.
7466     */
7467    public void autofill(@SuppressWarnings("unused") AutofillValue value) {
7468    }
7469
7470    /**
7471     * Automatically fills the content of a virtual views.
7472     *
7473     * <p>See {@link #autofill(AutofillValue)} and
7474     * {@link #onProvideAutofillVirtualStructure(ViewStructure, int)} for more info.
7475     * <p>To indicate that a virtual view was autofilled
7476     * <code>@android:drawable/autofilled_highlight</code> should be drawn over it until the data
7477     * changes.
7478     *
7479     * @param values map of values to be autofilled, keyed by virtual child id.
7480     */
7481    public void autofill(@NonNull @SuppressWarnings("unused") SparseArray<AutofillValue> values) {
7482    }
7483
7484    /**
7485     * Describes the autofill type that should be used on calls to
7486     * {@link #autofill(AutofillValue)} and {@link #autofill(SparseArray)}.
7487     *
7488     * <p>By default returns {@link #AUTOFILL_TYPE_NONE}, but views should override it (and
7489     * {@link #autofill(AutofillValue)} to support the Autofill Framework.
7490     */
7491    public @AutofillType int getAutofillType() {
7492        return AUTOFILL_TYPE_NONE;
7493    }
7494
7495    /**
7496     * Describes the content of a view so that a autofill service can fill in the appropriate data.
7497     *
7498     * @return The hints set via the attribute or {@code null} if no hint it set.
7499     *
7500     * @attr ref android.R.styleable#View_autofillHints
7501     */
7502    @ViewDebug.ExportedProperty()
7503    @Nullable public String[] getAutofillHints() {
7504        return mAutofillHints;
7505    }
7506
7507    /**
7508     * @hide
7509     */
7510    public boolean isAutofilled() {
7511        return (mPrivateFlags3 & PFLAG3_IS_AUTOFILLED) != 0;
7512    }
7513
7514    /**
7515     * Gets the {@link View}'s current autofill value.
7516     *
7517     * <p>By default returns {@code null}, but views should override it (and
7518     * {@link #autofill(AutofillValue)}, and {@link #getAutofillType()} to support the Autofill
7519     * Framework.
7520     */
7521    @Nullable
7522    public AutofillValue getAutofillValue() {
7523        return null;
7524    }
7525
7526    /**
7527     * Gets the mode for determining whether this View is important for autofill.
7528     *
7529     * <p>See {@link #setImportantForAutofill(int)} for more info about this mode.
7530     *
7531     * @return {@link #IMPORTANT_FOR_AUTOFILL_AUTO} by default, or value passed to
7532     * {@link #setImportantForAutofill(int)}.
7533     *
7534     * @attr ref android.R.styleable#View_importantForAutofill
7535     */
7536    @ViewDebug.ExportedProperty(mapping = {
7537            @ViewDebug.IntToString(from = IMPORTANT_FOR_AUTOFILL_AUTO, to = "auto"),
7538            @ViewDebug.IntToString(from = IMPORTANT_FOR_AUTOFILL_YES, to = "yes"),
7539            @ViewDebug.IntToString(from = IMPORTANT_FOR_AUTOFILL_NO, to = "no")})
7540    public @AutofillImportance int getImportantForAutofill() {
7541        return (mPrivateFlags3
7542                & PFLAG3_IMPORTANT_FOR_AUTOFILL_MASK) >> PFLAG3_IMPORTANT_FOR_AUTOFILL_SHIFT;
7543    }
7544
7545    /**
7546     * Sets the mode for determining whether this View is important for autofill.
7547     *
7548     * <p>See {@link #setImportantForAutofill(int)} for more info about this mode.
7549     *
7550     * @param mode {@link #IMPORTANT_FOR_AUTOFILL_AUTO}, {@link #IMPORTANT_FOR_AUTOFILL_YES},
7551     * or {@link #IMPORTANT_FOR_AUTOFILL_NO}.
7552     *
7553     * @attr ref android.R.styleable#View_importantForAutofill
7554     */
7555    public void setImportantForAutofill(@AutofillImportance int mode) {
7556        mPrivateFlags3 &= ~PFLAG3_IMPORTANT_FOR_AUTOFILL_MASK;
7557        mPrivateFlags3 |= (mode << PFLAG3_IMPORTANT_FOR_AUTOFILL_SHIFT)
7558                & PFLAG3_IMPORTANT_FOR_AUTOFILL_MASK;
7559    }
7560
7561    /**
7562     * Hints the Android System whether the {@link android.app.assist.AssistStructure.ViewNode}
7563     * associated with this View should be included in a {@link ViewStructure} used for
7564     * autofill purposes.
7565     *
7566     * <p>Generally speaking, a view is important for autofill if:
7567     * <ol>
7568     * <li>The view can-be autofilled by an {@link android.service.autofill.AutofillService}.
7569     * <li>The view contents can help an {@link android.service.autofill.AutofillService} to
7570     * autofill other views.
7571     * <ol>
7572     *
7573     * <p>For example, view containers should typically return {@code false} for performance reasons
7574     * (since the important info is provided by their children), but if the container is actually
7575     * whose children are part of a compound view, it should return {@code true} (and then override
7576     * {@link #dispatchProvideAutofillStructure(ViewStructure, int)} to simply call
7577     * {@link #onProvideAutofillStructure(ViewStructure, int)} so its children are not included in
7578     * the structure). On the other hand, views representing labels or editable fields should
7579     * typically return {@code true}, but in some cases they could return {@code false} (for
7580     * example, if they're part of a "Captcha" mechanism).
7581     *
7582     * <p>By default, this method returns {@code true} if {@link #getImportantForAutofill()} returns
7583     * {@link #IMPORTANT_FOR_AUTOFILL_YES}, {@code false } if it returns
7584     * {@link #IMPORTANT_FOR_AUTOFILL_NO}, and use some heuristics to define the importance when it
7585     * returns {@link #IMPORTANT_FOR_AUTOFILL_AUTO}. Hence, it should rarely be overridden - Views
7586     * should use {@link #setImportantForAutofill(int)} instead.
7587     *
7588     * <p><strong>Note:</strong> returning {@code false} does not guarantee the view will be
7589     * excluded from the structure; for example, if the user explicitly requested auto-fill, the
7590     * View might be always included.
7591     *
7592     * <p>This decision applies just for the view, not its children - if the view children are not
7593     * important for autofill, the view should override
7594     * {@link #dispatchProvideAutofillStructure(ViewStructure, int)} to simply call
7595     * {@link #onProvideAutofillStructure(ViewStructure, int)} (instead of calling
7596     * {@link #dispatchProvideAutofillStructure(ViewStructure, int)} for each child).
7597     *
7598     * @return whether the view is considered important for autofill.
7599     *
7600     * @see #IMPORTANT_FOR_AUTOFILL_AUTO
7601     * @see #IMPORTANT_FOR_AUTOFILL_YES
7602     * @see #IMPORTANT_FOR_AUTOFILL_NO
7603     */
7604    public final boolean isImportantForAutofill() {
7605        final int flag = getImportantForAutofill();
7606
7607        // First, check if view explicity set it to YES or NO
7608        if ((flag & IMPORTANT_FOR_AUTOFILL_YES) != 0) {
7609            return true;
7610        }
7611        if ((flag & IMPORTANT_FOR_AUTOFILL_NO) != 0) {
7612            return false;
7613        }
7614
7615        // Then use some heuristics to handle AUTO.
7616
7617        // Always include views that have a explicity resource id.
7618        final int id = mID;
7619        if (id != NO_ID && !isViewIdGenerated(id)) {
7620            final Resources res = getResources();
7621            String entry = null;
7622            String pkg = null;
7623            try {
7624                entry = res.getResourceEntryName(id);
7625                pkg = res.getResourcePackageName(id);
7626            } catch (Resources.NotFoundException e) {
7627                // ignore
7628            }
7629            if (entry != null && pkg != null && pkg.equals(mContext.getPackageName())) {
7630                return true;
7631            }
7632        }
7633
7634        // Otherwise, assume it's not important...
7635        return false;
7636    }
7637
7638    @Nullable
7639    private AutofillManager getAutofillManager() {
7640        return mContext.getSystemService(AutofillManager.class);
7641    }
7642
7643    private boolean isAutofillable() {
7644        return getAutofillType() != AUTOFILL_TYPE_NONE && !isAutofillBlocked();
7645    }
7646
7647    private void populateVirtualStructure(ViewStructure structure,
7648            AccessibilityNodeProvider provider, AccessibilityNodeInfo info, boolean forAutofill) {
7649        structure.setId(AccessibilityNodeInfo.getVirtualDescendantId(info.getSourceNodeId()),
7650                null, null, null);
7651        Rect rect = structure.getTempRect();
7652        info.getBoundsInParent(rect);
7653        structure.setDimens(rect.left, rect.top, 0, 0, rect.width(), rect.height());
7654        structure.setVisibility(VISIBLE);
7655        structure.setEnabled(info.isEnabled());
7656        if (info.isClickable()) {
7657            structure.setClickable(true);
7658        }
7659        if (info.isFocusable()) {
7660            structure.setFocusable(true);
7661        }
7662        if (info.isFocused()) {
7663            structure.setFocused(true);
7664        }
7665        if (info.isAccessibilityFocused()) {
7666            structure.setAccessibilityFocused(true);
7667        }
7668        if (info.isSelected()) {
7669            structure.setSelected(true);
7670        }
7671        if (info.isLongClickable()) {
7672            structure.setLongClickable(true);
7673        }
7674        if (info.isCheckable()) {
7675            structure.setCheckable(true);
7676            if (info.isChecked()) {
7677                structure.setChecked(true);
7678            }
7679        }
7680        if (info.isContextClickable()) {
7681            structure.setContextClickable(true);
7682        }
7683        CharSequence cname = info.getClassName();
7684        structure.setClassName(cname != null ? cname.toString() : null);
7685        structure.setContentDescription(info.getContentDescription());
7686        if (!forAutofill && (info.getText() != null || info.getError() != null)) {
7687            // TODO(b/33197203) (b/33269702): when sanitized, try to use the Accessibility API to
7688            // just set sanitized values (like text coming from resource files), rather than not
7689            // setting it at all.
7690            structure.setText(info.getText(), info.getTextSelectionStart(),
7691                    info.getTextSelectionEnd());
7692        }
7693        final int NCHILDREN = info.getChildCount();
7694        if (NCHILDREN > 0) {
7695            structure.setChildCount(NCHILDREN);
7696            for (int i=0; i<NCHILDREN; i++) {
7697                AccessibilityNodeInfo cinfo = provider.createAccessibilityNodeInfo(
7698                        AccessibilityNodeInfo.getVirtualDescendantId(info.getChildId(i)));
7699                ViewStructure child = structure.newChild(i);
7700                if (forAutofill) {
7701                    // TODO(b/33197203): add CTS test to autofill virtual children based on
7702                    // Accessibility API.
7703                    child.setAutofillId(structure, i);
7704                }
7705                populateVirtualStructure(child, provider, cinfo, forAutofill);
7706                cinfo.recycle();
7707            }
7708        }
7709    }
7710
7711    /**
7712     * Dispatch creation of {@link ViewStructure} down the hierarchy.  The default
7713     * implementation calls {@link #onProvideStructure} and
7714     * {@link #onProvideVirtualStructure}.
7715     */
7716    public void dispatchProvideStructure(ViewStructure structure) {
7717        dispatchProvideStructureForAssistOrAutofill(structure, false);
7718    }
7719
7720    /**
7721     * Dispatch creation of {@link ViewStructure} down the hierarchy.
7722     *
7723     * <p>The structure must be filled according to the request type, which is set in the
7724     * {@code flags} parameter - see the documentation on each flag for more details.
7725     *
7726     * <p>The default implementation calls {@link #onProvideAutofillStructure(ViewStructure, int)}
7727     * and {@link #onProvideAutofillVirtualStructure(ViewStructure, int)}.
7728     *
7729     * @param structure Fill in with structured view data.
7730     * @param flags optional flags (currently {@code 0}).
7731     */
7732    public void dispatchProvideAutofillStructure(ViewStructure structure, int flags) {
7733        dispatchProvideStructureForAssistOrAutofill(structure, true);
7734    }
7735
7736    private void dispatchProvideStructureForAssistOrAutofill(ViewStructure structure,
7737            boolean forAutofill) {
7738        boolean blocked = forAutofill ? isAutofillBlocked() : isAssistBlocked();
7739        if (!blocked) {
7740            if (forAutofill) {
7741                setAutofillId(structure);
7742                // NOTE: flags are not currently supported, hence 0
7743                onProvideAutofillStructure(structure, 0);
7744                onProvideAutofillVirtualStructure(structure, 0);
7745            } else {
7746                onProvideStructure(structure);
7747                onProvideVirtualStructure(structure);
7748            }
7749        } else {
7750            structure.setClassName(getAccessibilityClassName().toString());
7751            structure.setAssistBlocked(true);
7752        }
7753    }
7754
7755    /**
7756     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
7757     *
7758     * Note: Called from the default {@link AccessibilityDelegate}.
7759     *
7760     * @hide
7761     */
7762    public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
7763        if (mAttachInfo == null) {
7764            return;
7765        }
7766
7767        Rect bounds = mAttachInfo.mTmpInvalRect;
7768
7769        getDrawingRect(bounds);
7770        info.setBoundsInParent(bounds);
7771
7772        getBoundsOnScreen(bounds, true);
7773        info.setBoundsInScreen(bounds);
7774
7775        ViewParent parent = getParentForAccessibility();
7776        if (parent instanceof View) {
7777            info.setParent((View) parent);
7778        }
7779
7780        if (mID != View.NO_ID) {
7781            View rootView = getRootView();
7782            if (rootView == null) {
7783                rootView = this;
7784            }
7785
7786            View label = rootView.findLabelForView(this, mID);
7787            if (label != null) {
7788                info.setLabeledBy(label);
7789            }
7790
7791            if ((mAttachInfo.mAccessibilityFetchFlags
7792                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
7793                    && Resources.resourceHasPackage(mID)) {
7794                try {
7795                    String viewId = getResources().getResourceName(mID);
7796                    info.setViewIdResourceName(viewId);
7797                } catch (Resources.NotFoundException nfe) {
7798                    /* ignore */
7799                }
7800            }
7801        }
7802
7803        if (mLabelForId != View.NO_ID) {
7804            View rootView = getRootView();
7805            if (rootView == null) {
7806                rootView = this;
7807            }
7808            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
7809            if (labeled != null) {
7810                info.setLabelFor(labeled);
7811            }
7812        }
7813
7814        if (mAccessibilityTraversalBeforeId != View.NO_ID) {
7815            View rootView = getRootView();
7816            if (rootView == null) {
7817                rootView = this;
7818            }
7819            View next = rootView.findViewInsideOutShouldExist(this,
7820                    mAccessibilityTraversalBeforeId);
7821            if (next != null && next.includeForAccessibility()) {
7822                info.setTraversalBefore(next);
7823            }
7824        }
7825
7826        if (mAccessibilityTraversalAfterId != View.NO_ID) {
7827            View rootView = getRootView();
7828            if (rootView == null) {
7829                rootView = this;
7830            }
7831            View next = rootView.findViewInsideOutShouldExist(this,
7832                    mAccessibilityTraversalAfterId);
7833            if (next != null && next.includeForAccessibility()) {
7834                info.setTraversalAfter(next);
7835            }
7836        }
7837
7838        info.setVisibleToUser(isVisibleToUser());
7839
7840        info.setImportantForAccessibility(isImportantForAccessibility());
7841        info.setPackageName(mContext.getPackageName());
7842        info.setClassName(getAccessibilityClassName());
7843        info.setContentDescription(getContentDescription());
7844
7845        info.setEnabled(isEnabled());
7846        info.setClickable(isClickable());
7847        info.setFocusable(isFocusable());
7848        info.setFocused(isFocused());
7849        info.setAccessibilityFocused(isAccessibilityFocused());
7850        info.setSelected(isSelected());
7851        info.setLongClickable(isLongClickable());
7852        info.setContextClickable(isContextClickable());
7853        info.setLiveRegion(getAccessibilityLiveRegion());
7854
7855        // TODO: These make sense only if we are in an AdapterView but all
7856        // views can be selected. Maybe from accessibility perspective
7857        // we should report as selectable view in an AdapterView.
7858        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
7859        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
7860
7861        if (isFocusable()) {
7862            if (isFocused()) {
7863                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
7864            } else {
7865                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
7866            }
7867        }
7868
7869        if (!isAccessibilityFocused()) {
7870            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
7871        } else {
7872            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
7873        }
7874
7875        if (isClickable() && isEnabled()) {
7876            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
7877        }
7878
7879        if (isLongClickable() && isEnabled()) {
7880            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
7881        }
7882
7883        if (isContextClickable() && isEnabled()) {
7884            info.addAction(AccessibilityAction.ACTION_CONTEXT_CLICK);
7885        }
7886
7887        CharSequence text = getIterableTextForAccessibility();
7888        if (text != null && text.length() > 0) {
7889            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
7890
7891            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
7892            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
7893            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
7894            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
7895                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
7896                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
7897        }
7898
7899        info.addAction(AccessibilityAction.ACTION_SHOW_ON_SCREEN);
7900        populateAccessibilityNodeInfoDrawingOrderInParent(info);
7901    }
7902
7903    /**
7904     * Adds extra data to an {@link AccessibilityNodeInfo} based on an explicit request for the
7905     * additional data.
7906     * <p>
7907     * This method only needs overloading if the node is marked as having extra data available.
7908     * </p>
7909     *
7910     * @param info The info to which to add the extra data. Never {@code null}.
7911     * @param extraDataKey A key specifying the type of extra data to add to the info. The
7912     *                     extra data should be added to the {@link Bundle} returned by
7913     *                     the info's {@link AccessibilityNodeInfo#getExtras} method. Never
7914     *                     {@code null}.
7915     * @param arguments A {@link Bundle} holding any arguments relevant for this request. May be
7916     *                  {@code null} if the service provided no arguments.
7917     *
7918     * @see AccessibilityNodeInfo#setAvailableExtraData(List)
7919     */
7920    public void addExtraDataToAccessibilityNodeInfo(
7921            @NonNull AccessibilityNodeInfo info, @NonNull String extraDataKey,
7922            @Nullable Bundle arguments) {
7923    }
7924
7925    /**
7926     * Determine the order in which this view will be drawn relative to its siblings for a11y
7927     *
7928     * @param info The info whose drawing order should be populated
7929     */
7930    private void populateAccessibilityNodeInfoDrawingOrderInParent(AccessibilityNodeInfo info) {
7931        /*
7932         * If the view's bounds haven't been set yet, layout has not completed. In that situation,
7933         * drawing order may not be well-defined, and some Views with custom drawing order may
7934         * not be initialized sufficiently to respond properly getChildDrawingOrder.
7935         */
7936        if ((mPrivateFlags & PFLAG_HAS_BOUNDS) == 0) {
7937            info.setDrawingOrder(0);
7938            return;
7939        }
7940        int drawingOrderInParent = 1;
7941        // Iterate up the hierarchy if parents are not important for a11y
7942        View viewAtDrawingLevel = this;
7943        final ViewParent parent = getParentForAccessibility();
7944        while (viewAtDrawingLevel != parent) {
7945            final ViewParent currentParent = viewAtDrawingLevel.getParent();
7946            if (!(currentParent instanceof ViewGroup)) {
7947                // Should only happen for the Decor
7948                drawingOrderInParent = 0;
7949                break;
7950            } else {
7951                final ViewGroup parentGroup = (ViewGroup) currentParent;
7952                final int childCount = parentGroup.getChildCount();
7953                if (childCount > 1) {
7954                    List<View> preorderedList = parentGroup.buildOrderedChildList();
7955                    if (preorderedList != null) {
7956                        final int childDrawIndex = preorderedList.indexOf(viewAtDrawingLevel);
7957                        for (int i = 0; i < childDrawIndex; i++) {
7958                            drawingOrderInParent += numViewsForAccessibility(preorderedList.get(i));
7959                        }
7960                    } else {
7961                        final int childIndex = parentGroup.indexOfChild(viewAtDrawingLevel);
7962                        final boolean customOrder = parentGroup.isChildrenDrawingOrderEnabled();
7963                        final int childDrawIndex = ((childIndex >= 0) && customOrder) ? parentGroup
7964                                .getChildDrawingOrder(childCount, childIndex) : childIndex;
7965                        final int numChildrenToIterate = customOrder ? childCount : childDrawIndex;
7966                        if (childDrawIndex != 0) {
7967                            for (int i = 0; i < numChildrenToIterate; i++) {
7968                                final int otherDrawIndex = (customOrder ?
7969                                        parentGroup.getChildDrawingOrder(childCount, i) : i);
7970                                if (otherDrawIndex < childDrawIndex) {
7971                                    drawingOrderInParent +=
7972                                            numViewsForAccessibility(parentGroup.getChildAt(i));
7973                                }
7974                            }
7975                        }
7976                    }
7977                }
7978            }
7979            viewAtDrawingLevel = (View) currentParent;
7980        }
7981        info.setDrawingOrder(drawingOrderInParent);
7982    }
7983
7984    private static int numViewsForAccessibility(View view) {
7985        if (view != null) {
7986            if (view.includeForAccessibility()) {
7987                return 1;
7988            } else if (view instanceof ViewGroup) {
7989                return ((ViewGroup) view).getNumChildrenForAccessibility();
7990            }
7991        }
7992        return 0;
7993    }
7994
7995    private View findLabelForView(View view, int labeledId) {
7996        if (mMatchLabelForPredicate == null) {
7997            mMatchLabelForPredicate = new MatchLabelForPredicate();
7998        }
7999        mMatchLabelForPredicate.mLabeledId = labeledId;
8000        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
8001    }
8002
8003    /**
8004     * Computes whether this view is visible to the user. Such a view is
8005     * attached, visible, all its predecessors are visible, it is not clipped
8006     * entirely by its predecessors, and has an alpha greater than zero.
8007     *
8008     * @return Whether the view is visible on the screen.
8009     *
8010     * @hide
8011     */
8012    protected boolean isVisibleToUser() {
8013        return isVisibleToUser(null);
8014    }
8015
8016    /**
8017     * Computes whether the given portion of this view is visible to the user.
8018     * Such a view is attached, visible, all its predecessors are visible,
8019     * has an alpha greater than zero, and the specified portion is not
8020     * clipped entirely by its predecessors.
8021     *
8022     * @param boundInView the portion of the view to test; coordinates should be relative; may be
8023     *                    <code>null</code>, and the entire view will be tested in this case.
8024     *                    When <code>true</code> is returned by the function, the actual visible
8025     *                    region will be stored in this parameter; that is, if boundInView is fully
8026     *                    contained within the view, no modification will be made, otherwise regions
8027     *                    outside of the visible area of the view will be clipped.
8028     *
8029     * @return Whether the specified portion of the view is visible on the screen.
8030     *
8031     * @hide
8032     */
8033    protected boolean isVisibleToUser(Rect boundInView) {
8034        if (mAttachInfo != null) {
8035            // Attached to invisible window means this view is not visible.
8036            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
8037                return false;
8038            }
8039            // An invisible predecessor or one with alpha zero means
8040            // that this view is not visible to the user.
8041            Object current = this;
8042            while (current instanceof View) {
8043                View view = (View) current;
8044                // We have attach info so this view is attached and there is no
8045                // need to check whether we reach to ViewRootImpl on the way up.
8046                if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
8047                        view.getVisibility() != VISIBLE) {
8048                    return false;
8049                }
8050                current = view.mParent;
8051            }
8052            // Check if the view is entirely covered by its predecessors.
8053            Rect visibleRect = mAttachInfo.mTmpInvalRect;
8054            Point offset = mAttachInfo.mPoint;
8055            if (!getGlobalVisibleRect(visibleRect, offset)) {
8056                return false;
8057            }
8058            // Check if the visible portion intersects the rectangle of interest.
8059            if (boundInView != null) {
8060                visibleRect.offset(-offset.x, -offset.y);
8061                return boundInView.intersect(visibleRect);
8062            }
8063            return true;
8064        }
8065        return false;
8066    }
8067
8068    /**
8069     * Returns the delegate for implementing accessibility support via
8070     * composition. For more details see {@link AccessibilityDelegate}.
8071     *
8072     * @return The delegate, or null if none set.
8073     *
8074     * @hide
8075     */
8076    public AccessibilityDelegate getAccessibilityDelegate() {
8077        return mAccessibilityDelegate;
8078    }
8079
8080    /**
8081     * Sets a delegate for implementing accessibility support via composition
8082     * (as opposed to inheritance). For more details, see
8083     * {@link AccessibilityDelegate}.
8084     * <p>
8085     * <strong>Note:</strong> On platform versions prior to
8086     * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on
8087     * views in the {@code android.widget.*} package are called <i>before</i>
8088     * host methods. This prevents certain properties such as class name from
8089     * being modified by overriding
8090     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)},
8091     * as any changes will be overwritten by the host class.
8092     * <p>
8093     * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate
8094     * methods are called <i>after</i> host methods, which all properties to be
8095     * modified without being overwritten by the host class.
8096     *
8097     * @param delegate the object to which accessibility method calls should be
8098     *                 delegated
8099     * @see AccessibilityDelegate
8100     */
8101    public void setAccessibilityDelegate(@Nullable AccessibilityDelegate delegate) {
8102        mAccessibilityDelegate = delegate;
8103    }
8104
8105    /**
8106     * Gets the provider for managing a virtual view hierarchy rooted at this View
8107     * and reported to {@link android.accessibilityservice.AccessibilityService}s
8108     * that explore the window content.
8109     * <p>
8110     * If this method returns an instance, this instance is responsible for managing
8111     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
8112     * View including the one representing the View itself. Similarly the returned
8113     * instance is responsible for performing accessibility actions on any virtual
8114     * view or the root view itself.
8115     * </p>
8116     * <p>
8117     * If an {@link AccessibilityDelegate} has been specified via calling
8118     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
8119     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
8120     * is responsible for handling this call.
8121     * </p>
8122     *
8123     * @return The provider.
8124     *
8125     * @see AccessibilityNodeProvider
8126     */
8127    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
8128        if (mAccessibilityDelegate != null) {
8129            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
8130        } else {
8131            return null;
8132        }
8133    }
8134
8135    /**
8136     * Gets the unique identifier of this view on the screen for accessibility purposes.
8137     *
8138     * @return The view accessibility id.
8139     *
8140     * @hide
8141     */
8142    public int getAccessibilityViewId() {
8143        if (mAccessibilityViewId == NO_ID) {
8144            mAccessibilityViewId = sNextAccessibilityViewId++;
8145        }
8146        return mAccessibilityViewId;
8147    }
8148
8149    /**
8150     * Gets the unique identifier of the window in which this View reseides.
8151     *
8152     * @return The window accessibility id.
8153     *
8154     * @hide
8155     */
8156    public int getAccessibilityWindowId() {
8157        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId
8158                : AccessibilityWindowInfo.UNDEFINED_WINDOW_ID;
8159    }
8160
8161    /**
8162     * Returns the {@link View}'s content description.
8163     * <p>
8164     * <strong>Note:</strong> Do not override this method, as it will have no
8165     * effect on the content description presented to accessibility services.
8166     * You must call {@link #setContentDescription(CharSequence)} to modify the
8167     * content description.
8168     *
8169     * @return the content description
8170     * @see #setContentDescription(CharSequence)
8171     * @attr ref android.R.styleable#View_contentDescription
8172     */
8173    @ViewDebug.ExportedProperty(category = "accessibility")
8174    public CharSequence getContentDescription() {
8175        return mContentDescription;
8176    }
8177
8178    /**
8179     * Sets the {@link View}'s content description.
8180     * <p>
8181     * A content description briefly describes the view and is primarily used
8182     * for accessibility support to determine how a view should be presented to
8183     * the user. In the case of a view with no textual representation, such as
8184     * {@link android.widget.ImageButton}, a useful content description
8185     * explains what the view does. For example, an image button with a phone
8186     * icon that is used to place a call may use "Call" as its content
8187     * description. An image of a floppy disk that is used to save a file may
8188     * use "Save".
8189     *
8190     * @param contentDescription The content description.
8191     * @see #getContentDescription()
8192     * @attr ref android.R.styleable#View_contentDescription
8193     */
8194    @RemotableViewMethod
8195    public void setContentDescription(CharSequence contentDescription) {
8196        if (mContentDescription == null) {
8197            if (contentDescription == null) {
8198                return;
8199            }
8200        } else if (mContentDescription.equals(contentDescription)) {
8201            return;
8202        }
8203        mContentDescription = contentDescription;
8204        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
8205        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
8206            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
8207            notifySubtreeAccessibilityStateChangedIfNeeded();
8208        } else {
8209            notifyViewAccessibilityStateChangedIfNeeded(
8210                    AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
8211        }
8212    }
8213
8214    /**
8215     * Sets the id of a view before which this one is visited in accessibility traversal.
8216     * A screen-reader must visit the content of this view before the content of the one
8217     * it precedes. For example, if view B is set to be before view A, then a screen-reader
8218     * will traverse the entire content of B before traversing the entire content of A,
8219     * regardles of what traversal strategy it is using.
8220     * <p>
8221     * Views that do not have specified before/after relationships are traversed in order
8222     * determined by the screen-reader.
8223     * </p>
8224     * <p>
8225     * Setting that this view is before a view that is not important for accessibility
8226     * or if this view is not important for accessibility will have no effect as the
8227     * screen-reader is not aware of unimportant views.
8228     * </p>
8229     *
8230     * @param beforeId The id of a view this one precedes in accessibility traversal.
8231     *
8232     * @attr ref android.R.styleable#View_accessibilityTraversalBefore
8233     *
8234     * @see #setImportantForAccessibility(int)
8235     */
8236    @RemotableViewMethod
8237    public void setAccessibilityTraversalBefore(int beforeId) {
8238        if (mAccessibilityTraversalBeforeId == beforeId) {
8239            return;
8240        }
8241        mAccessibilityTraversalBeforeId = beforeId;
8242        notifyViewAccessibilityStateChangedIfNeeded(
8243                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
8244    }
8245
8246    /**
8247     * Gets the id of a view before which this one is visited in accessibility traversal.
8248     *
8249     * @return The id of a view this one precedes in accessibility traversal if
8250     *         specified, otherwise {@link #NO_ID}.
8251     *
8252     * @see #setAccessibilityTraversalBefore(int)
8253     */
8254    public int getAccessibilityTraversalBefore() {
8255        return mAccessibilityTraversalBeforeId;
8256    }
8257
8258    /**
8259     * Sets the id of a view after which this one is visited in accessibility traversal.
8260     * A screen-reader must visit the content of the other view before the content of this
8261     * one. For example, if view B is set to be after view A, then a screen-reader
8262     * will traverse the entire content of A before traversing the entire content of B,
8263     * regardles of what traversal strategy it is using.
8264     * <p>
8265     * Views that do not have specified before/after relationships are traversed in order
8266     * determined by the screen-reader.
8267     * </p>
8268     * <p>
8269     * Setting that this view is after a view that is not important for accessibility
8270     * or if this view is not important for accessibility will have no effect as the
8271     * screen-reader is not aware of unimportant views.
8272     * </p>
8273     *
8274     * @param afterId The id of a view this one succedees in accessibility traversal.
8275     *
8276     * @attr ref android.R.styleable#View_accessibilityTraversalAfter
8277     *
8278     * @see #setImportantForAccessibility(int)
8279     */
8280    @RemotableViewMethod
8281    public void setAccessibilityTraversalAfter(int afterId) {
8282        if (mAccessibilityTraversalAfterId == afterId) {
8283            return;
8284        }
8285        mAccessibilityTraversalAfterId = afterId;
8286        notifyViewAccessibilityStateChangedIfNeeded(
8287                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
8288    }
8289
8290    /**
8291     * Gets the id of a view after which this one is visited in accessibility traversal.
8292     *
8293     * @return The id of a view this one succeedes in accessibility traversal if
8294     *         specified, otherwise {@link #NO_ID}.
8295     *
8296     * @see #setAccessibilityTraversalAfter(int)
8297     */
8298    public int getAccessibilityTraversalAfter() {
8299        return mAccessibilityTraversalAfterId;
8300    }
8301
8302    /**
8303     * Gets the id of a view for which this view serves as a label for
8304     * accessibility purposes.
8305     *
8306     * @return The labeled view id.
8307     */
8308    @ViewDebug.ExportedProperty(category = "accessibility")
8309    public int getLabelFor() {
8310        return mLabelForId;
8311    }
8312
8313    /**
8314     * Sets the id of a view for which this view serves as a label for
8315     * accessibility purposes.
8316     *
8317     * @param id The labeled view id.
8318     */
8319    @RemotableViewMethod
8320    public void setLabelFor(@IdRes int id) {
8321        if (mLabelForId == id) {
8322            return;
8323        }
8324        mLabelForId = id;
8325        if (mLabelForId != View.NO_ID
8326                && mID == View.NO_ID) {
8327            mID = generateViewId();
8328        }
8329        notifyViewAccessibilityStateChangedIfNeeded(
8330                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
8331    }
8332
8333    /**
8334     * Invoked whenever this view loses focus, either by losing window focus or by losing
8335     * focus within its window. This method can be used to clear any state tied to the
8336     * focus. For instance, if a button is held pressed with the trackball and the window
8337     * loses focus, this method can be used to cancel the press.
8338     *
8339     * Subclasses of View overriding this method should always call super.onFocusLost().
8340     *
8341     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
8342     * @see #onWindowFocusChanged(boolean)
8343     *
8344     * @hide pending API council approval
8345     */
8346    @CallSuper
8347    protected void onFocusLost() {
8348        resetPressedState();
8349    }
8350
8351    private void resetPressedState() {
8352        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8353            return;
8354        }
8355
8356        if (isPressed()) {
8357            setPressed(false);
8358
8359            if (!mHasPerformedLongPress) {
8360                removeLongPressCallback();
8361            }
8362        }
8363    }
8364
8365    /**
8366     * Returns true if this view has focus
8367     *
8368     * @return True if this view has focus, false otherwise.
8369     */
8370    @ViewDebug.ExportedProperty(category = "focus")
8371    public boolean isFocused() {
8372        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
8373    }
8374
8375    /**
8376     * Find the view in the hierarchy rooted at this view that currently has
8377     * focus.
8378     *
8379     * @return The view that currently has focus, or null if no focused view can
8380     *         be found.
8381     */
8382    public View findFocus() {
8383        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
8384    }
8385
8386    /**
8387     * Indicates whether this view is one of the set of scrollable containers in
8388     * its window.
8389     *
8390     * @return whether this view is one of the set of scrollable containers in
8391     * its window
8392     *
8393     * @attr ref android.R.styleable#View_isScrollContainer
8394     */
8395    public boolean isScrollContainer() {
8396        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
8397    }
8398
8399    /**
8400     * Change whether this view is one of the set of scrollable containers in
8401     * its window.  This will be used to determine whether the window can
8402     * resize or must pan when a soft input area is open -- scrollable
8403     * containers allow the window to use resize mode since the container
8404     * will appropriately shrink.
8405     *
8406     * @attr ref android.R.styleable#View_isScrollContainer
8407     */
8408    public void setScrollContainer(boolean isScrollContainer) {
8409        if (isScrollContainer) {
8410            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
8411                mAttachInfo.mScrollContainers.add(this);
8412                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
8413            }
8414            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
8415        } else {
8416            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
8417                mAttachInfo.mScrollContainers.remove(this);
8418            }
8419            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
8420        }
8421    }
8422
8423    /**
8424     * Returns the quality of the drawing cache.
8425     *
8426     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
8427     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
8428     *
8429     * @see #setDrawingCacheQuality(int)
8430     * @see #setDrawingCacheEnabled(boolean)
8431     * @see #isDrawingCacheEnabled()
8432     *
8433     * @attr ref android.R.styleable#View_drawingCacheQuality
8434     */
8435    @DrawingCacheQuality
8436    public int getDrawingCacheQuality() {
8437        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
8438    }
8439
8440    /**
8441     * Set the drawing cache quality of this view. This value is used only when the
8442     * drawing cache is enabled
8443     *
8444     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
8445     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
8446     *
8447     * @see #getDrawingCacheQuality()
8448     * @see #setDrawingCacheEnabled(boolean)
8449     * @see #isDrawingCacheEnabled()
8450     *
8451     * @attr ref android.R.styleable#View_drawingCacheQuality
8452     */
8453    public void setDrawingCacheQuality(@DrawingCacheQuality int quality) {
8454        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
8455    }
8456
8457    /**
8458     * Returns whether the screen should remain on, corresponding to the current
8459     * value of {@link #KEEP_SCREEN_ON}.
8460     *
8461     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
8462     *
8463     * @see #setKeepScreenOn(boolean)
8464     *
8465     * @attr ref android.R.styleable#View_keepScreenOn
8466     */
8467    public boolean getKeepScreenOn() {
8468        return (mViewFlags & KEEP_SCREEN_ON) != 0;
8469    }
8470
8471    /**
8472     * Controls whether the screen should remain on, modifying the
8473     * value of {@link #KEEP_SCREEN_ON}.
8474     *
8475     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
8476     *
8477     * @see #getKeepScreenOn()
8478     *
8479     * @attr ref android.R.styleable#View_keepScreenOn
8480     */
8481    public void setKeepScreenOn(boolean keepScreenOn) {
8482        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
8483    }
8484
8485    /**
8486     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
8487     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
8488     *
8489     * @attr ref android.R.styleable#View_nextFocusLeft
8490     */
8491    public int getNextFocusLeftId() {
8492        return mNextFocusLeftId;
8493    }
8494
8495    /**
8496     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
8497     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
8498     * decide automatically.
8499     *
8500     * @attr ref android.R.styleable#View_nextFocusLeft
8501     */
8502    public void setNextFocusLeftId(int nextFocusLeftId) {
8503        mNextFocusLeftId = nextFocusLeftId;
8504    }
8505
8506    /**
8507     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
8508     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
8509     *
8510     * @attr ref android.R.styleable#View_nextFocusRight
8511     */
8512    public int getNextFocusRightId() {
8513        return mNextFocusRightId;
8514    }
8515
8516    /**
8517     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
8518     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
8519     * decide automatically.
8520     *
8521     * @attr ref android.R.styleable#View_nextFocusRight
8522     */
8523    public void setNextFocusRightId(int nextFocusRightId) {
8524        mNextFocusRightId = nextFocusRightId;
8525    }
8526
8527    /**
8528     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
8529     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
8530     *
8531     * @attr ref android.R.styleable#View_nextFocusUp
8532     */
8533    public int getNextFocusUpId() {
8534        return mNextFocusUpId;
8535    }
8536
8537    /**
8538     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
8539     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
8540     * decide automatically.
8541     *
8542     * @attr ref android.R.styleable#View_nextFocusUp
8543     */
8544    public void setNextFocusUpId(int nextFocusUpId) {
8545        mNextFocusUpId = nextFocusUpId;
8546    }
8547
8548    /**
8549     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
8550     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
8551     *
8552     * @attr ref android.R.styleable#View_nextFocusDown
8553     */
8554    public int getNextFocusDownId() {
8555        return mNextFocusDownId;
8556    }
8557
8558    /**
8559     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
8560     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
8561     * decide automatically.
8562     *
8563     * @attr ref android.R.styleable#View_nextFocusDown
8564     */
8565    public void setNextFocusDownId(int nextFocusDownId) {
8566        mNextFocusDownId = nextFocusDownId;
8567    }
8568
8569    /**
8570     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
8571     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
8572     *
8573     * @attr ref android.R.styleable#View_nextFocusForward
8574     */
8575    public int getNextFocusForwardId() {
8576        return mNextFocusForwardId;
8577    }
8578
8579    /**
8580     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
8581     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
8582     * decide automatically.
8583     *
8584     * @attr ref android.R.styleable#View_nextFocusForward
8585     */
8586    public void setNextFocusForwardId(int nextFocusForwardId) {
8587        mNextFocusForwardId = nextFocusForwardId;
8588    }
8589
8590    /**
8591     * Gets the id of the root of the next keyboard navigation cluster.
8592     * @return The next keyboard navigation cluster ID, or {@link #NO_ID} if the framework should
8593     * decide automatically.
8594     *
8595     * @attr ref android.R.styleable#View_nextClusterForward
8596     */
8597    public int getNextClusterForwardId() {
8598        return mNextClusterForwardId;
8599    }
8600
8601    /**
8602     * Sets the id of the view to use as the root of the next keyboard navigation cluster.
8603     * @param nextClusterForwardId The next cluster ID, or {@link #NO_ID} if the framework should
8604     * decide automatically.
8605     *
8606     * @attr ref android.R.styleable#View_nextClusterForward
8607     */
8608    public void setNextClusterForwardId(int nextClusterForwardId) {
8609        mNextClusterForwardId = nextClusterForwardId;
8610    }
8611
8612    /**
8613     * Returns the visibility of this view and all of its ancestors
8614     *
8615     * @return True if this view and all of its ancestors are {@link #VISIBLE}
8616     */
8617    public boolean isShown() {
8618        View current = this;
8619        //noinspection ConstantConditions
8620        do {
8621            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
8622                return false;
8623            }
8624            ViewParent parent = current.mParent;
8625            if (parent == null) {
8626                return false; // We are not attached to the view root
8627            }
8628            if (!(parent instanceof View)) {
8629                return true;
8630            }
8631            current = (View) parent;
8632        } while (current != null);
8633
8634        return false;
8635    }
8636
8637    /**
8638     * Called by the view hierarchy when the content insets for a window have
8639     * changed, to allow it to adjust its content to fit within those windows.
8640     * The content insets tell you the space that the status bar, input method,
8641     * and other system windows infringe on the application's window.
8642     *
8643     * <p>You do not normally need to deal with this function, since the default
8644     * window decoration given to applications takes care of applying it to the
8645     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
8646     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
8647     * and your content can be placed under those system elements.  You can then
8648     * use this method within your view hierarchy if you have parts of your UI
8649     * which you would like to ensure are not being covered.
8650     *
8651     * <p>The default implementation of this method simply applies the content
8652     * insets to the view's padding, consuming that content (modifying the
8653     * insets to be 0), and returning true.  This behavior is off by default, but can
8654     * be enabled through {@link #setFitsSystemWindows(boolean)}.
8655     *
8656     * <p>This function's traversal down the hierarchy is depth-first.  The same content
8657     * insets object is propagated down the hierarchy, so any changes made to it will
8658     * be seen by all following views (including potentially ones above in
8659     * the hierarchy since this is a depth-first traversal).  The first view
8660     * that returns true will abort the entire traversal.
8661     *
8662     * <p>The default implementation works well for a situation where it is
8663     * used with a container that covers the entire window, allowing it to
8664     * apply the appropriate insets to its content on all edges.  If you need
8665     * a more complicated layout (such as two different views fitting system
8666     * windows, one on the top of the window, and one on the bottom),
8667     * you can override the method and handle the insets however you would like.
8668     * Note that the insets provided by the framework are always relative to the
8669     * far edges of the window, not accounting for the location of the called view
8670     * within that window.  (In fact when this method is called you do not yet know
8671     * where the layout will place the view, as it is done before layout happens.)
8672     *
8673     * <p>Note: unlike many View methods, there is no dispatch phase to this
8674     * call.  If you are overriding it in a ViewGroup and want to allow the
8675     * call to continue to your children, you must be sure to call the super
8676     * implementation.
8677     *
8678     * <p>Here is a sample layout that makes use of fitting system windows
8679     * to have controls for a video view placed inside of the window decorations
8680     * that it hides and shows.  This can be used with code like the second
8681     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
8682     *
8683     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
8684     *
8685     * @param insets Current content insets of the window.  Prior to
8686     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
8687     * the insets or else you and Android will be unhappy.
8688     *
8689     * @return {@code true} if this view applied the insets and it should not
8690     * continue propagating further down the hierarchy, {@code false} otherwise.
8691     * @see #getFitsSystemWindows()
8692     * @see #setFitsSystemWindows(boolean)
8693     * @see #setSystemUiVisibility(int)
8694     *
8695     * @deprecated As of API 20 use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply
8696     * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use
8697     * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)}
8698     * to implement handling their own insets.
8699     */
8700    @Deprecated
8701    protected boolean fitSystemWindows(Rect insets) {
8702        if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) {
8703            if (insets == null) {
8704                // Null insets by definition have already been consumed.
8705                // This call cannot apply insets since there are none to apply,
8706                // so return false.
8707                return false;
8708            }
8709            // If we're not in the process of dispatching the newer apply insets call,
8710            // that means we're not in the compatibility path. Dispatch into the newer
8711            // apply insets path and take things from there.
8712            try {
8713                mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS;
8714                return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed();
8715            } finally {
8716                mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS;
8717            }
8718        } else {
8719            // We're being called from the newer apply insets path.
8720            // Perform the standard fallback behavior.
8721            return fitSystemWindowsInt(insets);
8722        }
8723    }
8724
8725    private boolean fitSystemWindowsInt(Rect insets) {
8726        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
8727            mUserPaddingStart = UNDEFINED_PADDING;
8728            mUserPaddingEnd = UNDEFINED_PADDING;
8729            Rect localInsets = sThreadLocal.get();
8730            if (localInsets == null) {
8731                localInsets = new Rect();
8732                sThreadLocal.set(localInsets);
8733            }
8734            boolean res = computeFitSystemWindows(insets, localInsets);
8735            mUserPaddingLeftInitial = localInsets.left;
8736            mUserPaddingRightInitial = localInsets.right;
8737            internalSetPadding(localInsets.left, localInsets.top,
8738                    localInsets.right, localInsets.bottom);
8739            return res;
8740        }
8741        return false;
8742    }
8743
8744    /**
8745     * Called when the view should apply {@link WindowInsets} according to its internal policy.
8746     *
8747     * <p>This method should be overridden by views that wish to apply a policy different from or
8748     * in addition to the default behavior. Clients that wish to force a view subtree
8749     * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p>
8750     *
8751     * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set
8752     * it will be called during dispatch instead of this method. The listener may optionally
8753     * call this method from its own implementation if it wishes to apply the view's default
8754     * insets policy in addition to its own.</p>
8755     *
8756     * <p>Implementations of this method should either return the insets parameter unchanged
8757     * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed
8758     * that this view applied itself. This allows new inset types added in future platform
8759     * versions to pass through existing implementations unchanged without being erroneously
8760     * consumed.</p>
8761     *
8762     * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows}
8763     * property is set then the view will consume the system window insets and apply them
8764     * as padding for the view.</p>
8765     *
8766     * @param insets Insets to apply
8767     * @return The supplied insets with any applied insets consumed
8768     */
8769    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
8770        if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) {
8771            // We weren't called from within a direct call to fitSystemWindows,
8772            // call into it as a fallback in case we're in a class that overrides it
8773            // and has logic to perform.
8774            if (fitSystemWindows(insets.getSystemWindowInsets())) {
8775                return insets.consumeSystemWindowInsets();
8776            }
8777        } else {
8778            // We were called from within a direct call to fitSystemWindows.
8779            if (fitSystemWindowsInt(insets.getSystemWindowInsets())) {
8780                return insets.consumeSystemWindowInsets();
8781            }
8782        }
8783        return insets;
8784    }
8785
8786    /**
8787     * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying
8788     * window insets to this view. The listener's
8789     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
8790     * method will be called instead of the view's
8791     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
8792     *
8793     * @param listener Listener to set
8794     *
8795     * @see #onApplyWindowInsets(WindowInsets)
8796     */
8797    public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {
8798        getListenerInfo().mOnApplyWindowInsetsListener = listener;
8799    }
8800
8801    /**
8802     * Request to apply the given window insets to this view or another view in its subtree.
8803     *
8804     * <p>This method should be called by clients wishing to apply insets corresponding to areas
8805     * obscured by window decorations or overlays. This can include the status and navigation bars,
8806     * action bars, input methods and more. New inset categories may be added in the future.
8807     * The method returns the insets provided minus any that were applied by this view or its
8808     * children.</p>
8809     *
8810     * <p>Clients wishing to provide custom behavior should override the
8811     * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a
8812     * {@link OnApplyWindowInsetsListener} via the
8813     * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener}
8814     * method.</p>
8815     *
8816     * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method.
8817     * </p>
8818     *
8819     * @param insets Insets to apply
8820     * @return The provided insets minus the insets that were consumed
8821     */
8822    public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
8823        try {
8824            mPrivateFlags3 |= PFLAG3_APPLYING_INSETS;
8825            if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
8826                return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);
8827            } else {
8828                return onApplyWindowInsets(insets);
8829            }
8830        } finally {
8831            mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS;
8832        }
8833    }
8834
8835    /**
8836     * Compute the view's coordinate within the surface.
8837     *
8838     * <p>Computes the coordinates of this view in its surface. The argument
8839     * must be an array of two integers. After the method returns, the array
8840     * contains the x and y location in that order.</p>
8841     * @hide
8842     * @param location an array of two integers in which to hold the coordinates
8843     */
8844    public void getLocationInSurface(@Size(2) int[] location) {
8845        getLocationInWindow(location);
8846        if (mAttachInfo != null && mAttachInfo.mViewRootImpl != null) {
8847            location[0] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.left;
8848            location[1] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.top;
8849        }
8850    }
8851
8852    /**
8853     * Provide original WindowInsets that are dispatched to the view hierarchy. The insets are
8854     * only available if the view is attached.
8855     *
8856     * @return WindowInsets from the top of the view hierarchy or null if View is detached
8857     */
8858    public WindowInsets getRootWindowInsets() {
8859        if (mAttachInfo != null) {
8860            return mAttachInfo.mViewRootImpl.getWindowInsets(false /* forceConstruct */);
8861        }
8862        return null;
8863    }
8864
8865    /**
8866     * @hide Compute the insets that should be consumed by this view and the ones
8867     * that should propagate to those under it.
8868     */
8869    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
8870        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
8871                || mAttachInfo == null
8872                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
8873                        && !mAttachInfo.mOverscanRequested)) {
8874            outLocalInsets.set(inoutInsets);
8875            inoutInsets.set(0, 0, 0, 0);
8876            return true;
8877        } else {
8878            // The application wants to take care of fitting system window for
8879            // the content...  however we still need to take care of any overscan here.
8880            final Rect overscan = mAttachInfo.mOverscanInsets;
8881            outLocalInsets.set(overscan);
8882            inoutInsets.left -= overscan.left;
8883            inoutInsets.top -= overscan.top;
8884            inoutInsets.right -= overscan.right;
8885            inoutInsets.bottom -= overscan.bottom;
8886            return false;
8887        }
8888    }
8889
8890    /**
8891     * Compute insets that should be consumed by this view and the ones that should propagate
8892     * to those under it.
8893     *
8894     * @param in Insets currently being processed by this View, likely received as a parameter
8895     *           to {@link #onApplyWindowInsets(WindowInsets)}.
8896     * @param outLocalInsets A Rect that will receive the insets that should be consumed
8897     *                       by this view
8898     * @return Insets that should be passed along to views under this one
8899     */
8900    public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) {
8901        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
8902                || mAttachInfo == null
8903                || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
8904            outLocalInsets.set(in.getSystemWindowInsets());
8905            return in.consumeSystemWindowInsets();
8906        } else {
8907            outLocalInsets.set(0, 0, 0, 0);
8908            return in;
8909        }
8910    }
8911
8912    /**
8913     * Sets whether or not this view should account for system screen decorations
8914     * such as the status bar and inset its content; that is, controlling whether
8915     * the default implementation of {@link #fitSystemWindows(Rect)} will be
8916     * executed.  See that method for more details.
8917     *
8918     * <p>Note that if you are providing your own implementation of
8919     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
8920     * flag to true -- your implementation will be overriding the default
8921     * implementation that checks this flag.
8922     *
8923     * @param fitSystemWindows If true, then the default implementation of
8924     * {@link #fitSystemWindows(Rect)} will be executed.
8925     *
8926     * @attr ref android.R.styleable#View_fitsSystemWindows
8927     * @see #getFitsSystemWindows()
8928     * @see #fitSystemWindows(Rect)
8929     * @see #setSystemUiVisibility(int)
8930     */
8931    public void setFitsSystemWindows(boolean fitSystemWindows) {
8932        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
8933    }
8934
8935    /**
8936     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
8937     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
8938     * will be executed.
8939     *
8940     * @return {@code true} if the default implementation of
8941     * {@link #fitSystemWindows(Rect)} will be executed.
8942     *
8943     * @attr ref android.R.styleable#View_fitsSystemWindows
8944     * @see #setFitsSystemWindows(boolean)
8945     * @see #fitSystemWindows(Rect)
8946     * @see #setSystemUiVisibility(int)
8947     */
8948    @ViewDebug.ExportedProperty
8949    public boolean getFitsSystemWindows() {
8950        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
8951    }
8952
8953    /** @hide */
8954    public boolean fitsSystemWindows() {
8955        return getFitsSystemWindows();
8956    }
8957
8958    /**
8959     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
8960     * @deprecated Use {@link #requestApplyInsets()} for newer platform versions.
8961     */
8962    @Deprecated
8963    public void requestFitSystemWindows() {
8964        if (mParent != null) {
8965            mParent.requestFitSystemWindows();
8966        }
8967    }
8968
8969    /**
8970     * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed.
8971     */
8972    public void requestApplyInsets() {
8973        requestFitSystemWindows();
8974    }
8975
8976    /**
8977     * For use by PhoneWindow to make its own system window fitting optional.
8978     * @hide
8979     */
8980    public void makeOptionalFitsSystemWindows() {
8981        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
8982    }
8983
8984    /**
8985     * Returns the outsets, which areas of the device that aren't a surface, but we would like to
8986     * treat them as such.
8987     * @hide
8988     */
8989    public void getOutsets(Rect outOutsetRect) {
8990        if (mAttachInfo != null) {
8991            outOutsetRect.set(mAttachInfo.mOutsets);
8992        } else {
8993            outOutsetRect.setEmpty();
8994        }
8995    }
8996
8997    /**
8998     * Returns the visibility status for this view.
8999     *
9000     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
9001     * @attr ref android.R.styleable#View_visibility
9002     */
9003    @ViewDebug.ExportedProperty(mapping = {
9004        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
9005        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
9006        @ViewDebug.IntToString(from = GONE,      to = "GONE")
9007    })
9008    @Visibility
9009    public int getVisibility() {
9010        return mViewFlags & VISIBILITY_MASK;
9011    }
9012
9013    /**
9014     * Set the visibility state of this view.
9015     *
9016     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
9017     * @attr ref android.R.styleable#View_visibility
9018     */
9019    @RemotableViewMethod
9020    public void setVisibility(@Visibility int visibility) {
9021        setFlags(visibility, VISIBILITY_MASK);
9022    }
9023
9024    /**
9025     * Returns the enabled status for this view. The interpretation of the
9026     * enabled state varies by subclass.
9027     *
9028     * @return True if this view is enabled, false otherwise.
9029     */
9030    @ViewDebug.ExportedProperty
9031    public boolean isEnabled() {
9032        return (mViewFlags & ENABLED_MASK) == ENABLED;
9033    }
9034
9035    /**
9036     * Set the enabled state of this view. The interpretation of the enabled
9037     * state varies by subclass.
9038     *
9039     * @param enabled True if this view is enabled, false otherwise.
9040     */
9041    @RemotableViewMethod
9042    public void setEnabled(boolean enabled) {
9043        if (enabled == isEnabled()) return;
9044
9045        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
9046
9047        /*
9048         * The View most likely has to change its appearance, so refresh
9049         * the drawable state.
9050         */
9051        refreshDrawableState();
9052
9053        // Invalidate too, since the default behavior for views is to be
9054        // be drawn at 50% alpha rather than to change the drawable.
9055        invalidate(true);
9056
9057        if (!enabled) {
9058            cancelPendingInputEvents();
9059        }
9060    }
9061
9062    /**
9063     * Set whether this view can receive the focus.
9064     * <p>
9065     * Setting this to false will also ensure that this view is not focusable
9066     * in touch mode.
9067     *
9068     * @param focusable If true, this view can receive the focus.
9069     *
9070     * @see #setFocusableInTouchMode(boolean)
9071     * @see #setFocusable(int)
9072     * @attr ref android.R.styleable#View_focusable
9073     */
9074    public void setFocusable(boolean focusable) {
9075        setFocusable(focusable ? FOCUSABLE : NOT_FOCUSABLE);
9076    }
9077
9078    /**
9079     * Sets whether this view can receive focus.
9080     * <p>
9081     * Setting this to {@link #FOCUSABLE_AUTO} tells the framework to determine focusability
9082     * automatically based on the view's interactivity. This is the default.
9083     * <p>
9084     * Setting this to NOT_FOCUSABLE will ensure that this view is also not focusable
9085     * in touch mode.
9086     *
9087     * @param focusable One of {@link #NOT_FOCUSABLE}, {@link #FOCUSABLE},
9088     *                  or {@link #FOCUSABLE_AUTO}.
9089     * @see #setFocusableInTouchMode(boolean)
9090     * @attr ref android.R.styleable#View_focusable
9091     */
9092    public void setFocusable(@Focusable int focusable) {
9093        if ((focusable & (FOCUSABLE_AUTO | FOCUSABLE)) == 0) {
9094            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
9095        }
9096        setFlags(focusable, FOCUSABLE_MASK);
9097    }
9098
9099    /**
9100     * Set whether this view can receive focus while in touch mode.
9101     *
9102     * Setting this to true will also ensure that this view is focusable.
9103     *
9104     * @param focusableInTouchMode If true, this view can receive the focus while
9105     *   in touch mode.
9106     *
9107     * @see #setFocusable(boolean)
9108     * @attr ref android.R.styleable#View_focusableInTouchMode
9109     */
9110    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
9111        // Focusable in touch mode should always be set before the focusable flag
9112        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
9113        // which, in touch mode, will not successfully request focus on this view
9114        // because the focusable in touch mode flag is not set
9115        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
9116
9117        // Clear FOCUSABLE_AUTO if set.
9118        if (focusableInTouchMode) {
9119            // Clears FOCUSABLE_AUTO if set.
9120            setFlags(FOCUSABLE, FOCUSABLE_MASK);
9121        }
9122    }
9123
9124    /**
9125     * Set autofill mode for the view.
9126     *
9127     * @param autofillMode One of {@link #AUTOFILL_MODE_INHERIT}, {@link #AUTOFILL_MODE_AUTO},
9128     *                     or {@link #AUTOFILL_MODE_MANUAL}.
9129     * @attr ref android.R.styleable#View_autofillMode
9130     */
9131    public void setAutofillMode(@AutofillMode int autofillMode) {
9132        Preconditions.checkArgumentInRange(autofillMode, AUTOFILL_MODE_INHERIT,
9133                AUTOFILL_MODE_MANUAL, "autofillMode");
9134
9135        mPrivateFlags3 &= ~PFLAG3_AUTOFILL_MODE_MASK;
9136        mPrivateFlags3 |= autofillMode << PFLAG3_AUTOFILL_MODE_SHIFT;
9137    }
9138
9139    /**
9140     * Sets the hints that helps the autofill service to select the appropriate data to fill the
9141     * view.
9142     *
9143     * @param autofillHints The autofill hints to set. If the array is emtpy, {@code null} is set.
9144     * @attr ref android.R.styleable#View_autofillHints
9145     */
9146    public void setAutofillHints(@Nullable String... autofillHints) {
9147        if (autofillHints == null || autofillHints.length == 0) {
9148            mAutofillHints = null;
9149        } else {
9150            mAutofillHints = autofillHints;
9151        }
9152    }
9153
9154    /**
9155     * @hide
9156     */
9157    @TestApi
9158    public void setAutofilled(boolean isAutofilled) {
9159        boolean wasChanged = isAutofilled != isAutofilled();
9160
9161        if (wasChanged) {
9162            if (isAutofilled) {
9163                mPrivateFlags3 |= PFLAG3_IS_AUTOFILLED;
9164            } else {
9165                mPrivateFlags3 &= ~PFLAG3_IS_AUTOFILLED;
9166            }
9167
9168            invalidate();
9169        }
9170    }
9171
9172    /**
9173     * Set whether this view should have sound effects enabled for events such as
9174     * clicking and touching.
9175     *
9176     * <p>You may wish to disable sound effects for a view if you already play sounds,
9177     * for instance, a dial key that plays dtmf tones.
9178     *
9179     * @param soundEffectsEnabled whether sound effects are enabled for this view.
9180     * @see #isSoundEffectsEnabled()
9181     * @see #playSoundEffect(int)
9182     * @attr ref android.R.styleable#View_soundEffectsEnabled
9183     */
9184    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
9185        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
9186    }
9187
9188    /**
9189     * @return whether this view should have sound effects enabled for events such as
9190     *     clicking and touching.
9191     *
9192     * @see #setSoundEffectsEnabled(boolean)
9193     * @see #playSoundEffect(int)
9194     * @attr ref android.R.styleable#View_soundEffectsEnabled
9195     */
9196    @ViewDebug.ExportedProperty
9197    public boolean isSoundEffectsEnabled() {
9198        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
9199    }
9200
9201    /**
9202     * Set whether this view should have haptic feedback for events such as
9203     * long presses.
9204     *
9205     * <p>You may wish to disable haptic feedback if your view already controls
9206     * its own haptic feedback.
9207     *
9208     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
9209     * @see #isHapticFeedbackEnabled()
9210     * @see #performHapticFeedback(int)
9211     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
9212     */
9213    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
9214        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
9215    }
9216
9217    /**
9218     * @return whether this view should have haptic feedback enabled for events
9219     * long presses.
9220     *
9221     * @see #setHapticFeedbackEnabled(boolean)
9222     * @see #performHapticFeedback(int)
9223     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
9224     */
9225    @ViewDebug.ExportedProperty
9226    public boolean isHapticFeedbackEnabled() {
9227        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
9228    }
9229
9230    /**
9231     * Returns the layout direction for this view.
9232     *
9233     * @return One of {@link #LAYOUT_DIRECTION_LTR},
9234     *   {@link #LAYOUT_DIRECTION_RTL},
9235     *   {@link #LAYOUT_DIRECTION_INHERIT} or
9236     *   {@link #LAYOUT_DIRECTION_LOCALE}.
9237     *
9238     * @attr ref android.R.styleable#View_layoutDirection
9239     *
9240     * @hide
9241     */
9242    @ViewDebug.ExportedProperty(category = "layout", mapping = {
9243        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
9244        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
9245        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
9246        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
9247    })
9248    @LayoutDir
9249    public int getRawLayoutDirection() {
9250        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
9251    }
9252
9253    /**
9254     * Set the layout direction for this view. This will propagate a reset of layout direction
9255     * resolution to the view's children and resolve layout direction for this view.
9256     *
9257     * @param layoutDirection the layout direction to set. Should be one of:
9258     *
9259     * {@link #LAYOUT_DIRECTION_LTR},
9260     * {@link #LAYOUT_DIRECTION_RTL},
9261     * {@link #LAYOUT_DIRECTION_INHERIT},
9262     * {@link #LAYOUT_DIRECTION_LOCALE}.
9263     *
9264     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
9265     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
9266     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
9267     *
9268     * @attr ref android.R.styleable#View_layoutDirection
9269     */
9270    @RemotableViewMethod
9271    public void setLayoutDirection(@LayoutDir int layoutDirection) {
9272        if (getRawLayoutDirection() != layoutDirection) {
9273            // Reset the current layout direction and the resolved one
9274            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
9275            resetRtlProperties();
9276            // Set the new layout direction (filtered)
9277            mPrivateFlags2 |=
9278                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
9279            // We need to resolve all RTL properties as they all depend on layout direction
9280            resolveRtlPropertiesIfNeeded();
9281            requestLayout();
9282            invalidate(true);
9283        }
9284    }
9285
9286    /**
9287     * Returns the resolved layout direction for this view.
9288     *
9289     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
9290     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
9291     *
9292     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
9293     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
9294     *
9295     * @attr ref android.R.styleable#View_layoutDirection
9296     */
9297    @ViewDebug.ExportedProperty(category = "layout", mapping = {
9298        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
9299        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
9300    })
9301    @ResolvedLayoutDir
9302    public int getLayoutDirection() {
9303        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
9304        if (targetSdkVersion < Build.VERSION_CODES.JELLY_BEAN_MR1) {
9305            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
9306            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
9307        }
9308        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
9309                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
9310    }
9311
9312    /**
9313     * Indicates whether or not this view's layout is right-to-left. This is resolved from
9314     * layout attribute and/or the inherited value from the parent
9315     *
9316     * @return true if the layout is right-to-left.
9317     *
9318     * @hide
9319     */
9320    @ViewDebug.ExportedProperty(category = "layout")
9321    public boolean isLayoutRtl() {
9322        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
9323    }
9324
9325    /**
9326     * Indicates whether the view is currently tracking transient state that the
9327     * app should not need to concern itself with saving and restoring, but that
9328     * the framework should take special note to preserve when possible.
9329     *
9330     * <p>A view with transient state cannot be trivially rebound from an external
9331     * data source, such as an adapter binding item views in a list. This may be
9332     * because the view is performing an animation, tracking user selection
9333     * of content, or similar.</p>
9334     *
9335     * @return true if the view has transient state
9336     */
9337    @ViewDebug.ExportedProperty(category = "layout")
9338    public boolean hasTransientState() {
9339        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
9340    }
9341
9342    /**
9343     * Set whether this view is currently tracking transient state that the
9344     * framework should attempt to preserve when possible. This flag is reference counted,
9345     * so every call to setHasTransientState(true) should be paired with a later call
9346     * to setHasTransientState(false).
9347     *
9348     * <p>A view with transient state cannot be trivially rebound from an external
9349     * data source, such as an adapter binding item views in a list. This may be
9350     * because the view is performing an animation, tracking user selection
9351     * of content, or similar.</p>
9352     *
9353     * @param hasTransientState true if this view has transient state
9354     */
9355    public void setHasTransientState(boolean hasTransientState) {
9356        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
9357                mTransientStateCount - 1;
9358        if (mTransientStateCount < 0) {
9359            mTransientStateCount = 0;
9360            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
9361                    "unmatched pair of setHasTransientState calls");
9362        } else if ((hasTransientState && mTransientStateCount == 1) ||
9363                (!hasTransientState && mTransientStateCount == 0)) {
9364            // update flag if we've just incremented up from 0 or decremented down to 0
9365            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
9366                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
9367            if (mParent != null) {
9368                try {
9369                    mParent.childHasTransientStateChanged(this, hasTransientState);
9370                } catch (AbstractMethodError e) {
9371                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
9372                            " does not fully implement ViewParent", e);
9373                }
9374            }
9375        }
9376    }
9377
9378    /**
9379     * Returns true if this view is currently attached to a window.
9380     */
9381    public boolean isAttachedToWindow() {
9382        return mAttachInfo != null;
9383    }
9384
9385    /**
9386     * Returns true if this view has been through at least one layout since it
9387     * was last attached to or detached from a window.
9388     */
9389    public boolean isLaidOut() {
9390        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
9391    }
9392
9393    /**
9394     * If this view doesn't do any drawing on its own, set this flag to
9395     * allow further optimizations. By default, this flag is not set on
9396     * View, but could be set on some View subclasses such as ViewGroup.
9397     *
9398     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
9399     * you should clear this flag.
9400     *
9401     * @param willNotDraw whether or not this View draw on its own
9402     */
9403    public void setWillNotDraw(boolean willNotDraw) {
9404        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
9405    }
9406
9407    /**
9408     * Returns whether or not this View draws on its own.
9409     *
9410     * @return true if this view has nothing to draw, false otherwise
9411     */
9412    @ViewDebug.ExportedProperty(category = "drawing")
9413    public boolean willNotDraw() {
9414        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
9415    }
9416
9417    /**
9418     * When a View's drawing cache is enabled, drawing is redirected to an
9419     * offscreen bitmap. Some views, like an ImageView, must be able to
9420     * bypass this mechanism if they already draw a single bitmap, to avoid
9421     * unnecessary usage of the memory.
9422     *
9423     * @param willNotCacheDrawing true if this view does not cache its
9424     *        drawing, false otherwise
9425     */
9426    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
9427        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
9428    }
9429
9430    /**
9431     * Returns whether or not this View can cache its drawing or not.
9432     *
9433     * @return true if this view does not cache its drawing, false otherwise
9434     */
9435    @ViewDebug.ExportedProperty(category = "drawing")
9436    public boolean willNotCacheDrawing() {
9437        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
9438    }
9439
9440    /**
9441     * Indicates whether this view reacts to click events or not.
9442     *
9443     * @return true if the view is clickable, false otherwise
9444     *
9445     * @see #setClickable(boolean)
9446     * @attr ref android.R.styleable#View_clickable
9447     */
9448    @ViewDebug.ExportedProperty
9449    public boolean isClickable() {
9450        return (mViewFlags & CLICKABLE) == CLICKABLE;
9451    }
9452
9453    /**
9454     * Enables or disables click events for this view. When a view
9455     * is clickable it will change its state to "pressed" on every click.
9456     * Subclasses should set the view clickable to visually react to
9457     * user's clicks.
9458     *
9459     * @param clickable true to make the view clickable, false otherwise
9460     *
9461     * @see #isClickable()
9462     * @attr ref android.R.styleable#View_clickable
9463     */
9464    public void setClickable(boolean clickable) {
9465        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
9466    }
9467
9468    /**
9469     * Indicates whether this view reacts to long click events or not.
9470     *
9471     * @return true if the view is long clickable, false otherwise
9472     *
9473     * @see #setLongClickable(boolean)
9474     * @attr ref android.R.styleable#View_longClickable
9475     */
9476    public boolean isLongClickable() {
9477        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
9478    }
9479
9480    /**
9481     * Enables or disables long click events for this view. When a view is long
9482     * clickable it reacts to the user holding down the button for a longer
9483     * duration than a tap. This event can either launch the listener or a
9484     * context menu.
9485     *
9486     * @param longClickable true to make the view long clickable, false otherwise
9487     * @see #isLongClickable()
9488     * @attr ref android.R.styleable#View_longClickable
9489     */
9490    public void setLongClickable(boolean longClickable) {
9491        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
9492    }
9493
9494    /**
9495     * Indicates whether this view reacts to context clicks or not.
9496     *
9497     * @return true if the view is context clickable, false otherwise
9498     * @see #setContextClickable(boolean)
9499     * @attr ref android.R.styleable#View_contextClickable
9500     */
9501    public boolean isContextClickable() {
9502        return (mViewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
9503    }
9504
9505    /**
9506     * Enables or disables context clicking for this view. This event can launch the listener.
9507     *
9508     * @param contextClickable true to make the view react to a context click, false otherwise
9509     * @see #isContextClickable()
9510     * @attr ref android.R.styleable#View_contextClickable
9511     */
9512    public void setContextClickable(boolean contextClickable) {
9513        setFlags(contextClickable ? CONTEXT_CLICKABLE : 0, CONTEXT_CLICKABLE);
9514    }
9515
9516    /**
9517     * Sets the pressed state for this view and provides a touch coordinate for
9518     * animation hinting.
9519     *
9520     * @param pressed Pass true to set the View's internal state to "pressed",
9521     *            or false to reverts the View's internal state from a
9522     *            previously set "pressed" state.
9523     * @param x The x coordinate of the touch that caused the press
9524     * @param y The y coordinate of the touch that caused the press
9525     */
9526    private void setPressed(boolean pressed, float x, float y) {
9527        if (pressed) {
9528            drawableHotspotChanged(x, y);
9529        }
9530
9531        setPressed(pressed);
9532    }
9533
9534    /**
9535     * Sets the pressed state for this view.
9536     *
9537     * @see #isClickable()
9538     * @see #setClickable(boolean)
9539     *
9540     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
9541     *        the View's internal state from a previously set "pressed" state.
9542     */
9543    public void setPressed(boolean pressed) {
9544        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
9545
9546        if (pressed) {
9547            mPrivateFlags |= PFLAG_PRESSED;
9548        } else {
9549            mPrivateFlags &= ~PFLAG_PRESSED;
9550        }
9551
9552        if (needsRefresh) {
9553            refreshDrawableState();
9554        }
9555        dispatchSetPressed(pressed);
9556    }
9557
9558    /**
9559     * Dispatch setPressed to all of this View's children.
9560     *
9561     * @see #setPressed(boolean)
9562     *
9563     * @param pressed The new pressed state
9564     */
9565    protected void dispatchSetPressed(boolean pressed) {
9566    }
9567
9568    /**
9569     * Indicates whether the view is currently in pressed state. Unless
9570     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
9571     * the pressed state.
9572     *
9573     * @see #setPressed(boolean)
9574     * @see #isClickable()
9575     * @see #setClickable(boolean)
9576     *
9577     * @return true if the view is currently pressed, false otherwise
9578     */
9579    @ViewDebug.ExportedProperty
9580    public boolean isPressed() {
9581        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
9582    }
9583
9584    /**
9585     * @hide
9586     * Indicates whether this view will participate in data collection through
9587     * {@link ViewStructure}.  If true, it will not provide any data
9588     * for itself or its children.  If false, the normal data collection will be allowed.
9589     *
9590     * @return Returns false if assist data collection is not blocked, else true.
9591     *
9592     * @see #setAssistBlocked(boolean)
9593     * @attr ref android.R.styleable#View_assistBlocked
9594     */
9595    public boolean isAssistBlocked() {
9596        return (mPrivateFlags3 & PFLAG3_ASSIST_BLOCKED) != 0;
9597    }
9598
9599    /**
9600     * @hide
9601     * Indicates whether this view will participate in data collection through
9602     * {@link ViewStructure} for autofill purposes.
9603     *
9604     * <p>If {@code true}, it will not provide any data for itself or its children.
9605     * <p>If {@code false}, the normal data collection will be allowed.
9606     *
9607     * @return Returns {@code false} if assist data collection for autofill is not blocked,
9608     * else {@code true}.
9609     *
9610     * TODO(b/33197203): update / remove javadoc tags below
9611     * @see #setAssistBlocked(boolean)
9612     * @attr ref android.R.styleable#View_assistBlocked
9613     */
9614    public boolean isAutofillBlocked() {
9615        return false; // TODO(b/33197203): properly implement it
9616    }
9617
9618    /**
9619     * @hide
9620     * Controls whether assist data collection from this view and its children is enabled
9621     * (that is, whether {@link #onProvideStructure} and
9622     * {@link #onProvideVirtualStructure} will be called).  The default value is false,
9623     * allowing normal assist collection.  Setting this to false will disable assist collection.
9624     *
9625     * @param enabled Set to true to <em>disable</em> assist data collection, or false
9626     * (the default) to allow it.
9627     *
9628     * @see #isAssistBlocked()
9629     * @see #onProvideStructure
9630     * @see #onProvideVirtualStructure
9631     * @attr ref android.R.styleable#View_assistBlocked
9632     */
9633    public void setAssistBlocked(boolean enabled) {
9634        if (enabled) {
9635            mPrivateFlags3 |= PFLAG3_ASSIST_BLOCKED;
9636        } else {
9637            mPrivateFlags3 &= ~PFLAG3_ASSIST_BLOCKED;
9638        }
9639    }
9640
9641    /**
9642     * Indicates whether this view will save its state (that is,
9643     * whether its {@link #onSaveInstanceState} method will be called).
9644     *
9645     * @return Returns true if the view state saving is enabled, else false.
9646     *
9647     * @see #setSaveEnabled(boolean)
9648     * @attr ref android.R.styleable#View_saveEnabled
9649     */
9650    public boolean isSaveEnabled() {
9651        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
9652    }
9653
9654    /**
9655     * Controls whether the saving of this view's state is
9656     * enabled (that is, whether its {@link #onSaveInstanceState} method
9657     * will be called).  Note that even if freezing is enabled, the
9658     * view still must have an id assigned to it (via {@link #setId(int)})
9659     * for its state to be saved.  This flag can only disable the
9660     * saving of this view; any child views may still have their state saved.
9661     *
9662     * @param enabled Set to false to <em>disable</em> state saving, or true
9663     * (the default) to allow it.
9664     *
9665     * @see #isSaveEnabled()
9666     * @see #setId(int)
9667     * @see #onSaveInstanceState()
9668     * @attr ref android.R.styleable#View_saveEnabled
9669     */
9670    public void setSaveEnabled(boolean enabled) {
9671        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
9672    }
9673
9674    /**
9675     * Gets whether the framework should discard touches when the view's
9676     * window is obscured by another visible window.
9677     * Refer to the {@link View} security documentation for more details.
9678     *
9679     * @return True if touch filtering is enabled.
9680     *
9681     * @see #setFilterTouchesWhenObscured(boolean)
9682     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
9683     */
9684    @ViewDebug.ExportedProperty
9685    public boolean getFilterTouchesWhenObscured() {
9686        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
9687    }
9688
9689    /**
9690     * Sets whether the framework should discard touches when the view's
9691     * window is obscured by another visible window.
9692     * Refer to the {@link View} security documentation for more details.
9693     *
9694     * @param enabled True if touch filtering should be enabled.
9695     *
9696     * @see #getFilterTouchesWhenObscured
9697     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
9698     */
9699    public void setFilterTouchesWhenObscured(boolean enabled) {
9700        setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0,
9701                FILTER_TOUCHES_WHEN_OBSCURED);
9702    }
9703
9704    /**
9705     * Indicates whether the entire hierarchy under this view will save its
9706     * state when a state saving traversal occurs from its parent.  The default
9707     * is true; if false, these views will not be saved unless
9708     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
9709     *
9710     * @return Returns true if the view state saving from parent is enabled, else false.
9711     *
9712     * @see #setSaveFromParentEnabled(boolean)
9713     */
9714    public boolean isSaveFromParentEnabled() {
9715        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
9716    }
9717
9718    /**
9719     * Controls whether the entire hierarchy under this view will save its
9720     * state when a state saving traversal occurs from its parent.  The default
9721     * is true; if false, these views will not be saved unless
9722     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
9723     *
9724     * @param enabled Set to false to <em>disable</em> state saving, or true
9725     * (the default) to allow it.
9726     *
9727     * @see #isSaveFromParentEnabled()
9728     * @see #setId(int)
9729     * @see #onSaveInstanceState()
9730     */
9731    public void setSaveFromParentEnabled(boolean enabled) {
9732        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
9733    }
9734
9735
9736    /**
9737     * Returns whether this View is currently able to take focus.
9738     *
9739     * @return True if this view can take focus, or false otherwise.
9740     */
9741    @ViewDebug.ExportedProperty(category = "focus")
9742    public final boolean isFocusable() {
9743        return FOCUSABLE == (mViewFlags & FOCUSABLE);
9744    }
9745
9746    /**
9747     * Returns the focusable setting for this view.
9748     *
9749     * @return One of {@link #NOT_FOCUSABLE}, {@link #FOCUSABLE}, or {@link #FOCUSABLE_AUTO}.
9750     * @attr ref android.R.styleable#View_focusable
9751     */
9752    @ViewDebug.ExportedProperty(mapping = {
9753            @ViewDebug.IntToString(from = NOT_FOCUSABLE, to = "NOT_FOCUSABLE"),
9754            @ViewDebug.IntToString(from = FOCUSABLE, to = "FOCUSABLE"),
9755            @ViewDebug.IntToString(from = FOCUSABLE_AUTO, to = "FOCUSABLE_AUTO")
9756            })
9757    @Focusable
9758    public int getFocusable() {
9759        return (mViewFlags & FOCUSABLE_AUTO) > 0 ? FOCUSABLE_AUTO : mViewFlags & FOCUSABLE;
9760    }
9761
9762    /**
9763     * When a view is focusable, it may not want to take focus when in touch mode.
9764     * For example, a button would like focus when the user is navigating via a D-pad
9765     * so that the user can click on it, but once the user starts touching the screen,
9766     * the button shouldn't take focus
9767     * @return Whether the view is focusable in touch mode.
9768     * @attr ref android.R.styleable#View_focusableInTouchMode
9769     */
9770    @ViewDebug.ExportedProperty
9771    public final boolean isFocusableInTouchMode() {
9772        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
9773    }
9774
9775    /**
9776     * Returns the autofill mode for this view.
9777     *
9778     * @return One of {@link #AUTOFILL_MODE_INHERIT}, {@link #AUTOFILL_MODE_AUTO}, or
9779     * {@link #AUTOFILL_MODE_MANUAL}.
9780     * @attr ref android.R.styleable#View_autofillMode
9781     */
9782    @ViewDebug.ExportedProperty(mapping = {
9783            @ViewDebug.IntToString(from = AUTOFILL_MODE_INHERIT, to = "AUTOFILL_MODE_INHERIT"),
9784            @ViewDebug.IntToString(from = AUTOFILL_MODE_AUTO, to = "AUTOFILL_MODE_AUTO"),
9785            @ViewDebug.IntToString(from = AUTOFILL_MODE_MANUAL, to = "AUTOFILL_MODE_MANUAL")
9786            })
9787    @AutofillMode
9788    public int getAutofillMode() {
9789        return (mPrivateFlags3 & PFLAG3_AUTOFILL_MODE_MASK) >> PFLAG3_AUTOFILL_MODE_SHIFT;
9790    }
9791
9792    /**
9793     * Returns the resolved autofill mode for this view.
9794     *
9795     * This is the same as {@link #getAutofillMode()} but if the mode is
9796     * {@link #AUTOFILL_MODE_INHERIT} the parents autofill mode will be returned.
9797     *
9798     * @return One of {@link #AUTOFILL_MODE_AUTO}, or {@link #AUTOFILL_MODE_MANUAL}. If the auto-
9799     *         fill mode can not be resolved e.g. {@link #getAutofillMode()} is
9800     *         {@link #AUTOFILL_MODE_INHERIT} and the {@link View} is detached
9801     *         {@link #AUTOFILL_MODE_AUTO} is returned.
9802     */
9803    public @AutofillMode int getResolvedAutofillMode() {
9804        @AutofillMode int autofillMode = getAutofillMode();
9805
9806        if (autofillMode == AUTOFILL_MODE_INHERIT) {
9807            if (mParent == null) {
9808                return AUTOFILL_MODE_AUTO;
9809            } else {
9810                return mParent.getResolvedAutofillMode();
9811            }
9812        } else {
9813            return autofillMode;
9814        }
9815    }
9816
9817    /**
9818     * Find the nearest view in the specified direction that can take focus.
9819     * This does not actually give focus to that view.
9820     *
9821     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
9822     *
9823     * @return The nearest focusable in the specified direction, or null if none
9824     *         can be found.
9825     */
9826    public View focusSearch(@FocusRealDirection int direction) {
9827        if (mParent != null) {
9828            return mParent.focusSearch(this, direction);
9829        } else {
9830            return null;
9831        }
9832    }
9833
9834    /**
9835     * Returns whether this View is a root of a keyboard navigation cluster.
9836     *
9837     * @return True if this view is a root of a cluster, or false otherwise.
9838     * @attr ref android.R.styleable#View_keyboardNavigationCluster
9839     */
9840    @ViewDebug.ExportedProperty(category = "keyboardNavigationCluster")
9841    public final boolean isKeyboardNavigationCluster() {
9842        return (mPrivateFlags3 & PFLAG3_CLUSTER) != 0;
9843    }
9844
9845    /**
9846     * Set whether this view is a root of a keyboard navigation cluster.
9847     *
9848     * @param isCluster If true, this view is a root of a cluster.
9849     *
9850     * @attr ref android.R.styleable#View_keyboardNavigationCluster
9851     */
9852    public void setKeyboardNavigationCluster(boolean isCluster) {
9853        if (isCluster) {
9854            mPrivateFlags3 |= PFLAG3_CLUSTER;
9855        } else {
9856            mPrivateFlags3 &= ~PFLAG3_CLUSTER;
9857        }
9858    }
9859
9860    /**
9861     * Sets this View as the one which receives focus the next time cluster navigation jumps
9862     * to the cluster containing this View. This does NOT change focus even if the cluster
9863     * containing this view is current.
9864     *
9865     * @hide
9866     */
9867    public void setFocusedInCluster() {
9868        if (mParent instanceof ViewGroup) {
9869            ((ViewGroup) mParent).setFocusInCluster(this);
9870        }
9871    }
9872
9873    /**
9874     * Returns whether this View should receive focus when the focus is restored for the view
9875     * hierarchy containing this view.
9876     * <p>
9877     * Focus gets restored for a view hierarchy when the root of the hierarchy gets added to a
9878     * window or serves as a target of cluster navigation.
9879     *
9880     * @see #restoreDefaultFocus()
9881     *
9882     * @return {@code true} if this view is the default-focus view, {@code false} otherwise
9883     * @attr ref android.R.styleable#View_focusedByDefault
9884     */
9885    @ViewDebug.ExportedProperty(category = "focusedByDefault")
9886    public final boolean isFocusedByDefault() {
9887        return (mPrivateFlags3 & PFLAG3_FOCUSED_BY_DEFAULT) != 0;
9888    }
9889
9890    /**
9891     * Sets whether this View should receive focus when the focus is restored for the view
9892     * hierarchy containing this view.
9893     * <p>
9894     * Focus gets restored for a view hierarchy when the root of the hierarchy gets added to a
9895     * window or serves as a target of cluster navigation.
9896     *
9897     * @param isFocusedByDefault {@code true} to set this view as the default-focus view,
9898     *                           {@code false} otherwise.
9899     *
9900     * @see #restoreDefaultFocus()
9901     *
9902     * @attr ref android.R.styleable#View_focusedByDefault
9903     */
9904    public void setFocusedByDefault(boolean isFocusedByDefault) {
9905        if (isFocusedByDefault == ((mPrivateFlags3 & PFLAG3_FOCUSED_BY_DEFAULT) != 0)) {
9906            return;
9907        }
9908
9909        if (isFocusedByDefault) {
9910            mPrivateFlags3 |= PFLAG3_FOCUSED_BY_DEFAULT;
9911        } else {
9912            mPrivateFlags3 &= ~PFLAG3_FOCUSED_BY_DEFAULT;
9913        }
9914
9915        if (mParent instanceof ViewGroup) {
9916            if (isFocusedByDefault) {
9917                ((ViewGroup) mParent).setDefaultFocus(this);
9918            } else {
9919                ((ViewGroup) mParent).clearDefaultFocus(this);
9920            }
9921        }
9922    }
9923
9924    /**
9925     * Returns whether the view hierarchy with this view as a root contain a default-focus view.
9926     *
9927     * @return {@code true} if this view has default focus, {@code false} otherwise
9928     */
9929    boolean hasDefaultFocus() {
9930        return isFocusedByDefault();
9931    }
9932
9933    /**
9934     * Find the nearest keyboard navigation cluster in the specified direction.
9935     * This does not actually give focus to that cluster.
9936     *
9937     * @param currentCluster The starting point of the search. Null means the current cluster is not
9938     *                       found yet
9939     * @param direction Direction to look
9940     *
9941     * @return The nearest keyboard navigation cluster in the specified direction, or null if none
9942     *         can be found
9943     */
9944    public View keyboardNavigationClusterSearch(View currentCluster,
9945            @FocusDirection int direction) {
9946        if (isKeyboardNavigationCluster()) {
9947            currentCluster = this;
9948        }
9949        if (isRootNamespace()) {
9950            // Root namespace means we should consider ourselves the top of the
9951            // tree for group searching; otherwise we could be group searching
9952            // into other tabs.  see LocalActivityManager and TabHost for more info.
9953            return FocusFinder.getInstance().findNextKeyboardNavigationCluster(
9954                    this, currentCluster, direction);
9955        } else if (mParent != null) {
9956            return mParent.keyboardNavigationClusterSearch(currentCluster, direction);
9957        }
9958        return null;
9959    }
9960
9961    /**
9962     * This method is the last chance for the focused view and its ancestors to
9963     * respond to an arrow key. This is called when the focused view did not
9964     * consume the key internally, nor could the view system find a new view in
9965     * the requested direction to give focus to.
9966     *
9967     * @param focused The currently focused view.
9968     * @param direction The direction focus wants to move. One of FOCUS_UP,
9969     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
9970     * @return True if the this view consumed this unhandled move.
9971     */
9972    public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) {
9973        return false;
9974    }
9975
9976    /**
9977     * If a user manually specified the next view id for a particular direction,
9978     * use the root to look up the view.
9979     * @param root The root view of the hierarchy containing this view.
9980     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
9981     * or FOCUS_BACKWARD.
9982     * @return The user specified next view, or null if there is none.
9983     */
9984    View findUserSetNextFocus(View root, @FocusDirection int direction) {
9985        switch (direction) {
9986            case FOCUS_LEFT:
9987                if (mNextFocusLeftId == View.NO_ID) return null;
9988                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
9989            case FOCUS_RIGHT:
9990                if (mNextFocusRightId == View.NO_ID) return null;
9991                return findViewInsideOutShouldExist(root, mNextFocusRightId);
9992            case FOCUS_UP:
9993                if (mNextFocusUpId == View.NO_ID) return null;
9994                return findViewInsideOutShouldExist(root, mNextFocusUpId);
9995            case FOCUS_DOWN:
9996                if (mNextFocusDownId == View.NO_ID) return null;
9997                return findViewInsideOutShouldExist(root, mNextFocusDownId);
9998            case FOCUS_FORWARD:
9999                if (mNextFocusForwardId == View.NO_ID) return null;
10000                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
10001            case FOCUS_BACKWARD: {
10002                if (mID == View.NO_ID) return null;
10003                final int id = mID;
10004                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
10005                    @Override
10006                    public boolean test(View t) {
10007                        return t.mNextFocusForwardId == id;
10008                    }
10009                });
10010            }
10011        }
10012        return null;
10013    }
10014
10015    /**
10016     * If a user manually specified the next keyboard-navigation cluster for a particular direction,
10017     * use the root to look up the view.
10018     *
10019     * @param root the root view of the hierarchy containing this view
10020     * @param direction {@link #FOCUS_FORWARD} or {@link #FOCUS_BACKWARD}
10021     * @return the user-specified next cluster, or {@code null} if there is none
10022     */
10023    View findUserSetNextKeyboardNavigationCluster(View root, @FocusDirection int direction) {
10024        switch (direction) {
10025            case FOCUS_FORWARD:
10026                if (mNextClusterForwardId == View.NO_ID) return null;
10027                return findViewInsideOutShouldExist(root, mNextClusterForwardId);
10028            case FOCUS_BACKWARD: {
10029                if (mID == View.NO_ID) return null;
10030                final int id = mID;
10031                return root.findViewByPredicateInsideOut(this,
10032                        (Predicate<View>) t -> t.mNextClusterForwardId == id);
10033            }
10034        }
10035        return null;
10036    }
10037
10038    private View findViewInsideOutShouldExist(View root, int id) {
10039        if (mMatchIdPredicate == null) {
10040            mMatchIdPredicate = new MatchIdPredicate();
10041        }
10042        mMatchIdPredicate.mId = id;
10043        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
10044        if (result == null) {
10045            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
10046        }
10047        return result;
10048    }
10049
10050    /**
10051     * Find and return all focusable views that are descendants of this view,
10052     * possibly including this view if it is focusable itself.
10053     *
10054     * @param direction The direction of the focus
10055     * @return A list of focusable views
10056     */
10057    public ArrayList<View> getFocusables(@FocusDirection int direction) {
10058        ArrayList<View> result = new ArrayList<View>(24);
10059        addFocusables(result, direction);
10060        return result;
10061    }
10062
10063    /**
10064     * Add any focusable views that are descendants of this view (possibly
10065     * including this view if it is focusable itself) to views.  If we are in touch mode,
10066     * only add views that are also focusable in touch mode.
10067     *
10068     * @param views Focusable views found so far
10069     * @param direction The direction of the focus
10070     */
10071    public void addFocusables(ArrayList<View> views, @FocusDirection int direction) {
10072        addFocusables(views, direction, isInTouchMode() ? FOCUSABLES_TOUCH_MODE : FOCUSABLES_ALL);
10073    }
10074
10075    /**
10076     * Adds any focusable views that are descendants of this view (possibly
10077     * including this view if it is focusable itself) to views. This method
10078     * adds all focusable views regardless if we are in touch mode or
10079     * only views focusable in touch mode if we are in touch mode or
10080     * only views that can take accessibility focus if accessibility is enabled
10081     * depending on the focusable mode parameter.
10082     *
10083     * @param views Focusable views found so far or null if all we are interested is
10084     *        the number of focusables.
10085     * @param direction The direction of the focus.
10086     * @param focusableMode The type of focusables to be added.
10087     *
10088     * @see #FOCUSABLES_ALL
10089     * @see #FOCUSABLES_TOUCH_MODE
10090     */
10091    public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
10092            @FocusableMode int focusableMode) {
10093        if (views == null) {
10094            return;
10095        }
10096        if (!isFocusable()) {
10097            return;
10098        }
10099        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
10100                && !isFocusableInTouchMode()) {
10101            return;
10102        }
10103        views.add(this);
10104    }
10105
10106    /**
10107     * Adds any keyboard navigation cluster roots that are descendants of this view (possibly
10108     * including this view if it is a cluster root itself) to views.
10109     *
10110     * @param views Keyboard navigation cluster roots found so far
10111     * @param direction Direction to look
10112     */
10113    public void addKeyboardNavigationClusters(
10114            @NonNull Collection<View> views,
10115            int direction) {
10116        if (!isKeyboardNavigationCluster()) {
10117            return;
10118        }
10119        if (!hasFocusable()) {
10120            return;
10121        }
10122        views.add(this);
10123    }
10124
10125    /**
10126     * Finds the Views that contain given text. The containment is case insensitive.
10127     * The search is performed by either the text that the View renders or the content
10128     * description that describes the view for accessibility purposes and the view does
10129     * not render or both. Clients can specify how the search is to be performed via
10130     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
10131     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
10132     *
10133     * @param outViews The output list of matching Views.
10134     * @param searched The text to match against.
10135     *
10136     * @see #FIND_VIEWS_WITH_TEXT
10137     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
10138     * @see #setContentDescription(CharSequence)
10139     */
10140    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched,
10141            @FindViewFlags int flags) {
10142        if (getAccessibilityNodeProvider() != null) {
10143            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
10144                outViews.add(this);
10145            }
10146        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
10147                && (searched != null && searched.length() > 0)
10148                && (mContentDescription != null && mContentDescription.length() > 0)) {
10149            String searchedLowerCase = searched.toString().toLowerCase();
10150            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
10151            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
10152                outViews.add(this);
10153            }
10154        }
10155    }
10156
10157    /**
10158     * Find and return all touchable views that are descendants of this view,
10159     * possibly including this view if it is touchable itself.
10160     *
10161     * @return A list of touchable views
10162     */
10163    public ArrayList<View> getTouchables() {
10164        ArrayList<View> result = new ArrayList<View>();
10165        addTouchables(result);
10166        return result;
10167    }
10168
10169    /**
10170     * Add any touchable views that are descendants of this view (possibly
10171     * including this view if it is touchable itself) to views.
10172     *
10173     * @param views Touchable views found so far
10174     */
10175    public void addTouchables(ArrayList<View> views) {
10176        final int viewFlags = mViewFlags;
10177
10178        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE
10179                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE)
10180                && (viewFlags & ENABLED_MASK) == ENABLED) {
10181            views.add(this);
10182        }
10183    }
10184
10185    /**
10186     * Returns whether this View is accessibility focused.
10187     *
10188     * @return True if this View is accessibility focused.
10189     */
10190    public boolean isAccessibilityFocused() {
10191        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
10192    }
10193
10194    /**
10195     * Call this to try to give accessibility focus to this view.
10196     *
10197     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
10198     * returns false or the view is no visible or the view already has accessibility
10199     * focus.
10200     *
10201     * See also {@link #focusSearch(int)}, which is what you call to say that you
10202     * have focus, and you want your parent to look for the next one.
10203     *
10204     * @return Whether this view actually took accessibility focus.
10205     *
10206     * @hide
10207     */
10208    public boolean requestAccessibilityFocus() {
10209        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
10210        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
10211            return false;
10212        }
10213        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
10214            return false;
10215        }
10216        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
10217            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
10218            ViewRootImpl viewRootImpl = getViewRootImpl();
10219            if (viewRootImpl != null) {
10220                viewRootImpl.setAccessibilityFocus(this, null);
10221            }
10222            invalidate();
10223            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
10224            return true;
10225        }
10226        return false;
10227    }
10228
10229    /**
10230     * Call this to try to clear accessibility focus of this view.
10231     *
10232     * See also {@link #focusSearch(int)}, which is what you call to say that you
10233     * have focus, and you want your parent to look for the next one.
10234     *
10235     * @hide
10236     */
10237    public void clearAccessibilityFocus() {
10238        clearAccessibilityFocusNoCallbacks(0);
10239
10240        // Clear the global reference of accessibility focus if this view or
10241        // any of its descendants had accessibility focus. This will NOT send
10242        // an event or update internal state if focus is cleared from a
10243        // descendant view, which may leave views in inconsistent states.
10244        final ViewRootImpl viewRootImpl = getViewRootImpl();
10245        if (viewRootImpl != null) {
10246            final View focusHost = viewRootImpl.getAccessibilityFocusedHost();
10247            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
10248                viewRootImpl.setAccessibilityFocus(null, null);
10249            }
10250        }
10251    }
10252
10253    private void sendAccessibilityHoverEvent(int eventType) {
10254        // Since we are not delivering to a client accessibility events from not
10255        // important views (unless the clinet request that) we need to fire the
10256        // event from the deepest view exposed to the client. As a consequence if
10257        // the user crosses a not exposed view the client will see enter and exit
10258        // of the exposed predecessor followed by and enter and exit of that same
10259        // predecessor when entering and exiting the not exposed descendant. This
10260        // is fine since the client has a clear idea which view is hovered at the
10261        // price of a couple more events being sent. This is a simple and
10262        // working solution.
10263        View source = this;
10264        while (true) {
10265            if (source.includeForAccessibility()) {
10266                source.sendAccessibilityEvent(eventType);
10267                return;
10268            }
10269            ViewParent parent = source.getParent();
10270            if (parent instanceof View) {
10271                source = (View) parent;
10272            } else {
10273                return;
10274            }
10275        }
10276    }
10277
10278    /**
10279     * Clears accessibility focus without calling any callback methods
10280     * normally invoked in {@link #clearAccessibilityFocus()}. This method
10281     * is used separately from that one for clearing accessibility focus when
10282     * giving this focus to another view.
10283     *
10284     * @param action The action, if any, that led to focus being cleared. Set to
10285     * AccessibilityNodeInfo#ACTION_ACCESSIBILITY_FOCUS to specify that focus is moving within
10286     * the window.
10287     */
10288    void clearAccessibilityFocusNoCallbacks(int action) {
10289        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
10290            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
10291            invalidate();
10292            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
10293                AccessibilityEvent event = AccessibilityEvent.obtain(
10294                        AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
10295                event.setAction(action);
10296                if (mAccessibilityDelegate != null) {
10297                    mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
10298                } else {
10299                    sendAccessibilityEventUnchecked(event);
10300                }
10301            }
10302        }
10303    }
10304
10305    /**
10306     * Call this to try to give focus to a specific view or to one of its
10307     * descendants.
10308     *
10309     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
10310     * false), or if it is focusable and it is not focusable in touch mode
10311     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
10312     *
10313     * See also {@link #focusSearch(int)}, which is what you call to say that you
10314     * have focus, and you want your parent to look for the next one.
10315     *
10316     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
10317     * {@link #FOCUS_DOWN} and <code>null</code>.
10318     *
10319     * @return Whether this view or one of its descendants actually took focus.
10320     */
10321    public final boolean requestFocus() {
10322        return requestFocus(View.FOCUS_DOWN);
10323    }
10324
10325    /**
10326     * This will request focus for whichever View was last focused within this
10327     * cluster before a focus-jump out of it.
10328     *
10329     * @hide
10330     */
10331    @TestApi
10332    public boolean restoreFocusInCluster(@FocusRealDirection int direction) {
10333        // Prioritize focusableByDefault over algorithmic focus selection.
10334        if (restoreDefaultFocus()) {
10335            return true;
10336        }
10337        return requestFocus(direction);
10338    }
10339
10340    /**
10341     * This will request focus for whichever View not in a cluster was last focused before a
10342     * focus-jump to a cluster. If no non-cluster View has previously had focus, this will focus
10343     * the "first" focusable view it finds.
10344     *
10345     * @hide
10346     */
10347    @TestApi
10348    public boolean restoreFocusNotInCluster() {
10349        return requestFocus(View.FOCUS_DOWN);
10350    }
10351
10352    /**
10353     * Gives focus to the default-focus view in the view hierarchy that has this view as a root.
10354     * If the default-focus view cannot be found, falls back to calling {@link #requestFocus(int)}.
10355     *
10356     * @return Whether this view or one of its descendants actually took focus
10357     */
10358    public boolean restoreDefaultFocus() {
10359        return requestFocus(View.FOCUS_DOWN);
10360    }
10361
10362    /**
10363     * Call this to try to give focus to a specific view or to one of its
10364     * descendants and give it a hint about what direction focus is heading.
10365     *
10366     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
10367     * false), or if it is focusable and it is not focusable in touch mode
10368     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
10369     *
10370     * See also {@link #focusSearch(int)}, which is what you call to say that you
10371     * have focus, and you want your parent to look for the next one.
10372     *
10373     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
10374     * <code>null</code> set for the previously focused rectangle.
10375     *
10376     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
10377     * @return Whether this view or one of its descendants actually took focus.
10378     */
10379    public final boolean requestFocus(int direction) {
10380        return requestFocus(direction, null);
10381    }
10382
10383    /**
10384     * Call this to try to give focus to a specific view or to one of its descendants
10385     * and give it hints about the direction and a specific rectangle that the focus
10386     * is coming from.  The rectangle can help give larger views a finer grained hint
10387     * about where focus is coming from, and therefore, where to show selection, or
10388     * forward focus change internally.
10389     *
10390     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
10391     * false), or if it is focusable and it is not focusable in touch mode
10392     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
10393     *
10394     * A View will not take focus if it is not visible.
10395     *
10396     * A View will not take focus if one of its parents has
10397     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
10398     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
10399     *
10400     * See also {@link #focusSearch(int)}, which is what you call to say that you
10401     * have focus, and you want your parent to look for the next one.
10402     *
10403     * You may wish to override this method if your custom {@link View} has an internal
10404     * {@link View} that it wishes to forward the request to.
10405     *
10406     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
10407     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
10408     *        to give a finer grained hint about where focus is coming from.  May be null
10409     *        if there is no hint.
10410     * @return Whether this view or one of its descendants actually took focus.
10411     */
10412    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
10413        return requestFocusNoSearch(direction, previouslyFocusedRect);
10414    }
10415
10416    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
10417        // need to be focusable
10418        if ((mViewFlags & FOCUSABLE) != FOCUSABLE
10419                || (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
10420            return false;
10421        }
10422
10423        // need to be focusable in touch mode if in touch mode
10424        if (isInTouchMode() &&
10425            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
10426               return false;
10427        }
10428
10429        // need to not have any parents blocking us
10430        if (hasAncestorThatBlocksDescendantFocus()) {
10431            return false;
10432        }
10433
10434        handleFocusGainInternal(direction, previouslyFocusedRect);
10435        return true;
10436    }
10437
10438    /**
10439     * Call this to try to give focus to a specific view or to one of its descendants. This is a
10440     * special variant of {@link #requestFocus() } that will allow views that are not focusable in
10441     * touch mode to request focus when they are touched.
10442     *
10443     * @return Whether this view or one of its descendants actually took focus.
10444     *
10445     * @see #isInTouchMode()
10446     *
10447     */
10448    public final boolean requestFocusFromTouch() {
10449        // Leave touch mode if we need to
10450        if (isInTouchMode()) {
10451            ViewRootImpl viewRoot = getViewRootImpl();
10452            if (viewRoot != null) {
10453                viewRoot.ensureTouchMode(false);
10454            }
10455        }
10456        return requestFocus(View.FOCUS_DOWN);
10457    }
10458
10459    /**
10460     * @return Whether any ancestor of this view blocks descendant focus.
10461     */
10462    private boolean hasAncestorThatBlocksDescendantFocus() {
10463        final boolean focusableInTouchMode = isFocusableInTouchMode();
10464        ViewParent ancestor = mParent;
10465        while (ancestor instanceof ViewGroup) {
10466            final ViewGroup vgAncestor = (ViewGroup) ancestor;
10467            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS
10468                    || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) {
10469                return true;
10470            } else {
10471                ancestor = vgAncestor.getParent();
10472            }
10473        }
10474        return false;
10475    }
10476
10477    /**
10478     * Gets the mode for determining whether this View is important for accessibility.
10479     * A view is important for accessibility if it fires accessibility events and if it
10480     * is reported to accessibility services that query the screen.
10481     *
10482     * @return The mode for determining whether a view is important for accessibility, one
10483     * of {@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, {@link #IMPORTANT_FOR_ACCESSIBILITY_YES},
10484     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO}, or
10485     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}.
10486     *
10487     * @attr ref android.R.styleable#View_importantForAccessibility
10488     *
10489     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
10490     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
10491     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
10492     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
10493     */
10494    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
10495            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
10496            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
10497            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"),
10498            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
10499                    to = "noHideDescendants")
10500        })
10501    public int getImportantForAccessibility() {
10502        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
10503                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
10504    }
10505
10506    /**
10507     * Sets the live region mode for this view. This indicates to accessibility
10508     * services whether they should automatically notify the user about changes
10509     * to the view's content description or text, or to the content descriptions
10510     * or text of the view's children (where applicable).
10511     * <p>
10512     * For example, in a login screen with a TextView that displays an "incorrect
10513     * password" notification, that view should be marked as a live region with
10514     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
10515     * <p>
10516     * To disable change notifications for this view, use
10517     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
10518     * mode for most views.
10519     * <p>
10520     * To indicate that the user should be notified of changes, use
10521     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
10522     * <p>
10523     * If the view's changes should interrupt ongoing speech and notify the user
10524     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
10525     *
10526     * @param mode The live region mode for this view, one of:
10527     *        <ul>
10528     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
10529     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
10530     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
10531     *        </ul>
10532     * @attr ref android.R.styleable#View_accessibilityLiveRegion
10533     */
10534    public void setAccessibilityLiveRegion(int mode) {
10535        if (mode != getAccessibilityLiveRegion()) {
10536            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
10537            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
10538                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
10539            notifyViewAccessibilityStateChangedIfNeeded(
10540                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10541        }
10542    }
10543
10544    /**
10545     * Gets the live region mode for this View.
10546     *
10547     * @return The live region mode for the view.
10548     *
10549     * @attr ref android.R.styleable#View_accessibilityLiveRegion
10550     *
10551     * @see #setAccessibilityLiveRegion(int)
10552     */
10553    public int getAccessibilityLiveRegion() {
10554        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
10555                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
10556    }
10557
10558    /**
10559     * Sets how to determine whether this view is important for accessibility
10560     * which is if it fires accessibility events and if it is reported to
10561     * accessibility services that query the screen.
10562     *
10563     * @param mode How to determine whether this view is important for accessibility.
10564     *
10565     * @attr ref android.R.styleable#View_importantForAccessibility
10566     *
10567     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
10568     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
10569     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
10570     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
10571     */
10572    public void setImportantForAccessibility(int mode) {
10573        final int oldMode = getImportantForAccessibility();
10574        if (mode != oldMode) {
10575            final boolean hideDescendants =
10576                    mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS;
10577
10578            // If this node or its descendants are no longer important, try to
10579            // clear accessibility focus.
10580            if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO || hideDescendants) {
10581                final View focusHost = findAccessibilityFocusHost(hideDescendants);
10582                if (focusHost != null) {
10583                    focusHost.clearAccessibilityFocus();
10584                }
10585            }
10586
10587            // If we're moving between AUTO and another state, we might not need
10588            // to send a subtree changed notification. We'll store the computed
10589            // importance, since we'll need to check it later to make sure.
10590            final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO
10591                    || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO;
10592            final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility();
10593            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
10594            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
10595                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
10596            if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) {
10597                notifySubtreeAccessibilityStateChangedIfNeeded();
10598            } else {
10599                notifyViewAccessibilityStateChangedIfNeeded(
10600                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10601            }
10602        }
10603    }
10604
10605    /**
10606     * Returns the view within this view's hierarchy that is hosting
10607     * accessibility focus.
10608     *
10609     * @param searchDescendants whether to search for focus in descendant views
10610     * @return the view hosting accessibility focus, or {@code null}
10611     */
10612    private View findAccessibilityFocusHost(boolean searchDescendants) {
10613        if (isAccessibilityFocusedViewOrHost()) {
10614            return this;
10615        }
10616
10617        if (searchDescendants) {
10618            final ViewRootImpl viewRoot = getViewRootImpl();
10619            if (viewRoot != null) {
10620                final View focusHost = viewRoot.getAccessibilityFocusedHost();
10621                if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
10622                    return focusHost;
10623                }
10624            }
10625        }
10626
10627        return null;
10628    }
10629
10630    /**
10631     * Computes whether this view should be exposed for accessibility. In
10632     * general, views that are interactive or provide information are exposed
10633     * while views that serve only as containers are hidden.
10634     * <p>
10635     * If an ancestor of this view has importance
10636     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method
10637     * returns <code>false</code>.
10638     * <p>
10639     * Otherwise, the value is computed according to the view's
10640     * {@link #getImportantForAccessibility()} value:
10641     * <ol>
10642     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or
10643     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false
10644     * </code>
10645     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code>
10646     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if
10647     * view satisfies any of the following:
10648     * <ul>
10649     * <li>Is actionable, e.g. {@link #isClickable()},
10650     * {@link #isLongClickable()}, or {@link #isFocusable()}
10651     * <li>Has an {@link AccessibilityDelegate}
10652     * <li>Has an interaction listener, e.g. {@link OnTouchListener},
10653     * {@link OnKeyListener}, etc.
10654     * <li>Is an accessibility live region, e.g.
10655     * {@link #getAccessibilityLiveRegion()} is not
10656     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}.
10657     * </ul>
10658     * </ol>
10659     *
10660     * @return Whether the view is exposed for accessibility.
10661     * @see #setImportantForAccessibility(int)
10662     * @see #getImportantForAccessibility()
10663     */
10664    public boolean isImportantForAccessibility() {
10665        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
10666                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
10667        if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO
10668                || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
10669            return false;
10670        }
10671
10672        // Check parent mode to ensure we're not hidden.
10673        ViewParent parent = mParent;
10674        while (parent instanceof View) {
10675            if (((View) parent).getImportantForAccessibility()
10676                    == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
10677                return false;
10678            }
10679            parent = parent.getParent();
10680        }
10681
10682        return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
10683                || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
10684                || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE;
10685    }
10686
10687    /**
10688     * Gets the parent for accessibility purposes. Note that the parent for
10689     * accessibility is not necessary the immediate parent. It is the first
10690     * predecessor that is important for accessibility.
10691     *
10692     * @return The parent for accessibility purposes.
10693     */
10694    public ViewParent getParentForAccessibility() {
10695        if (mParent instanceof View) {
10696            View parentView = (View) mParent;
10697            if (parentView.includeForAccessibility()) {
10698                return mParent;
10699            } else {
10700                return mParent.getParentForAccessibility();
10701            }
10702        }
10703        return null;
10704    }
10705
10706    /**
10707     * Adds the children of this View relevant for accessibility to the given list
10708     * as output. Since some Views are not important for accessibility the added
10709     * child views are not necessarily direct children of this view, rather they are
10710     * the first level of descendants important for accessibility.
10711     *
10712     * @param outChildren The output list that will receive children for accessibility.
10713     */
10714    public void addChildrenForAccessibility(ArrayList<View> outChildren) {
10715
10716    }
10717
10718    /**
10719     * Whether to regard this view for accessibility. A view is regarded for
10720     * accessibility if it is important for accessibility or the querying
10721     * accessibility service has explicitly requested that view not
10722     * important for accessibility are regarded.
10723     *
10724     * @return Whether to regard the view for accessibility.
10725     *
10726     * @hide
10727     */
10728    public boolean includeForAccessibility() {
10729        if (mAttachInfo != null) {
10730            return (mAttachInfo.mAccessibilityFetchFlags
10731                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
10732                    || isImportantForAccessibility();
10733        }
10734        return false;
10735    }
10736
10737    /**
10738     * Returns whether the View is considered actionable from
10739     * accessibility perspective. Such view are important for
10740     * accessibility.
10741     *
10742     * @return True if the view is actionable for accessibility.
10743     *
10744     * @hide
10745     */
10746    public boolean isActionableForAccessibility() {
10747        return (isClickable() || isLongClickable() || isFocusable());
10748    }
10749
10750    /**
10751     * Returns whether the View has registered callbacks which makes it
10752     * important for accessibility.
10753     *
10754     * @return True if the view is actionable for accessibility.
10755     */
10756    private boolean hasListenersForAccessibility() {
10757        ListenerInfo info = getListenerInfo();
10758        return mTouchDelegate != null || info.mOnKeyListener != null
10759                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
10760                || info.mOnHoverListener != null || info.mOnDragListener != null;
10761    }
10762
10763    /**
10764     * Notifies that the accessibility state of this view changed. The change
10765     * is local to this view and does not represent structural changes such
10766     * as children and parent. For example, the view became focusable. The
10767     * notification is at at most once every
10768     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
10769     * to avoid unnecessary load to the system. Also once a view has a pending
10770     * notification this method is a NOP until the notification has been sent.
10771     *
10772     * @hide
10773     */
10774    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
10775        if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) {
10776            return;
10777        }
10778        if (mSendViewStateChangedAccessibilityEvent == null) {
10779            mSendViewStateChangedAccessibilityEvent =
10780                    new SendViewStateChangedAccessibilityEvent();
10781        }
10782        mSendViewStateChangedAccessibilityEvent.runOrPost(changeType);
10783    }
10784
10785    /**
10786     * Notifies that the accessibility state of this view changed. The change
10787     * is *not* local to this view and does represent structural changes such
10788     * as children and parent. For example, the view size changed. The
10789     * notification is at at most once every
10790     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
10791     * to avoid unnecessary load to the system. Also once a view has a pending
10792     * notification this method is a NOP until the notification has been sent.
10793     *
10794     * @hide
10795     */
10796    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
10797        if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) {
10798            return;
10799        }
10800        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
10801            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
10802            if (mParent != null) {
10803                try {
10804                    mParent.notifySubtreeAccessibilityStateChanged(
10805                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
10806                } catch (AbstractMethodError e) {
10807                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
10808                            " does not fully implement ViewParent", e);
10809                }
10810            }
10811        }
10812    }
10813
10814    /**
10815     * Change the visibility of the View without triggering any other changes. This is
10816     * important for transitions, where visibility changes should not adjust focus or
10817     * trigger a new layout. This is only used when the visibility has already been changed
10818     * and we need a transient value during an animation. When the animation completes,
10819     * the original visibility value is always restored.
10820     *
10821     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
10822     * @hide
10823     */
10824    public void setTransitionVisibility(@Visibility int visibility) {
10825        mViewFlags = (mViewFlags & ~View.VISIBILITY_MASK) | visibility;
10826    }
10827
10828    /**
10829     * Reset the flag indicating the accessibility state of the subtree rooted
10830     * at this view changed.
10831     */
10832    void resetSubtreeAccessibilityStateChanged() {
10833        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
10834    }
10835
10836    /**
10837     * Report an accessibility action to this view's parents for delegated processing.
10838     *
10839     * <p>Implementations of {@link #performAccessibilityAction(int, Bundle)} may internally
10840     * call this method to delegate an accessibility action to a supporting parent. If the parent
10841     * returns true from its
10842     * {@link ViewParent#onNestedPrePerformAccessibilityAction(View, int, android.os.Bundle)}
10843     * method this method will return true to signify that the action was consumed.</p>
10844     *
10845     * <p>This method is useful for implementing nested scrolling child views. If
10846     * {@link #isNestedScrollingEnabled()} returns true and the action is a scrolling action
10847     * a custom view implementation may invoke this method to allow a parent to consume the
10848     * scroll first. If this method returns true the custom view should skip its own scrolling
10849     * behavior.</p>
10850     *
10851     * @param action Accessibility action to delegate
10852     * @param arguments Optional action arguments
10853     * @return true if the action was consumed by a parent
10854     */
10855    public boolean dispatchNestedPrePerformAccessibilityAction(int action, Bundle arguments) {
10856        for (ViewParent p = getParent(); p != null; p = p.getParent()) {
10857            if (p.onNestedPrePerformAccessibilityAction(this, action, arguments)) {
10858                return true;
10859            }
10860        }
10861        return false;
10862    }
10863
10864    /**
10865     * Performs the specified accessibility action on the view. For
10866     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
10867     * <p>
10868     * If an {@link AccessibilityDelegate} has been specified via calling
10869     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
10870     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
10871     * is responsible for handling this call.
10872     * </p>
10873     *
10874     * <p>The default implementation will delegate
10875     * {@link AccessibilityNodeInfo#ACTION_SCROLL_BACKWARD} and
10876     * {@link AccessibilityNodeInfo#ACTION_SCROLL_FORWARD} to nested scrolling parents if
10877     * {@link #isNestedScrollingEnabled() nested scrolling is enabled} on this view.</p>
10878     *
10879     * @param action The action to perform.
10880     * @param arguments Optional action arguments.
10881     * @return Whether the action was performed.
10882     */
10883    public boolean performAccessibilityAction(int action, Bundle arguments) {
10884      if (mAccessibilityDelegate != null) {
10885          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
10886      } else {
10887          return performAccessibilityActionInternal(action, arguments);
10888      }
10889    }
10890
10891   /**
10892    * @see #performAccessibilityAction(int, Bundle)
10893    *
10894    * Note: Called from the default {@link AccessibilityDelegate}.
10895    *
10896    * @hide
10897    */
10898    public boolean performAccessibilityActionInternal(int action, Bundle arguments) {
10899        if (isNestedScrollingEnabled()
10900                && (action == AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD
10901                || action == AccessibilityNodeInfo.ACTION_SCROLL_FORWARD
10902                || action == R.id.accessibilityActionScrollUp
10903                || action == R.id.accessibilityActionScrollLeft
10904                || action == R.id.accessibilityActionScrollDown
10905                || action == R.id.accessibilityActionScrollRight)) {
10906            if (dispatchNestedPrePerformAccessibilityAction(action, arguments)) {
10907                return true;
10908            }
10909        }
10910
10911        switch (action) {
10912            case AccessibilityNodeInfo.ACTION_CLICK: {
10913                if (isClickable()) {
10914                    performClick();
10915                    return true;
10916                }
10917            } break;
10918            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
10919                if (isLongClickable()) {
10920                    performLongClick();
10921                    return true;
10922                }
10923            } break;
10924            case AccessibilityNodeInfo.ACTION_FOCUS: {
10925                if (!hasFocus()) {
10926                    // Get out of touch mode since accessibility
10927                    // wants to move focus around.
10928                    getViewRootImpl().ensureTouchMode(false);
10929                    return requestFocus();
10930                }
10931            } break;
10932            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
10933                if (hasFocus()) {
10934                    clearFocus();
10935                    return !isFocused();
10936                }
10937            } break;
10938            case AccessibilityNodeInfo.ACTION_SELECT: {
10939                if (!isSelected()) {
10940                    setSelected(true);
10941                    return isSelected();
10942                }
10943            } break;
10944            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
10945                if (isSelected()) {
10946                    setSelected(false);
10947                    return !isSelected();
10948                }
10949            } break;
10950            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
10951                if (!isAccessibilityFocused()) {
10952                    return requestAccessibilityFocus();
10953                }
10954            } break;
10955            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
10956                if (isAccessibilityFocused()) {
10957                    clearAccessibilityFocus();
10958                    return true;
10959                }
10960            } break;
10961            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
10962                if (arguments != null) {
10963                    final int granularity = arguments.getInt(
10964                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
10965                    final boolean extendSelection = arguments.getBoolean(
10966                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
10967                    return traverseAtGranularity(granularity, true, extendSelection);
10968                }
10969            } break;
10970            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
10971                if (arguments != null) {
10972                    final int granularity = arguments.getInt(
10973                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
10974                    final boolean extendSelection = arguments.getBoolean(
10975                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
10976                    return traverseAtGranularity(granularity, false, extendSelection);
10977                }
10978            } break;
10979            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
10980                CharSequence text = getIterableTextForAccessibility();
10981                if (text == null) {
10982                    return false;
10983                }
10984                final int start = (arguments != null) ? arguments.getInt(
10985                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
10986                final int end = (arguments != null) ? arguments.getInt(
10987                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
10988                // Only cursor position can be specified (selection length == 0)
10989                if ((getAccessibilitySelectionStart() != start
10990                        || getAccessibilitySelectionEnd() != end)
10991                        && (start == end)) {
10992                    setAccessibilitySelection(start, end);
10993                    notifyViewAccessibilityStateChangedIfNeeded(
10994                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10995                    return true;
10996                }
10997            } break;
10998            case R.id.accessibilityActionShowOnScreen: {
10999                if (mAttachInfo != null) {
11000                    final Rect r = mAttachInfo.mTmpInvalRect;
11001                    getDrawingRect(r);
11002                    return requestRectangleOnScreen(r, true);
11003                }
11004            } break;
11005            case R.id.accessibilityActionContextClick: {
11006                if (isContextClickable()) {
11007                    performContextClick();
11008                    return true;
11009                }
11010            } break;
11011        }
11012        return false;
11013    }
11014
11015    private boolean traverseAtGranularity(int granularity, boolean forward,
11016            boolean extendSelection) {
11017        CharSequence text = getIterableTextForAccessibility();
11018        if (text == null || text.length() == 0) {
11019            return false;
11020        }
11021        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
11022        if (iterator == null) {
11023            return false;
11024        }
11025        int current = getAccessibilitySelectionEnd();
11026        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
11027            current = forward ? 0 : text.length();
11028        }
11029        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
11030        if (range == null) {
11031            return false;
11032        }
11033        final int segmentStart = range[0];
11034        final int segmentEnd = range[1];
11035        int selectionStart;
11036        int selectionEnd;
11037        if (extendSelection && isAccessibilitySelectionExtendable()) {
11038            selectionStart = getAccessibilitySelectionStart();
11039            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
11040                selectionStart = forward ? segmentStart : segmentEnd;
11041            }
11042            selectionEnd = forward ? segmentEnd : segmentStart;
11043        } else {
11044            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
11045        }
11046        setAccessibilitySelection(selectionStart, selectionEnd);
11047        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
11048                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
11049        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
11050        return true;
11051    }
11052
11053    /**
11054     * Gets the text reported for accessibility purposes.
11055     *
11056     * @return The accessibility text.
11057     *
11058     * @hide
11059     */
11060    public CharSequence getIterableTextForAccessibility() {
11061        return getContentDescription();
11062    }
11063
11064    /**
11065     * Gets whether accessibility selection can be extended.
11066     *
11067     * @return If selection is extensible.
11068     *
11069     * @hide
11070     */
11071    public boolean isAccessibilitySelectionExtendable() {
11072        return false;
11073    }
11074
11075    /**
11076     * @hide
11077     */
11078    public int getAccessibilitySelectionStart() {
11079        return mAccessibilityCursorPosition;
11080    }
11081
11082    /**
11083     * @hide
11084     */
11085    public int getAccessibilitySelectionEnd() {
11086        return getAccessibilitySelectionStart();
11087    }
11088
11089    /**
11090     * @hide
11091     */
11092    public void setAccessibilitySelection(int start, int end) {
11093        if (start ==  end && end == mAccessibilityCursorPosition) {
11094            return;
11095        }
11096        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
11097            mAccessibilityCursorPosition = start;
11098        } else {
11099            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
11100        }
11101        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
11102    }
11103
11104    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
11105            int fromIndex, int toIndex) {
11106        if (mParent == null) {
11107            return;
11108        }
11109        AccessibilityEvent event = AccessibilityEvent.obtain(
11110                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
11111        onInitializeAccessibilityEvent(event);
11112        onPopulateAccessibilityEvent(event);
11113        event.setFromIndex(fromIndex);
11114        event.setToIndex(toIndex);
11115        event.setAction(action);
11116        event.setMovementGranularity(granularity);
11117        mParent.requestSendAccessibilityEvent(this, event);
11118    }
11119
11120    /**
11121     * @hide
11122     */
11123    public TextSegmentIterator getIteratorForGranularity(int granularity) {
11124        switch (granularity) {
11125            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
11126                CharSequence text = getIterableTextForAccessibility();
11127                if (text != null && text.length() > 0) {
11128                    CharacterTextSegmentIterator iterator =
11129                        CharacterTextSegmentIterator.getInstance(
11130                                mContext.getResources().getConfiguration().locale);
11131                    iterator.initialize(text.toString());
11132                    return iterator;
11133                }
11134            } break;
11135            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
11136                CharSequence text = getIterableTextForAccessibility();
11137                if (text != null && text.length() > 0) {
11138                    WordTextSegmentIterator iterator =
11139                        WordTextSegmentIterator.getInstance(
11140                                mContext.getResources().getConfiguration().locale);
11141                    iterator.initialize(text.toString());
11142                    return iterator;
11143                }
11144            } break;
11145            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
11146                CharSequence text = getIterableTextForAccessibility();
11147                if (text != null && text.length() > 0) {
11148                    ParagraphTextSegmentIterator iterator =
11149                        ParagraphTextSegmentIterator.getInstance();
11150                    iterator.initialize(text.toString());
11151                    return iterator;
11152                }
11153            } break;
11154        }
11155        return null;
11156    }
11157
11158    /**
11159     * Tells whether the {@link View} is in the state between {@link #onStartTemporaryDetach()}
11160     * and {@link #onFinishTemporaryDetach()}.
11161     *
11162     * <p>This method always returns {@code true} when called directly or indirectly from
11163     * {@link #onStartTemporaryDetach()}. The return value when called directly or indirectly from
11164     * {@link #onFinishTemporaryDetach()}, however, depends on the OS version.
11165     * <ul>
11166     *     <li>{@code true} on {@link android.os.Build.VERSION_CODES#N API 24}</li>
11167     *     <li>{@code false} on {@link android.os.Build.VERSION_CODES#N_MR1 API 25}} and later</li>
11168     * </ul>
11169     * </p>
11170     *
11171     * @return {@code true} when the View is in the state between {@link #onStartTemporaryDetach()}
11172     * and {@link #onFinishTemporaryDetach()}.
11173     */
11174    public final boolean isTemporarilyDetached() {
11175        return (mPrivateFlags3 & PFLAG3_TEMPORARY_DETACH) != 0;
11176    }
11177
11178    /**
11179     * Dispatch {@link #onStartTemporaryDetach()} to this View and its direct children if this is
11180     * a container View.
11181     */
11182    @CallSuper
11183    public void dispatchStartTemporaryDetach() {
11184        mPrivateFlags3 |= PFLAG3_TEMPORARY_DETACH;
11185        notifyEnterOrExitForAutoFillIfNeeded(false);
11186        onStartTemporaryDetach();
11187    }
11188
11189    /**
11190     * This is called when a container is going to temporarily detach a child, with
11191     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
11192     * It will either be followed by {@link #onFinishTemporaryDetach()} or
11193     * {@link #onDetachedFromWindow()} when the container is done.
11194     */
11195    public void onStartTemporaryDetach() {
11196        removeUnsetPressCallback();
11197        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
11198    }
11199
11200    /**
11201     * Dispatch {@link #onFinishTemporaryDetach()} to this View and its direct children if this is
11202     * a container View.
11203     */
11204    @CallSuper
11205    public void dispatchFinishTemporaryDetach() {
11206        mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH;
11207        onFinishTemporaryDetach();
11208        if (hasWindowFocus() && hasFocus()) {
11209            InputMethodManager.getInstance().focusIn(this);
11210        }
11211        notifyEnterOrExitForAutoFillIfNeeded(true);
11212    }
11213
11214    /**
11215     * Called after {@link #onStartTemporaryDetach} when the container is done
11216     * changing the view.
11217     */
11218    public void onFinishTemporaryDetach() {
11219    }
11220
11221    /**
11222     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
11223     * for this view's window.  Returns null if the view is not currently attached
11224     * to the window.  Normally you will not need to use this directly, but
11225     * just use the standard high-level event callbacks like
11226     * {@link #onKeyDown(int, KeyEvent)}.
11227     */
11228    public KeyEvent.DispatcherState getKeyDispatcherState() {
11229        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
11230    }
11231
11232    /**
11233     * Dispatch a key event before it is processed by any input method
11234     * associated with the view hierarchy.  This can be used to intercept
11235     * key events in special situations before the IME consumes them; a
11236     * typical example would be handling the BACK key to update the application's
11237     * UI instead of allowing the IME to see it and close itself.
11238     *
11239     * @param event The key event to be dispatched.
11240     * @return True if the event was handled, false otherwise.
11241     */
11242    public boolean dispatchKeyEventPreIme(KeyEvent event) {
11243        return onKeyPreIme(event.getKeyCode(), event);
11244    }
11245
11246    /**
11247     * Dispatch a key event to the next view on the focus path. This path runs
11248     * from the top of the view tree down to the currently focused view. If this
11249     * view has focus, it will dispatch to itself. Otherwise it will dispatch
11250     * the next node down the focus path. This method also fires any key
11251     * listeners.
11252     *
11253     * @param event The key event to be dispatched.
11254     * @return True if the event was handled, false otherwise.
11255     */
11256    public boolean dispatchKeyEvent(KeyEvent event) {
11257        if (mInputEventConsistencyVerifier != null) {
11258            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
11259        }
11260
11261        // Give any attached key listener a first crack at the event.
11262        //noinspection SimplifiableIfStatement
11263        ListenerInfo li = mListenerInfo;
11264        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
11265                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
11266            return true;
11267        }
11268
11269        if (event.dispatch(this, mAttachInfo != null
11270                ? mAttachInfo.mKeyDispatchState : null, this)) {
11271            return true;
11272        }
11273
11274        if (mInputEventConsistencyVerifier != null) {
11275            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
11276        }
11277        return false;
11278    }
11279
11280    /**
11281     * Dispatches a key shortcut event.
11282     *
11283     * @param event The key event to be dispatched.
11284     * @return True if the event was handled by the view, false otherwise.
11285     */
11286    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
11287        return onKeyShortcut(event.getKeyCode(), event);
11288    }
11289
11290    /**
11291     * Pass the touch screen motion event down to the target view, or this
11292     * view if it is the target.
11293     *
11294     * @param event The motion event to be dispatched.
11295     * @return True if the event was handled by the view, false otherwise.
11296     */
11297    public boolean dispatchTouchEvent(MotionEvent event) {
11298        // If the event should be handled by accessibility focus first.
11299        if (event.isTargetAccessibilityFocus()) {
11300            // We don't have focus or no virtual descendant has it, do not handle the event.
11301            if (!isAccessibilityFocusedViewOrHost()) {
11302                return false;
11303            }
11304            // We have focus and got the event, then use normal event dispatch.
11305            event.setTargetAccessibilityFocus(false);
11306        }
11307
11308        boolean result = false;
11309
11310        if (mInputEventConsistencyVerifier != null) {
11311            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
11312        }
11313
11314        final int actionMasked = event.getActionMasked();
11315        if (actionMasked == MotionEvent.ACTION_DOWN) {
11316            // Defensive cleanup for new gesture
11317            stopNestedScroll();
11318        }
11319
11320        if (onFilterTouchEventForSecurity(event)) {
11321            if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
11322                result = true;
11323            }
11324            //noinspection SimplifiableIfStatement
11325            ListenerInfo li = mListenerInfo;
11326            if (li != null && li.mOnTouchListener != null
11327                    && (mViewFlags & ENABLED_MASK) == ENABLED
11328                    && li.mOnTouchListener.onTouch(this, event)) {
11329                result = true;
11330            }
11331
11332            if (!result && onTouchEvent(event)) {
11333                result = true;
11334            }
11335        }
11336
11337        if (!result && mInputEventConsistencyVerifier != null) {
11338            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
11339        }
11340
11341        // Clean up after nested scrolls if this is the end of a gesture;
11342        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
11343        // of the gesture.
11344        if (actionMasked == MotionEvent.ACTION_UP ||
11345                actionMasked == MotionEvent.ACTION_CANCEL ||
11346                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
11347            stopNestedScroll();
11348        }
11349
11350        return result;
11351    }
11352
11353    boolean isAccessibilityFocusedViewOrHost() {
11354        return isAccessibilityFocused() || (getViewRootImpl() != null && getViewRootImpl()
11355                .getAccessibilityFocusedHost() == this);
11356    }
11357
11358    /**
11359     * Filter the touch event to apply security policies.
11360     *
11361     * @param event The motion event to be filtered.
11362     * @return True if the event should be dispatched, false if the event should be dropped.
11363     *
11364     * @see #getFilterTouchesWhenObscured
11365     */
11366    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
11367        //noinspection RedundantIfStatement
11368        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
11369                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
11370            // Window is obscured, drop this touch.
11371            return false;
11372        }
11373        return true;
11374    }
11375
11376    /**
11377     * Pass a trackball motion event down to the focused view.
11378     *
11379     * @param event The motion event to be dispatched.
11380     * @return True if the event was handled by the view, false otherwise.
11381     */
11382    public boolean dispatchTrackballEvent(MotionEvent event) {
11383        if (mInputEventConsistencyVerifier != null) {
11384            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
11385        }
11386
11387        return onTrackballEvent(event);
11388    }
11389
11390    /**
11391     * Pass a captured pointer event down to the focused view.
11392     *
11393     * @param event The motion event to be dispatched.
11394     * @return True if the event was handled by the view, false otherwise.
11395     */
11396    public boolean dispatchCapturedPointerEvent(MotionEvent event) {
11397        if (!hasPointerCapture()) {
11398            return false;
11399        }
11400        //noinspection SimplifiableIfStatement
11401        ListenerInfo li = mListenerInfo;
11402        if (li != null && li.mOnCapturedPointerListener != null
11403                && li.mOnCapturedPointerListener.onCapturedPointer(this, event)) {
11404            return true;
11405        }
11406        return onCapturedPointerEvent(event);
11407    }
11408
11409    /**
11410     * Dispatch a generic motion event.
11411     * <p>
11412     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
11413     * are delivered to the view under the pointer.  All other generic motion events are
11414     * delivered to the focused view.  Hover events are handled specially and are delivered
11415     * to {@link #onHoverEvent(MotionEvent)}.
11416     * </p>
11417     *
11418     * @param event The motion event to be dispatched.
11419     * @return True if the event was handled by the view, false otherwise.
11420     */
11421    public boolean dispatchGenericMotionEvent(MotionEvent event) {
11422        if (mInputEventConsistencyVerifier != null) {
11423            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
11424        }
11425
11426        final int source = event.getSource();
11427        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
11428            final int action = event.getAction();
11429            if (action == MotionEvent.ACTION_HOVER_ENTER
11430                    || action == MotionEvent.ACTION_HOVER_MOVE
11431                    || action == MotionEvent.ACTION_HOVER_EXIT) {
11432                if (dispatchHoverEvent(event)) {
11433                    return true;
11434                }
11435            } else if (dispatchGenericPointerEvent(event)) {
11436                return true;
11437            }
11438        } else if (dispatchGenericFocusedEvent(event)) {
11439            return true;
11440        }
11441
11442        if (dispatchGenericMotionEventInternal(event)) {
11443            return true;
11444        }
11445
11446        if (mInputEventConsistencyVerifier != null) {
11447            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
11448        }
11449        return false;
11450    }
11451
11452    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
11453        //noinspection SimplifiableIfStatement
11454        ListenerInfo li = mListenerInfo;
11455        if (li != null && li.mOnGenericMotionListener != null
11456                && (mViewFlags & ENABLED_MASK) == ENABLED
11457                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
11458            return true;
11459        }
11460
11461        if (onGenericMotionEvent(event)) {
11462            return true;
11463        }
11464
11465        final int actionButton = event.getActionButton();
11466        switch (event.getActionMasked()) {
11467            case MotionEvent.ACTION_BUTTON_PRESS:
11468                if (isContextClickable() && !mInContextButtonPress && !mHasPerformedLongPress
11469                        && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY
11470                        || actionButton == MotionEvent.BUTTON_SECONDARY)) {
11471                    if (performContextClick(event.getX(), event.getY())) {
11472                        mInContextButtonPress = true;
11473                        setPressed(true, event.getX(), event.getY());
11474                        removeTapCallback();
11475                        removeLongPressCallback();
11476                        return true;
11477                    }
11478                }
11479                break;
11480
11481            case MotionEvent.ACTION_BUTTON_RELEASE:
11482                if (mInContextButtonPress && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY
11483                        || actionButton == MotionEvent.BUTTON_SECONDARY)) {
11484                    mInContextButtonPress = false;
11485                    mIgnoreNextUpEvent = true;
11486                }
11487                break;
11488        }
11489
11490        if (mInputEventConsistencyVerifier != null) {
11491            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
11492        }
11493        return false;
11494    }
11495
11496    /**
11497     * Dispatch a hover event.
11498     * <p>
11499     * Do not call this method directly.
11500     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
11501     * </p>
11502     *
11503     * @param event The motion event to be dispatched.
11504     * @return True if the event was handled by the view, false otherwise.
11505     */
11506    protected boolean dispatchHoverEvent(MotionEvent event) {
11507        ListenerInfo li = mListenerInfo;
11508        //noinspection SimplifiableIfStatement
11509        if (li != null && li.mOnHoverListener != null
11510                && (mViewFlags & ENABLED_MASK) == ENABLED
11511                && li.mOnHoverListener.onHover(this, event)) {
11512            return true;
11513        }
11514
11515        return onHoverEvent(event);
11516    }
11517
11518    /**
11519     * Returns true if the view has a child to which it has recently sent
11520     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
11521     * it does not have a hovered child, then it must be the innermost hovered view.
11522     * @hide
11523     */
11524    protected boolean hasHoveredChild() {
11525        return false;
11526    }
11527
11528    /**
11529     * Dispatch a generic motion event to the view under the first pointer.
11530     * <p>
11531     * Do not call this method directly.
11532     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
11533     * </p>
11534     *
11535     * @param event The motion event to be dispatched.
11536     * @return True if the event was handled by the view, false otherwise.
11537     */
11538    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
11539        return false;
11540    }
11541
11542    /**
11543     * Dispatch a generic motion event to the currently focused view.
11544     * <p>
11545     * Do not call this method directly.
11546     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
11547     * </p>
11548     *
11549     * @param event The motion event to be dispatched.
11550     * @return True if the event was handled by the view, false otherwise.
11551     */
11552    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
11553        return false;
11554    }
11555
11556    /**
11557     * Dispatch a pointer event.
11558     * <p>
11559     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
11560     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
11561     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
11562     * and should not be expected to handle other pointing device features.
11563     * </p>
11564     *
11565     * @param event The motion event to be dispatched.
11566     * @return True if the event was handled by the view, false otherwise.
11567     * @hide
11568     */
11569    public final boolean dispatchPointerEvent(MotionEvent event) {
11570        if (event.isTouchEvent()) {
11571            return dispatchTouchEvent(event);
11572        } else {
11573            return dispatchGenericMotionEvent(event);
11574        }
11575    }
11576
11577    /**
11578     * Called when the window containing this view gains or loses window focus.
11579     * ViewGroups should override to route to their children.
11580     *
11581     * @param hasFocus True if the window containing this view now has focus,
11582     *        false otherwise.
11583     */
11584    public void dispatchWindowFocusChanged(boolean hasFocus) {
11585        onWindowFocusChanged(hasFocus);
11586    }
11587
11588    /**
11589     * Called when the window containing this view gains or loses focus.  Note
11590     * that this is separate from view focus: to receive key events, both
11591     * your view and its window must have focus.  If a window is displayed
11592     * on top of yours that takes input focus, then your own window will lose
11593     * focus but the view focus will remain unchanged.
11594     *
11595     * @param hasWindowFocus True if the window containing this view now has
11596     *        focus, false otherwise.
11597     */
11598    public void onWindowFocusChanged(boolean hasWindowFocus) {
11599        InputMethodManager imm = InputMethodManager.peekInstance();
11600        if (!hasWindowFocus) {
11601            if (isPressed()) {
11602                setPressed(false);
11603            }
11604            mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
11605            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
11606                imm.focusOut(this);
11607            }
11608            removeLongPressCallback();
11609            removeTapCallback();
11610            onFocusLost();
11611        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
11612            imm.focusIn(this);
11613        }
11614
11615        notifyEnterOrExitForAutoFillIfNeeded(hasWindowFocus);
11616
11617        refreshDrawableState();
11618    }
11619
11620    /**
11621     * Returns true if this view is in a window that currently has window focus.
11622     * Note that this is not the same as the view itself having focus.
11623     *
11624     * @return True if this view is in a window that currently has window focus.
11625     */
11626    public boolean hasWindowFocus() {
11627        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
11628    }
11629
11630    /**
11631     * Dispatch a view visibility change down the view hierarchy.
11632     * ViewGroups should override to route to their children.
11633     * @param changedView The view whose visibility changed. Could be 'this' or
11634     * an ancestor view.
11635     * @param visibility The new visibility of changedView: {@link #VISIBLE},
11636     * {@link #INVISIBLE} or {@link #GONE}.
11637     */
11638    protected void dispatchVisibilityChanged(@NonNull View changedView,
11639            @Visibility int visibility) {
11640        onVisibilityChanged(changedView, visibility);
11641    }
11642
11643    /**
11644     * Called when the visibility of the view or an ancestor of the view has
11645     * changed.
11646     *
11647     * @param changedView The view whose visibility changed. May be
11648     *                    {@code this} or an ancestor view.
11649     * @param visibility The new visibility, one of {@link #VISIBLE},
11650     *                   {@link #INVISIBLE} or {@link #GONE}.
11651     */
11652    protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) {
11653    }
11654
11655    /**
11656     * Dispatch a hint about whether this view is displayed. For instance, when
11657     * a View moves out of the screen, it might receives a display hint indicating
11658     * the view is not displayed. Applications should not <em>rely</em> on this hint
11659     * as there is no guarantee that they will receive one.
11660     *
11661     * @param hint A hint about whether or not this view is displayed:
11662     * {@link #VISIBLE} or {@link #INVISIBLE}.
11663     */
11664    public void dispatchDisplayHint(@Visibility int hint) {
11665        onDisplayHint(hint);
11666    }
11667
11668    /**
11669     * Gives this view a hint about whether is displayed or not. For instance, when
11670     * a View moves out of the screen, it might receives a display hint indicating
11671     * the view is not displayed. Applications should not <em>rely</em> on this hint
11672     * as there is no guarantee that they will receive one.
11673     *
11674     * @param hint A hint about whether or not this view is displayed:
11675     * {@link #VISIBLE} or {@link #INVISIBLE}.
11676     */
11677    protected void onDisplayHint(@Visibility int hint) {
11678    }
11679
11680    /**
11681     * Dispatch a window visibility change down the view hierarchy.
11682     * ViewGroups should override to route to their children.
11683     *
11684     * @param visibility The new visibility of the window.
11685     *
11686     * @see #onWindowVisibilityChanged(int)
11687     */
11688    public void dispatchWindowVisibilityChanged(@Visibility int visibility) {
11689        onWindowVisibilityChanged(visibility);
11690    }
11691
11692    /**
11693     * Called when the window containing has change its visibility
11694     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
11695     * that this tells you whether or not your window is being made visible
11696     * to the window manager; this does <em>not</em> tell you whether or not
11697     * your window is obscured by other windows on the screen, even if it
11698     * is itself visible.
11699     *
11700     * @param visibility The new visibility of the window.
11701     */
11702    protected void onWindowVisibilityChanged(@Visibility int visibility) {
11703        if (visibility == VISIBLE) {
11704            initialAwakenScrollBars();
11705        }
11706    }
11707
11708    /**
11709     * Internal dispatching method for {@link #onVisibilityAggregated}. Overridden by
11710     * ViewGroup. Intended to only be called when {@link #isAttachedToWindow()},
11711     * {@link #getWindowVisibility()} is {@link #VISIBLE} and this view's parent {@link #isShown()}.
11712     *
11713     * @param isVisible true if this view's visibility to the user is uninterrupted by its
11714     *                  ancestors or by window visibility
11715     * @return true if this view is visible to the user, not counting clipping or overlapping
11716     */
11717    boolean dispatchVisibilityAggregated(boolean isVisible) {
11718        final boolean thisVisible = getVisibility() == VISIBLE;
11719        // If we're not visible but something is telling us we are, ignore it.
11720        if (thisVisible || !isVisible) {
11721            onVisibilityAggregated(isVisible);
11722        }
11723        return thisVisible && isVisible;
11724    }
11725
11726    /**
11727     * Called when the user-visibility of this View is potentially affected by a change
11728     * to this view itself, an ancestor view or the window this view is attached to.
11729     *
11730     * @param isVisible true if this view and all of its ancestors are {@link #VISIBLE}
11731     *                  and this view's window is also visible
11732     */
11733    @CallSuper
11734    public void onVisibilityAggregated(boolean isVisible) {
11735        if (isVisible && mAttachInfo != null) {
11736            initialAwakenScrollBars();
11737        }
11738
11739        final Drawable dr = mBackground;
11740        if (dr != null && isVisible != dr.isVisible()) {
11741            dr.setVisible(isVisible, false);
11742        }
11743        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
11744        if (fg != null && isVisible != fg.isVisible()) {
11745            fg.setVisible(isVisible, false);
11746        }
11747    }
11748
11749    /**
11750     * Returns the current visibility of the window this view is attached to
11751     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
11752     *
11753     * @return Returns the current visibility of the view's window.
11754     */
11755    @Visibility
11756    public int getWindowVisibility() {
11757        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
11758    }
11759
11760    /**
11761     * Retrieve the overall visible display size in which the window this view is
11762     * attached to has been positioned in.  This takes into account screen
11763     * decorations above the window, for both cases where the window itself
11764     * is being position inside of them or the window is being placed under
11765     * then and covered insets are used for the window to position its content
11766     * inside.  In effect, this tells you the available area where content can
11767     * be placed and remain visible to users.
11768     *
11769     * <p>This function requires an IPC back to the window manager to retrieve
11770     * the requested information, so should not be used in performance critical
11771     * code like drawing.
11772     *
11773     * @param outRect Filled in with the visible display frame.  If the view
11774     * is not attached to a window, this is simply the raw display size.
11775     */
11776    public void getWindowVisibleDisplayFrame(Rect outRect) {
11777        if (mAttachInfo != null) {
11778            try {
11779                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
11780            } catch (RemoteException e) {
11781                return;
11782            }
11783            // XXX This is really broken, and probably all needs to be done
11784            // in the window manager, and we need to know more about whether
11785            // we want the area behind or in front of the IME.
11786            final Rect insets = mAttachInfo.mVisibleInsets;
11787            outRect.left += insets.left;
11788            outRect.top += insets.top;
11789            outRect.right -= insets.right;
11790            outRect.bottom -= insets.bottom;
11791            return;
11792        }
11793        // The view is not attached to a display so we don't have a context.
11794        // Make a best guess about the display size.
11795        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
11796        d.getRectSize(outRect);
11797    }
11798
11799    /**
11800     * Like {@link #getWindowVisibleDisplayFrame}, but returns the "full" display frame this window
11801     * is currently in without any insets.
11802     *
11803     * @hide
11804     */
11805    public void getWindowDisplayFrame(Rect outRect) {
11806        if (mAttachInfo != null) {
11807            try {
11808                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
11809            } catch (RemoteException e) {
11810                return;
11811            }
11812            return;
11813        }
11814        // The view is not attached to a display so we don't have a context.
11815        // Make a best guess about the display size.
11816        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
11817        d.getRectSize(outRect);
11818    }
11819
11820    /**
11821     * Dispatch a notification about a resource configuration change down
11822     * the view hierarchy.
11823     * ViewGroups should override to route to their children.
11824     *
11825     * @param newConfig The new resource configuration.
11826     *
11827     * @see #onConfigurationChanged(android.content.res.Configuration)
11828     */
11829    public void dispatchConfigurationChanged(Configuration newConfig) {
11830        onConfigurationChanged(newConfig);
11831    }
11832
11833    /**
11834     * Called when the current configuration of the resources being used
11835     * by the application have changed.  You can use this to decide when
11836     * to reload resources that can changed based on orientation and other
11837     * configuration characteristics.  You only need to use this if you are
11838     * not relying on the normal {@link android.app.Activity} mechanism of
11839     * recreating the activity instance upon a configuration change.
11840     *
11841     * @param newConfig The new resource configuration.
11842     */
11843    protected void onConfigurationChanged(Configuration newConfig) {
11844    }
11845
11846    /**
11847     * Private function to aggregate all per-view attributes in to the view
11848     * root.
11849     */
11850    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
11851        performCollectViewAttributes(attachInfo, visibility);
11852    }
11853
11854    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
11855        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
11856            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
11857                attachInfo.mKeepScreenOn = true;
11858            }
11859            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
11860            ListenerInfo li = mListenerInfo;
11861            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
11862                attachInfo.mHasSystemUiListeners = true;
11863            }
11864        }
11865    }
11866
11867    void needGlobalAttributesUpdate(boolean force) {
11868        final AttachInfo ai = mAttachInfo;
11869        if (ai != null && !ai.mRecomputeGlobalAttributes) {
11870            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
11871                    || ai.mHasSystemUiListeners) {
11872                ai.mRecomputeGlobalAttributes = true;
11873            }
11874        }
11875    }
11876
11877    /**
11878     * Returns whether the device is currently in touch mode.  Touch mode is entered
11879     * once the user begins interacting with the device by touch, and affects various
11880     * things like whether focus is always visible to the user.
11881     *
11882     * @return Whether the device is in touch mode.
11883     */
11884    @ViewDebug.ExportedProperty
11885    public boolean isInTouchMode() {
11886        if (mAttachInfo != null) {
11887            return mAttachInfo.mInTouchMode;
11888        } else {
11889            return ViewRootImpl.isInTouchMode();
11890        }
11891    }
11892
11893    /**
11894     * Returns the context the view is running in, through which it can
11895     * access the current theme, resources, etc.
11896     *
11897     * @return The view's Context.
11898     */
11899    @ViewDebug.CapturedViewProperty
11900    public final Context getContext() {
11901        return mContext;
11902    }
11903
11904    /**
11905     * Handle a key event before it is processed by any input method
11906     * associated with the view hierarchy.  This can be used to intercept
11907     * key events in special situations before the IME consumes them; a
11908     * typical example would be handling the BACK key to update the application's
11909     * UI instead of allowing the IME to see it and close itself.
11910     *
11911     * @param keyCode The value in event.getKeyCode().
11912     * @param event Description of the key event.
11913     * @return If you handled the event, return true. If you want to allow the
11914     *         event to be handled by the next receiver, return false.
11915     */
11916    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
11917        return false;
11918    }
11919
11920    /**
11921     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
11922     * KeyEvent.Callback.onKeyDown()}: perform press of the view
11923     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
11924     * is released, if the view is enabled and clickable.
11925     * <p>
11926     * Key presses in software keyboards will generally NOT trigger this
11927     * listener, although some may elect to do so in some situations. Do not
11928     * rely on this to catch software key presses.
11929     *
11930     * @param keyCode a key code that represents the button pressed, from
11931     *                {@link android.view.KeyEvent}
11932     * @param event the KeyEvent object that defines the button action
11933     */
11934    public boolean onKeyDown(int keyCode, KeyEvent event) {
11935        if (KeyEvent.isConfirmKey(keyCode)) {
11936            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
11937                return true;
11938            }
11939
11940            if (event.getRepeatCount() == 0) {
11941                // Long clickable items don't necessarily have to be clickable.
11942                final boolean clickable = (mViewFlags & CLICKABLE) == CLICKABLE
11943                        || (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
11944                if (clickable || (mViewFlags & TOOLTIP) == TOOLTIP) {
11945                    // For the purposes of menu anchoring and drawable hotspots,
11946                    // key events are considered to be at the center of the view.
11947                    final float x = getWidth() / 2f;
11948                    final float y = getHeight() / 2f;
11949                    if (clickable) {
11950                        setPressed(true, x, y);
11951                    }
11952                    checkForLongClick(0, x, y);
11953                    return true;
11954                }
11955            }
11956        }
11957
11958        return false;
11959    }
11960
11961    /**
11962     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
11963     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
11964     * the event).
11965     * <p>Key presses in software keyboards will generally NOT trigger this listener,
11966     * although some may elect to do so in some situations. Do not rely on this to
11967     * catch software key presses.
11968     */
11969    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
11970        return false;
11971    }
11972
11973    /**
11974     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
11975     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
11976     * when {@link KeyEvent#KEYCODE_DPAD_CENTER}, {@link KeyEvent#KEYCODE_ENTER}
11977     * or {@link KeyEvent#KEYCODE_SPACE} is released.
11978     * <p>Key presses in software keyboards will generally NOT trigger this listener,
11979     * although some may elect to do so in some situations. Do not rely on this to
11980     * catch software key presses.
11981     *
11982     * @param keyCode A key code that represents the button pressed, from
11983     *                {@link android.view.KeyEvent}.
11984     * @param event   The KeyEvent object that defines the button action.
11985     */
11986    public boolean onKeyUp(int keyCode, KeyEvent event) {
11987        if (KeyEvent.isConfirmKey(keyCode)) {
11988            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
11989                return true;
11990            }
11991            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
11992                setPressed(false);
11993
11994                if (!mHasPerformedLongPress) {
11995                    // This is a tap, so remove the longpress check
11996                    removeLongPressCallback();
11997                    if (!event.isCanceled()) {
11998                        return performClick();
11999                    }
12000                }
12001            }
12002        }
12003        return false;
12004    }
12005
12006    /**
12007     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
12008     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
12009     * the event).
12010     * <p>Key presses in software keyboards will generally NOT trigger this listener,
12011     * although some may elect to do so in some situations. Do not rely on this to
12012     * catch software key presses.
12013     *
12014     * @param keyCode     A key code that represents the button pressed, from
12015     *                    {@link android.view.KeyEvent}.
12016     * @param repeatCount The number of times the action was made.
12017     * @param event       The KeyEvent object that defines the button action.
12018     */
12019    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
12020        return false;
12021    }
12022
12023    /**
12024     * Called on the focused view when a key shortcut event is not handled.
12025     * Override this method to implement local key shortcuts for the View.
12026     * Key shortcuts can also be implemented by setting the
12027     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
12028     *
12029     * @param keyCode The value in event.getKeyCode().
12030     * @param event Description of the key event.
12031     * @return If you handled the event, return true. If you want to allow the
12032     *         event to be handled by the next receiver, return false.
12033     */
12034    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
12035        return false;
12036    }
12037
12038    /**
12039     * Check whether the called view is a text editor, in which case it
12040     * would make sense to automatically display a soft input window for
12041     * it.  Subclasses should override this if they implement
12042     * {@link #onCreateInputConnection(EditorInfo)} to return true if
12043     * a call on that method would return a non-null InputConnection, and
12044     * they are really a first-class editor that the user would normally
12045     * start typing on when the go into a window containing your view.
12046     *
12047     * <p>The default implementation always returns false.  This does
12048     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
12049     * will not be called or the user can not otherwise perform edits on your
12050     * view; it is just a hint to the system that this is not the primary
12051     * purpose of this view.
12052     *
12053     * @return Returns true if this view is a text editor, else false.
12054     */
12055    public boolean onCheckIsTextEditor() {
12056        return false;
12057    }
12058
12059    /**
12060     * Create a new InputConnection for an InputMethod to interact
12061     * with the view.  The default implementation returns null, since it doesn't
12062     * support input methods.  You can override this to implement such support.
12063     * This is only needed for views that take focus and text input.
12064     *
12065     * <p>When implementing this, you probably also want to implement
12066     * {@link #onCheckIsTextEditor()} to indicate you will return a
12067     * non-null InputConnection.</p>
12068     *
12069     * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo}
12070     * object correctly and in its entirety, so that the connected IME can rely
12071     * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart}
12072     * and  {@link android.view.inputmethod.EditorInfo#initialSelEnd} members
12073     * must be filled in with the correct cursor position for IMEs to work correctly
12074     * with your application.</p>
12075     *
12076     * @param outAttrs Fill in with attribute information about the connection.
12077     */
12078    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
12079        return null;
12080    }
12081
12082    /**
12083     * Called by the {@link android.view.inputmethod.InputMethodManager}
12084     * when a view who is not the current
12085     * input connection target is trying to make a call on the manager.  The
12086     * default implementation returns false; you can override this to return
12087     * true for certain views if you are performing InputConnection proxying
12088     * to them.
12089     * @param view The View that is making the InputMethodManager call.
12090     * @return Return true to allow the call, false to reject.
12091     */
12092    public boolean checkInputConnectionProxy(View view) {
12093        return false;
12094    }
12095
12096    /**
12097     * Show the context menu for this view. It is not safe to hold on to the
12098     * menu after returning from this method.
12099     *
12100     * You should normally not overload this method. Overload
12101     * {@link #onCreateContextMenu(ContextMenu)} or define an
12102     * {@link OnCreateContextMenuListener} to add items to the context menu.
12103     *
12104     * @param menu The context menu to populate
12105     */
12106    public void createContextMenu(ContextMenu menu) {
12107        ContextMenuInfo menuInfo = getContextMenuInfo();
12108
12109        // Sets the current menu info so all items added to menu will have
12110        // my extra info set.
12111        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
12112
12113        onCreateContextMenu(menu);
12114        ListenerInfo li = mListenerInfo;
12115        if (li != null && li.mOnCreateContextMenuListener != null) {
12116            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
12117        }
12118
12119        // Clear the extra information so subsequent items that aren't mine don't
12120        // have my extra info.
12121        ((MenuBuilder)menu).setCurrentMenuInfo(null);
12122
12123        if (mParent != null) {
12124            mParent.createContextMenu(menu);
12125        }
12126    }
12127
12128    /**
12129     * Views should implement this if they have extra information to associate
12130     * with the context menu. The return result is supplied as a parameter to
12131     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
12132     * callback.
12133     *
12134     * @return Extra information about the item for which the context menu
12135     *         should be shown. This information will vary across different
12136     *         subclasses of View.
12137     */
12138    protected ContextMenuInfo getContextMenuInfo() {
12139        return null;
12140    }
12141
12142    /**
12143     * Views should implement this if the view itself is going to add items to
12144     * the context menu.
12145     *
12146     * @param menu the context menu to populate
12147     */
12148    protected void onCreateContextMenu(ContextMenu menu) {
12149    }
12150
12151    /**
12152     * Implement this method to handle trackball motion events.  The
12153     * <em>relative</em> movement of the trackball since the last event
12154     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
12155     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
12156     * that a movement of 1 corresponds to the user pressing one DPAD key (so
12157     * they will often be fractional values, representing the more fine-grained
12158     * movement information available from a trackball).
12159     *
12160     * @param event The motion event.
12161     * @return True if the event was handled, false otherwise.
12162     */
12163    public boolean onTrackballEvent(MotionEvent event) {
12164        return false;
12165    }
12166
12167    /**
12168     * Implement this method to handle generic motion events.
12169     * <p>
12170     * Generic motion events describe joystick movements, mouse hovers, track pad
12171     * touches, scroll wheel movements and other input events.  The
12172     * {@link MotionEvent#getSource() source} of the motion event specifies
12173     * the class of input that was received.  Implementations of this method
12174     * must examine the bits in the source before processing the event.
12175     * The following code example shows how this is done.
12176     * </p><p>
12177     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
12178     * are delivered to the view under the pointer.  All other generic motion events are
12179     * delivered to the focused view.
12180     * </p>
12181     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
12182     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
12183     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
12184     *             // process the joystick movement...
12185     *             return true;
12186     *         }
12187     *     }
12188     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
12189     *         switch (event.getAction()) {
12190     *             case MotionEvent.ACTION_HOVER_MOVE:
12191     *                 // process the mouse hover movement...
12192     *                 return true;
12193     *             case MotionEvent.ACTION_SCROLL:
12194     *                 // process the scroll wheel movement...
12195     *                 return true;
12196     *         }
12197     *     }
12198     *     return super.onGenericMotionEvent(event);
12199     * }</pre>
12200     *
12201     * @param event The generic motion event being processed.
12202     * @return True if the event was handled, false otherwise.
12203     */
12204    public boolean onGenericMotionEvent(MotionEvent event) {
12205        return false;
12206    }
12207
12208    /**
12209     * Implement this method to handle hover events.
12210     * <p>
12211     * This method is called whenever a pointer is hovering into, over, or out of the
12212     * bounds of a view and the view is not currently being touched.
12213     * Hover events are represented as pointer events with action
12214     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
12215     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
12216     * </p>
12217     * <ul>
12218     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
12219     * when the pointer enters the bounds of the view.</li>
12220     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
12221     * when the pointer has already entered the bounds of the view and has moved.</li>
12222     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
12223     * when the pointer has exited the bounds of the view or when the pointer is
12224     * about to go down due to a button click, tap, or similar user action that
12225     * causes the view to be touched.</li>
12226     * </ul>
12227     * <p>
12228     * The view should implement this method to return true to indicate that it is
12229     * handling the hover event, such as by changing its drawable state.
12230     * </p><p>
12231     * The default implementation calls {@link #setHovered} to update the hovered state
12232     * of the view when a hover enter or hover exit event is received, if the view
12233     * is enabled and is clickable.  The default implementation also sends hover
12234     * accessibility events.
12235     * </p>
12236     *
12237     * @param event The motion event that describes the hover.
12238     * @return True if the view handled the hover event.
12239     *
12240     * @see #isHovered
12241     * @see #setHovered
12242     * @see #onHoverChanged
12243     */
12244    public boolean onHoverEvent(MotionEvent event) {
12245        // The root view may receive hover (or touch) events that are outside the bounds of
12246        // the window.  This code ensures that we only send accessibility events for
12247        // hovers that are actually within the bounds of the root view.
12248        final int action = event.getActionMasked();
12249        if (!mSendingHoverAccessibilityEvents) {
12250            if ((action == MotionEvent.ACTION_HOVER_ENTER
12251                    || action == MotionEvent.ACTION_HOVER_MOVE)
12252                    && !hasHoveredChild()
12253                    && pointInView(event.getX(), event.getY())) {
12254                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
12255                mSendingHoverAccessibilityEvents = true;
12256            }
12257        } else {
12258            if (action == MotionEvent.ACTION_HOVER_EXIT
12259                    || (action == MotionEvent.ACTION_MOVE
12260                            && !pointInView(event.getX(), event.getY()))) {
12261                mSendingHoverAccessibilityEvents = false;
12262                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
12263            }
12264        }
12265
12266        if ((action == MotionEvent.ACTION_HOVER_ENTER || action == MotionEvent.ACTION_HOVER_MOVE)
12267                && event.isFromSource(InputDevice.SOURCE_MOUSE)
12268                && isOnScrollbar(event.getX(), event.getY())) {
12269            awakenScrollBars();
12270        }
12271
12272        // If we consider ourself hoverable, or if we we're already hovered,
12273        // handle changing state in response to ENTER and EXIT events.
12274        if (isHoverable() || isHovered()) {
12275            switch (action) {
12276                case MotionEvent.ACTION_HOVER_ENTER:
12277                    setHovered(true);
12278                    break;
12279                case MotionEvent.ACTION_HOVER_EXIT:
12280                    setHovered(false);
12281                    break;
12282            }
12283
12284            // Dispatch the event to onGenericMotionEvent before returning true.
12285            // This is to provide compatibility with existing applications that
12286            // handled HOVER_MOVE events in onGenericMotionEvent and that would
12287            // break because of the new default handling for hoverable views
12288            // in onHoverEvent.
12289            // Note that onGenericMotionEvent will be called by default when
12290            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
12291            dispatchGenericMotionEventInternal(event);
12292            // The event was already handled by calling setHovered(), so always
12293            // return true.
12294            return true;
12295        }
12296
12297        return false;
12298    }
12299
12300    /**
12301     * Returns true if the view should handle {@link #onHoverEvent}
12302     * by calling {@link #setHovered} to change its hovered state.
12303     *
12304     * @return True if the view is hoverable.
12305     */
12306    private boolean isHoverable() {
12307        final int viewFlags = mViewFlags;
12308        if ((viewFlags & ENABLED_MASK) == DISABLED) {
12309            return false;
12310        }
12311
12312        return (viewFlags & CLICKABLE) == CLICKABLE
12313                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE
12314                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
12315    }
12316
12317    /**
12318     * Returns true if the view is currently hovered.
12319     *
12320     * @return True if the view is currently hovered.
12321     *
12322     * @see #setHovered
12323     * @see #onHoverChanged
12324     */
12325    @ViewDebug.ExportedProperty
12326    public boolean isHovered() {
12327        return (mPrivateFlags & PFLAG_HOVERED) != 0;
12328    }
12329
12330    /**
12331     * Sets whether the view is currently hovered.
12332     * <p>
12333     * Calling this method also changes the drawable state of the view.  This
12334     * enables the view to react to hover by using different drawable resources
12335     * to change its appearance.
12336     * </p><p>
12337     * The {@link #onHoverChanged} method is called when the hovered state changes.
12338     * </p>
12339     *
12340     * @param hovered True if the view is hovered.
12341     *
12342     * @see #isHovered
12343     * @see #onHoverChanged
12344     */
12345    public void setHovered(boolean hovered) {
12346        if (hovered) {
12347            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
12348                mPrivateFlags |= PFLAG_HOVERED;
12349                refreshDrawableState();
12350                onHoverChanged(true);
12351            }
12352        } else {
12353            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
12354                mPrivateFlags &= ~PFLAG_HOVERED;
12355                refreshDrawableState();
12356                onHoverChanged(false);
12357            }
12358        }
12359    }
12360
12361    /**
12362     * Implement this method to handle hover state changes.
12363     * <p>
12364     * This method is called whenever the hover state changes as a result of a
12365     * call to {@link #setHovered}.
12366     * </p>
12367     *
12368     * @param hovered The current hover state, as returned by {@link #isHovered}.
12369     *
12370     * @see #isHovered
12371     * @see #setHovered
12372     */
12373    public void onHoverChanged(boolean hovered) {
12374    }
12375
12376    /**
12377     * Handles scroll bar dragging by mouse input.
12378     *
12379     * @hide
12380     * @param event The motion event.
12381     *
12382     * @return true if the event was handled as a scroll bar dragging, false otherwise.
12383     */
12384    protected boolean handleScrollBarDragging(MotionEvent event) {
12385        if (mScrollCache == null) {
12386            return false;
12387        }
12388        final float x = event.getX();
12389        final float y = event.getY();
12390        final int action = event.getAction();
12391        if ((mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING
12392                && action != MotionEvent.ACTION_DOWN)
12393                    || !event.isFromSource(InputDevice.SOURCE_MOUSE)
12394                    || !event.isButtonPressed(MotionEvent.BUTTON_PRIMARY)) {
12395            mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING;
12396            return false;
12397        }
12398
12399        switch (action) {
12400            case MotionEvent.ACTION_MOVE:
12401                if (mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING) {
12402                    return false;
12403                }
12404                if (mScrollCache.mScrollBarDraggingState
12405                        == ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR) {
12406                    final Rect bounds = mScrollCache.mScrollBarBounds;
12407                    getVerticalScrollBarBounds(bounds, null);
12408                    final int range = computeVerticalScrollRange();
12409                    final int offset = computeVerticalScrollOffset();
12410                    final int extent = computeVerticalScrollExtent();
12411
12412                    final int thumbLength = ScrollBarUtils.getThumbLength(
12413                            bounds.height(), bounds.width(), extent, range);
12414                    final int thumbOffset = ScrollBarUtils.getThumbOffset(
12415                            bounds.height(), thumbLength, extent, range, offset);
12416
12417                    final float diff = y - mScrollCache.mScrollBarDraggingPos;
12418                    final float maxThumbOffset = bounds.height() - thumbLength;
12419                    final float newThumbOffset =
12420                            Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset);
12421                    final int height = getHeight();
12422                    if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0
12423                            && height > 0 && extent > 0) {
12424                        final int newY = Math.round((range - extent)
12425                                / ((float)extent / height) * (newThumbOffset / maxThumbOffset));
12426                        if (newY != getScrollY()) {
12427                            mScrollCache.mScrollBarDraggingPos = y;
12428                            setScrollY(newY);
12429                        }
12430                    }
12431                    return true;
12432                }
12433                if (mScrollCache.mScrollBarDraggingState
12434                        == ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR) {
12435                    final Rect bounds = mScrollCache.mScrollBarBounds;
12436                    getHorizontalScrollBarBounds(bounds, null);
12437                    final int range = computeHorizontalScrollRange();
12438                    final int offset = computeHorizontalScrollOffset();
12439                    final int extent = computeHorizontalScrollExtent();
12440
12441                    final int thumbLength = ScrollBarUtils.getThumbLength(
12442                            bounds.width(), bounds.height(), extent, range);
12443                    final int thumbOffset = ScrollBarUtils.getThumbOffset(
12444                            bounds.width(), thumbLength, extent, range, offset);
12445
12446                    final float diff = x - mScrollCache.mScrollBarDraggingPos;
12447                    final float maxThumbOffset = bounds.width() - thumbLength;
12448                    final float newThumbOffset =
12449                            Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset);
12450                    final int width = getWidth();
12451                    if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0
12452                            && width > 0 && extent > 0) {
12453                        final int newX = Math.round((range - extent)
12454                                / ((float)extent / width) * (newThumbOffset / maxThumbOffset));
12455                        if (newX != getScrollX()) {
12456                            mScrollCache.mScrollBarDraggingPos = x;
12457                            setScrollX(newX);
12458                        }
12459                    }
12460                    return true;
12461                }
12462            case MotionEvent.ACTION_DOWN:
12463                if (mScrollCache.state == ScrollabilityCache.OFF) {
12464                    return false;
12465                }
12466                if (isOnVerticalScrollbarThumb(x, y)) {
12467                    mScrollCache.mScrollBarDraggingState =
12468                            ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR;
12469                    mScrollCache.mScrollBarDraggingPos = y;
12470                    return true;
12471                }
12472                if (isOnHorizontalScrollbarThumb(x, y)) {
12473                    mScrollCache.mScrollBarDraggingState =
12474                            ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR;
12475                    mScrollCache.mScrollBarDraggingPos = x;
12476                    return true;
12477                }
12478        }
12479        mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING;
12480        return false;
12481    }
12482
12483    /**
12484     * Implement this method to handle touch screen motion events.
12485     * <p>
12486     * If this method is used to detect click actions, it is recommended that
12487     * the actions be performed by implementing and calling
12488     * {@link #performClick()}. This will ensure consistent system behavior,
12489     * including:
12490     * <ul>
12491     * <li>obeying click sound preferences
12492     * <li>dispatching OnClickListener calls
12493     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
12494     * accessibility features are enabled
12495     * </ul>
12496     *
12497     * @param event The motion event.
12498     * @return True if the event was handled, false otherwise.
12499     */
12500    public boolean onTouchEvent(MotionEvent event) {
12501        final float x = event.getX();
12502        final float y = event.getY();
12503        final int viewFlags = mViewFlags;
12504        final int action = event.getAction();
12505
12506        final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE
12507                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
12508                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
12509
12510        if ((viewFlags & ENABLED_MASK) == DISABLED) {
12511            if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
12512                setPressed(false);
12513            }
12514            mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
12515            // A disabled view that is clickable still consumes the touch
12516            // events, it just doesn't respond to them.
12517            return clickable;
12518        }
12519        if (mTouchDelegate != null) {
12520            if (mTouchDelegate.onTouchEvent(event)) {
12521                return true;
12522            }
12523        }
12524
12525        if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
12526            switch (action) {
12527                case MotionEvent.ACTION_UP:
12528                    mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
12529                    if ((viewFlags & TOOLTIP) == TOOLTIP) {
12530                        handleTooltipUp();
12531                    }
12532                    if (!clickable) {
12533                        removeTapCallback();
12534                        removeLongPressCallback();
12535                        mInContextButtonPress = false;
12536                        mHasPerformedLongPress = false;
12537                        mIgnoreNextUpEvent = false;
12538                        break;
12539                    }
12540                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
12541                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
12542                        // take focus if we don't have it already and we should in
12543                        // touch mode.
12544                        boolean focusTaken = false;
12545                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
12546                            focusTaken = requestFocus();
12547                        }
12548
12549                        if (prepressed) {
12550                            // The button is being released before we actually
12551                            // showed it as pressed.  Make it show the pressed
12552                            // state now (before scheduling the click) to ensure
12553                            // the user sees it.
12554                            setPressed(true, x, y);
12555                        }
12556
12557                        if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
12558                            // This is a tap, so remove the longpress check
12559                            removeLongPressCallback();
12560
12561                            // Only perform take click actions if we were in the pressed state
12562                            if (!focusTaken) {
12563                                // Use a Runnable and post this rather than calling
12564                                // performClick directly. This lets other visual state
12565                                // of the view update before click actions start.
12566                                if (mPerformClick == null) {
12567                                    mPerformClick = new PerformClick();
12568                                }
12569                                if (!post(mPerformClick)) {
12570                                    performClick();
12571                                }
12572                            }
12573                        }
12574
12575                        if (mUnsetPressedState == null) {
12576                            mUnsetPressedState = new UnsetPressedState();
12577                        }
12578
12579                        if (prepressed) {
12580                            postDelayed(mUnsetPressedState,
12581                                    ViewConfiguration.getPressedStateDuration());
12582                        } else if (!post(mUnsetPressedState)) {
12583                            // If the post failed, unpress right now
12584                            mUnsetPressedState.run();
12585                        }
12586
12587                        removeTapCallback();
12588                    }
12589                    mIgnoreNextUpEvent = false;
12590                    break;
12591
12592                case MotionEvent.ACTION_DOWN:
12593                    if (event.getSource() == InputDevice.SOURCE_TOUCHSCREEN) {
12594                        mPrivateFlags3 |= PFLAG3_FINGER_DOWN;
12595                    }
12596                    mHasPerformedLongPress = false;
12597
12598                    if (!clickable) {
12599                        checkForLongClick(0, x, y);
12600                        break;
12601                    }
12602
12603                    if (performButtonActionOnTouchDown(event)) {
12604                        break;
12605                    }
12606
12607                    // Walk up the hierarchy to determine if we're inside a scrolling container.
12608                    boolean isInScrollingContainer = isInScrollingContainer();
12609
12610                    // For views inside a scrolling container, delay the pressed feedback for
12611                    // a short period in case this is a scroll.
12612                    if (isInScrollingContainer) {
12613                        mPrivateFlags |= PFLAG_PREPRESSED;
12614                        if (mPendingCheckForTap == null) {
12615                            mPendingCheckForTap = new CheckForTap();
12616                        }
12617                        mPendingCheckForTap.x = event.getX();
12618                        mPendingCheckForTap.y = event.getY();
12619                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
12620                    } else {
12621                        // Not inside a scrolling container, so show the feedback right away
12622                        setPressed(true, x, y);
12623                        checkForLongClick(0, x, y);
12624                    }
12625                    break;
12626
12627                case MotionEvent.ACTION_CANCEL:
12628                    if (clickable) {
12629                        setPressed(false);
12630                    }
12631                    removeTapCallback();
12632                    removeLongPressCallback();
12633                    mInContextButtonPress = false;
12634                    mHasPerformedLongPress = false;
12635                    mIgnoreNextUpEvent = false;
12636                    mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
12637                    break;
12638
12639                case MotionEvent.ACTION_MOVE:
12640                    if (clickable) {
12641                        drawableHotspotChanged(x, y);
12642                    }
12643
12644                    // Be lenient about moving outside of buttons
12645                    if (!pointInView(x, y, mTouchSlop)) {
12646                        // Outside button
12647                        // Remove any future long press/tap checks
12648                        removeTapCallback();
12649                        removeLongPressCallback();
12650                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
12651                            setPressed(false);
12652                        }
12653                        mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
12654                    }
12655                    break;
12656            }
12657
12658            return true;
12659        }
12660
12661        return false;
12662    }
12663
12664    /**
12665     * @hide
12666     */
12667    public boolean isInScrollingContainer() {
12668        ViewParent p = getParent();
12669        while (p != null && p instanceof ViewGroup) {
12670            if (((ViewGroup) p).shouldDelayChildPressedState()) {
12671                return true;
12672            }
12673            p = p.getParent();
12674        }
12675        return false;
12676    }
12677
12678    /**
12679     * Remove the longpress detection timer.
12680     */
12681    private void removeLongPressCallback() {
12682        if (mPendingCheckForLongPress != null) {
12683            removeCallbacks(mPendingCheckForLongPress);
12684        }
12685    }
12686
12687    /**
12688     * Remove the pending click action
12689     */
12690    private void removePerformClickCallback() {
12691        if (mPerformClick != null) {
12692            removeCallbacks(mPerformClick);
12693        }
12694    }
12695
12696    /**
12697     * Remove the prepress detection timer.
12698     */
12699    private void removeUnsetPressCallback() {
12700        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
12701            setPressed(false);
12702            removeCallbacks(mUnsetPressedState);
12703        }
12704    }
12705
12706    /**
12707     * Remove the tap detection timer.
12708     */
12709    private void removeTapCallback() {
12710        if (mPendingCheckForTap != null) {
12711            mPrivateFlags &= ~PFLAG_PREPRESSED;
12712            removeCallbacks(mPendingCheckForTap);
12713        }
12714    }
12715
12716    /**
12717     * Cancels a pending long press.  Your subclass can use this if you
12718     * want the context menu to come up if the user presses and holds
12719     * at the same place, but you don't want it to come up if they press
12720     * and then move around enough to cause scrolling.
12721     */
12722    public void cancelLongPress() {
12723        removeLongPressCallback();
12724
12725        /*
12726         * The prepressed state handled by the tap callback is a display
12727         * construct, but the tap callback will post a long press callback
12728         * less its own timeout. Remove it here.
12729         */
12730        removeTapCallback();
12731    }
12732
12733    /**
12734     * Remove the pending callback for sending a
12735     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
12736     */
12737    private void removeSendViewScrolledAccessibilityEventCallback() {
12738        if (mSendViewScrolledAccessibilityEvent != null) {
12739            removeCallbacks(mSendViewScrolledAccessibilityEvent);
12740            mSendViewScrolledAccessibilityEvent.mIsPending = false;
12741        }
12742    }
12743
12744    /**
12745     * Sets the TouchDelegate for this View.
12746     */
12747    public void setTouchDelegate(TouchDelegate delegate) {
12748        mTouchDelegate = delegate;
12749    }
12750
12751    /**
12752     * Gets the TouchDelegate for this View.
12753     */
12754    public TouchDelegate getTouchDelegate() {
12755        return mTouchDelegate;
12756    }
12757
12758    /**
12759     * Request unbuffered dispatch of the given stream of MotionEvents to this View.
12760     *
12761     * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input
12762     * system not batch {@link MotionEvent}s but instead deliver them as soon as they're
12763     * available. This method should only be called for touch events.
12764     *
12765     * <p class="note">This api is not intended for most applications. Buffered dispatch
12766     * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent
12767     * streams will not improve your input latency. Side effects include: increased latency,
12768     * jittery scrolls and inability to take advantage of system resampling. Talk to your input
12769     * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for
12770     * you.</p>
12771     */
12772    public final void requestUnbufferedDispatch(MotionEvent event) {
12773        final int action = event.getAction();
12774        if (mAttachInfo == null
12775                || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE
12776                || !event.isTouchEvent()) {
12777            return;
12778        }
12779        mAttachInfo.mUnbufferedDispatchRequested = true;
12780    }
12781
12782    /**
12783     * Set flags controlling behavior of this view.
12784     *
12785     * @param flags Constant indicating the value which should be set
12786     * @param mask Constant indicating the bit range that should be changed
12787     */
12788    void setFlags(int flags, int mask) {
12789        final boolean accessibilityEnabled =
12790                AccessibilityManager.getInstance(mContext).isEnabled();
12791        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
12792
12793        int old = mViewFlags;
12794        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
12795
12796        int changed = mViewFlags ^ old;
12797        if (changed == 0) {
12798            return;
12799        }
12800        int privateFlags = mPrivateFlags;
12801
12802        // If focusable is auto, update the FOCUSABLE bit.
12803        int focusableChangedByAuto = 0;
12804        if (((mViewFlags & FOCUSABLE_AUTO) != 0)
12805                && (changed & (FOCUSABLE_MASK | CLICKABLE)) != 0) {
12806            // Heuristic only takes into account whether view is clickable.
12807            final int newFocus;
12808            if ((mViewFlags & CLICKABLE) != 0) {
12809                newFocus = FOCUSABLE;
12810            } else {
12811                newFocus = NOT_FOCUSABLE;
12812            }
12813            mViewFlags = (mViewFlags & ~FOCUSABLE) | newFocus;
12814            focusableChangedByAuto = (old & FOCUSABLE) ^ (newFocus & FOCUSABLE);
12815            changed = (changed & ~FOCUSABLE) | focusableChangedByAuto;
12816        }
12817
12818        /* Check if the FOCUSABLE bit has changed */
12819        if (((changed & FOCUSABLE) != 0) && ((privateFlags & PFLAG_HAS_BOUNDS) != 0)) {
12820            if (((old & FOCUSABLE) == FOCUSABLE)
12821                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
12822                /* Give up focus if we are no longer focusable */
12823                clearFocus();
12824            } else if (((old & FOCUSABLE) == NOT_FOCUSABLE)
12825                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
12826                /*
12827                 * Tell the view system that we are now available to take focus
12828                 * if no one else already has it.
12829                 */
12830                if (mParent != null) {
12831                    ViewRootImpl viewRootImpl = getViewRootImpl();
12832                    if (!sAutoFocusableOffUIThreadWontNotifyParents
12833                            || focusableChangedByAuto == 0
12834                            || viewRootImpl == null
12835                            || viewRootImpl.mThread == Thread.currentThread()) {
12836                        mParent.focusableViewAvailable(this);
12837                    }
12838                }
12839            }
12840        }
12841
12842        final int newVisibility = flags & VISIBILITY_MASK;
12843        if (newVisibility == VISIBLE) {
12844            if ((changed & VISIBILITY_MASK) != 0) {
12845                /*
12846                 * If this view is becoming visible, invalidate it in case it changed while
12847                 * it was not visible. Marking it drawn ensures that the invalidation will
12848                 * go through.
12849                 */
12850                mPrivateFlags |= PFLAG_DRAWN;
12851                invalidate(true);
12852
12853                needGlobalAttributesUpdate(true);
12854
12855                // a view becoming visible is worth notifying the parent
12856                // about in case nothing has focus.  even if this specific view
12857                // isn't focusable, it may contain something that is, so let
12858                // the root view try to give this focus if nothing else does.
12859                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
12860                    mParent.focusableViewAvailable(this);
12861                }
12862            }
12863        }
12864
12865        /* Check if the GONE bit has changed */
12866        if ((changed & GONE) != 0) {
12867            needGlobalAttributesUpdate(false);
12868            requestLayout();
12869
12870            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
12871                if (hasFocus()) clearFocus();
12872                clearAccessibilityFocus();
12873                destroyDrawingCache();
12874                if (mParent instanceof View) {
12875                    // GONE views noop invalidation, so invalidate the parent
12876                    ((View) mParent).invalidate(true);
12877                }
12878                // Mark the view drawn to ensure that it gets invalidated properly the next
12879                // time it is visible and gets invalidated
12880                mPrivateFlags |= PFLAG_DRAWN;
12881            }
12882            if (mAttachInfo != null) {
12883                mAttachInfo.mViewVisibilityChanged = true;
12884            }
12885        }
12886
12887        /* Check if the VISIBLE bit has changed */
12888        if ((changed & INVISIBLE) != 0) {
12889            needGlobalAttributesUpdate(false);
12890            /*
12891             * If this view is becoming invisible, set the DRAWN flag so that
12892             * the next invalidate() will not be skipped.
12893             */
12894            mPrivateFlags |= PFLAG_DRAWN;
12895
12896            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
12897                // root view becoming invisible shouldn't clear focus and accessibility focus
12898                if (getRootView() != this) {
12899                    if (hasFocus()) clearFocus();
12900                    clearAccessibilityFocus();
12901                }
12902            }
12903            if (mAttachInfo != null) {
12904                mAttachInfo.mViewVisibilityChanged = true;
12905            }
12906        }
12907
12908        if ((changed & VISIBILITY_MASK) != 0) {
12909            // If the view is invisible, cleanup its display list to free up resources
12910            if (newVisibility != VISIBLE && mAttachInfo != null) {
12911                cleanupDraw();
12912            }
12913
12914            if (mParent instanceof ViewGroup) {
12915                ((ViewGroup) mParent).onChildVisibilityChanged(this,
12916                        (changed & VISIBILITY_MASK), newVisibility);
12917                ((View) mParent).invalidate(true);
12918            } else if (mParent != null) {
12919                mParent.invalidateChild(this, null);
12920            }
12921
12922            if (mAttachInfo != null) {
12923                dispatchVisibilityChanged(this, newVisibility);
12924
12925                // Aggregated visibility changes are dispatched to attached views
12926                // in visible windows where the parent is currently shown/drawn
12927                // or the parent is not a ViewGroup (and therefore assumed to be a ViewRoot),
12928                // discounting clipping or overlapping. This makes it a good place
12929                // to change animation states.
12930                if (mParent != null && getWindowVisibility() == VISIBLE &&
12931                        ((!(mParent instanceof ViewGroup)) || ((ViewGroup) mParent).isShown())) {
12932                    dispatchVisibilityAggregated(newVisibility == VISIBLE);
12933                }
12934                notifySubtreeAccessibilityStateChangedIfNeeded();
12935            }
12936        }
12937
12938        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
12939            destroyDrawingCache();
12940        }
12941
12942        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
12943            destroyDrawingCache();
12944            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
12945            invalidateParentCaches();
12946        }
12947
12948        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
12949            destroyDrawingCache();
12950            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
12951        }
12952
12953        if ((changed & DRAW_MASK) != 0) {
12954            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
12955                if (mBackground != null
12956                        || (mForegroundInfo != null && mForegroundInfo.mDrawable != null)) {
12957                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
12958                } else {
12959                    mPrivateFlags |= PFLAG_SKIP_DRAW;
12960                }
12961            } else {
12962                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
12963            }
12964            requestLayout();
12965            invalidate(true);
12966        }
12967
12968        if ((changed & KEEP_SCREEN_ON) != 0) {
12969            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
12970                mParent.recomputeViewAttributes(this);
12971            }
12972        }
12973
12974        if (accessibilityEnabled) {
12975            if ((changed & FOCUSABLE) != 0 || (changed & VISIBILITY_MASK) != 0
12976                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0
12977                    || (changed & CONTEXT_CLICKABLE) != 0) {
12978                if (oldIncludeForAccessibility != includeForAccessibility()) {
12979                    notifySubtreeAccessibilityStateChangedIfNeeded();
12980                } else {
12981                    notifyViewAccessibilityStateChangedIfNeeded(
12982                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
12983                }
12984            } else if ((changed & ENABLED_MASK) != 0) {
12985                notifyViewAccessibilityStateChangedIfNeeded(
12986                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
12987            }
12988        }
12989    }
12990
12991    /**
12992     * Change the view's z order in the tree, so it's on top of other sibling
12993     * views. This ordering change may affect layout, if the parent container
12994     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
12995     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
12996     * method should be followed by calls to {@link #requestLayout()} and
12997     * {@link View#invalidate()} on the view's parent to force the parent to redraw
12998     * with the new child ordering.
12999     *
13000     * @see ViewGroup#bringChildToFront(View)
13001     */
13002    public void bringToFront() {
13003        if (mParent != null) {
13004            mParent.bringChildToFront(this);
13005        }
13006    }
13007
13008    /**
13009     * This is called in response to an internal scroll in this view (i.e., the
13010     * view scrolled its own contents). This is typically as a result of
13011     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
13012     * called.
13013     *
13014     * @param l Current horizontal scroll origin.
13015     * @param t Current vertical scroll origin.
13016     * @param oldl Previous horizontal scroll origin.
13017     * @param oldt Previous vertical scroll origin.
13018     */
13019    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
13020        notifySubtreeAccessibilityStateChangedIfNeeded();
13021
13022        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
13023            postSendViewScrolledAccessibilityEventCallback();
13024        }
13025
13026        mBackgroundSizeChanged = true;
13027        if (mForegroundInfo != null) {
13028            mForegroundInfo.mBoundsChanged = true;
13029        }
13030
13031        final AttachInfo ai = mAttachInfo;
13032        if (ai != null) {
13033            ai.mViewScrollChanged = true;
13034        }
13035
13036        if (mListenerInfo != null && mListenerInfo.mOnScrollChangeListener != null) {
13037            mListenerInfo.mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt);
13038        }
13039    }
13040
13041    /**
13042     * Interface definition for a callback to be invoked when the scroll
13043     * X or Y positions of a view change.
13044     * <p>
13045     * <b>Note:</b> Some views handle scrolling independently from View and may
13046     * have their own separate listeners for scroll-type events. For example,
13047     * {@link android.widget.ListView ListView} allows clients to register an
13048     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
13049     * to listen for changes in list scroll position.
13050     *
13051     * @see #setOnScrollChangeListener(View.OnScrollChangeListener)
13052     */
13053    public interface OnScrollChangeListener {
13054        /**
13055         * Called when the scroll position of a view changes.
13056         *
13057         * @param v The view whose scroll position has changed.
13058         * @param scrollX Current horizontal scroll origin.
13059         * @param scrollY Current vertical scroll origin.
13060         * @param oldScrollX Previous horizontal scroll origin.
13061         * @param oldScrollY Previous vertical scroll origin.
13062         */
13063        void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY);
13064    }
13065
13066    /**
13067     * Interface definition for a callback to be invoked when the layout bounds of a view
13068     * changes due to layout processing.
13069     */
13070    public interface OnLayoutChangeListener {
13071        /**
13072         * Called when the layout bounds of a view changes due to layout processing.
13073         *
13074         * @param v The view whose bounds have changed.
13075         * @param left The new value of the view's left property.
13076         * @param top The new value of the view's top property.
13077         * @param right The new value of the view's right property.
13078         * @param bottom The new value of the view's bottom property.
13079         * @param oldLeft The previous value of the view's left property.
13080         * @param oldTop The previous value of the view's top property.
13081         * @param oldRight The previous value of the view's right property.
13082         * @param oldBottom The previous value of the view's bottom property.
13083         */
13084        void onLayoutChange(View v, int left, int top, int right, int bottom,
13085            int oldLeft, int oldTop, int oldRight, int oldBottom);
13086    }
13087
13088    /**
13089     * This is called during layout when the size of this view has changed. If
13090     * you were just added to the view hierarchy, you're called with the old
13091     * values of 0.
13092     *
13093     * @param w Current width of this view.
13094     * @param h Current height of this view.
13095     * @param oldw Old width of this view.
13096     * @param oldh Old height of this view.
13097     */
13098    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
13099    }
13100
13101    /**
13102     * Called by draw to draw the child views. This may be overridden
13103     * by derived classes to gain control just before its children are drawn
13104     * (but after its own view has been drawn).
13105     * @param canvas the canvas on which to draw the view
13106     */
13107    protected void dispatchDraw(Canvas canvas) {
13108
13109    }
13110
13111    /**
13112     * Gets the parent of this view. Note that the parent is a
13113     * ViewParent and not necessarily a View.
13114     *
13115     * @return Parent of this view.
13116     */
13117    public final ViewParent getParent() {
13118        return mParent;
13119    }
13120
13121    /**
13122     * Set the horizontal scrolled position of your view. This will cause a call to
13123     * {@link #onScrollChanged(int, int, int, int)} and the view will be
13124     * invalidated.
13125     * @param value the x position to scroll to
13126     */
13127    public void setScrollX(int value) {
13128        scrollTo(value, mScrollY);
13129    }
13130
13131    /**
13132     * Set the vertical scrolled position of your view. This will cause a call to
13133     * {@link #onScrollChanged(int, int, int, int)} and the view will be
13134     * invalidated.
13135     * @param value the y position to scroll to
13136     */
13137    public void setScrollY(int value) {
13138        scrollTo(mScrollX, value);
13139    }
13140
13141    /**
13142     * Return the scrolled left position of this view. This is the left edge of
13143     * the displayed part of your view. You do not need to draw any pixels
13144     * farther left, since those are outside of the frame of your view on
13145     * screen.
13146     *
13147     * @return The left edge of the displayed part of your view, in pixels.
13148     */
13149    public final int getScrollX() {
13150        return mScrollX;
13151    }
13152
13153    /**
13154     * Return the scrolled top position of this view. This is the top edge of
13155     * the displayed part of your view. You do not need to draw any pixels above
13156     * it, since those are outside of the frame of your view on screen.
13157     *
13158     * @return The top edge of the displayed part of your view, in pixels.
13159     */
13160    public final int getScrollY() {
13161        return mScrollY;
13162    }
13163
13164    /**
13165     * Return the width of the your view.
13166     *
13167     * @return The width of your view, in pixels.
13168     */
13169    @ViewDebug.ExportedProperty(category = "layout")
13170    public final int getWidth() {
13171        return mRight - mLeft;
13172    }
13173
13174    /**
13175     * Return the height of your view.
13176     *
13177     * @return The height of your view, in pixels.
13178     */
13179    @ViewDebug.ExportedProperty(category = "layout")
13180    public final int getHeight() {
13181        return mBottom - mTop;
13182    }
13183
13184    /**
13185     * Return the visible drawing bounds of your view. Fills in the output
13186     * rectangle with the values from getScrollX(), getScrollY(),
13187     * getWidth(), and getHeight(). These bounds do not account for any
13188     * transformation properties currently set on the view, such as
13189     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
13190     *
13191     * @param outRect The (scrolled) drawing bounds of the view.
13192     */
13193    public void getDrawingRect(Rect outRect) {
13194        outRect.left = mScrollX;
13195        outRect.top = mScrollY;
13196        outRect.right = mScrollX + (mRight - mLeft);
13197        outRect.bottom = mScrollY + (mBottom - mTop);
13198    }
13199
13200    /**
13201     * Like {@link #getMeasuredWidthAndState()}, but only returns the
13202     * raw width component (that is the result is masked by
13203     * {@link #MEASURED_SIZE_MASK}).
13204     *
13205     * @return The raw measured width of this view.
13206     */
13207    public final int getMeasuredWidth() {
13208        return mMeasuredWidth & MEASURED_SIZE_MASK;
13209    }
13210
13211    /**
13212     * Return the full width measurement information for this view as computed
13213     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
13214     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
13215     * This should be used during measurement and layout calculations only. Use
13216     * {@link #getWidth()} to see how wide a view is after layout.
13217     *
13218     * @return The measured width of this view as a bit mask.
13219     */
13220    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
13221            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
13222                    name = "MEASURED_STATE_TOO_SMALL"),
13223    })
13224    public final int getMeasuredWidthAndState() {
13225        return mMeasuredWidth;
13226    }
13227
13228    /**
13229     * Like {@link #getMeasuredHeightAndState()}, but only returns the
13230     * raw height component (that is the result is masked by
13231     * {@link #MEASURED_SIZE_MASK}).
13232     *
13233     * @return The raw measured height of this view.
13234     */
13235    public final int getMeasuredHeight() {
13236        return mMeasuredHeight & MEASURED_SIZE_MASK;
13237    }
13238
13239    /**
13240     * Return the full height measurement information for this view as computed
13241     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
13242     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
13243     * This should be used during measurement and layout calculations only. Use
13244     * {@link #getHeight()} to see how wide a view is after layout.
13245     *
13246     * @return The measured height of this view as a bit mask.
13247     */
13248    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
13249            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
13250                    name = "MEASURED_STATE_TOO_SMALL"),
13251    })
13252    public final int getMeasuredHeightAndState() {
13253        return mMeasuredHeight;
13254    }
13255
13256    /**
13257     * Return only the state bits of {@link #getMeasuredWidthAndState()}
13258     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
13259     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
13260     * and the height component is at the shifted bits
13261     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
13262     */
13263    public final int getMeasuredState() {
13264        return (mMeasuredWidth&MEASURED_STATE_MASK)
13265                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
13266                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
13267    }
13268
13269    /**
13270     * The transform matrix of this view, which is calculated based on the current
13271     * rotation, scale, and pivot properties.
13272     *
13273     * @see #getRotation()
13274     * @see #getScaleX()
13275     * @see #getScaleY()
13276     * @see #getPivotX()
13277     * @see #getPivotY()
13278     * @return The current transform matrix for the view
13279     */
13280    public Matrix getMatrix() {
13281        ensureTransformationInfo();
13282        final Matrix matrix = mTransformationInfo.mMatrix;
13283        mRenderNode.getMatrix(matrix);
13284        return matrix;
13285    }
13286
13287    /**
13288     * Returns true if the transform matrix is the identity matrix.
13289     * Recomputes the matrix if necessary.
13290     *
13291     * @return True if the transform matrix is the identity matrix, false otherwise.
13292     */
13293    final boolean hasIdentityMatrix() {
13294        return mRenderNode.hasIdentityMatrix();
13295    }
13296
13297    void ensureTransformationInfo() {
13298        if (mTransformationInfo == null) {
13299            mTransformationInfo = new TransformationInfo();
13300        }
13301    }
13302
13303    /**
13304     * Utility method to retrieve the inverse of the current mMatrix property.
13305     * We cache the matrix to avoid recalculating it when transform properties
13306     * have not changed.
13307     *
13308     * @return The inverse of the current matrix of this view.
13309     * @hide
13310     */
13311    public final Matrix getInverseMatrix() {
13312        ensureTransformationInfo();
13313        if (mTransformationInfo.mInverseMatrix == null) {
13314            mTransformationInfo.mInverseMatrix = new Matrix();
13315        }
13316        final Matrix matrix = mTransformationInfo.mInverseMatrix;
13317        mRenderNode.getInverseMatrix(matrix);
13318        return matrix;
13319    }
13320
13321    /**
13322     * Gets the distance along the Z axis from the camera to this view.
13323     *
13324     * @see #setCameraDistance(float)
13325     *
13326     * @return The distance along the Z axis.
13327     */
13328    public float getCameraDistance() {
13329        final float dpi = mResources.getDisplayMetrics().densityDpi;
13330        return -(mRenderNode.getCameraDistance() * dpi);
13331    }
13332
13333    /**
13334     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
13335     * views are drawn) from the camera to this view. The camera's distance
13336     * affects 3D transformations, for instance rotations around the X and Y
13337     * axis. If the rotationX or rotationY properties are changed and this view is
13338     * large (more than half the size of the screen), it is recommended to always
13339     * use a camera distance that's greater than the height (X axis rotation) or
13340     * the width (Y axis rotation) of this view.</p>
13341     *
13342     * <p>The distance of the camera from the view plane can have an affect on the
13343     * perspective distortion of the view when it is rotated around the x or y axis.
13344     * For example, a large distance will result in a large viewing angle, and there
13345     * will not be much perspective distortion of the view as it rotates. A short
13346     * distance may cause much more perspective distortion upon rotation, and can
13347     * also result in some drawing artifacts if the rotated view ends up partially
13348     * behind the camera (which is why the recommendation is to use a distance at
13349     * least as far as the size of the view, if the view is to be rotated.)</p>
13350     *
13351     * <p>The distance is expressed in "depth pixels." The default distance depends
13352     * on the screen density. For instance, on a medium density display, the
13353     * default distance is 1280. On a high density display, the default distance
13354     * is 1920.</p>
13355     *
13356     * <p>If you want to specify a distance that leads to visually consistent
13357     * results across various densities, use the following formula:</p>
13358     * <pre>
13359     * float scale = context.getResources().getDisplayMetrics().density;
13360     * view.setCameraDistance(distance * scale);
13361     * </pre>
13362     *
13363     * <p>The density scale factor of a high density display is 1.5,
13364     * and 1920 = 1280 * 1.5.</p>
13365     *
13366     * @param distance The distance in "depth pixels", if negative the opposite
13367     *        value is used
13368     *
13369     * @see #setRotationX(float)
13370     * @see #setRotationY(float)
13371     */
13372    public void setCameraDistance(float distance) {
13373        final float dpi = mResources.getDisplayMetrics().densityDpi;
13374
13375        invalidateViewProperty(true, false);
13376        mRenderNode.setCameraDistance(-Math.abs(distance) / dpi);
13377        invalidateViewProperty(false, false);
13378
13379        invalidateParentIfNeededAndWasQuickRejected();
13380    }
13381
13382    /**
13383     * The degrees that the view is rotated around the pivot point.
13384     *
13385     * @see #setRotation(float)
13386     * @see #getPivotX()
13387     * @see #getPivotY()
13388     *
13389     * @return The degrees of rotation.
13390     */
13391    @ViewDebug.ExportedProperty(category = "drawing")
13392    public float getRotation() {
13393        return mRenderNode.getRotation();
13394    }
13395
13396    /**
13397     * Sets the degrees that the view is rotated around the pivot point. Increasing values
13398     * result in clockwise rotation.
13399     *
13400     * @param rotation The degrees of rotation.
13401     *
13402     * @see #getRotation()
13403     * @see #getPivotX()
13404     * @see #getPivotY()
13405     * @see #setRotationX(float)
13406     * @see #setRotationY(float)
13407     *
13408     * @attr ref android.R.styleable#View_rotation
13409     */
13410    public void setRotation(float rotation) {
13411        if (rotation != getRotation()) {
13412            // Double-invalidation is necessary to capture view's old and new areas
13413            invalidateViewProperty(true, false);
13414            mRenderNode.setRotation(rotation);
13415            invalidateViewProperty(false, true);
13416
13417            invalidateParentIfNeededAndWasQuickRejected();
13418            notifySubtreeAccessibilityStateChangedIfNeeded();
13419        }
13420    }
13421
13422    /**
13423     * The degrees that the view is rotated around the vertical axis through the pivot point.
13424     *
13425     * @see #getPivotX()
13426     * @see #getPivotY()
13427     * @see #setRotationY(float)
13428     *
13429     * @return The degrees of Y rotation.
13430     */
13431    @ViewDebug.ExportedProperty(category = "drawing")
13432    public float getRotationY() {
13433        return mRenderNode.getRotationY();
13434    }
13435
13436    /**
13437     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
13438     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
13439     * down the y axis.
13440     *
13441     * When rotating large views, it is recommended to adjust the camera distance
13442     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
13443     *
13444     * @param rotationY The degrees of Y rotation.
13445     *
13446     * @see #getRotationY()
13447     * @see #getPivotX()
13448     * @see #getPivotY()
13449     * @see #setRotation(float)
13450     * @see #setRotationX(float)
13451     * @see #setCameraDistance(float)
13452     *
13453     * @attr ref android.R.styleable#View_rotationY
13454     */
13455    public void setRotationY(float rotationY) {
13456        if (rotationY != getRotationY()) {
13457            invalidateViewProperty(true, false);
13458            mRenderNode.setRotationY(rotationY);
13459            invalidateViewProperty(false, true);
13460
13461            invalidateParentIfNeededAndWasQuickRejected();
13462            notifySubtreeAccessibilityStateChangedIfNeeded();
13463        }
13464    }
13465
13466    /**
13467     * The degrees that the view is rotated around the horizontal axis through the pivot point.
13468     *
13469     * @see #getPivotX()
13470     * @see #getPivotY()
13471     * @see #setRotationX(float)
13472     *
13473     * @return The degrees of X rotation.
13474     */
13475    @ViewDebug.ExportedProperty(category = "drawing")
13476    public float getRotationX() {
13477        return mRenderNode.getRotationX();
13478    }
13479
13480    /**
13481     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
13482     * Increasing values result in clockwise rotation from the viewpoint of looking down the
13483     * x axis.
13484     *
13485     * When rotating large views, it is recommended to adjust the camera distance
13486     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
13487     *
13488     * @param rotationX The degrees of X rotation.
13489     *
13490     * @see #getRotationX()
13491     * @see #getPivotX()
13492     * @see #getPivotY()
13493     * @see #setRotation(float)
13494     * @see #setRotationY(float)
13495     * @see #setCameraDistance(float)
13496     *
13497     * @attr ref android.R.styleable#View_rotationX
13498     */
13499    public void setRotationX(float rotationX) {
13500        if (rotationX != getRotationX()) {
13501            invalidateViewProperty(true, false);
13502            mRenderNode.setRotationX(rotationX);
13503            invalidateViewProperty(false, true);
13504
13505            invalidateParentIfNeededAndWasQuickRejected();
13506            notifySubtreeAccessibilityStateChangedIfNeeded();
13507        }
13508    }
13509
13510    /**
13511     * The amount that the view is scaled in x around the pivot point, as a proportion of
13512     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
13513     *
13514     * <p>By default, this is 1.0f.
13515     *
13516     * @see #getPivotX()
13517     * @see #getPivotY()
13518     * @return The scaling factor.
13519     */
13520    @ViewDebug.ExportedProperty(category = "drawing")
13521    public float getScaleX() {
13522        return mRenderNode.getScaleX();
13523    }
13524
13525    /**
13526     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
13527     * the view's unscaled width. A value of 1 means that no scaling is applied.
13528     *
13529     * @param scaleX The scaling factor.
13530     * @see #getPivotX()
13531     * @see #getPivotY()
13532     *
13533     * @attr ref android.R.styleable#View_scaleX
13534     */
13535    public void setScaleX(float scaleX) {
13536        if (scaleX != getScaleX()) {
13537            invalidateViewProperty(true, false);
13538            mRenderNode.setScaleX(scaleX);
13539            invalidateViewProperty(false, true);
13540
13541            invalidateParentIfNeededAndWasQuickRejected();
13542            notifySubtreeAccessibilityStateChangedIfNeeded();
13543        }
13544    }
13545
13546    /**
13547     * The amount that the view is scaled in y around the pivot point, as a proportion of
13548     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
13549     *
13550     * <p>By default, this is 1.0f.
13551     *
13552     * @see #getPivotX()
13553     * @see #getPivotY()
13554     * @return The scaling factor.
13555     */
13556    @ViewDebug.ExportedProperty(category = "drawing")
13557    public float getScaleY() {
13558        return mRenderNode.getScaleY();
13559    }
13560
13561    /**
13562     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
13563     * the view's unscaled width. A value of 1 means that no scaling is applied.
13564     *
13565     * @param scaleY The scaling factor.
13566     * @see #getPivotX()
13567     * @see #getPivotY()
13568     *
13569     * @attr ref android.R.styleable#View_scaleY
13570     */
13571    public void setScaleY(float scaleY) {
13572        if (scaleY != getScaleY()) {
13573            invalidateViewProperty(true, false);
13574            mRenderNode.setScaleY(scaleY);
13575            invalidateViewProperty(false, true);
13576
13577            invalidateParentIfNeededAndWasQuickRejected();
13578            notifySubtreeAccessibilityStateChangedIfNeeded();
13579        }
13580    }
13581
13582    /**
13583     * The x location of the point around which the view is {@link #setRotation(float) rotated}
13584     * and {@link #setScaleX(float) scaled}.
13585     *
13586     * @see #getRotation()
13587     * @see #getScaleX()
13588     * @see #getScaleY()
13589     * @see #getPivotY()
13590     * @return The x location of the pivot point.
13591     *
13592     * @attr ref android.R.styleable#View_transformPivotX
13593     */
13594    @ViewDebug.ExportedProperty(category = "drawing")
13595    public float getPivotX() {
13596        return mRenderNode.getPivotX();
13597    }
13598
13599    /**
13600     * Sets the x location of the point around which the view is
13601     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
13602     * By default, the pivot point is centered on the object.
13603     * Setting this property disables this behavior and causes the view to use only the
13604     * explicitly set pivotX and pivotY values.
13605     *
13606     * @param pivotX The x location of the pivot point.
13607     * @see #getRotation()
13608     * @see #getScaleX()
13609     * @see #getScaleY()
13610     * @see #getPivotY()
13611     *
13612     * @attr ref android.R.styleable#View_transformPivotX
13613     */
13614    public void setPivotX(float pivotX) {
13615        if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) {
13616            invalidateViewProperty(true, false);
13617            mRenderNode.setPivotX(pivotX);
13618            invalidateViewProperty(false, true);
13619
13620            invalidateParentIfNeededAndWasQuickRejected();
13621        }
13622    }
13623
13624    /**
13625     * The y location of the point around which the view is {@link #setRotation(float) rotated}
13626     * and {@link #setScaleY(float) scaled}.
13627     *
13628     * @see #getRotation()
13629     * @see #getScaleX()
13630     * @see #getScaleY()
13631     * @see #getPivotY()
13632     * @return The y location of the pivot point.
13633     *
13634     * @attr ref android.R.styleable#View_transformPivotY
13635     */
13636    @ViewDebug.ExportedProperty(category = "drawing")
13637    public float getPivotY() {
13638        return mRenderNode.getPivotY();
13639    }
13640
13641    /**
13642     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
13643     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
13644     * Setting this property disables this behavior and causes the view to use only the
13645     * explicitly set pivotX and pivotY values.
13646     *
13647     * @param pivotY The y location of the pivot point.
13648     * @see #getRotation()
13649     * @see #getScaleX()
13650     * @see #getScaleY()
13651     * @see #getPivotY()
13652     *
13653     * @attr ref android.R.styleable#View_transformPivotY
13654     */
13655    public void setPivotY(float pivotY) {
13656        if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) {
13657            invalidateViewProperty(true, false);
13658            mRenderNode.setPivotY(pivotY);
13659            invalidateViewProperty(false, true);
13660
13661            invalidateParentIfNeededAndWasQuickRejected();
13662        }
13663    }
13664
13665    /**
13666     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
13667     * completely transparent and 1 means the view is completely opaque.
13668     *
13669     * <p>By default this is 1.0f.
13670     * @return The opacity of the view.
13671     */
13672    @ViewDebug.ExportedProperty(category = "drawing")
13673    public float getAlpha() {
13674        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
13675    }
13676
13677    /**
13678     * Sets the behavior for overlapping rendering for this view (see {@link
13679     * #hasOverlappingRendering()} for more details on this behavior). Calling this method
13680     * is an alternative to overriding {@link #hasOverlappingRendering()} in a subclass,
13681     * providing the value which is then used internally. That is, when {@link
13682     * #forceHasOverlappingRendering(boolean)} is called, the value of {@link
13683     * #hasOverlappingRendering()} is ignored and the value passed into this method is used
13684     * instead.
13685     *
13686     * @param hasOverlappingRendering The value for overlapping rendering to be used internally
13687     * instead of that returned by {@link #hasOverlappingRendering()}.
13688     *
13689     * @attr ref android.R.styleable#View_forceHasOverlappingRendering
13690     */
13691    public void forceHasOverlappingRendering(boolean hasOverlappingRendering) {
13692        mPrivateFlags3 |= PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED;
13693        if (hasOverlappingRendering) {
13694            mPrivateFlags3 |= PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE;
13695        } else {
13696            mPrivateFlags3 &= ~PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE;
13697        }
13698    }
13699
13700    /**
13701     * Returns the value for overlapping rendering that is used internally. This is either
13702     * the value passed into {@link #forceHasOverlappingRendering(boolean)}, if called, or
13703     * the return value of {@link #hasOverlappingRendering()}, otherwise.
13704     *
13705     * @return The value for overlapping rendering being used internally.
13706     */
13707    public final boolean getHasOverlappingRendering() {
13708        return (mPrivateFlags3 & PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED) != 0 ?
13709                (mPrivateFlags3 & PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE) != 0 :
13710                hasOverlappingRendering();
13711    }
13712
13713    /**
13714     * Returns whether this View has content which overlaps.
13715     *
13716     * <p>This function, intended to be overridden by specific View types, is an optimization when
13717     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
13718     * an offscreen buffer and then composited into place, which can be expensive. If the view has
13719     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
13720     * directly. An example of overlapping rendering is a TextView with a background image, such as
13721     * a Button. An example of non-overlapping rendering is a TextView with no background, or an
13722     * ImageView with only the foreground image. The default implementation returns true; subclasses
13723     * should override if they have cases which can be optimized.</p>
13724     *
13725     * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas}
13726     * necessitates that a View return true if it uses the methods internally without passing the
13727     * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p>
13728     *
13729     * <p><strong>Note:</strong> The return value of this method is ignored if {@link
13730     * #forceHasOverlappingRendering(boolean)} has been called on this view.</p>
13731     *
13732     * @return true if the content in this view might overlap, false otherwise.
13733     */
13734    @ViewDebug.ExportedProperty(category = "drawing")
13735    public boolean hasOverlappingRendering() {
13736        return true;
13737    }
13738
13739    /**
13740     * Sets the opacity of the view to a value from 0 to 1, where 0 means the view is
13741     * completely transparent and 1 means the view is completely opaque.
13742     *
13743     * <p class="note"><strong>Note:</strong> setting alpha to a translucent value (0 < alpha < 1)
13744     * can have significant performance implications, especially for large views. It is best to use
13745     * the alpha property sparingly and transiently, as in the case of fading animations.</p>
13746     *
13747     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
13748     * strongly recommended for performance reasons to either override
13749     * {@link #hasOverlappingRendering()} to return <code>false</code> if appropriate, or setting a
13750     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view for the duration
13751     * of the animation. On versions {@link android.os.Build.VERSION_CODES#M} and below,
13752     * the default path for rendering an unlayered View with alpha could add multiple milliseconds
13753     * of rendering cost, even for simple or small views. Starting with
13754     * {@link android.os.Build.VERSION_CODES#M}, {@link #LAYER_TYPE_HARDWARE} is automatically
13755     * applied to the view at the rendering level.</p>
13756     *
13757     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
13758     * responsible for applying the opacity itself.</p>
13759     *
13760     * <p>On versions {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} and below, note that if
13761     * the view is backed by a {@link #setLayerType(int, android.graphics.Paint) layer} and is
13762     * associated with a {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an
13763     * alpha value less than 1.0 will supersede the alpha of the layer paint.</p>
13764     *
13765     * <p>Starting with {@link android.os.Build.VERSION_CODES#M}, setting a translucent alpha
13766     * value will clip a View to its bounds, unless the View returns <code>false</code> from
13767     * {@link #hasOverlappingRendering}.</p>
13768     *
13769     * @param alpha The opacity of the view.
13770     *
13771     * @see #hasOverlappingRendering()
13772     * @see #setLayerType(int, android.graphics.Paint)
13773     *
13774     * @attr ref android.R.styleable#View_alpha
13775     */
13776    public void setAlpha(@FloatRange(from=0.0, to=1.0) float alpha) {
13777        ensureTransformationInfo();
13778        if (mTransformationInfo.mAlpha != alpha) {
13779            // Report visibility changes, which can affect children, to accessibility
13780            if ((alpha == 0) ^ (mTransformationInfo.mAlpha == 0)) {
13781                notifySubtreeAccessibilityStateChangedIfNeeded();
13782            }
13783            mTransformationInfo.mAlpha = alpha;
13784            if (onSetAlpha((int) (alpha * 255))) {
13785                mPrivateFlags |= PFLAG_ALPHA_SET;
13786                // subclass is handling alpha - don't optimize rendering cache invalidation
13787                invalidateParentCaches();
13788                invalidate(true);
13789            } else {
13790                mPrivateFlags &= ~PFLAG_ALPHA_SET;
13791                invalidateViewProperty(true, false);
13792                mRenderNode.setAlpha(getFinalAlpha());
13793            }
13794        }
13795    }
13796
13797    /**
13798     * Faster version of setAlpha() which performs the same steps except there are
13799     * no calls to invalidate(). The caller of this function should perform proper invalidation
13800     * on the parent and this object. The return value indicates whether the subclass handles
13801     * alpha (the return value for onSetAlpha()).
13802     *
13803     * @param alpha The new value for the alpha property
13804     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
13805     *         the new value for the alpha property is different from the old value
13806     */
13807    boolean setAlphaNoInvalidation(float alpha) {
13808        ensureTransformationInfo();
13809        if (mTransformationInfo.mAlpha != alpha) {
13810            mTransformationInfo.mAlpha = alpha;
13811            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
13812            if (subclassHandlesAlpha) {
13813                mPrivateFlags |= PFLAG_ALPHA_SET;
13814                return true;
13815            } else {
13816                mPrivateFlags &= ~PFLAG_ALPHA_SET;
13817                mRenderNode.setAlpha(getFinalAlpha());
13818            }
13819        }
13820        return false;
13821    }
13822
13823    /**
13824     * This property is hidden and intended only for use by the Fade transition, which
13825     * animates it to produce a visual translucency that does not side-effect (or get
13826     * affected by) the real alpha property. This value is composited with the other
13827     * alpha value (and the AlphaAnimation value, when that is present) to produce
13828     * a final visual translucency result, which is what is passed into the DisplayList.
13829     *
13830     * @hide
13831     */
13832    public void setTransitionAlpha(float alpha) {
13833        ensureTransformationInfo();
13834        if (mTransformationInfo.mTransitionAlpha != alpha) {
13835            mTransformationInfo.mTransitionAlpha = alpha;
13836            mPrivateFlags &= ~PFLAG_ALPHA_SET;
13837            invalidateViewProperty(true, false);
13838            mRenderNode.setAlpha(getFinalAlpha());
13839        }
13840    }
13841
13842    /**
13843     * Calculates the visual alpha of this view, which is a combination of the actual
13844     * alpha value and the transitionAlpha value (if set).
13845     */
13846    private float getFinalAlpha() {
13847        if (mTransformationInfo != null) {
13848            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
13849        }
13850        return 1;
13851    }
13852
13853    /**
13854     * This property is hidden and intended only for use by the Fade transition, which
13855     * animates it to produce a visual translucency that does not side-effect (or get
13856     * affected by) the real alpha property. This value is composited with the other
13857     * alpha value (and the AlphaAnimation value, when that is present) to produce
13858     * a final visual translucency result, which is what is passed into the DisplayList.
13859     *
13860     * @hide
13861     */
13862    @ViewDebug.ExportedProperty(category = "drawing")
13863    public float getTransitionAlpha() {
13864        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
13865    }
13866
13867    /**
13868     * Top position of this view relative to its parent.
13869     *
13870     * @return The top of this view, in pixels.
13871     */
13872    @ViewDebug.CapturedViewProperty
13873    public final int getTop() {
13874        return mTop;
13875    }
13876
13877    /**
13878     * Sets the top position of this view relative to its parent. This method is meant to be called
13879     * by the layout system and should not generally be called otherwise, because the property
13880     * may be changed at any time by the layout.
13881     *
13882     * @param top The top of this view, in pixels.
13883     */
13884    public final void setTop(int top) {
13885        if (top != mTop) {
13886            final boolean matrixIsIdentity = hasIdentityMatrix();
13887            if (matrixIsIdentity) {
13888                if (mAttachInfo != null) {
13889                    int minTop;
13890                    int yLoc;
13891                    if (top < mTop) {
13892                        minTop = top;
13893                        yLoc = top - mTop;
13894                    } else {
13895                        minTop = mTop;
13896                        yLoc = 0;
13897                    }
13898                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
13899                }
13900            } else {
13901                // Double-invalidation is necessary to capture view's old and new areas
13902                invalidate(true);
13903            }
13904
13905            int width = mRight - mLeft;
13906            int oldHeight = mBottom - mTop;
13907
13908            mTop = top;
13909            mRenderNode.setTop(mTop);
13910
13911            sizeChange(width, mBottom - mTop, width, oldHeight);
13912
13913            if (!matrixIsIdentity) {
13914                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
13915                invalidate(true);
13916            }
13917            mBackgroundSizeChanged = true;
13918            if (mForegroundInfo != null) {
13919                mForegroundInfo.mBoundsChanged = true;
13920            }
13921            invalidateParentIfNeeded();
13922            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
13923                // View was rejected last time it was drawn by its parent; this may have changed
13924                invalidateParentIfNeeded();
13925            }
13926        }
13927    }
13928
13929    /**
13930     * Bottom position of this view relative to its parent.
13931     *
13932     * @return The bottom of this view, in pixels.
13933     */
13934    @ViewDebug.CapturedViewProperty
13935    public final int getBottom() {
13936        return mBottom;
13937    }
13938
13939    /**
13940     * True if this view has changed since the last time being drawn.
13941     *
13942     * @return The dirty state of this view.
13943     */
13944    public boolean isDirty() {
13945        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
13946    }
13947
13948    /**
13949     * Sets the bottom position of this view relative to its parent. This method is meant to be
13950     * called by the layout system and should not generally be called otherwise, because the
13951     * property may be changed at any time by the layout.
13952     *
13953     * @param bottom The bottom of this view, in pixels.
13954     */
13955    public final void setBottom(int bottom) {
13956        if (bottom != mBottom) {
13957            final boolean matrixIsIdentity = hasIdentityMatrix();
13958            if (matrixIsIdentity) {
13959                if (mAttachInfo != null) {
13960                    int maxBottom;
13961                    if (bottom < mBottom) {
13962                        maxBottom = mBottom;
13963                    } else {
13964                        maxBottom = bottom;
13965                    }
13966                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
13967                }
13968            } else {
13969                // Double-invalidation is necessary to capture view's old and new areas
13970                invalidate(true);
13971            }
13972
13973            int width = mRight - mLeft;
13974            int oldHeight = mBottom - mTop;
13975
13976            mBottom = bottom;
13977            mRenderNode.setBottom(mBottom);
13978
13979            sizeChange(width, mBottom - mTop, width, oldHeight);
13980
13981            if (!matrixIsIdentity) {
13982                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
13983                invalidate(true);
13984            }
13985            mBackgroundSizeChanged = 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     * Left position of this view relative to its parent.
13999     *
14000     * @return The left edge of this view, in pixels.
14001     */
14002    @ViewDebug.CapturedViewProperty
14003    public final int getLeft() {
14004        return mLeft;
14005    }
14006
14007    /**
14008     * Sets the left position of this view relative to its parent. This method is meant to be called
14009     * by the layout system and should not generally be called otherwise, because the property
14010     * may be changed at any time by the layout.
14011     *
14012     * @param left The left of this view, in pixels.
14013     */
14014    public final void setLeft(int left) {
14015        if (left != mLeft) {
14016            final boolean matrixIsIdentity = hasIdentityMatrix();
14017            if (matrixIsIdentity) {
14018                if (mAttachInfo != null) {
14019                    int minLeft;
14020                    int xLoc;
14021                    if (left < mLeft) {
14022                        minLeft = left;
14023                        xLoc = left - mLeft;
14024                    } else {
14025                        minLeft = mLeft;
14026                        xLoc = 0;
14027                    }
14028                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
14029                }
14030            } else {
14031                // Double-invalidation is necessary to capture view's old and new areas
14032                invalidate(true);
14033            }
14034
14035            int oldWidth = mRight - mLeft;
14036            int height = mBottom - mTop;
14037
14038            mLeft = left;
14039            mRenderNode.setLeft(left);
14040
14041            sizeChange(mRight - mLeft, height, oldWidth, height);
14042
14043            if (!matrixIsIdentity) {
14044                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
14045                invalidate(true);
14046            }
14047            mBackgroundSizeChanged = true;
14048            if (mForegroundInfo != null) {
14049                mForegroundInfo.mBoundsChanged = true;
14050            }
14051            invalidateParentIfNeeded();
14052            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
14053                // View was rejected last time it was drawn by its parent; this may have changed
14054                invalidateParentIfNeeded();
14055            }
14056        }
14057    }
14058
14059    /**
14060     * Right position of this view relative to its parent.
14061     *
14062     * @return The right edge of this view, in pixels.
14063     */
14064    @ViewDebug.CapturedViewProperty
14065    public final int getRight() {
14066        return mRight;
14067    }
14068
14069    /**
14070     * Sets the right position of this view relative to its parent. This method is meant to be called
14071     * by the layout system and should not generally be called otherwise, because the property
14072     * may be changed at any time by the layout.
14073     *
14074     * @param right The right of this view, in pixels.
14075     */
14076    public final void setRight(int right) {
14077        if (right != mRight) {
14078            final boolean matrixIsIdentity = hasIdentityMatrix();
14079            if (matrixIsIdentity) {
14080                if (mAttachInfo != null) {
14081                    int maxRight;
14082                    if (right < mRight) {
14083                        maxRight = mRight;
14084                    } else {
14085                        maxRight = right;
14086                    }
14087                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
14088                }
14089            } else {
14090                // Double-invalidation is necessary to capture view's old and new areas
14091                invalidate(true);
14092            }
14093
14094            int oldWidth = mRight - mLeft;
14095            int height = mBottom - mTop;
14096
14097            mRight = right;
14098            mRenderNode.setRight(mRight);
14099
14100            sizeChange(mRight - mLeft, height, oldWidth, height);
14101
14102            if (!matrixIsIdentity) {
14103                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
14104                invalidate(true);
14105            }
14106            mBackgroundSizeChanged = true;
14107            if (mForegroundInfo != null) {
14108                mForegroundInfo.mBoundsChanged = true;
14109            }
14110            invalidateParentIfNeeded();
14111            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
14112                // View was rejected last time it was drawn by its parent; this may have changed
14113                invalidateParentIfNeeded();
14114            }
14115        }
14116    }
14117
14118    /**
14119     * The visual x position of this view, in pixels. This is equivalent to the
14120     * {@link #setTranslationX(float) translationX} property plus the current
14121     * {@link #getLeft() left} property.
14122     *
14123     * @return The visual x position of this view, in pixels.
14124     */
14125    @ViewDebug.ExportedProperty(category = "drawing")
14126    public float getX() {
14127        return mLeft + getTranslationX();
14128    }
14129
14130    /**
14131     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
14132     * {@link #setTranslationX(float) translationX} property to be the difference between
14133     * the x value passed in and the current {@link #getLeft() left} property.
14134     *
14135     * @param x The visual x position of this view, in pixels.
14136     */
14137    public void setX(float x) {
14138        setTranslationX(x - mLeft);
14139    }
14140
14141    /**
14142     * The visual y position of this view, in pixels. This is equivalent to the
14143     * {@link #setTranslationY(float) translationY} property plus the current
14144     * {@link #getTop() top} property.
14145     *
14146     * @return The visual y position of this view, in pixels.
14147     */
14148    @ViewDebug.ExportedProperty(category = "drawing")
14149    public float getY() {
14150        return mTop + getTranslationY();
14151    }
14152
14153    /**
14154     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
14155     * {@link #setTranslationY(float) translationY} property to be the difference between
14156     * the y value passed in and the current {@link #getTop() top} property.
14157     *
14158     * @param y The visual y position of this view, in pixels.
14159     */
14160    public void setY(float y) {
14161        setTranslationY(y - mTop);
14162    }
14163
14164    /**
14165     * The visual z position of this view, in pixels. This is equivalent to the
14166     * {@link #setTranslationZ(float) translationZ} property plus the current
14167     * {@link #getElevation() elevation} property.
14168     *
14169     * @return The visual z position of this view, in pixels.
14170     */
14171    @ViewDebug.ExportedProperty(category = "drawing")
14172    public float getZ() {
14173        return getElevation() + getTranslationZ();
14174    }
14175
14176    /**
14177     * Sets the visual z position of this view, in pixels. This is equivalent to setting the
14178     * {@link #setTranslationZ(float) translationZ} property to be the difference between
14179     * the x value passed in and the current {@link #getElevation() elevation} property.
14180     *
14181     * @param z The visual z position of this view, in pixels.
14182     */
14183    public void setZ(float z) {
14184        setTranslationZ(z - getElevation());
14185    }
14186
14187    /**
14188     * The base elevation of this view relative to its parent, in pixels.
14189     *
14190     * @return The base depth position of the view, in pixels.
14191     */
14192    @ViewDebug.ExportedProperty(category = "drawing")
14193    public float getElevation() {
14194        return mRenderNode.getElevation();
14195    }
14196
14197    /**
14198     * Sets the base elevation of this view, in pixels.
14199     *
14200     * @attr ref android.R.styleable#View_elevation
14201     */
14202    public void setElevation(float elevation) {
14203        if (elevation != getElevation()) {
14204            invalidateViewProperty(true, false);
14205            mRenderNode.setElevation(elevation);
14206            invalidateViewProperty(false, true);
14207
14208            invalidateParentIfNeededAndWasQuickRejected();
14209        }
14210    }
14211
14212    /**
14213     * The horizontal location of this view relative to its {@link #getLeft() left} position.
14214     * This position is post-layout, in addition to wherever the object's
14215     * layout placed it.
14216     *
14217     * @return The horizontal position of this view relative to its left position, in pixels.
14218     */
14219    @ViewDebug.ExportedProperty(category = "drawing")
14220    public float getTranslationX() {
14221        return mRenderNode.getTranslationX();
14222    }
14223
14224    /**
14225     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
14226     * This effectively positions the object post-layout, in addition to wherever the object's
14227     * layout placed it.
14228     *
14229     * @param translationX The horizontal position of this view relative to its left position,
14230     * in pixels.
14231     *
14232     * @attr ref android.R.styleable#View_translationX
14233     */
14234    public void setTranslationX(float translationX) {
14235        if (translationX != getTranslationX()) {
14236            invalidateViewProperty(true, false);
14237            mRenderNode.setTranslationX(translationX);
14238            invalidateViewProperty(false, true);
14239
14240            invalidateParentIfNeededAndWasQuickRejected();
14241            notifySubtreeAccessibilityStateChangedIfNeeded();
14242        }
14243    }
14244
14245    /**
14246     * The vertical location of this view relative to its {@link #getTop() top} position.
14247     * This position is post-layout, in addition to wherever the object's
14248     * layout placed it.
14249     *
14250     * @return The vertical position of this view relative to its top position,
14251     * in pixels.
14252     */
14253    @ViewDebug.ExportedProperty(category = "drawing")
14254    public float getTranslationY() {
14255        return mRenderNode.getTranslationY();
14256    }
14257
14258    /**
14259     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
14260     * This effectively positions the object post-layout, in addition to wherever the object's
14261     * layout placed it.
14262     *
14263     * @param translationY The vertical position of this view relative to its top position,
14264     * in pixels.
14265     *
14266     * @attr ref android.R.styleable#View_translationY
14267     */
14268    public void setTranslationY(float translationY) {
14269        if (translationY != getTranslationY()) {
14270            invalidateViewProperty(true, false);
14271            mRenderNode.setTranslationY(translationY);
14272            invalidateViewProperty(false, true);
14273
14274            invalidateParentIfNeededAndWasQuickRejected();
14275            notifySubtreeAccessibilityStateChangedIfNeeded();
14276        }
14277    }
14278
14279    /**
14280     * The depth location of this view relative to its {@link #getElevation() elevation}.
14281     *
14282     * @return The depth of this view relative to its elevation.
14283     */
14284    @ViewDebug.ExportedProperty(category = "drawing")
14285    public float getTranslationZ() {
14286        return mRenderNode.getTranslationZ();
14287    }
14288
14289    /**
14290     * Sets the depth location of this view relative to its {@link #getElevation() elevation}.
14291     *
14292     * @attr ref android.R.styleable#View_translationZ
14293     */
14294    public void setTranslationZ(float translationZ) {
14295        if (translationZ != getTranslationZ()) {
14296            invalidateViewProperty(true, false);
14297            mRenderNode.setTranslationZ(translationZ);
14298            invalidateViewProperty(false, true);
14299
14300            invalidateParentIfNeededAndWasQuickRejected();
14301        }
14302    }
14303
14304    /** @hide */
14305    public void setAnimationMatrix(Matrix matrix) {
14306        invalidateViewProperty(true, false);
14307        mRenderNode.setAnimationMatrix(matrix);
14308        invalidateViewProperty(false, true);
14309
14310        invalidateParentIfNeededAndWasQuickRejected();
14311    }
14312
14313    /**
14314     * Returns the current StateListAnimator if exists.
14315     *
14316     * @return StateListAnimator or null if it does not exists
14317     * @see    #setStateListAnimator(android.animation.StateListAnimator)
14318     */
14319    public StateListAnimator getStateListAnimator() {
14320        return mStateListAnimator;
14321    }
14322
14323    /**
14324     * Attaches the provided StateListAnimator to this View.
14325     * <p>
14326     * Any previously attached StateListAnimator will be detached.
14327     *
14328     * @param stateListAnimator The StateListAnimator to update the view
14329     * @see android.animation.StateListAnimator
14330     */
14331    public void setStateListAnimator(StateListAnimator stateListAnimator) {
14332        if (mStateListAnimator == stateListAnimator) {
14333            return;
14334        }
14335        if (mStateListAnimator != null) {
14336            mStateListAnimator.setTarget(null);
14337        }
14338        mStateListAnimator = stateListAnimator;
14339        if (stateListAnimator != null) {
14340            stateListAnimator.setTarget(this);
14341            if (isAttachedToWindow()) {
14342                stateListAnimator.setState(getDrawableState());
14343            }
14344        }
14345    }
14346
14347    /**
14348     * Returns whether the Outline should be used to clip the contents of the View.
14349     * <p>
14350     * Note that this flag will only be respected if the View's Outline returns true from
14351     * {@link Outline#canClip()}.
14352     *
14353     * @see #setOutlineProvider(ViewOutlineProvider)
14354     * @see #setClipToOutline(boolean)
14355     */
14356    public final boolean getClipToOutline() {
14357        return mRenderNode.getClipToOutline();
14358    }
14359
14360    /**
14361     * Sets whether the View's Outline should be used to clip the contents of the View.
14362     * <p>
14363     * Only a single non-rectangular clip can be applied on a View at any time.
14364     * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float)
14365     * circular reveal} animation take priority over Outline clipping, and
14366     * child Outline clipping takes priority over Outline clipping done by a
14367     * parent.
14368     * <p>
14369     * Note that this flag will only be respected if the View's Outline returns true from
14370     * {@link Outline#canClip()}.
14371     *
14372     * @see #setOutlineProvider(ViewOutlineProvider)
14373     * @see #getClipToOutline()
14374     */
14375    public void setClipToOutline(boolean clipToOutline) {
14376        damageInParent();
14377        if (getClipToOutline() != clipToOutline) {
14378            mRenderNode.setClipToOutline(clipToOutline);
14379        }
14380    }
14381
14382    // correspond to the enum values of View_outlineProvider
14383    private static final int PROVIDER_BACKGROUND = 0;
14384    private static final int PROVIDER_NONE = 1;
14385    private static final int PROVIDER_BOUNDS = 2;
14386    private static final int PROVIDER_PADDED_BOUNDS = 3;
14387    private void setOutlineProviderFromAttribute(int providerInt) {
14388        switch (providerInt) {
14389            case PROVIDER_BACKGROUND:
14390                setOutlineProvider(ViewOutlineProvider.BACKGROUND);
14391                break;
14392            case PROVIDER_NONE:
14393                setOutlineProvider(null);
14394                break;
14395            case PROVIDER_BOUNDS:
14396                setOutlineProvider(ViewOutlineProvider.BOUNDS);
14397                break;
14398            case PROVIDER_PADDED_BOUNDS:
14399                setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS);
14400                break;
14401        }
14402    }
14403
14404    /**
14405     * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines
14406     * the shape of the shadow it casts, and enables outline clipping.
14407     * <p>
14408     * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline
14409     * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the
14410     * outline provider with this method allows this behavior to be overridden.
14411     * <p>
14412     * If the ViewOutlineProvider is null, if querying it for an outline returns false,
14413     * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast.
14414     * <p>
14415     * Only outlines that return true from {@link Outline#canClip()} may be used for clipping.
14416     *
14417     * @see #setClipToOutline(boolean)
14418     * @see #getClipToOutline()
14419     * @see #getOutlineProvider()
14420     */
14421    public void setOutlineProvider(ViewOutlineProvider provider) {
14422        mOutlineProvider = provider;
14423        invalidateOutline();
14424    }
14425
14426    /**
14427     * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline
14428     * that defines the shape of the shadow it casts, and enables outline clipping.
14429     *
14430     * @see #setOutlineProvider(ViewOutlineProvider)
14431     */
14432    public ViewOutlineProvider getOutlineProvider() {
14433        return mOutlineProvider;
14434    }
14435
14436    /**
14437     * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider}
14438     *
14439     * @see #setOutlineProvider(ViewOutlineProvider)
14440     */
14441    public void invalidateOutline() {
14442        rebuildOutline();
14443
14444        notifySubtreeAccessibilityStateChangedIfNeeded();
14445        invalidateViewProperty(false, false);
14446    }
14447
14448    /**
14449     * Internal version of {@link #invalidateOutline()} which invalidates the
14450     * outline without invalidating the view itself. This is intended to be called from
14451     * within methods in the View class itself which are the result of the view being
14452     * invalidated already. For example, when we are drawing the background of a View,
14453     * we invalidate the outline in case it changed in the meantime, but we do not
14454     * need to invalidate the view because we're already drawing the background as part
14455     * of drawing the view in response to an earlier invalidation of the view.
14456     */
14457    private void rebuildOutline() {
14458        // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow()
14459        if (mAttachInfo == null) return;
14460
14461        if (mOutlineProvider == null) {
14462            // no provider, remove outline
14463            mRenderNode.setOutline(null);
14464        } else {
14465            final Outline outline = mAttachInfo.mTmpOutline;
14466            outline.setEmpty();
14467            outline.setAlpha(1.0f);
14468
14469            mOutlineProvider.getOutline(this, outline);
14470            mRenderNode.setOutline(outline);
14471        }
14472    }
14473
14474    /**
14475     * HierarchyViewer only
14476     *
14477     * @hide
14478     */
14479    @ViewDebug.ExportedProperty(category = "drawing")
14480    public boolean hasShadow() {
14481        return mRenderNode.hasShadow();
14482    }
14483
14484
14485    /** @hide */
14486    public void setRevealClip(boolean shouldClip, float x, float y, float radius) {
14487        mRenderNode.setRevealClip(shouldClip, x, y, radius);
14488        invalidateViewProperty(false, false);
14489    }
14490
14491    /**
14492     * Hit rectangle in parent's coordinates
14493     *
14494     * @param outRect The hit rectangle of the view.
14495     */
14496    public void getHitRect(Rect outRect) {
14497        if (hasIdentityMatrix() || mAttachInfo == null) {
14498            outRect.set(mLeft, mTop, mRight, mBottom);
14499        } else {
14500            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
14501            tmpRect.set(0, 0, getWidth(), getHeight());
14502            getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect)
14503            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
14504                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
14505        }
14506    }
14507
14508    /**
14509     * Determines whether the given point, in local coordinates is inside the view.
14510     */
14511    /*package*/ final boolean pointInView(float localX, float localY) {
14512        return pointInView(localX, localY, 0);
14513    }
14514
14515    /**
14516     * Utility method to determine whether the given point, in local coordinates,
14517     * is inside the view, where the area of the view is expanded by the slop factor.
14518     * This method is called while processing touch-move events to determine if the event
14519     * is still within the view.
14520     *
14521     * @hide
14522     */
14523    public boolean pointInView(float localX, float localY, float slop) {
14524        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
14525                localY < ((mBottom - mTop) + slop);
14526    }
14527
14528    /**
14529     * When a view has focus and the user navigates away from it, the next view is searched for
14530     * starting from the rectangle filled in by this method.
14531     *
14532     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
14533     * of the view.  However, if your view maintains some idea of internal selection,
14534     * such as a cursor, or a selected row or column, you should override this method and
14535     * fill in a more specific rectangle.
14536     *
14537     * @param r The rectangle to fill in, in this view's coordinates.
14538     */
14539    public void getFocusedRect(Rect r) {
14540        getDrawingRect(r);
14541    }
14542
14543    /**
14544     * If some part of this view is not clipped by any of its parents, then
14545     * return that area in r in global (root) coordinates. To convert r to local
14546     * coordinates (without taking possible View rotations into account), offset
14547     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
14548     * If the view is completely clipped or translated out, return false.
14549     *
14550     * @param r If true is returned, r holds the global coordinates of the
14551     *        visible portion of this view.
14552     * @param globalOffset If true is returned, globalOffset holds the dx,dy
14553     *        between this view and its root. globalOffet may be null.
14554     * @return true if r is non-empty (i.e. part of the view is visible at the
14555     *         root level.
14556     */
14557    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
14558        int width = mRight - mLeft;
14559        int height = mBottom - mTop;
14560        if (width > 0 && height > 0) {
14561            r.set(0, 0, width, height);
14562            if (globalOffset != null) {
14563                globalOffset.set(-mScrollX, -mScrollY);
14564            }
14565            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
14566        }
14567        return false;
14568    }
14569
14570    public final boolean getGlobalVisibleRect(Rect r) {
14571        return getGlobalVisibleRect(r, null);
14572    }
14573
14574    public final boolean getLocalVisibleRect(Rect r) {
14575        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
14576        if (getGlobalVisibleRect(r, offset)) {
14577            r.offset(-offset.x, -offset.y); // make r local
14578            return true;
14579        }
14580        return false;
14581    }
14582
14583    /**
14584     * Offset this view's vertical location by the specified number of pixels.
14585     *
14586     * @param offset the number of pixels to offset the view by
14587     */
14588    public void offsetTopAndBottom(int offset) {
14589        if (offset != 0) {
14590            final boolean matrixIsIdentity = hasIdentityMatrix();
14591            if (matrixIsIdentity) {
14592                if (isHardwareAccelerated()) {
14593                    invalidateViewProperty(false, false);
14594                } else {
14595                    final ViewParent p = mParent;
14596                    if (p != null && mAttachInfo != null) {
14597                        final Rect r = mAttachInfo.mTmpInvalRect;
14598                        int minTop;
14599                        int maxBottom;
14600                        int yLoc;
14601                        if (offset < 0) {
14602                            minTop = mTop + offset;
14603                            maxBottom = mBottom;
14604                            yLoc = offset;
14605                        } else {
14606                            minTop = mTop;
14607                            maxBottom = mBottom + offset;
14608                            yLoc = 0;
14609                        }
14610                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
14611                        p.invalidateChild(this, r);
14612                    }
14613                }
14614            } else {
14615                invalidateViewProperty(false, false);
14616            }
14617
14618            mTop += offset;
14619            mBottom += offset;
14620            mRenderNode.offsetTopAndBottom(offset);
14621            if (isHardwareAccelerated()) {
14622                invalidateViewProperty(false, false);
14623                invalidateParentIfNeededAndWasQuickRejected();
14624            } else {
14625                if (!matrixIsIdentity) {
14626                    invalidateViewProperty(false, true);
14627                }
14628                invalidateParentIfNeeded();
14629            }
14630            notifySubtreeAccessibilityStateChangedIfNeeded();
14631        }
14632    }
14633
14634    /**
14635     * Offset this view's horizontal location by the specified amount of pixels.
14636     *
14637     * @param offset the number of pixels to offset the view by
14638     */
14639    public void offsetLeftAndRight(int offset) {
14640        if (offset != 0) {
14641            final boolean matrixIsIdentity = hasIdentityMatrix();
14642            if (matrixIsIdentity) {
14643                if (isHardwareAccelerated()) {
14644                    invalidateViewProperty(false, false);
14645                } else {
14646                    final ViewParent p = mParent;
14647                    if (p != null && mAttachInfo != null) {
14648                        final Rect r = mAttachInfo.mTmpInvalRect;
14649                        int minLeft;
14650                        int maxRight;
14651                        if (offset < 0) {
14652                            minLeft = mLeft + offset;
14653                            maxRight = mRight;
14654                        } else {
14655                            minLeft = mLeft;
14656                            maxRight = mRight + offset;
14657                        }
14658                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
14659                        p.invalidateChild(this, r);
14660                    }
14661                }
14662            } else {
14663                invalidateViewProperty(false, false);
14664            }
14665
14666            mLeft += offset;
14667            mRight += offset;
14668            mRenderNode.offsetLeftAndRight(offset);
14669            if (isHardwareAccelerated()) {
14670                invalidateViewProperty(false, false);
14671                invalidateParentIfNeededAndWasQuickRejected();
14672            } else {
14673                if (!matrixIsIdentity) {
14674                    invalidateViewProperty(false, true);
14675                }
14676                invalidateParentIfNeeded();
14677            }
14678            notifySubtreeAccessibilityStateChangedIfNeeded();
14679        }
14680    }
14681
14682    /**
14683     * Get the LayoutParams associated with this view. All views should have
14684     * layout parameters. These supply parameters to the <i>parent</i> of this
14685     * view specifying how it should be arranged. There are many subclasses of
14686     * ViewGroup.LayoutParams, and these correspond to the different subclasses
14687     * of ViewGroup that are responsible for arranging their children.
14688     *
14689     * This method may return null if this View is not attached to a parent
14690     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
14691     * was not invoked successfully. When a View is attached to a parent
14692     * ViewGroup, this method must not return null.
14693     *
14694     * @return The LayoutParams associated with this view, or null if no
14695     *         parameters have been set yet
14696     */
14697    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
14698    public ViewGroup.LayoutParams getLayoutParams() {
14699        return mLayoutParams;
14700    }
14701
14702    /**
14703     * Set the layout parameters associated with this view. These supply
14704     * parameters to the <i>parent</i> of this view specifying how it should be
14705     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
14706     * correspond to the different subclasses of ViewGroup that are responsible
14707     * for arranging their children.
14708     *
14709     * @param params The layout parameters for this view, cannot be null
14710     */
14711    public void setLayoutParams(ViewGroup.LayoutParams params) {
14712        if (params == null) {
14713            throw new NullPointerException("Layout parameters cannot be null");
14714        }
14715        mLayoutParams = params;
14716        resolveLayoutParams();
14717        if (mParent instanceof ViewGroup) {
14718            ((ViewGroup) mParent).onSetLayoutParams(this, params);
14719        }
14720        requestLayout();
14721    }
14722
14723    /**
14724     * Resolve the layout parameters depending on the resolved layout direction
14725     *
14726     * @hide
14727     */
14728    public void resolveLayoutParams() {
14729        if (mLayoutParams != null) {
14730            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
14731        }
14732    }
14733
14734    /**
14735     * Set the scrolled position of your view. This will cause a call to
14736     * {@link #onScrollChanged(int, int, int, int)} and the view will be
14737     * invalidated.
14738     * @param x the x position to scroll to
14739     * @param y the y position to scroll to
14740     */
14741    public void scrollTo(int x, int y) {
14742        if (mScrollX != x || mScrollY != y) {
14743            int oldX = mScrollX;
14744            int oldY = mScrollY;
14745            mScrollX = x;
14746            mScrollY = y;
14747            invalidateParentCaches();
14748            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
14749            if (!awakenScrollBars()) {
14750                postInvalidateOnAnimation();
14751            }
14752        }
14753    }
14754
14755    /**
14756     * Move the scrolled position of your view. This will cause a call to
14757     * {@link #onScrollChanged(int, int, int, int)} and the view will be
14758     * invalidated.
14759     * @param x the amount of pixels to scroll by horizontally
14760     * @param y the amount of pixels to scroll by vertically
14761     */
14762    public void scrollBy(int x, int y) {
14763        scrollTo(mScrollX + x, mScrollY + y);
14764    }
14765
14766    /**
14767     * <p>Trigger the scrollbars to draw. When invoked this method starts an
14768     * animation to fade the scrollbars out after a default delay. If a subclass
14769     * provides animated scrolling, the start delay should equal the duration
14770     * of the scrolling animation.</p>
14771     *
14772     * <p>The animation starts only if at least one of the scrollbars is
14773     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
14774     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
14775     * this method returns true, and false otherwise. If the animation is
14776     * started, this method calls {@link #invalidate()}; in that case the
14777     * caller should not call {@link #invalidate()}.</p>
14778     *
14779     * <p>This method should be invoked every time a subclass directly updates
14780     * the scroll parameters.</p>
14781     *
14782     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
14783     * and {@link #scrollTo(int, int)}.</p>
14784     *
14785     * @return true if the animation is played, false otherwise
14786     *
14787     * @see #awakenScrollBars(int)
14788     * @see #scrollBy(int, int)
14789     * @see #scrollTo(int, int)
14790     * @see #isHorizontalScrollBarEnabled()
14791     * @see #isVerticalScrollBarEnabled()
14792     * @see #setHorizontalScrollBarEnabled(boolean)
14793     * @see #setVerticalScrollBarEnabled(boolean)
14794     */
14795    protected boolean awakenScrollBars() {
14796        return mScrollCache != null &&
14797                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
14798    }
14799
14800    /**
14801     * Trigger the scrollbars to draw.
14802     * This method differs from awakenScrollBars() only in its default duration.
14803     * initialAwakenScrollBars() will show the scroll bars for longer than
14804     * usual to give the user more of a chance to notice them.
14805     *
14806     * @return true if the animation is played, false otherwise.
14807     */
14808    private boolean initialAwakenScrollBars() {
14809        return mScrollCache != null &&
14810                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
14811    }
14812
14813    /**
14814     * <p>
14815     * Trigger the scrollbars to draw. When invoked this method starts an
14816     * animation to fade the scrollbars out after a fixed delay. If a subclass
14817     * provides animated scrolling, the start delay should equal the duration of
14818     * the scrolling animation.
14819     * </p>
14820     *
14821     * <p>
14822     * The animation starts only if at least one of the scrollbars is enabled,
14823     * as specified by {@link #isHorizontalScrollBarEnabled()} and
14824     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
14825     * this method returns true, and false otherwise. If the animation is
14826     * started, this method calls {@link #invalidate()}; in that case the caller
14827     * should not call {@link #invalidate()}.
14828     * </p>
14829     *
14830     * <p>
14831     * This method should be invoked every time a subclass directly updates the
14832     * scroll parameters.
14833     * </p>
14834     *
14835     * @param startDelay the delay, in milliseconds, after which the animation
14836     *        should start; when the delay is 0, the animation starts
14837     *        immediately
14838     * @return true if the animation is played, false otherwise
14839     *
14840     * @see #scrollBy(int, int)
14841     * @see #scrollTo(int, int)
14842     * @see #isHorizontalScrollBarEnabled()
14843     * @see #isVerticalScrollBarEnabled()
14844     * @see #setHorizontalScrollBarEnabled(boolean)
14845     * @see #setVerticalScrollBarEnabled(boolean)
14846     */
14847    protected boolean awakenScrollBars(int startDelay) {
14848        return awakenScrollBars(startDelay, true);
14849    }
14850
14851    /**
14852     * <p>
14853     * Trigger the scrollbars to draw. When invoked this method starts an
14854     * animation to fade the scrollbars out after a fixed delay. If a subclass
14855     * provides animated scrolling, the start delay should equal the duration of
14856     * the scrolling animation.
14857     * </p>
14858     *
14859     * <p>
14860     * The animation starts only if at least one of the scrollbars is enabled,
14861     * as specified by {@link #isHorizontalScrollBarEnabled()} and
14862     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
14863     * this method returns true, and false otherwise. If the animation is
14864     * started, this method calls {@link #invalidate()} if the invalidate parameter
14865     * is set to true; in that case the caller
14866     * should not call {@link #invalidate()}.
14867     * </p>
14868     *
14869     * <p>
14870     * This method should be invoked every time a subclass directly updates the
14871     * scroll parameters.
14872     * </p>
14873     *
14874     * @param startDelay the delay, in milliseconds, after which the animation
14875     *        should start; when the delay is 0, the animation starts
14876     *        immediately
14877     *
14878     * @param invalidate Whether this method should call invalidate
14879     *
14880     * @return true if the animation is played, false otherwise
14881     *
14882     * @see #scrollBy(int, int)
14883     * @see #scrollTo(int, int)
14884     * @see #isHorizontalScrollBarEnabled()
14885     * @see #isVerticalScrollBarEnabled()
14886     * @see #setHorizontalScrollBarEnabled(boolean)
14887     * @see #setVerticalScrollBarEnabled(boolean)
14888     */
14889    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
14890        final ScrollabilityCache scrollCache = mScrollCache;
14891
14892        if (scrollCache == null || !scrollCache.fadeScrollBars) {
14893            return false;
14894        }
14895
14896        if (scrollCache.scrollBar == null) {
14897            scrollCache.scrollBar = new ScrollBarDrawable();
14898            scrollCache.scrollBar.setState(getDrawableState());
14899            scrollCache.scrollBar.setCallback(this);
14900        }
14901
14902        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
14903
14904            if (invalidate) {
14905                // Invalidate to show the scrollbars
14906                postInvalidateOnAnimation();
14907            }
14908
14909            if (scrollCache.state == ScrollabilityCache.OFF) {
14910                // FIXME: this is copied from WindowManagerService.
14911                // We should get this value from the system when it
14912                // is possible to do so.
14913                final int KEY_REPEAT_FIRST_DELAY = 750;
14914                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
14915            }
14916
14917            // Tell mScrollCache when we should start fading. This may
14918            // extend the fade start time if one was already scheduled
14919            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
14920            scrollCache.fadeStartTime = fadeStartTime;
14921            scrollCache.state = ScrollabilityCache.ON;
14922
14923            // Schedule our fader to run, unscheduling any old ones first
14924            if (mAttachInfo != null) {
14925                mAttachInfo.mHandler.removeCallbacks(scrollCache);
14926                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
14927            }
14928
14929            return true;
14930        }
14931
14932        return false;
14933    }
14934
14935    /**
14936     * Do not invalidate views which are not visible and which are not running an animation. They
14937     * will not get drawn and they should not set dirty flags as if they will be drawn
14938     */
14939    private boolean skipInvalidate() {
14940        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
14941                (!(mParent instanceof ViewGroup) ||
14942                        !((ViewGroup) mParent).isViewTransitioning(this));
14943    }
14944
14945    /**
14946     * Mark the area defined by dirty as needing to be drawn. If the view is
14947     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
14948     * point in the future.
14949     * <p>
14950     * This must be called from a UI thread. To call from a non-UI thread, call
14951     * {@link #postInvalidate()}.
14952     * <p>
14953     * <b>WARNING:</b> In API 19 and below, this method may be destructive to
14954     * {@code dirty}.
14955     *
14956     * @param dirty the rectangle representing the bounds of the dirty region
14957     */
14958    public void invalidate(Rect dirty) {
14959        final int scrollX = mScrollX;
14960        final int scrollY = mScrollY;
14961        invalidateInternal(dirty.left - scrollX, dirty.top - scrollY,
14962                dirty.right - scrollX, dirty.bottom - scrollY, true, false);
14963    }
14964
14965    /**
14966     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The
14967     * coordinates of the dirty rect are relative to the view. If the view is
14968     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
14969     * point in the future.
14970     * <p>
14971     * This must be called from a UI thread. To call from a non-UI thread, call
14972     * {@link #postInvalidate()}.
14973     *
14974     * @param l the left position of the dirty region
14975     * @param t the top position of the dirty region
14976     * @param r the right position of the dirty region
14977     * @param b the bottom position of the dirty region
14978     */
14979    public void invalidate(int l, int t, int r, int b) {
14980        final int scrollX = mScrollX;
14981        final int scrollY = mScrollY;
14982        invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false);
14983    }
14984
14985    /**
14986     * Invalidate the whole view. If the view is visible,
14987     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
14988     * the future.
14989     * <p>
14990     * This must be called from a UI thread. To call from a non-UI thread, call
14991     * {@link #postInvalidate()}.
14992     */
14993    public void invalidate() {
14994        invalidate(true);
14995    }
14996
14997    /**
14998     * This is where the invalidate() work actually happens. A full invalidate()
14999     * causes the drawing cache to be invalidated, but this function can be
15000     * called with invalidateCache set to false to skip that invalidation step
15001     * for cases that do not need it (for example, a component that remains at
15002     * the same dimensions with the same content).
15003     *
15004     * @param invalidateCache Whether the drawing cache for this view should be
15005     *            invalidated as well. This is usually true for a full
15006     *            invalidate, but may be set to false if the View's contents or
15007     *            dimensions have not changed.
15008     * @hide
15009     */
15010    public void invalidate(boolean invalidateCache) {
15011        invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
15012    }
15013
15014    void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
15015            boolean fullInvalidate) {
15016        if (mGhostView != null) {
15017            mGhostView.invalidate(true);
15018            return;
15019        }
15020
15021        if (skipInvalidate()) {
15022            return;
15023        }
15024
15025        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)
15026                || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID)
15027                || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED
15028                || (fullInvalidate && isOpaque() != mLastIsOpaque)) {
15029            if (fullInvalidate) {
15030                mLastIsOpaque = isOpaque();
15031                mPrivateFlags &= ~PFLAG_DRAWN;
15032            }
15033
15034            mPrivateFlags |= PFLAG_DIRTY;
15035
15036            if (invalidateCache) {
15037                mPrivateFlags |= PFLAG_INVALIDATED;
15038                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
15039            }
15040
15041            // Propagate the damage rectangle to the parent view.
15042            final AttachInfo ai = mAttachInfo;
15043            final ViewParent p = mParent;
15044            if (p != null && ai != null && l < r && t < b) {
15045                final Rect damage = ai.mTmpInvalRect;
15046                damage.set(l, t, r, b);
15047                p.invalidateChild(this, damage);
15048            }
15049
15050            // Damage the entire projection receiver, if necessary.
15051            if (mBackground != null && mBackground.isProjected()) {
15052                final View receiver = getProjectionReceiver();
15053                if (receiver != null) {
15054                    receiver.damageInParent();
15055                }
15056            }
15057        }
15058    }
15059
15060    /**
15061     * @return this view's projection receiver, or {@code null} if none exists
15062     */
15063    private View getProjectionReceiver() {
15064        ViewParent p = getParent();
15065        while (p != null && p instanceof View) {
15066            final View v = (View) p;
15067            if (v.isProjectionReceiver()) {
15068                return v;
15069            }
15070            p = p.getParent();
15071        }
15072
15073        return null;
15074    }
15075
15076    /**
15077     * @return whether the view is a projection receiver
15078     */
15079    private boolean isProjectionReceiver() {
15080        return mBackground != null;
15081    }
15082
15083    /**
15084     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
15085     * set any flags or handle all of the cases handled by the default invalidation methods.
15086     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
15087     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
15088     * walk up the hierarchy, transforming the dirty rect as necessary.
15089     *
15090     * The method also handles normal invalidation logic if display list properties are not
15091     * being used in this view. The invalidateParent and forceRedraw flags are used by that
15092     * backup approach, to handle these cases used in the various property-setting methods.
15093     *
15094     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
15095     * are not being used in this view
15096     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
15097     * list properties are not being used in this view
15098     */
15099    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
15100        if (!isHardwareAccelerated()
15101                || !mRenderNode.isValid()
15102                || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) {
15103            if (invalidateParent) {
15104                invalidateParentCaches();
15105            }
15106            if (forceRedraw) {
15107                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
15108            }
15109            invalidate(false);
15110        } else {
15111            damageInParent();
15112        }
15113    }
15114
15115    /**
15116     * Tells the parent view to damage this view's bounds.
15117     *
15118     * @hide
15119     */
15120    protected void damageInParent() {
15121        if (mParent != null && mAttachInfo != null) {
15122            mParent.onDescendantInvalidated(this, this);
15123        }
15124    }
15125
15126    /**
15127     * Utility method to transform a given Rect by the current matrix of this view.
15128     */
15129    void transformRect(final Rect rect) {
15130        if (!getMatrix().isIdentity()) {
15131            RectF boundingRect = mAttachInfo.mTmpTransformRect;
15132            boundingRect.set(rect);
15133            getMatrix().mapRect(boundingRect);
15134            rect.set((int) Math.floor(boundingRect.left),
15135                    (int) Math.floor(boundingRect.top),
15136                    (int) Math.ceil(boundingRect.right),
15137                    (int) Math.ceil(boundingRect.bottom));
15138        }
15139    }
15140
15141    /**
15142     * Used to indicate that the parent of this view should clear its caches. This functionality
15143     * is used to force the parent to rebuild its display list (when hardware-accelerated),
15144     * which is necessary when various parent-managed properties of the view change, such as
15145     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
15146     * clears the parent caches and does not causes an invalidate event.
15147     *
15148     * @hide
15149     */
15150    protected void invalidateParentCaches() {
15151        if (mParent instanceof View) {
15152            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
15153        }
15154    }
15155
15156    /**
15157     * Used to indicate that the parent of this view should be invalidated. This functionality
15158     * is used to force the parent to rebuild its display list (when hardware-accelerated),
15159     * which is necessary when various parent-managed properties of the view change, such as
15160     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
15161     * an invalidation event to the parent.
15162     *
15163     * @hide
15164     */
15165    protected void invalidateParentIfNeeded() {
15166        if (isHardwareAccelerated() && mParent instanceof View) {
15167            ((View) mParent).invalidate(true);
15168        }
15169    }
15170
15171    /**
15172     * @hide
15173     */
15174    protected void invalidateParentIfNeededAndWasQuickRejected() {
15175        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) {
15176            // View was rejected last time it was drawn by its parent; this may have changed
15177            invalidateParentIfNeeded();
15178        }
15179    }
15180
15181    /**
15182     * Indicates whether this View is opaque. An opaque View guarantees that it will
15183     * draw all the pixels overlapping its bounds using a fully opaque color.
15184     *
15185     * Subclasses of View should override this method whenever possible to indicate
15186     * whether an instance is opaque. Opaque Views are treated in a special way by
15187     * the View hierarchy, possibly allowing it to perform optimizations during
15188     * invalidate/draw passes.
15189     *
15190     * @return True if this View is guaranteed to be fully opaque, false otherwise.
15191     */
15192    @ViewDebug.ExportedProperty(category = "drawing")
15193    public boolean isOpaque() {
15194        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
15195                getFinalAlpha() >= 1.0f;
15196    }
15197
15198    /**
15199     * @hide
15200     */
15201    protected void computeOpaqueFlags() {
15202        // Opaque if:
15203        //   - Has a background
15204        //   - Background is opaque
15205        //   - Doesn't have scrollbars or scrollbars overlay
15206
15207        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
15208            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
15209        } else {
15210            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
15211        }
15212
15213        final int flags = mViewFlags;
15214        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
15215                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
15216                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
15217            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
15218        } else {
15219            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
15220        }
15221    }
15222
15223    /**
15224     * @hide
15225     */
15226    protected boolean hasOpaqueScrollbars() {
15227        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
15228    }
15229
15230    /**
15231     * @return A handler associated with the thread running the View. This
15232     * handler can be used to pump events in the UI events queue.
15233     */
15234    public Handler getHandler() {
15235        final AttachInfo attachInfo = mAttachInfo;
15236        if (attachInfo != null) {
15237            return attachInfo.mHandler;
15238        }
15239        return null;
15240    }
15241
15242    /**
15243     * Returns the queue of runnable for this view.
15244     *
15245     * @return the queue of runnables for this view
15246     */
15247    private HandlerActionQueue getRunQueue() {
15248        if (mRunQueue == null) {
15249            mRunQueue = new HandlerActionQueue();
15250        }
15251        return mRunQueue;
15252    }
15253
15254    /**
15255     * Gets the view root associated with the View.
15256     * @return The view root, or null if none.
15257     * @hide
15258     */
15259    public ViewRootImpl getViewRootImpl() {
15260        if (mAttachInfo != null) {
15261            return mAttachInfo.mViewRootImpl;
15262        }
15263        return null;
15264    }
15265
15266    /**
15267     * @hide
15268     */
15269    public ThreadedRenderer getThreadedRenderer() {
15270        return mAttachInfo != null ? mAttachInfo.mThreadedRenderer : null;
15271    }
15272
15273    /**
15274     * <p>Causes the Runnable to be added to the message queue.
15275     * The runnable will be run on the user interface thread.</p>
15276     *
15277     * @param action The Runnable that will be executed.
15278     *
15279     * @return Returns true if the Runnable was successfully placed in to the
15280     *         message queue.  Returns false on failure, usually because the
15281     *         looper processing the message queue is exiting.
15282     *
15283     * @see #postDelayed
15284     * @see #removeCallbacks
15285     */
15286    public boolean post(Runnable action) {
15287        final AttachInfo attachInfo = mAttachInfo;
15288        if (attachInfo != null) {
15289            return attachInfo.mHandler.post(action);
15290        }
15291
15292        // Postpone the runnable until we know on which thread it needs to run.
15293        // Assume that the runnable will be successfully placed after attach.
15294        getRunQueue().post(action);
15295        return true;
15296    }
15297
15298    /**
15299     * <p>Causes the Runnable to be added to the message queue, to be run
15300     * after the specified amount of time elapses.
15301     * The runnable will be run on the user interface thread.</p>
15302     *
15303     * @param action The Runnable that will be executed.
15304     * @param delayMillis The delay (in milliseconds) until the Runnable
15305     *        will be executed.
15306     *
15307     * @return true if the Runnable was successfully placed in to the
15308     *         message queue.  Returns false on failure, usually because the
15309     *         looper processing the message queue is exiting.  Note that a
15310     *         result of true does not mean the Runnable will be processed --
15311     *         if the looper is quit before the delivery time of the message
15312     *         occurs then the message will be dropped.
15313     *
15314     * @see #post
15315     * @see #removeCallbacks
15316     */
15317    public boolean postDelayed(Runnable action, long delayMillis) {
15318        final AttachInfo attachInfo = mAttachInfo;
15319        if (attachInfo != null) {
15320            return attachInfo.mHandler.postDelayed(action, delayMillis);
15321        }
15322
15323        // Postpone the runnable until we know on which thread it needs to run.
15324        // Assume that the runnable will be successfully placed after attach.
15325        getRunQueue().postDelayed(action, delayMillis);
15326        return true;
15327    }
15328
15329    /**
15330     * <p>Causes the Runnable to execute on the next animation time step.
15331     * The runnable will be run on the user interface thread.</p>
15332     *
15333     * @param action The Runnable that will be executed.
15334     *
15335     * @see #postOnAnimationDelayed
15336     * @see #removeCallbacks
15337     */
15338    public void postOnAnimation(Runnable action) {
15339        final AttachInfo attachInfo = mAttachInfo;
15340        if (attachInfo != null) {
15341            attachInfo.mViewRootImpl.mChoreographer.postCallback(
15342                    Choreographer.CALLBACK_ANIMATION, action, null);
15343        } else {
15344            // Postpone the runnable until we know
15345            // on which thread it needs to run.
15346            getRunQueue().post(action);
15347        }
15348    }
15349
15350    /**
15351     * <p>Causes the Runnable to execute on the next animation time step,
15352     * after the specified amount of time elapses.
15353     * The runnable will be run on the user interface thread.</p>
15354     *
15355     * @param action The Runnable that will be executed.
15356     * @param delayMillis The delay (in milliseconds) until the Runnable
15357     *        will be executed.
15358     *
15359     * @see #postOnAnimation
15360     * @see #removeCallbacks
15361     */
15362    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
15363        final AttachInfo attachInfo = mAttachInfo;
15364        if (attachInfo != null) {
15365            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
15366                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
15367        } else {
15368            // Postpone the runnable until we know
15369            // on which thread it needs to run.
15370            getRunQueue().postDelayed(action, delayMillis);
15371        }
15372    }
15373
15374    /**
15375     * <p>Removes the specified Runnable from the message queue.</p>
15376     *
15377     * @param action The Runnable to remove from the message handling queue
15378     *
15379     * @return true if this view could ask the Handler to remove the Runnable,
15380     *         false otherwise. When the returned value is true, the Runnable
15381     *         may or may not have been actually removed from the message queue
15382     *         (for instance, if the Runnable was not in the queue already.)
15383     *
15384     * @see #post
15385     * @see #postDelayed
15386     * @see #postOnAnimation
15387     * @see #postOnAnimationDelayed
15388     */
15389    public boolean removeCallbacks(Runnable action) {
15390        if (action != null) {
15391            final AttachInfo attachInfo = mAttachInfo;
15392            if (attachInfo != null) {
15393                attachInfo.mHandler.removeCallbacks(action);
15394                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15395                        Choreographer.CALLBACK_ANIMATION, action, null);
15396            }
15397            getRunQueue().removeCallbacks(action);
15398        }
15399        return true;
15400    }
15401
15402    /**
15403     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
15404     * Use this to invalidate the View from a non-UI thread.</p>
15405     *
15406     * <p>This method can be invoked from outside of the UI thread
15407     * only when this View is attached to a window.</p>
15408     *
15409     * @see #invalidate()
15410     * @see #postInvalidateDelayed(long)
15411     */
15412    public void postInvalidate() {
15413        postInvalidateDelayed(0);
15414    }
15415
15416    /**
15417     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
15418     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
15419     *
15420     * <p>This method can be invoked from outside of the UI thread
15421     * only when this View is attached to a window.</p>
15422     *
15423     * @param left The left coordinate of the rectangle to invalidate.
15424     * @param top The top coordinate of the rectangle to invalidate.
15425     * @param right The right coordinate of the rectangle to invalidate.
15426     * @param bottom The bottom coordinate of the rectangle to invalidate.
15427     *
15428     * @see #invalidate(int, int, int, int)
15429     * @see #invalidate(Rect)
15430     * @see #postInvalidateDelayed(long, int, int, int, int)
15431     */
15432    public void postInvalidate(int left, int top, int right, int bottom) {
15433        postInvalidateDelayed(0, left, top, right, bottom);
15434    }
15435
15436    /**
15437     * <p>Cause an invalidate to happen on a subsequent cycle through the event
15438     * loop. Waits for the specified amount of time.</p>
15439     *
15440     * <p>This method can be invoked from outside of the UI thread
15441     * only when this View is attached to a window.</p>
15442     *
15443     * @param delayMilliseconds the duration in milliseconds to delay the
15444     *         invalidation by
15445     *
15446     * @see #invalidate()
15447     * @see #postInvalidate()
15448     */
15449    public void postInvalidateDelayed(long delayMilliseconds) {
15450        // We try only with the AttachInfo because there's no point in invalidating
15451        // if we are not attached to our window
15452        final AttachInfo attachInfo = mAttachInfo;
15453        if (attachInfo != null) {
15454            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
15455        }
15456    }
15457
15458    /**
15459     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
15460     * through the event loop. Waits for the specified amount of time.</p>
15461     *
15462     * <p>This method can be invoked from outside of the UI thread
15463     * only when this View is attached to a window.</p>
15464     *
15465     * @param delayMilliseconds the duration in milliseconds to delay the
15466     *         invalidation by
15467     * @param left The left coordinate of the rectangle to invalidate.
15468     * @param top The top coordinate of the rectangle to invalidate.
15469     * @param right The right coordinate of the rectangle to invalidate.
15470     * @param bottom The bottom coordinate of the rectangle to invalidate.
15471     *
15472     * @see #invalidate(int, int, int, int)
15473     * @see #invalidate(Rect)
15474     * @see #postInvalidate(int, int, int, int)
15475     */
15476    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
15477            int right, int bottom) {
15478
15479        // We try only with the AttachInfo because there's no point in invalidating
15480        // if we are not attached to our window
15481        final AttachInfo attachInfo = mAttachInfo;
15482        if (attachInfo != null) {
15483            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
15484            info.target = this;
15485            info.left = left;
15486            info.top = top;
15487            info.right = right;
15488            info.bottom = bottom;
15489
15490            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
15491        }
15492    }
15493
15494    /**
15495     * <p>Cause an invalidate to happen on the next animation time step, typically the
15496     * next display frame.</p>
15497     *
15498     * <p>This method can be invoked from outside of the UI thread
15499     * only when this View is attached to a window.</p>
15500     *
15501     * @see #invalidate()
15502     */
15503    public void postInvalidateOnAnimation() {
15504        // We try only with the AttachInfo because there's no point in invalidating
15505        // if we are not attached to our window
15506        final AttachInfo attachInfo = mAttachInfo;
15507        if (attachInfo != null) {
15508            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
15509        }
15510    }
15511
15512    /**
15513     * <p>Cause an invalidate of the specified area to happen on the next animation
15514     * time step, typically the next display frame.</p>
15515     *
15516     * <p>This method can be invoked from outside of the UI thread
15517     * only when this View is attached to a window.</p>
15518     *
15519     * @param left The left coordinate of the rectangle to invalidate.
15520     * @param top The top coordinate of the rectangle to invalidate.
15521     * @param right The right coordinate of the rectangle to invalidate.
15522     * @param bottom The bottom coordinate of the rectangle to invalidate.
15523     *
15524     * @see #invalidate(int, int, int, int)
15525     * @see #invalidate(Rect)
15526     */
15527    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
15528        // We try only with the AttachInfo because there's no point in invalidating
15529        // if we are not attached to our window
15530        final AttachInfo attachInfo = mAttachInfo;
15531        if (attachInfo != null) {
15532            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
15533            info.target = this;
15534            info.left = left;
15535            info.top = top;
15536            info.right = right;
15537            info.bottom = bottom;
15538
15539            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
15540        }
15541    }
15542
15543    /**
15544     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
15545     * This event is sent at most once every
15546     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
15547     */
15548    private void postSendViewScrolledAccessibilityEventCallback() {
15549        if (mSendViewScrolledAccessibilityEvent == null) {
15550            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
15551        }
15552        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
15553            mSendViewScrolledAccessibilityEvent.mIsPending = true;
15554            postDelayed(mSendViewScrolledAccessibilityEvent,
15555                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
15556        }
15557    }
15558
15559    /**
15560     * Called by a parent to request that a child update its values for mScrollX
15561     * and mScrollY if necessary. This will typically be done if the child is
15562     * animating a scroll using a {@link android.widget.Scroller Scroller}
15563     * object.
15564     */
15565    public void computeScroll() {
15566    }
15567
15568    /**
15569     * <p>Indicate whether the horizontal edges are faded when the view is
15570     * scrolled horizontally.</p>
15571     *
15572     * @return true if the horizontal edges should are faded on scroll, false
15573     *         otherwise
15574     *
15575     * @see #setHorizontalFadingEdgeEnabled(boolean)
15576     *
15577     * @attr ref android.R.styleable#View_requiresFadingEdge
15578     */
15579    public boolean isHorizontalFadingEdgeEnabled() {
15580        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
15581    }
15582
15583    /**
15584     * <p>Define whether the horizontal edges should be faded when this view
15585     * is scrolled horizontally.</p>
15586     *
15587     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
15588     *                                    be faded when the view is scrolled
15589     *                                    horizontally
15590     *
15591     * @see #isHorizontalFadingEdgeEnabled()
15592     *
15593     * @attr ref android.R.styleable#View_requiresFadingEdge
15594     */
15595    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
15596        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
15597            if (horizontalFadingEdgeEnabled) {
15598                initScrollCache();
15599            }
15600
15601            mViewFlags ^= FADING_EDGE_HORIZONTAL;
15602        }
15603    }
15604
15605    /**
15606     * <p>Indicate whether the vertical edges are faded when the view is
15607     * scrolled horizontally.</p>
15608     *
15609     * @return true if the vertical edges should are faded on scroll, false
15610     *         otherwise
15611     *
15612     * @see #setVerticalFadingEdgeEnabled(boolean)
15613     *
15614     * @attr ref android.R.styleable#View_requiresFadingEdge
15615     */
15616    public boolean isVerticalFadingEdgeEnabled() {
15617        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
15618    }
15619
15620    /**
15621     * <p>Define whether the vertical edges should be faded when this view
15622     * is scrolled vertically.</p>
15623     *
15624     * @param verticalFadingEdgeEnabled true if the vertical edges should
15625     *                                  be faded when the view is scrolled
15626     *                                  vertically
15627     *
15628     * @see #isVerticalFadingEdgeEnabled()
15629     *
15630     * @attr ref android.R.styleable#View_requiresFadingEdge
15631     */
15632    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
15633        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
15634            if (verticalFadingEdgeEnabled) {
15635                initScrollCache();
15636            }
15637
15638            mViewFlags ^= FADING_EDGE_VERTICAL;
15639        }
15640    }
15641
15642    /**
15643     * Returns the strength, or intensity, of the top faded edge. The strength is
15644     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
15645     * returns 0.0 or 1.0 but no value in between.
15646     *
15647     * Subclasses should override this method to provide a smoother fade transition
15648     * when scrolling occurs.
15649     *
15650     * @return the intensity of the top fade as a float between 0.0f and 1.0f
15651     */
15652    protected float getTopFadingEdgeStrength() {
15653        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
15654    }
15655
15656    /**
15657     * Returns the strength, or intensity, of the bottom faded edge. The strength is
15658     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
15659     * returns 0.0 or 1.0 but no value in between.
15660     *
15661     * Subclasses should override this method to provide a smoother fade transition
15662     * when scrolling occurs.
15663     *
15664     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
15665     */
15666    protected float getBottomFadingEdgeStrength() {
15667        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
15668                computeVerticalScrollRange() ? 1.0f : 0.0f;
15669    }
15670
15671    /**
15672     * Returns the strength, or intensity, of the left faded edge. The strength is
15673     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
15674     * returns 0.0 or 1.0 but no value in between.
15675     *
15676     * Subclasses should override this method to provide a smoother fade transition
15677     * when scrolling occurs.
15678     *
15679     * @return the intensity of the left fade as a float between 0.0f and 1.0f
15680     */
15681    protected float getLeftFadingEdgeStrength() {
15682        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
15683    }
15684
15685    /**
15686     * Returns the strength, or intensity, of the right faded edge. The strength is
15687     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
15688     * returns 0.0 or 1.0 but no value in between.
15689     *
15690     * Subclasses should override this method to provide a smoother fade transition
15691     * when scrolling occurs.
15692     *
15693     * @return the intensity of the right fade as a float between 0.0f and 1.0f
15694     */
15695    protected float getRightFadingEdgeStrength() {
15696        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
15697                computeHorizontalScrollRange() ? 1.0f : 0.0f;
15698    }
15699
15700    /**
15701     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
15702     * scrollbar is not drawn by default.</p>
15703     *
15704     * @return true if the horizontal scrollbar should be painted, false
15705     *         otherwise
15706     *
15707     * @see #setHorizontalScrollBarEnabled(boolean)
15708     */
15709    public boolean isHorizontalScrollBarEnabled() {
15710        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
15711    }
15712
15713    /**
15714     * <p>Define whether the horizontal scrollbar should be drawn or not. The
15715     * scrollbar is not drawn by default.</p>
15716     *
15717     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
15718     *                                   be painted
15719     *
15720     * @see #isHorizontalScrollBarEnabled()
15721     */
15722    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
15723        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
15724            mViewFlags ^= SCROLLBARS_HORIZONTAL;
15725            computeOpaqueFlags();
15726            resolvePadding();
15727        }
15728    }
15729
15730    /**
15731     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
15732     * scrollbar is not drawn by default.</p>
15733     *
15734     * @return true if the vertical scrollbar should be painted, false
15735     *         otherwise
15736     *
15737     * @see #setVerticalScrollBarEnabled(boolean)
15738     */
15739    public boolean isVerticalScrollBarEnabled() {
15740        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
15741    }
15742
15743    /**
15744     * <p>Define whether the vertical scrollbar should be drawn or not. The
15745     * scrollbar is not drawn by default.</p>
15746     *
15747     * @param verticalScrollBarEnabled true if the vertical scrollbar should
15748     *                                 be painted
15749     *
15750     * @see #isVerticalScrollBarEnabled()
15751     */
15752    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
15753        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
15754            mViewFlags ^= SCROLLBARS_VERTICAL;
15755            computeOpaqueFlags();
15756            resolvePadding();
15757        }
15758    }
15759
15760    /**
15761     * @hide
15762     */
15763    protected void recomputePadding() {
15764        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
15765    }
15766
15767    /**
15768     * Define whether scrollbars will fade when the view is not scrolling.
15769     *
15770     * @param fadeScrollbars whether to enable fading
15771     *
15772     * @attr ref android.R.styleable#View_fadeScrollbars
15773     */
15774    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
15775        initScrollCache();
15776        final ScrollabilityCache scrollabilityCache = mScrollCache;
15777        scrollabilityCache.fadeScrollBars = fadeScrollbars;
15778        if (fadeScrollbars) {
15779            scrollabilityCache.state = ScrollabilityCache.OFF;
15780        } else {
15781            scrollabilityCache.state = ScrollabilityCache.ON;
15782        }
15783    }
15784
15785    /**
15786     *
15787     * Returns true if scrollbars will fade when this view is not scrolling
15788     *
15789     * @return true if scrollbar fading is enabled
15790     *
15791     * @attr ref android.R.styleable#View_fadeScrollbars
15792     */
15793    public boolean isScrollbarFadingEnabled() {
15794        return mScrollCache != null && mScrollCache.fadeScrollBars;
15795    }
15796
15797    /**
15798     *
15799     * Returns the delay before scrollbars fade.
15800     *
15801     * @return the delay before scrollbars fade
15802     *
15803     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
15804     */
15805    public int getScrollBarDefaultDelayBeforeFade() {
15806        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
15807                mScrollCache.scrollBarDefaultDelayBeforeFade;
15808    }
15809
15810    /**
15811     * Define the delay before scrollbars fade.
15812     *
15813     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
15814     *
15815     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
15816     */
15817    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
15818        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
15819    }
15820
15821    /**
15822     *
15823     * Returns the scrollbar fade duration.
15824     *
15825     * @return the scrollbar fade duration, in milliseconds
15826     *
15827     * @attr ref android.R.styleable#View_scrollbarFadeDuration
15828     */
15829    public int getScrollBarFadeDuration() {
15830        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
15831                mScrollCache.scrollBarFadeDuration;
15832    }
15833
15834    /**
15835     * Define the scrollbar fade duration.
15836     *
15837     * @param scrollBarFadeDuration - the scrollbar fade duration, in milliseconds
15838     *
15839     * @attr ref android.R.styleable#View_scrollbarFadeDuration
15840     */
15841    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
15842        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
15843    }
15844
15845    /**
15846     *
15847     * Returns the scrollbar size.
15848     *
15849     * @return the scrollbar size
15850     *
15851     * @attr ref android.R.styleable#View_scrollbarSize
15852     */
15853    public int getScrollBarSize() {
15854        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
15855                mScrollCache.scrollBarSize;
15856    }
15857
15858    /**
15859     * Define the scrollbar size.
15860     *
15861     * @param scrollBarSize - the scrollbar size
15862     *
15863     * @attr ref android.R.styleable#View_scrollbarSize
15864     */
15865    public void setScrollBarSize(int scrollBarSize) {
15866        getScrollCache().scrollBarSize = scrollBarSize;
15867    }
15868
15869    /**
15870     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
15871     * inset. When inset, they add to the padding of the view. And the scrollbars
15872     * can be drawn inside the padding area or on the edge of the view. For example,
15873     * if a view has a background drawable and you want to draw the scrollbars
15874     * inside the padding specified by the drawable, you can use
15875     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
15876     * appear at the edge of the view, ignoring the padding, then you can use
15877     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
15878     * @param style the style of the scrollbars. Should be one of
15879     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
15880     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
15881     * @see #SCROLLBARS_INSIDE_OVERLAY
15882     * @see #SCROLLBARS_INSIDE_INSET
15883     * @see #SCROLLBARS_OUTSIDE_OVERLAY
15884     * @see #SCROLLBARS_OUTSIDE_INSET
15885     *
15886     * @attr ref android.R.styleable#View_scrollbarStyle
15887     */
15888    public void setScrollBarStyle(@ScrollBarStyle int style) {
15889        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
15890            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
15891            computeOpaqueFlags();
15892            resolvePadding();
15893        }
15894    }
15895
15896    /**
15897     * <p>Returns the current scrollbar style.</p>
15898     * @return the current scrollbar style
15899     * @see #SCROLLBARS_INSIDE_OVERLAY
15900     * @see #SCROLLBARS_INSIDE_INSET
15901     * @see #SCROLLBARS_OUTSIDE_OVERLAY
15902     * @see #SCROLLBARS_OUTSIDE_INSET
15903     *
15904     * @attr ref android.R.styleable#View_scrollbarStyle
15905     */
15906    @ViewDebug.ExportedProperty(mapping = {
15907            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
15908            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
15909            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
15910            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
15911    })
15912    @ScrollBarStyle
15913    public int getScrollBarStyle() {
15914        return mViewFlags & SCROLLBARS_STYLE_MASK;
15915    }
15916
15917    /**
15918     * <p>Compute the horizontal range that the horizontal scrollbar
15919     * represents.</p>
15920     *
15921     * <p>The range is expressed in arbitrary units that must be the same as the
15922     * units used by {@link #computeHorizontalScrollExtent()} and
15923     * {@link #computeHorizontalScrollOffset()}.</p>
15924     *
15925     * <p>The default range is the drawing width of this view.</p>
15926     *
15927     * @return the total horizontal range represented by the horizontal
15928     *         scrollbar
15929     *
15930     * @see #computeHorizontalScrollExtent()
15931     * @see #computeHorizontalScrollOffset()
15932     * @see android.widget.ScrollBarDrawable
15933     */
15934    protected int computeHorizontalScrollRange() {
15935        return getWidth();
15936    }
15937
15938    /**
15939     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
15940     * within the horizontal range. This value is used to compute the position
15941     * of the thumb within the scrollbar's track.</p>
15942     *
15943     * <p>The range is expressed in arbitrary units that must be the same as the
15944     * units used by {@link #computeHorizontalScrollRange()} and
15945     * {@link #computeHorizontalScrollExtent()}.</p>
15946     *
15947     * <p>The default offset is the scroll offset of this view.</p>
15948     *
15949     * @return the horizontal offset of the scrollbar's thumb
15950     *
15951     * @see #computeHorizontalScrollRange()
15952     * @see #computeHorizontalScrollExtent()
15953     * @see android.widget.ScrollBarDrawable
15954     */
15955    protected int computeHorizontalScrollOffset() {
15956        return mScrollX;
15957    }
15958
15959    /**
15960     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
15961     * within the horizontal range. This value is used to compute the length
15962     * of the thumb within the scrollbar's track.</p>
15963     *
15964     * <p>The range is expressed in arbitrary units that must be the same as the
15965     * units used by {@link #computeHorizontalScrollRange()} and
15966     * {@link #computeHorizontalScrollOffset()}.</p>
15967     *
15968     * <p>The default extent is the drawing width of this view.</p>
15969     *
15970     * @return the horizontal extent of the scrollbar's thumb
15971     *
15972     * @see #computeHorizontalScrollRange()
15973     * @see #computeHorizontalScrollOffset()
15974     * @see android.widget.ScrollBarDrawable
15975     */
15976    protected int computeHorizontalScrollExtent() {
15977        return getWidth();
15978    }
15979
15980    /**
15981     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
15982     *
15983     * <p>The range is expressed in arbitrary units that must be the same as the
15984     * units used by {@link #computeVerticalScrollExtent()} and
15985     * {@link #computeVerticalScrollOffset()}.</p>
15986     *
15987     * @return the total vertical range represented by the vertical scrollbar
15988     *
15989     * <p>The default range is the drawing height of this view.</p>
15990     *
15991     * @see #computeVerticalScrollExtent()
15992     * @see #computeVerticalScrollOffset()
15993     * @see android.widget.ScrollBarDrawable
15994     */
15995    protected int computeVerticalScrollRange() {
15996        return getHeight();
15997    }
15998
15999    /**
16000     * <p>Compute the vertical offset of the vertical scrollbar's thumb
16001     * within the horizontal range. This value is used to compute the position
16002     * of the thumb within the scrollbar's track.</p>
16003     *
16004     * <p>The range is expressed in arbitrary units that must be the same as the
16005     * units used by {@link #computeVerticalScrollRange()} and
16006     * {@link #computeVerticalScrollExtent()}.</p>
16007     *
16008     * <p>The default offset is the scroll offset of this view.</p>
16009     *
16010     * @return the vertical offset of the scrollbar's thumb
16011     *
16012     * @see #computeVerticalScrollRange()
16013     * @see #computeVerticalScrollExtent()
16014     * @see android.widget.ScrollBarDrawable
16015     */
16016    protected int computeVerticalScrollOffset() {
16017        return mScrollY;
16018    }
16019
16020    /**
16021     * <p>Compute the vertical extent of the vertical scrollbar's thumb
16022     * within the vertical range. This value is used to compute the length
16023     * of the thumb within the scrollbar's track.</p>
16024     *
16025     * <p>The range is expressed in arbitrary units that must be the same as the
16026     * units used by {@link #computeVerticalScrollRange()} and
16027     * {@link #computeVerticalScrollOffset()}.</p>
16028     *
16029     * <p>The default extent is the drawing height of this view.</p>
16030     *
16031     * @return the vertical extent of the scrollbar's thumb
16032     *
16033     * @see #computeVerticalScrollRange()
16034     * @see #computeVerticalScrollOffset()
16035     * @see android.widget.ScrollBarDrawable
16036     */
16037    protected int computeVerticalScrollExtent() {
16038        return getHeight();
16039    }
16040
16041    /**
16042     * Check if this view can be scrolled horizontally in a certain direction.
16043     *
16044     * @param direction Negative to check scrolling left, positive to check scrolling right.
16045     * @return true if this view can be scrolled in the specified direction, false otherwise.
16046     */
16047    public boolean canScrollHorizontally(int direction) {
16048        final int offset = computeHorizontalScrollOffset();
16049        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
16050        if (range == 0) return false;
16051        if (direction < 0) {
16052            return offset > 0;
16053        } else {
16054            return offset < range - 1;
16055        }
16056    }
16057
16058    /**
16059     * Check if this view can be scrolled vertically in a certain direction.
16060     *
16061     * @param direction Negative to check scrolling up, positive to check scrolling down.
16062     * @return true if this view can be scrolled in the specified direction, false otherwise.
16063     */
16064    public boolean canScrollVertically(int direction) {
16065        final int offset = computeVerticalScrollOffset();
16066        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
16067        if (range == 0) return false;
16068        if (direction < 0) {
16069            return offset > 0;
16070        } else {
16071            return offset < range - 1;
16072        }
16073    }
16074
16075    void getScrollIndicatorBounds(@NonNull Rect out) {
16076        out.left = mScrollX;
16077        out.right = mScrollX + mRight - mLeft;
16078        out.top = mScrollY;
16079        out.bottom = mScrollY + mBottom - mTop;
16080    }
16081
16082    private void onDrawScrollIndicators(Canvas c) {
16083        if ((mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK) == 0) {
16084            // No scroll indicators enabled.
16085            return;
16086        }
16087
16088        final Drawable dr = mScrollIndicatorDrawable;
16089        if (dr == null) {
16090            // Scroll indicators aren't supported here.
16091            return;
16092        }
16093
16094        final int h = dr.getIntrinsicHeight();
16095        final int w = dr.getIntrinsicWidth();
16096        final Rect rect = mAttachInfo.mTmpInvalRect;
16097        getScrollIndicatorBounds(rect);
16098
16099        if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_TOP) != 0) {
16100            final boolean canScrollUp = canScrollVertically(-1);
16101            if (canScrollUp) {
16102                dr.setBounds(rect.left, rect.top, rect.right, rect.top + h);
16103                dr.draw(c);
16104            }
16105        }
16106
16107        if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_BOTTOM) != 0) {
16108            final boolean canScrollDown = canScrollVertically(1);
16109            if (canScrollDown) {
16110                dr.setBounds(rect.left, rect.bottom - h, rect.right, rect.bottom);
16111                dr.draw(c);
16112            }
16113        }
16114
16115        final int leftRtl;
16116        final int rightRtl;
16117        if (getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
16118            leftRtl = PFLAG3_SCROLL_INDICATOR_END;
16119            rightRtl = PFLAG3_SCROLL_INDICATOR_START;
16120        } else {
16121            leftRtl = PFLAG3_SCROLL_INDICATOR_START;
16122            rightRtl = PFLAG3_SCROLL_INDICATOR_END;
16123        }
16124
16125        final int leftMask = PFLAG3_SCROLL_INDICATOR_LEFT | leftRtl;
16126        if ((mPrivateFlags3 & leftMask) != 0) {
16127            final boolean canScrollLeft = canScrollHorizontally(-1);
16128            if (canScrollLeft) {
16129                dr.setBounds(rect.left, rect.top, rect.left + w, rect.bottom);
16130                dr.draw(c);
16131            }
16132        }
16133
16134        final int rightMask = PFLAG3_SCROLL_INDICATOR_RIGHT | rightRtl;
16135        if ((mPrivateFlags3 & rightMask) != 0) {
16136            final boolean canScrollRight = canScrollHorizontally(1);
16137            if (canScrollRight) {
16138                dr.setBounds(rect.right - w, rect.top, rect.right, rect.bottom);
16139                dr.draw(c);
16140            }
16141        }
16142    }
16143
16144    private void getHorizontalScrollBarBounds(@Nullable Rect drawBounds,
16145            @Nullable Rect touchBounds) {
16146        final Rect bounds = drawBounds != null ? drawBounds : touchBounds;
16147        if (bounds == null) {
16148            return;
16149        }
16150        final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
16151        final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled()
16152                && !isVerticalScrollBarHidden();
16153        final int size = getHorizontalScrollbarHeight();
16154        final int verticalScrollBarGap = drawVerticalScrollBar ?
16155                getVerticalScrollbarWidth() : 0;
16156        final int width = mRight - mLeft;
16157        final int height = mBottom - mTop;
16158        bounds.top = mScrollY + height - size - (mUserPaddingBottom & inside);
16159        bounds.left = mScrollX + (mPaddingLeft & inside);
16160        bounds.right = mScrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
16161        bounds.bottom = bounds.top + size;
16162
16163        if (touchBounds == null) {
16164            return;
16165        }
16166        if (touchBounds != bounds) {
16167            touchBounds.set(bounds);
16168        }
16169        final int minTouchTarget = mScrollCache.scrollBarMinTouchTarget;
16170        if (touchBounds.height() < minTouchTarget) {
16171            final int adjust = (minTouchTarget - touchBounds.height()) / 2;
16172            touchBounds.bottom = Math.min(touchBounds.bottom + adjust, mScrollY + height);
16173            touchBounds.top = touchBounds.bottom - minTouchTarget;
16174        }
16175        if (touchBounds.width() < minTouchTarget) {
16176            final int adjust = (minTouchTarget - touchBounds.width()) / 2;
16177            touchBounds.left -= adjust;
16178            touchBounds.right = touchBounds.left + minTouchTarget;
16179        }
16180    }
16181
16182    private void getVerticalScrollBarBounds(@Nullable Rect bounds, @Nullable Rect touchBounds) {
16183        if (mRoundScrollbarRenderer == null) {
16184            getStraightVerticalScrollBarBounds(bounds, touchBounds);
16185        } else {
16186            getRoundVerticalScrollBarBounds(bounds != null ? bounds : touchBounds);
16187        }
16188    }
16189
16190    private void getRoundVerticalScrollBarBounds(Rect bounds) {
16191        final int width = mRight - mLeft;
16192        final int height = mBottom - mTop;
16193        // Do not take padding into account as we always want the scrollbars
16194        // to hug the screen for round wearable devices.
16195        bounds.left = mScrollX;
16196        bounds.top = mScrollY;
16197        bounds.right = bounds.left + width;
16198        bounds.bottom = mScrollY + height;
16199    }
16200
16201    private void getStraightVerticalScrollBarBounds(@Nullable Rect drawBounds,
16202            @Nullable Rect touchBounds) {
16203        final Rect bounds = drawBounds != null ? drawBounds : touchBounds;
16204        if (bounds == null) {
16205            return;
16206        }
16207        final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
16208        final int size = getVerticalScrollbarWidth();
16209        int verticalScrollbarPosition = mVerticalScrollbarPosition;
16210        if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
16211            verticalScrollbarPosition = isLayoutRtl() ?
16212                    SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
16213        }
16214        final int width = mRight - mLeft;
16215        final int height = mBottom - mTop;
16216        switch (verticalScrollbarPosition) {
16217            default:
16218            case SCROLLBAR_POSITION_RIGHT:
16219                bounds.left = mScrollX + width - size - (mUserPaddingRight & inside);
16220                break;
16221            case SCROLLBAR_POSITION_LEFT:
16222                bounds.left = mScrollX + (mUserPaddingLeft & inside);
16223                break;
16224        }
16225        bounds.top = mScrollY + (mPaddingTop & inside);
16226        bounds.right = bounds.left + size;
16227        bounds.bottom = mScrollY + height - (mUserPaddingBottom & inside);
16228
16229        if (touchBounds == null) {
16230            return;
16231        }
16232        if (touchBounds != bounds) {
16233            touchBounds.set(bounds);
16234        }
16235        final int minTouchTarget = mScrollCache.scrollBarMinTouchTarget;
16236        if (touchBounds.width() < minTouchTarget) {
16237            final int adjust = (minTouchTarget - touchBounds.width()) / 2;
16238            if (verticalScrollbarPosition == SCROLLBAR_POSITION_RIGHT) {
16239                touchBounds.right = Math.min(touchBounds.right + adjust, mScrollX + width);
16240                touchBounds.left = touchBounds.right - minTouchTarget;
16241            } else {
16242                touchBounds.left = Math.max(touchBounds.left + adjust, mScrollX);
16243                touchBounds.right = touchBounds.left + minTouchTarget;
16244            }
16245        }
16246        if (touchBounds.height() < minTouchTarget) {
16247            final int adjust = (minTouchTarget - touchBounds.height()) / 2;
16248            touchBounds.top -= adjust;
16249            touchBounds.bottom = touchBounds.top + minTouchTarget;
16250        }
16251    }
16252
16253    /**
16254     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
16255     * scrollbars are painted only if they have been awakened first.</p>
16256     *
16257     * @param canvas the canvas on which to draw the scrollbars
16258     *
16259     * @see #awakenScrollBars(int)
16260     */
16261    protected final void onDrawScrollBars(Canvas canvas) {
16262        // scrollbars are drawn only when the animation is running
16263        final ScrollabilityCache cache = mScrollCache;
16264
16265        if (cache != null) {
16266
16267            int state = cache.state;
16268
16269            if (state == ScrollabilityCache.OFF) {
16270                return;
16271            }
16272
16273            boolean invalidate = false;
16274
16275            if (state == ScrollabilityCache.FADING) {
16276                // We're fading -- get our fade interpolation
16277                if (cache.interpolatorValues == null) {
16278                    cache.interpolatorValues = new float[1];
16279                }
16280
16281                float[] values = cache.interpolatorValues;
16282
16283                // Stops the animation if we're done
16284                if (cache.scrollBarInterpolator.timeToValues(values) ==
16285                        Interpolator.Result.FREEZE_END) {
16286                    cache.state = ScrollabilityCache.OFF;
16287                } else {
16288                    cache.scrollBar.mutate().setAlpha(Math.round(values[0]));
16289                }
16290
16291                // This will make the scroll bars inval themselves after
16292                // drawing. We only want this when we're fading so that
16293                // we prevent excessive redraws
16294                invalidate = true;
16295            } else {
16296                // We're just on -- but we may have been fading before so
16297                // reset alpha
16298                cache.scrollBar.mutate().setAlpha(255);
16299            }
16300
16301            final boolean drawHorizontalScrollBar = isHorizontalScrollBarEnabled();
16302            final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled()
16303                    && !isVerticalScrollBarHidden();
16304
16305            // Fork out the scroll bar drawing for round wearable devices.
16306            if (mRoundScrollbarRenderer != null) {
16307                if (drawVerticalScrollBar) {
16308                    final Rect bounds = cache.mScrollBarBounds;
16309                    getVerticalScrollBarBounds(bounds, null);
16310                    mRoundScrollbarRenderer.drawRoundScrollbars(
16311                            canvas, (float) cache.scrollBar.getAlpha() / 255f, bounds);
16312                    if (invalidate) {
16313                        invalidate();
16314                    }
16315                }
16316                // Do not draw horizontal scroll bars for round wearable devices.
16317            } else if (drawVerticalScrollBar || drawHorizontalScrollBar) {
16318                final ScrollBarDrawable scrollBar = cache.scrollBar;
16319
16320                if (drawHorizontalScrollBar) {
16321                    scrollBar.setParameters(computeHorizontalScrollRange(),
16322                            computeHorizontalScrollOffset(),
16323                            computeHorizontalScrollExtent(), false);
16324                    final Rect bounds = cache.mScrollBarBounds;
16325                    getHorizontalScrollBarBounds(bounds, null);
16326                    onDrawHorizontalScrollBar(canvas, scrollBar, bounds.left, bounds.top,
16327                            bounds.right, bounds.bottom);
16328                    if (invalidate) {
16329                        invalidate(bounds);
16330                    }
16331                }
16332
16333                if (drawVerticalScrollBar) {
16334                    scrollBar.setParameters(computeVerticalScrollRange(),
16335                            computeVerticalScrollOffset(),
16336                            computeVerticalScrollExtent(), true);
16337                    final Rect bounds = cache.mScrollBarBounds;
16338                    getVerticalScrollBarBounds(bounds, null);
16339                    onDrawVerticalScrollBar(canvas, scrollBar, bounds.left, bounds.top,
16340                            bounds.right, bounds.bottom);
16341                    if (invalidate) {
16342                        invalidate(bounds);
16343                    }
16344                }
16345            }
16346        }
16347    }
16348
16349    /**
16350     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
16351     * FastScroller is visible.
16352     * @return whether to temporarily hide the vertical scrollbar
16353     * @hide
16354     */
16355    protected boolean isVerticalScrollBarHidden() {
16356        return false;
16357    }
16358
16359    /**
16360     * <p>Draw the horizontal scrollbar if
16361     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
16362     *
16363     * @param canvas the canvas on which to draw the scrollbar
16364     * @param scrollBar the scrollbar's drawable
16365     *
16366     * @see #isHorizontalScrollBarEnabled()
16367     * @see #computeHorizontalScrollRange()
16368     * @see #computeHorizontalScrollExtent()
16369     * @see #computeHorizontalScrollOffset()
16370     * @see android.widget.ScrollBarDrawable
16371     * @hide
16372     */
16373    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
16374            int l, int t, int r, int b) {
16375        scrollBar.setBounds(l, t, r, b);
16376        scrollBar.draw(canvas);
16377    }
16378
16379    /**
16380     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
16381     * returns true.</p>
16382     *
16383     * @param canvas the canvas on which to draw the scrollbar
16384     * @param scrollBar the scrollbar's drawable
16385     *
16386     * @see #isVerticalScrollBarEnabled()
16387     * @see #computeVerticalScrollRange()
16388     * @see #computeVerticalScrollExtent()
16389     * @see #computeVerticalScrollOffset()
16390     * @see android.widget.ScrollBarDrawable
16391     * @hide
16392     */
16393    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
16394            int l, int t, int r, int b) {
16395        scrollBar.setBounds(l, t, r, b);
16396        scrollBar.draw(canvas);
16397    }
16398
16399    /**
16400     * Implement this to do your drawing.
16401     *
16402     * @param canvas the canvas on which the background will be drawn
16403     */
16404    protected void onDraw(Canvas canvas) {
16405    }
16406
16407    /*
16408     * Caller is responsible for calling requestLayout if necessary.
16409     * (This allows addViewInLayout to not request a new layout.)
16410     */
16411    void assignParent(ViewParent parent) {
16412        if (mParent == null) {
16413            mParent = parent;
16414        } else if (parent == null) {
16415            mParent = null;
16416        } else {
16417            throw new RuntimeException("view " + this + " being added, but"
16418                    + " it already has a parent");
16419        }
16420    }
16421
16422    /**
16423     * This is called when the view is attached to a window.  At this point it
16424     * has a Surface and will start drawing.  Note that this function is
16425     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
16426     * however it may be called any time before the first onDraw -- including
16427     * before or after {@link #onMeasure(int, int)}.
16428     *
16429     * @see #onDetachedFromWindow()
16430     */
16431    @CallSuper
16432    protected void onAttachedToWindow() {
16433        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
16434            mParent.requestTransparentRegion(this);
16435        }
16436
16437        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
16438
16439        jumpDrawablesToCurrentState();
16440
16441        resetSubtreeAccessibilityStateChanged();
16442
16443        // rebuild, since Outline not maintained while View is detached
16444        rebuildOutline();
16445
16446        if (isFocused()) {
16447            InputMethodManager imm = InputMethodManager.peekInstance();
16448            if (imm != null) {
16449                imm.focusIn(this);
16450            }
16451        }
16452    }
16453
16454    /**
16455     * Resolve all RTL related properties.
16456     *
16457     * @return true if resolution of RTL properties has been done
16458     *
16459     * @hide
16460     */
16461    public boolean resolveRtlPropertiesIfNeeded() {
16462        if (!needRtlPropertiesResolution()) return false;
16463
16464        // Order is important here: LayoutDirection MUST be resolved first
16465        if (!isLayoutDirectionResolved()) {
16466            resolveLayoutDirection();
16467            resolveLayoutParams();
16468        }
16469        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
16470        if (!isTextDirectionResolved()) {
16471            resolveTextDirection();
16472        }
16473        if (!isTextAlignmentResolved()) {
16474            resolveTextAlignment();
16475        }
16476        // Should resolve Drawables before Padding because we need the layout direction of the
16477        // Drawable to correctly resolve Padding.
16478        if (!areDrawablesResolved()) {
16479            resolveDrawables();
16480        }
16481        if (!isPaddingResolved()) {
16482            resolvePadding();
16483        }
16484        onRtlPropertiesChanged(getLayoutDirection());
16485        return true;
16486    }
16487
16488    /**
16489     * Reset resolution of all RTL related properties.
16490     *
16491     * @hide
16492     */
16493    public void resetRtlProperties() {
16494        resetResolvedLayoutDirection();
16495        resetResolvedTextDirection();
16496        resetResolvedTextAlignment();
16497        resetResolvedPadding();
16498        resetResolvedDrawables();
16499    }
16500
16501    /**
16502     * @see #onScreenStateChanged(int)
16503     */
16504    void dispatchScreenStateChanged(int screenState) {
16505        onScreenStateChanged(screenState);
16506    }
16507
16508    /**
16509     * This method is called whenever the state of the screen this view is
16510     * attached to changes. A state change will usually occurs when the screen
16511     * turns on or off (whether it happens automatically or the user does it
16512     * manually.)
16513     *
16514     * @param screenState The new state of the screen. Can be either
16515     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
16516     */
16517    public void onScreenStateChanged(int screenState) {
16518    }
16519
16520    /**
16521     * @see #onMovedToDisplay(int, Configuration)
16522     */
16523    void dispatchMovedToDisplay(Display display, Configuration config) {
16524        mAttachInfo.mDisplay = display;
16525        mAttachInfo.mDisplayState = display.getState();
16526        onMovedToDisplay(display.getDisplayId(), config);
16527    }
16528
16529    /**
16530     * Called by the system when the hosting activity is moved from one display to another without
16531     * recreation. This means that the activity is declared to handle all changes to configuration
16532     * that happened when it was switched to another display, so it wasn't destroyed and created
16533     * again.
16534     *
16535     * <p>This call will be followed by {@link #onConfigurationChanged(Configuration)} if the
16536     * applied configuration actually changed. It is up to app developer to choose whether to handle
16537     * the change in this method or in the following {@link #onConfigurationChanged(Configuration)}
16538     * call.
16539     *
16540     * <p>Use this callback to track changes to the displays if some functionality relies on an
16541     * association with some display properties.
16542     *
16543     * @param displayId The id of the display to which the view was moved.
16544     * @param config Configuration of the resources on new display after move.
16545     *
16546     * @see #onConfigurationChanged(Configuration)
16547     */
16548    public void onMovedToDisplay(int displayId, Configuration config) {
16549    }
16550
16551    /**
16552     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
16553     */
16554    private boolean hasRtlSupport() {
16555        return mContext.getApplicationInfo().hasRtlSupport();
16556    }
16557
16558    /**
16559     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
16560     * RTL not supported)
16561     */
16562    private boolean isRtlCompatibilityMode() {
16563        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
16564        return targetSdkVersion < Build.VERSION_CODES.JELLY_BEAN_MR1 || !hasRtlSupport();
16565    }
16566
16567    /**
16568     * @return true if RTL properties need resolution.
16569     *
16570     */
16571    private boolean needRtlPropertiesResolution() {
16572        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
16573    }
16574
16575    /**
16576     * Called when any RTL property (layout direction or text direction or text alignment) has
16577     * been changed.
16578     *
16579     * Subclasses need to override this method to take care of cached information that depends on the
16580     * resolved layout direction, or to inform child views that inherit their layout direction.
16581     *
16582     * The default implementation does nothing.
16583     *
16584     * @param layoutDirection the direction of the layout
16585     *
16586     * @see #LAYOUT_DIRECTION_LTR
16587     * @see #LAYOUT_DIRECTION_RTL
16588     */
16589    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
16590    }
16591
16592    /**
16593     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
16594     * that the parent directionality can and will be resolved before its children.
16595     *
16596     * @return true if resolution has been done, false otherwise.
16597     *
16598     * @hide
16599     */
16600    public boolean resolveLayoutDirection() {
16601        // Clear any previous layout direction resolution
16602        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
16603
16604        if (hasRtlSupport()) {
16605            // Set resolved depending on layout direction
16606            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
16607                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
16608                case LAYOUT_DIRECTION_INHERIT:
16609                    // We cannot resolve yet. LTR is by default and let the resolution happen again
16610                    // later to get the correct resolved value
16611                    if (!canResolveLayoutDirection()) return false;
16612
16613                    // Parent has not yet resolved, LTR is still the default
16614                    try {
16615                        if (!mParent.isLayoutDirectionResolved()) return false;
16616
16617                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
16618                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
16619                        }
16620                    } catch (AbstractMethodError e) {
16621                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
16622                                " does not fully implement ViewParent", e);
16623                    }
16624                    break;
16625                case LAYOUT_DIRECTION_RTL:
16626                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
16627                    break;
16628                case LAYOUT_DIRECTION_LOCALE:
16629                    if((LAYOUT_DIRECTION_RTL ==
16630                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
16631                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
16632                    }
16633                    break;
16634                default:
16635                    // Nothing to do, LTR by default
16636            }
16637        }
16638
16639        // Set to resolved
16640        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
16641        return true;
16642    }
16643
16644    /**
16645     * Check if layout direction resolution can be done.
16646     *
16647     * @return true if layout direction resolution can be done otherwise return false.
16648     */
16649    public boolean canResolveLayoutDirection() {
16650        switch (getRawLayoutDirection()) {
16651            case LAYOUT_DIRECTION_INHERIT:
16652                if (mParent != null) {
16653                    try {
16654                        return mParent.canResolveLayoutDirection();
16655                    } catch (AbstractMethodError e) {
16656                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
16657                                " does not fully implement ViewParent", e);
16658                    }
16659                }
16660                return false;
16661
16662            default:
16663                return true;
16664        }
16665    }
16666
16667    /**
16668     * Reset the resolved layout direction. Layout direction will be resolved during a call to
16669     * {@link #onMeasure(int, int)}.
16670     *
16671     * @hide
16672     */
16673    public void resetResolvedLayoutDirection() {
16674        // Reset the current resolved bits
16675        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
16676    }
16677
16678    /**
16679     * @return true if the layout direction is inherited.
16680     *
16681     * @hide
16682     */
16683    public boolean isLayoutDirectionInherited() {
16684        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
16685    }
16686
16687    /**
16688     * @return true if layout direction has been resolved.
16689     */
16690    public boolean isLayoutDirectionResolved() {
16691        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
16692    }
16693
16694    /**
16695     * Return if padding has been resolved
16696     *
16697     * @hide
16698     */
16699    boolean isPaddingResolved() {
16700        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
16701    }
16702
16703    /**
16704     * Resolves padding depending on layout direction, if applicable, and
16705     * recomputes internal padding values to adjust for scroll bars.
16706     *
16707     * @hide
16708     */
16709    public void resolvePadding() {
16710        final int resolvedLayoutDirection = getLayoutDirection();
16711
16712        if (!isRtlCompatibilityMode()) {
16713            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
16714            // If start / end padding are defined, they will be resolved (hence overriding) to
16715            // left / right or right / left depending on the resolved layout direction.
16716            // If start / end padding are not defined, use the left / right ones.
16717            if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
16718                Rect padding = sThreadLocal.get();
16719                if (padding == null) {
16720                    padding = new Rect();
16721                    sThreadLocal.set(padding);
16722                }
16723                mBackground.getPadding(padding);
16724                if (!mLeftPaddingDefined) {
16725                    mUserPaddingLeftInitial = padding.left;
16726                }
16727                if (!mRightPaddingDefined) {
16728                    mUserPaddingRightInitial = padding.right;
16729                }
16730            }
16731            switch (resolvedLayoutDirection) {
16732                case LAYOUT_DIRECTION_RTL:
16733                    if (mUserPaddingStart != UNDEFINED_PADDING) {
16734                        mUserPaddingRight = mUserPaddingStart;
16735                    } else {
16736                        mUserPaddingRight = mUserPaddingRightInitial;
16737                    }
16738                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
16739                        mUserPaddingLeft = mUserPaddingEnd;
16740                    } else {
16741                        mUserPaddingLeft = mUserPaddingLeftInitial;
16742                    }
16743                    break;
16744                case LAYOUT_DIRECTION_LTR:
16745                default:
16746                    if (mUserPaddingStart != UNDEFINED_PADDING) {
16747                        mUserPaddingLeft = mUserPaddingStart;
16748                    } else {
16749                        mUserPaddingLeft = mUserPaddingLeftInitial;
16750                    }
16751                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
16752                        mUserPaddingRight = mUserPaddingEnd;
16753                    } else {
16754                        mUserPaddingRight = mUserPaddingRightInitial;
16755                    }
16756            }
16757
16758            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
16759        }
16760
16761        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
16762        onRtlPropertiesChanged(resolvedLayoutDirection);
16763
16764        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
16765    }
16766
16767    /**
16768     * Reset the resolved layout direction.
16769     *
16770     * @hide
16771     */
16772    public void resetResolvedPadding() {
16773        resetResolvedPaddingInternal();
16774    }
16775
16776    /**
16777     * Used when we only want to reset *this* view's padding and not trigger overrides
16778     * in ViewGroup that reset children too.
16779     */
16780    void resetResolvedPaddingInternal() {
16781        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
16782    }
16783
16784    /**
16785     * This is called when the view is detached from a window.  At this point it
16786     * no longer has a surface for drawing.
16787     *
16788     * @see #onAttachedToWindow()
16789     */
16790    @CallSuper
16791    protected void onDetachedFromWindow() {
16792    }
16793
16794    /**
16795     * This is a framework-internal mirror of onDetachedFromWindow() that's called
16796     * after onDetachedFromWindow().
16797     *
16798     * If you override this you *MUST* call super.onDetachedFromWindowInternal()!
16799     * The super method should be called at the end of the overridden method to ensure
16800     * subclasses are destroyed first
16801     *
16802     * @hide
16803     */
16804    @CallSuper
16805    protected void onDetachedFromWindowInternal() {
16806        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
16807        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
16808        mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH;
16809
16810        removeUnsetPressCallback();
16811        removeLongPressCallback();
16812        removePerformClickCallback();
16813        removeSendViewScrolledAccessibilityEventCallback();
16814        stopNestedScroll();
16815
16816        // Anything that started animating right before detach should already
16817        // be in its final state when re-attached.
16818        jumpDrawablesToCurrentState();
16819
16820        destroyDrawingCache();
16821
16822        cleanupDraw();
16823        mCurrentAnimation = null;
16824
16825        if ((mViewFlags & TOOLTIP) == TOOLTIP) {
16826            hideTooltip();
16827        }
16828    }
16829
16830    private void cleanupDraw() {
16831        resetDisplayList();
16832        if (mAttachInfo != null) {
16833            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
16834        }
16835    }
16836
16837    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
16838    }
16839
16840    /**
16841     * @return The number of times this view has been attached to a window
16842     */
16843    protected int getWindowAttachCount() {
16844        return mWindowAttachCount;
16845    }
16846
16847    /**
16848     * Retrieve a unique token identifying the window this view is attached to.
16849     * @return Return the window's token for use in
16850     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
16851     */
16852    public IBinder getWindowToken() {
16853        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
16854    }
16855
16856    /**
16857     * Retrieve the {@link WindowId} for the window this view is
16858     * currently attached to.
16859     */
16860    public WindowId getWindowId() {
16861        if (mAttachInfo == null) {
16862            return null;
16863        }
16864        if (mAttachInfo.mWindowId == null) {
16865            try {
16866                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
16867                        mAttachInfo.mWindowToken);
16868                mAttachInfo.mWindowId = new WindowId(
16869                        mAttachInfo.mIWindowId);
16870            } catch (RemoteException e) {
16871            }
16872        }
16873        return mAttachInfo.mWindowId;
16874    }
16875
16876    /**
16877     * Retrieve a unique token identifying the top-level "real" window of
16878     * the window that this view is attached to.  That is, this is like
16879     * {@link #getWindowToken}, except if the window this view in is a panel
16880     * window (attached to another containing window), then the token of
16881     * the containing window is returned instead.
16882     *
16883     * @return Returns the associated window token, either
16884     * {@link #getWindowToken()} or the containing window's token.
16885     */
16886    public IBinder getApplicationWindowToken() {
16887        AttachInfo ai = mAttachInfo;
16888        if (ai != null) {
16889            IBinder appWindowToken = ai.mPanelParentWindowToken;
16890            if (appWindowToken == null) {
16891                appWindowToken = ai.mWindowToken;
16892            }
16893            return appWindowToken;
16894        }
16895        return null;
16896    }
16897
16898    /**
16899     * Gets the logical display to which the view's window has been attached.
16900     *
16901     * @return The logical display, or null if the view is not currently attached to a window.
16902     */
16903    public Display getDisplay() {
16904        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
16905    }
16906
16907    /**
16908     * Retrieve private session object this view hierarchy is using to
16909     * communicate with the window manager.
16910     * @return the session object to communicate with the window manager
16911     */
16912    /*package*/ IWindowSession getWindowSession() {
16913        return mAttachInfo != null ? mAttachInfo.mSession : null;
16914    }
16915
16916    /**
16917     * Return the visibility value of the least visible component passed.
16918     */
16919    int combineVisibility(int vis1, int vis2) {
16920        // This works because VISIBLE < INVISIBLE < GONE.
16921        return Math.max(vis1, vis2);
16922    }
16923
16924    /**
16925     * @param info the {@link android.view.View.AttachInfo} to associated with
16926     *        this view
16927     */
16928    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
16929        mAttachInfo = info;
16930        if (mOverlay != null) {
16931            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
16932        }
16933        mWindowAttachCount++;
16934        // We will need to evaluate the drawable state at least once.
16935        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
16936        if (mFloatingTreeObserver != null) {
16937            info.mTreeObserver.merge(mFloatingTreeObserver);
16938            mFloatingTreeObserver = null;
16939        }
16940
16941        registerPendingFrameMetricsObservers();
16942
16943        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
16944            mAttachInfo.mScrollContainers.add(this);
16945            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
16946        }
16947        // Transfer all pending runnables.
16948        if (mRunQueue != null) {
16949            mRunQueue.executeActions(info.mHandler);
16950            mRunQueue = null;
16951        }
16952        performCollectViewAttributes(mAttachInfo, visibility);
16953        onAttachedToWindow();
16954
16955        ListenerInfo li = mListenerInfo;
16956        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
16957                li != null ? li.mOnAttachStateChangeListeners : null;
16958        if (listeners != null && listeners.size() > 0) {
16959            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
16960            // perform the dispatching. The iterator is a safe guard against listeners that
16961            // could mutate the list by calling the various add/remove methods. This prevents
16962            // the array from being modified while we iterate it.
16963            for (OnAttachStateChangeListener listener : listeners) {
16964                listener.onViewAttachedToWindow(this);
16965            }
16966        }
16967
16968        int vis = info.mWindowVisibility;
16969        if (vis != GONE) {
16970            onWindowVisibilityChanged(vis);
16971            if (isShown()) {
16972                // Calling onVisibilityAggregated directly here since the subtree will also
16973                // receive dispatchAttachedToWindow and this same call
16974                onVisibilityAggregated(vis == VISIBLE);
16975            }
16976        }
16977
16978        // Send onVisibilityChanged directly instead of dispatchVisibilityChanged.
16979        // As all views in the subtree will already receive dispatchAttachedToWindow
16980        // traversing the subtree again here is not desired.
16981        onVisibilityChanged(this, visibility);
16982
16983        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
16984            // If nobody has evaluated the drawable state yet, then do it now.
16985            refreshDrawableState();
16986        }
16987        needGlobalAttributesUpdate(false);
16988
16989        notifyEnterOrExitForAutoFillIfNeeded(true);
16990    }
16991
16992    void dispatchDetachedFromWindow() {
16993        AttachInfo info = mAttachInfo;
16994        if (info != null) {
16995            int vis = info.mWindowVisibility;
16996            if (vis != GONE) {
16997                onWindowVisibilityChanged(GONE);
16998                if (isShown()) {
16999                    // Invoking onVisibilityAggregated directly here since the subtree
17000                    // will also receive detached from window
17001                    onVisibilityAggregated(false);
17002                }
17003            }
17004        }
17005
17006        onDetachedFromWindow();
17007        onDetachedFromWindowInternal();
17008
17009        InputMethodManager imm = InputMethodManager.peekInstance();
17010        if (imm != null) {
17011            imm.onViewDetachedFromWindow(this);
17012        }
17013
17014        ListenerInfo li = mListenerInfo;
17015        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
17016                li != null ? li.mOnAttachStateChangeListeners : null;
17017        if (listeners != null && listeners.size() > 0) {
17018            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
17019            // perform the dispatching. The iterator is a safe guard against listeners that
17020            // could mutate the list by calling the various add/remove methods. This prevents
17021            // the array from being modified while we iterate it.
17022            for (OnAttachStateChangeListener listener : listeners) {
17023                listener.onViewDetachedFromWindow(this);
17024            }
17025        }
17026
17027        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
17028            mAttachInfo.mScrollContainers.remove(this);
17029            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
17030        }
17031
17032        mAttachInfo = null;
17033        if (mOverlay != null) {
17034            mOverlay.getOverlayView().dispatchDetachedFromWindow();
17035        }
17036
17037        notifyEnterOrExitForAutoFillIfNeeded(false);
17038    }
17039
17040    /**
17041     * Cancel any deferred high-level input events that were previously posted to the event queue.
17042     *
17043     * <p>Many views post high-level events such as click handlers to the event queue
17044     * to run deferred in order to preserve a desired user experience - clearing visible
17045     * pressed states before executing, etc. This method will abort any events of this nature
17046     * that are currently in flight.</p>
17047     *
17048     * <p>Custom views that generate their own high-level deferred input events should override
17049     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
17050     *
17051     * <p>This will also cancel pending input events for any child views.</p>
17052     *
17053     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
17054     * This will not impact newer events posted after this call that may occur as a result of
17055     * lower-level input events still waiting in the queue. If you are trying to prevent
17056     * double-submitted  events for the duration of some sort of asynchronous transaction
17057     * you should also take other steps to protect against unexpected double inputs e.g. calling
17058     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
17059     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
17060     */
17061    public final void cancelPendingInputEvents() {
17062        dispatchCancelPendingInputEvents();
17063    }
17064
17065    /**
17066     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
17067     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
17068     */
17069    void dispatchCancelPendingInputEvents() {
17070        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
17071        onCancelPendingInputEvents();
17072        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
17073            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
17074                    " did not call through to super.onCancelPendingInputEvents()");
17075        }
17076    }
17077
17078    /**
17079     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
17080     * a parent view.
17081     *
17082     * <p>This method is responsible for removing any pending high-level input events that were
17083     * posted to the event queue to run later. Custom view classes that post their own deferred
17084     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
17085     * {@link android.os.Handler} should override this method, call
17086     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
17087     * </p>
17088     */
17089    public void onCancelPendingInputEvents() {
17090        removePerformClickCallback();
17091        cancelLongPress();
17092        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
17093    }
17094
17095    /**
17096     * Store this view hierarchy's frozen state into the given container.
17097     *
17098     * @param container The SparseArray in which to save the view's state.
17099     *
17100     * @see #restoreHierarchyState(android.util.SparseArray)
17101     * @see #dispatchSaveInstanceState(android.util.SparseArray)
17102     * @see #onSaveInstanceState()
17103     */
17104    public void saveHierarchyState(SparseArray<Parcelable> container) {
17105        dispatchSaveInstanceState(container);
17106    }
17107
17108    /**
17109     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
17110     * this view and its children. May be overridden to modify how freezing happens to a
17111     * view's children; for example, some views may want to not store state for their children.
17112     *
17113     * @param container The SparseArray in which to save the view's state.
17114     *
17115     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
17116     * @see #saveHierarchyState(android.util.SparseArray)
17117     * @see #onSaveInstanceState()
17118     */
17119    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
17120        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
17121            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
17122            Parcelable state = onSaveInstanceState();
17123            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
17124                throw new IllegalStateException(
17125                        "Derived class did not call super.onSaveInstanceState()");
17126            }
17127            if (state != null) {
17128                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
17129                // + ": " + state);
17130                container.put(mID, state);
17131            }
17132        }
17133    }
17134
17135    /**
17136     * Hook allowing a view to generate a representation of its internal state
17137     * that can later be used to create a new instance with that same state.
17138     * This state should only contain information that is not persistent or can
17139     * not be reconstructed later. For example, you will never store your
17140     * current position on screen because that will be computed again when a
17141     * new instance of the view is placed in its view hierarchy.
17142     * <p>
17143     * Some examples of things you may store here: the current cursor position
17144     * in a text view (but usually not the text itself since that is stored in a
17145     * content provider or other persistent storage), the currently selected
17146     * item in a list view.
17147     *
17148     * @return Returns a Parcelable object containing the view's current dynamic
17149     *         state, or null if there is nothing interesting to save. The
17150     *         default implementation returns null.
17151     * @see #onRestoreInstanceState(android.os.Parcelable)
17152     * @see #saveHierarchyState(android.util.SparseArray)
17153     * @see #dispatchSaveInstanceState(android.util.SparseArray)
17154     * @see #setSaveEnabled(boolean)
17155     */
17156    @CallSuper
17157    protected Parcelable onSaveInstanceState() {
17158        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
17159        if (mStartActivityRequestWho != null || isAutofilled()) {
17160            BaseSavedState state = new BaseSavedState(AbsSavedState.EMPTY_STATE);
17161
17162            if (mStartActivityRequestWho != null) {
17163                state.mSavedData |= BaseSavedState.START_ACTIVITY_REQUESTED_WHO_SAVED;
17164            }
17165
17166            if (isAutofilled()) {
17167                state.mSavedData |= BaseSavedState.IS_AUTOFILLED;
17168            }
17169
17170            state.mStartActivityRequestWhoSaved = mStartActivityRequestWho;
17171            state.mIsAutofilled = isAutofilled();
17172            return state;
17173        }
17174        return BaseSavedState.EMPTY_STATE;
17175    }
17176
17177    /**
17178     * Restore this view hierarchy's frozen state from the given container.
17179     *
17180     * @param container The SparseArray which holds previously frozen states.
17181     *
17182     * @see #saveHierarchyState(android.util.SparseArray)
17183     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
17184     * @see #onRestoreInstanceState(android.os.Parcelable)
17185     */
17186    public void restoreHierarchyState(SparseArray<Parcelable> container) {
17187        dispatchRestoreInstanceState(container);
17188    }
17189
17190    /**
17191     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
17192     * state for this view and its children. May be overridden to modify how restoring
17193     * happens to a view's children; for example, some views may want to not store state
17194     * for their children.
17195     *
17196     * @param container The SparseArray which holds previously saved state.
17197     *
17198     * @see #dispatchSaveInstanceState(android.util.SparseArray)
17199     * @see #restoreHierarchyState(android.util.SparseArray)
17200     * @see #onRestoreInstanceState(android.os.Parcelable)
17201     */
17202    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
17203        if (mID != NO_ID) {
17204            Parcelable state = container.get(mID);
17205            if (state != null) {
17206                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
17207                // + ": " + state);
17208                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
17209                onRestoreInstanceState(state);
17210                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
17211                    throw new IllegalStateException(
17212                            "Derived class did not call super.onRestoreInstanceState()");
17213                }
17214            }
17215        }
17216    }
17217
17218    /**
17219     * Hook allowing a view to re-apply a representation of its internal state that had previously
17220     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
17221     * null state.
17222     *
17223     * @param state The frozen state that had previously been returned by
17224     *        {@link #onSaveInstanceState}.
17225     *
17226     * @see #onSaveInstanceState()
17227     * @see #restoreHierarchyState(android.util.SparseArray)
17228     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
17229     */
17230    @CallSuper
17231    protected void onRestoreInstanceState(Parcelable state) {
17232        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
17233        if (state != null && !(state instanceof AbsSavedState)) {
17234            throw new IllegalArgumentException("Wrong state class, expecting View State but "
17235                    + "received " + state.getClass().toString() + " instead. This usually happens "
17236                    + "when two views of different type have the same id in the same hierarchy. "
17237                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
17238                    + "other views do not use the same id.");
17239        }
17240        if (state != null && state instanceof BaseSavedState) {
17241            BaseSavedState baseState = (BaseSavedState) state;
17242
17243            if ((baseState.mSavedData & BaseSavedState.START_ACTIVITY_REQUESTED_WHO_SAVED) != 0) {
17244                mStartActivityRequestWho = baseState.mStartActivityRequestWhoSaved;
17245            }
17246            if ((baseState.mSavedData & BaseSavedState.IS_AUTOFILLED) != 0) {
17247                setAutofilled(baseState.mIsAutofilled);
17248            }
17249        }
17250    }
17251
17252    /**
17253     * <p>Return the time at which the drawing of the view hierarchy started.</p>
17254     *
17255     * @return the drawing start time in milliseconds
17256     */
17257    public long getDrawingTime() {
17258        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
17259    }
17260
17261    /**
17262     * <p>Enables or disables the duplication of the parent's state into this view. When
17263     * duplication is enabled, this view gets its drawable state from its parent rather
17264     * than from its own internal properties.</p>
17265     *
17266     * <p>Note: in the current implementation, setting this property to true after the
17267     * view was added to a ViewGroup might have no effect at all. This property should
17268     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
17269     *
17270     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
17271     * property is enabled, an exception will be thrown.</p>
17272     *
17273     * <p>Note: if the child view uses and updates additional states which are unknown to the
17274     * parent, these states should not be affected by this method.</p>
17275     *
17276     * @param enabled True to enable duplication of the parent's drawable state, false
17277     *                to disable it.
17278     *
17279     * @see #getDrawableState()
17280     * @see #isDuplicateParentStateEnabled()
17281     */
17282    public void setDuplicateParentStateEnabled(boolean enabled) {
17283        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
17284    }
17285
17286    /**
17287     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
17288     *
17289     * @return True if this view's drawable state is duplicated from the parent,
17290     *         false otherwise
17291     *
17292     * @see #getDrawableState()
17293     * @see #setDuplicateParentStateEnabled(boolean)
17294     */
17295    public boolean isDuplicateParentStateEnabled() {
17296        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
17297    }
17298
17299    /**
17300     * <p>Specifies the type of layer backing this view. The layer can be
17301     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
17302     * {@link #LAYER_TYPE_HARDWARE}.</p>
17303     *
17304     * <p>A layer is associated with an optional {@link android.graphics.Paint}
17305     * instance that controls how the layer is composed on screen. The following
17306     * properties of the paint are taken into account when composing the layer:</p>
17307     * <ul>
17308     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
17309     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
17310     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
17311     * </ul>
17312     *
17313     * <p>If this view has an alpha value set to < 1.0 by calling
17314     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superseded
17315     * by this view's alpha value.</p>
17316     *
17317     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
17318     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
17319     * for more information on when and how to use layers.</p>
17320     *
17321     * @param layerType The type of layer to use with this view, must be one of
17322     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
17323     *        {@link #LAYER_TYPE_HARDWARE}
17324     * @param paint The paint used to compose the layer. This argument is optional
17325     *        and can be null. It is ignored when the layer type is
17326     *        {@link #LAYER_TYPE_NONE}
17327     *
17328     * @see #getLayerType()
17329     * @see #LAYER_TYPE_NONE
17330     * @see #LAYER_TYPE_SOFTWARE
17331     * @see #LAYER_TYPE_HARDWARE
17332     * @see #setAlpha(float)
17333     *
17334     * @attr ref android.R.styleable#View_layerType
17335     */
17336    public void setLayerType(int layerType, @Nullable Paint paint) {
17337        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
17338            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
17339                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
17340        }
17341
17342        boolean typeChanged = mRenderNode.setLayerType(layerType);
17343
17344        if (!typeChanged) {
17345            setLayerPaint(paint);
17346            return;
17347        }
17348
17349        if (layerType != LAYER_TYPE_SOFTWARE) {
17350            // Destroy any previous software drawing cache if present
17351            // NOTE: even if previous layer type is HW, we do this to ensure we've cleaned up
17352            // drawing cache created in View#draw when drawing to a SW canvas.
17353            destroyDrawingCache();
17354        }
17355
17356        mLayerType = layerType;
17357        mLayerPaint = mLayerType == LAYER_TYPE_NONE ? null : paint;
17358        mRenderNode.setLayerPaint(mLayerPaint);
17359
17360        // draw() behaves differently if we are on a layer, so we need to
17361        // invalidate() here
17362        invalidateParentCaches();
17363        invalidate(true);
17364    }
17365
17366    /**
17367     * Updates the {@link Paint} object used with the current layer (used only if the current
17368     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
17369     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
17370     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
17371     * ensure that the view gets redrawn immediately.
17372     *
17373     * <p>A layer is associated with an optional {@link android.graphics.Paint}
17374     * instance that controls how the layer is composed on screen. The following
17375     * properties of the paint are taken into account when composing the layer:</p>
17376     * <ul>
17377     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
17378     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
17379     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
17380     * </ul>
17381     *
17382     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
17383     * alpha value of the layer's paint is superseded by this view's alpha value.</p>
17384     *
17385     * @param paint The paint used to compose the layer. This argument is optional
17386     *        and can be null. It is ignored when the layer type is
17387     *        {@link #LAYER_TYPE_NONE}
17388     *
17389     * @see #setLayerType(int, android.graphics.Paint)
17390     */
17391    public void setLayerPaint(@Nullable Paint paint) {
17392        int layerType = getLayerType();
17393        if (layerType != LAYER_TYPE_NONE) {
17394            mLayerPaint = paint;
17395            if (layerType == LAYER_TYPE_HARDWARE) {
17396                if (mRenderNode.setLayerPaint(paint)) {
17397                    invalidateViewProperty(false, false);
17398                }
17399            } else {
17400                invalidate();
17401            }
17402        }
17403    }
17404
17405    /**
17406     * Indicates what type of layer is currently associated with this view. By default
17407     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
17408     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
17409     * for more information on the different types of layers.
17410     *
17411     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
17412     *         {@link #LAYER_TYPE_HARDWARE}
17413     *
17414     * @see #setLayerType(int, android.graphics.Paint)
17415     * @see #buildLayer()
17416     * @see #LAYER_TYPE_NONE
17417     * @see #LAYER_TYPE_SOFTWARE
17418     * @see #LAYER_TYPE_HARDWARE
17419     */
17420    public int getLayerType() {
17421        return mLayerType;
17422    }
17423
17424    /**
17425     * Forces this view's layer to be created and this view to be rendered
17426     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
17427     * invoking this method will have no effect.
17428     *
17429     * This method can for instance be used to render a view into its layer before
17430     * starting an animation. If this view is complex, rendering into the layer
17431     * before starting the animation will avoid skipping frames.
17432     *
17433     * @throws IllegalStateException If this view is not attached to a window
17434     *
17435     * @see #setLayerType(int, android.graphics.Paint)
17436     */
17437    public void buildLayer() {
17438        if (mLayerType == LAYER_TYPE_NONE) return;
17439
17440        final AttachInfo attachInfo = mAttachInfo;
17441        if (attachInfo == null) {
17442            throw new IllegalStateException("This view must be attached to a window first");
17443        }
17444
17445        if (getWidth() == 0 || getHeight() == 0) {
17446            return;
17447        }
17448
17449        switch (mLayerType) {
17450            case LAYER_TYPE_HARDWARE:
17451                updateDisplayListIfDirty();
17452                if (attachInfo.mThreadedRenderer != null && mRenderNode.isValid()) {
17453                    attachInfo.mThreadedRenderer.buildLayer(mRenderNode);
17454                }
17455                break;
17456            case LAYER_TYPE_SOFTWARE:
17457                buildDrawingCache(true);
17458                break;
17459        }
17460    }
17461
17462    /**
17463     * Destroys all hardware rendering resources. This method is invoked
17464     * when the system needs to reclaim resources. Upon execution of this
17465     * method, you should free any OpenGL resources created by the view.
17466     *
17467     * Note: you <strong>must</strong> call
17468     * <code>super.destroyHardwareResources()</code> when overriding
17469     * this method.
17470     *
17471     * @hide
17472     */
17473    @CallSuper
17474    protected void destroyHardwareResources() {
17475        if (mOverlay != null) {
17476            mOverlay.getOverlayView().destroyHardwareResources();
17477        }
17478        if (mGhostView != null) {
17479            mGhostView.destroyHardwareResources();
17480        }
17481    }
17482
17483    /**
17484     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
17485     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
17486     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
17487     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
17488     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
17489     * null.</p>
17490     *
17491     * <p>Enabling the drawing cache is similar to
17492     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
17493     * acceleration is turned off. When hardware acceleration is turned on, enabling the
17494     * drawing cache has no effect on rendering because the system uses a different mechanism
17495     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
17496     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
17497     * for information on how to enable software and hardware layers.</p>
17498     *
17499     * <p>This API can be used to manually generate
17500     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
17501     * {@link #getDrawingCache()}.</p>
17502     *
17503     * @param enabled true to enable the drawing cache, false otherwise
17504     *
17505     * @see #isDrawingCacheEnabled()
17506     * @see #getDrawingCache()
17507     * @see #buildDrawingCache()
17508     * @see #setLayerType(int, android.graphics.Paint)
17509     */
17510    public void setDrawingCacheEnabled(boolean enabled) {
17511        mCachingFailed = false;
17512        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
17513    }
17514
17515    /**
17516     * <p>Indicates whether the drawing cache is enabled for this view.</p>
17517     *
17518     * @return true if the drawing cache is enabled
17519     *
17520     * @see #setDrawingCacheEnabled(boolean)
17521     * @see #getDrawingCache()
17522     */
17523    @ViewDebug.ExportedProperty(category = "drawing")
17524    public boolean isDrawingCacheEnabled() {
17525        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
17526    }
17527
17528    /**
17529     * Debugging utility which recursively outputs the dirty state of a view and its
17530     * descendants.
17531     *
17532     * @hide
17533     */
17534    @SuppressWarnings({"UnusedDeclaration"})
17535    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
17536        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
17537                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
17538                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
17539                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
17540        if (clear) {
17541            mPrivateFlags &= clearMask;
17542        }
17543        if (this instanceof ViewGroup) {
17544            ViewGroup parent = (ViewGroup) this;
17545            final int count = parent.getChildCount();
17546            for (int i = 0; i < count; i++) {
17547                final View child = parent.getChildAt(i);
17548                child.outputDirtyFlags(indent + "  ", clear, clearMask);
17549            }
17550        }
17551    }
17552
17553    /**
17554     * This method is used by ViewGroup to cause its children to restore or recreate their
17555     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
17556     * to recreate its own display list, which would happen if it went through the normal
17557     * draw/dispatchDraw mechanisms.
17558     *
17559     * @hide
17560     */
17561    protected void dispatchGetDisplayList() {}
17562
17563    /**
17564     * A view that is not attached or hardware accelerated cannot create a display list.
17565     * This method checks these conditions and returns the appropriate result.
17566     *
17567     * @return true if view has the ability to create a display list, false otherwise.
17568     *
17569     * @hide
17570     */
17571    public boolean canHaveDisplayList() {
17572        return !(mAttachInfo == null || mAttachInfo.mThreadedRenderer == null);
17573    }
17574
17575    /**
17576     * Gets the RenderNode for the view, and updates its DisplayList (if needed and supported)
17577     * @hide
17578     */
17579    @NonNull
17580    public RenderNode updateDisplayListIfDirty() {
17581        final RenderNode renderNode = mRenderNode;
17582        if (!canHaveDisplayList()) {
17583            // can't populate RenderNode, don't try
17584            return renderNode;
17585        }
17586
17587        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0
17588                || !renderNode.isValid()
17589                || (mRecreateDisplayList)) {
17590            // Don't need to recreate the display list, just need to tell our
17591            // children to restore/recreate theirs
17592            if (renderNode.isValid()
17593                    && !mRecreateDisplayList) {
17594                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
17595                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17596                dispatchGetDisplayList();
17597
17598                return renderNode; // no work needed
17599            }
17600
17601            // If we got here, we're recreating it. Mark it as such to ensure that
17602            // we copy in child display lists into ours in drawChild()
17603            mRecreateDisplayList = true;
17604
17605            int width = mRight - mLeft;
17606            int height = mBottom - mTop;
17607            int layerType = getLayerType();
17608
17609            final DisplayListCanvas canvas = renderNode.start(width, height);
17610            canvas.setHighContrastText(mAttachInfo.mHighContrastText);
17611
17612            try {
17613                if (layerType == LAYER_TYPE_SOFTWARE) {
17614                    buildDrawingCache(true);
17615                    Bitmap cache = getDrawingCache(true);
17616                    if (cache != null) {
17617                        canvas.drawBitmap(cache, 0, 0, mLayerPaint);
17618                    }
17619                } else {
17620                    computeScroll();
17621
17622                    canvas.translate(-mScrollX, -mScrollY);
17623                    mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
17624                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17625
17626                    // Fast path for layouts with no backgrounds
17627                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
17628                        dispatchDraw(canvas);
17629                        drawAutofilledHighlight(canvas);
17630                        if (mOverlay != null && !mOverlay.isEmpty()) {
17631                            mOverlay.getOverlayView().draw(canvas);
17632                        }
17633                        if (debugDraw()) {
17634                            debugDrawFocus(canvas);
17635                        }
17636                    } else {
17637                        draw(canvas);
17638                    }
17639                }
17640            } finally {
17641                renderNode.end(canvas);
17642                setDisplayListProperties(renderNode);
17643            }
17644        } else {
17645            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
17646            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17647        }
17648        return renderNode;
17649    }
17650
17651    private void resetDisplayList() {
17652        mRenderNode.discardDisplayList();
17653        if (mBackgroundRenderNode != null) {
17654            mBackgroundRenderNode.discardDisplayList();
17655        }
17656    }
17657
17658    /**
17659     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
17660     *
17661     * @return A non-scaled bitmap representing this view or null if cache is disabled.
17662     *
17663     * @see #getDrawingCache(boolean)
17664     */
17665    public Bitmap getDrawingCache() {
17666        return getDrawingCache(false);
17667    }
17668
17669    /**
17670     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
17671     * is null when caching is disabled. If caching is enabled and the cache is not ready,
17672     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
17673     * draw from the cache when the cache is enabled. To benefit from the cache, you must
17674     * request the drawing cache by calling this method and draw it on screen if the
17675     * returned bitmap is not null.</p>
17676     *
17677     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
17678     * this method will create a bitmap of the same size as this view. Because this bitmap
17679     * will be drawn scaled by the parent ViewGroup, the result on screen might show
17680     * scaling artifacts. To avoid such artifacts, you should call this method by setting
17681     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
17682     * size than the view. This implies that your application must be able to handle this
17683     * size.</p>
17684     *
17685     * @param autoScale Indicates whether the generated bitmap should be scaled based on
17686     *        the current density of the screen when the application is in compatibility
17687     *        mode.
17688     *
17689     * @return A bitmap representing this view or null if cache is disabled.
17690     *
17691     * @see #setDrawingCacheEnabled(boolean)
17692     * @see #isDrawingCacheEnabled()
17693     * @see #buildDrawingCache(boolean)
17694     * @see #destroyDrawingCache()
17695     */
17696    public Bitmap getDrawingCache(boolean autoScale) {
17697        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
17698            return null;
17699        }
17700        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
17701            buildDrawingCache(autoScale);
17702        }
17703        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
17704    }
17705
17706    /**
17707     * <p>Frees the resources used by the drawing cache. If you call
17708     * {@link #buildDrawingCache()} manually without calling
17709     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
17710     * should cleanup the cache with this method afterwards.</p>
17711     *
17712     * @see #setDrawingCacheEnabled(boolean)
17713     * @see #buildDrawingCache()
17714     * @see #getDrawingCache()
17715     */
17716    public void destroyDrawingCache() {
17717        if (mDrawingCache != null) {
17718            mDrawingCache.recycle();
17719            mDrawingCache = null;
17720        }
17721        if (mUnscaledDrawingCache != null) {
17722            mUnscaledDrawingCache.recycle();
17723            mUnscaledDrawingCache = null;
17724        }
17725    }
17726
17727    /**
17728     * Setting a solid background color for the drawing cache's bitmaps will improve
17729     * performance and memory usage. Note, though that this should only be used if this
17730     * view will always be drawn on top of a solid color.
17731     *
17732     * @param color The background color to use for the drawing cache's bitmap
17733     *
17734     * @see #setDrawingCacheEnabled(boolean)
17735     * @see #buildDrawingCache()
17736     * @see #getDrawingCache()
17737     */
17738    public void setDrawingCacheBackgroundColor(@ColorInt int color) {
17739        if (color != mDrawingCacheBackgroundColor) {
17740            mDrawingCacheBackgroundColor = color;
17741            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
17742        }
17743    }
17744
17745    /**
17746     * @see #setDrawingCacheBackgroundColor(int)
17747     *
17748     * @return The background color to used for the drawing cache's bitmap
17749     */
17750    @ColorInt
17751    public int getDrawingCacheBackgroundColor() {
17752        return mDrawingCacheBackgroundColor;
17753    }
17754
17755    /**
17756     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
17757     *
17758     * @see #buildDrawingCache(boolean)
17759     */
17760    public void buildDrawingCache() {
17761        buildDrawingCache(false);
17762    }
17763
17764    /**
17765     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
17766     *
17767     * <p>If you call {@link #buildDrawingCache()} manually without calling
17768     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
17769     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
17770     *
17771     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
17772     * this method will create a bitmap of the same size as this view. Because this bitmap
17773     * will be drawn scaled by the parent ViewGroup, the result on screen might show
17774     * scaling artifacts. To avoid such artifacts, you should call this method by setting
17775     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
17776     * size than the view. This implies that your application must be able to handle this
17777     * size.</p>
17778     *
17779     * <p>You should avoid calling this method when hardware acceleration is enabled. If
17780     * you do not need the drawing cache bitmap, calling this method will increase memory
17781     * usage and cause the view to be rendered in software once, thus negatively impacting
17782     * performance.</p>
17783     *
17784     * @see #getDrawingCache()
17785     * @see #destroyDrawingCache()
17786     */
17787    public void buildDrawingCache(boolean autoScale) {
17788        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
17789                mDrawingCache == null : mUnscaledDrawingCache == null)) {
17790            if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) {
17791                Trace.traceBegin(Trace.TRACE_TAG_VIEW,
17792                        "buildDrawingCache/SW Layer for " + getClass().getSimpleName());
17793            }
17794            try {
17795                buildDrawingCacheImpl(autoScale);
17796            } finally {
17797                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
17798            }
17799        }
17800    }
17801
17802    /**
17803     * private, internal implementation of buildDrawingCache, used to enable tracing
17804     */
17805    private void buildDrawingCacheImpl(boolean autoScale) {
17806        mCachingFailed = false;
17807
17808        int width = mRight - mLeft;
17809        int height = mBottom - mTop;
17810
17811        final AttachInfo attachInfo = mAttachInfo;
17812        final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
17813
17814        if (autoScale && scalingRequired) {
17815            width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
17816            height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
17817        }
17818
17819        final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
17820        final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
17821        final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
17822
17823        final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
17824        final long drawingCacheSize =
17825                ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
17826        if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
17827            if (width > 0 && height > 0) {
17828                Log.w(VIEW_LOG_TAG, getClass().getSimpleName() + " not displayed because it is"
17829                        + " too large to fit into a software layer (or drawing cache), needs "
17830                        + projectedBitmapSize + " bytes, only "
17831                        + drawingCacheSize + " available");
17832            }
17833            destroyDrawingCache();
17834            mCachingFailed = true;
17835            return;
17836        }
17837
17838        boolean clear = true;
17839        Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
17840
17841        if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
17842            Bitmap.Config quality;
17843            if (!opaque) {
17844                // Never pick ARGB_4444 because it looks awful
17845                // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
17846                switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
17847                    case DRAWING_CACHE_QUALITY_AUTO:
17848                    case DRAWING_CACHE_QUALITY_LOW:
17849                    case DRAWING_CACHE_QUALITY_HIGH:
17850                    default:
17851                        quality = Bitmap.Config.ARGB_8888;
17852                        break;
17853                }
17854            } else {
17855                // Optimization for translucent windows
17856                // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
17857                quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
17858            }
17859
17860            // Try to cleanup memory
17861            if (bitmap != null) bitmap.recycle();
17862
17863            try {
17864                bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
17865                        width, height, quality);
17866                bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
17867                if (autoScale) {
17868                    mDrawingCache = bitmap;
17869                } else {
17870                    mUnscaledDrawingCache = bitmap;
17871                }
17872                if (opaque && use32BitCache) bitmap.setHasAlpha(false);
17873            } catch (OutOfMemoryError e) {
17874                // If there is not enough memory to create the bitmap cache, just
17875                // ignore the issue as bitmap caches are not required to draw the
17876                // view hierarchy
17877                if (autoScale) {
17878                    mDrawingCache = null;
17879                } else {
17880                    mUnscaledDrawingCache = null;
17881                }
17882                mCachingFailed = true;
17883                return;
17884            }
17885
17886            clear = drawingCacheBackgroundColor != 0;
17887        }
17888
17889        Canvas canvas;
17890        if (attachInfo != null) {
17891            canvas = attachInfo.mCanvas;
17892            if (canvas == null) {
17893                canvas = new Canvas();
17894            }
17895            canvas.setBitmap(bitmap);
17896            // Temporarily clobber the cached Canvas in case one of our children
17897            // is also using a drawing cache. Without this, the children would
17898            // steal the canvas by attaching their own bitmap to it and bad, bad
17899            // thing would happen (invisible views, corrupted drawings, etc.)
17900            attachInfo.mCanvas = null;
17901        } else {
17902            // This case should hopefully never or seldom happen
17903            canvas = new Canvas(bitmap);
17904        }
17905
17906        if (clear) {
17907            bitmap.eraseColor(drawingCacheBackgroundColor);
17908        }
17909
17910        computeScroll();
17911        final int restoreCount = canvas.save();
17912
17913        if (autoScale && scalingRequired) {
17914            final float scale = attachInfo.mApplicationScale;
17915            canvas.scale(scale, scale);
17916        }
17917
17918        canvas.translate(-mScrollX, -mScrollY);
17919
17920        mPrivateFlags |= PFLAG_DRAWN;
17921        if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
17922                mLayerType != LAYER_TYPE_NONE) {
17923            mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
17924        }
17925
17926        // Fast path for layouts with no backgrounds
17927        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
17928            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17929            dispatchDraw(canvas);
17930            drawAutofilledHighlight(canvas);
17931            if (mOverlay != null && !mOverlay.isEmpty()) {
17932                mOverlay.getOverlayView().draw(canvas);
17933            }
17934        } else {
17935            draw(canvas);
17936        }
17937
17938        canvas.restoreToCount(restoreCount);
17939        canvas.setBitmap(null);
17940
17941        if (attachInfo != null) {
17942            // Restore the cached Canvas for our siblings
17943            attachInfo.mCanvas = canvas;
17944        }
17945    }
17946
17947    /**
17948     * Create a snapshot of the view into a bitmap.  We should probably make
17949     * some form of this public, but should think about the API.
17950     *
17951     * @hide
17952     */
17953    public Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
17954        int width = mRight - mLeft;
17955        int height = mBottom - mTop;
17956
17957        final AttachInfo attachInfo = mAttachInfo;
17958        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
17959        width = (int) ((width * scale) + 0.5f);
17960        height = (int) ((height * scale) + 0.5f);
17961
17962        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
17963                width > 0 ? width : 1, height > 0 ? height : 1, quality);
17964        if (bitmap == null) {
17965            throw new OutOfMemoryError();
17966        }
17967
17968        Resources resources = getResources();
17969        if (resources != null) {
17970            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
17971        }
17972
17973        Canvas canvas;
17974        if (attachInfo != null) {
17975            canvas = attachInfo.mCanvas;
17976            if (canvas == null) {
17977                canvas = new Canvas();
17978            }
17979            canvas.setBitmap(bitmap);
17980            // Temporarily clobber the cached Canvas in case one of our children
17981            // is also using a drawing cache. Without this, the children would
17982            // steal the canvas by attaching their own bitmap to it and bad, bad
17983            // things would happen (invisible views, corrupted drawings, etc.)
17984            attachInfo.mCanvas = null;
17985        } else {
17986            // This case should hopefully never or seldom happen
17987            canvas = new Canvas(bitmap);
17988        }
17989        boolean enabledHwBitmapsInSwMode = canvas.isHwBitmapsInSwModeEnabled();
17990        canvas.setHwBitmapsInSwModeEnabled(true);
17991        if ((backgroundColor & 0xff000000) != 0) {
17992            bitmap.eraseColor(backgroundColor);
17993        }
17994
17995        computeScroll();
17996        final int restoreCount = canvas.save();
17997        canvas.scale(scale, scale);
17998        canvas.translate(-mScrollX, -mScrollY);
17999
18000        // Temporarily remove the dirty mask
18001        int flags = mPrivateFlags;
18002        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
18003
18004        // Fast path for layouts with no backgrounds
18005        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
18006            dispatchDraw(canvas);
18007            drawAutofilledHighlight(canvas);
18008            if (mOverlay != null && !mOverlay.isEmpty()) {
18009                mOverlay.getOverlayView().draw(canvas);
18010            }
18011        } else {
18012            draw(canvas);
18013        }
18014
18015        mPrivateFlags = flags;
18016
18017        canvas.restoreToCount(restoreCount);
18018        canvas.setBitmap(null);
18019        canvas.setHwBitmapsInSwModeEnabled(enabledHwBitmapsInSwMode);
18020
18021        if (attachInfo != null) {
18022            // Restore the cached Canvas for our siblings
18023            attachInfo.mCanvas = canvas;
18024        }
18025
18026        return bitmap;
18027    }
18028
18029    /**
18030     * Indicates whether this View is currently in edit mode. A View is usually
18031     * in edit mode when displayed within a developer tool. For instance, if
18032     * this View is being drawn by a visual user interface builder, this method
18033     * should return true.
18034     *
18035     * Subclasses should check the return value of this method to provide
18036     * different behaviors if their normal behavior might interfere with the
18037     * host environment. For instance: the class spawns a thread in its
18038     * constructor, the drawing code relies on device-specific features, etc.
18039     *
18040     * This method is usually checked in the drawing code of custom widgets.
18041     *
18042     * @return True if this View is in edit mode, false otherwise.
18043     */
18044    public boolean isInEditMode() {
18045        return false;
18046    }
18047
18048    /**
18049     * If the View draws content inside its padding and enables fading edges,
18050     * it needs to support padding offsets. Padding offsets are added to the
18051     * fading edges to extend the length of the fade so that it covers pixels
18052     * drawn inside the padding.
18053     *
18054     * Subclasses of this class should override this method if they need
18055     * to draw content inside the padding.
18056     *
18057     * @return True if padding offset must be applied, false otherwise.
18058     *
18059     * @see #getLeftPaddingOffset()
18060     * @see #getRightPaddingOffset()
18061     * @see #getTopPaddingOffset()
18062     * @see #getBottomPaddingOffset()
18063     *
18064     * @since CURRENT
18065     */
18066    protected boolean isPaddingOffsetRequired() {
18067        return false;
18068    }
18069
18070    /**
18071     * Amount by which to extend the left fading region. Called only when
18072     * {@link #isPaddingOffsetRequired()} returns true.
18073     *
18074     * @return The left padding offset in pixels.
18075     *
18076     * @see #isPaddingOffsetRequired()
18077     *
18078     * @since CURRENT
18079     */
18080    protected int getLeftPaddingOffset() {
18081        return 0;
18082    }
18083
18084    /**
18085     * Amount by which to extend the right fading region. Called only when
18086     * {@link #isPaddingOffsetRequired()} returns true.
18087     *
18088     * @return The right padding offset in pixels.
18089     *
18090     * @see #isPaddingOffsetRequired()
18091     *
18092     * @since CURRENT
18093     */
18094    protected int getRightPaddingOffset() {
18095        return 0;
18096    }
18097
18098    /**
18099     * Amount by which to extend the top fading region. Called only when
18100     * {@link #isPaddingOffsetRequired()} returns true.
18101     *
18102     * @return The top padding offset in pixels.
18103     *
18104     * @see #isPaddingOffsetRequired()
18105     *
18106     * @since CURRENT
18107     */
18108    protected int getTopPaddingOffset() {
18109        return 0;
18110    }
18111
18112    /**
18113     * Amount by which to extend the bottom fading region. Called only when
18114     * {@link #isPaddingOffsetRequired()} returns true.
18115     *
18116     * @return The bottom padding offset in pixels.
18117     *
18118     * @see #isPaddingOffsetRequired()
18119     *
18120     * @since CURRENT
18121     */
18122    protected int getBottomPaddingOffset() {
18123        return 0;
18124    }
18125
18126    /**
18127     * @hide
18128     * @param offsetRequired
18129     */
18130    protected int getFadeTop(boolean offsetRequired) {
18131        int top = mPaddingTop;
18132        if (offsetRequired) top += getTopPaddingOffset();
18133        return top;
18134    }
18135
18136    /**
18137     * @hide
18138     * @param offsetRequired
18139     */
18140    protected int getFadeHeight(boolean offsetRequired) {
18141        int padding = mPaddingTop;
18142        if (offsetRequired) padding += getTopPaddingOffset();
18143        return mBottom - mTop - mPaddingBottom - padding;
18144    }
18145
18146    /**
18147     * <p>Indicates whether this view is attached to a hardware accelerated
18148     * window or not.</p>
18149     *
18150     * <p>Even if this method returns true, it does not mean that every call
18151     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
18152     * accelerated {@link android.graphics.Canvas}. For instance, if this view
18153     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
18154     * window is hardware accelerated,
18155     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
18156     * return false, and this method will return true.</p>
18157     *
18158     * @return True if the view is attached to a window and the window is
18159     *         hardware accelerated; false in any other case.
18160     */
18161    @ViewDebug.ExportedProperty(category = "drawing")
18162    public boolean isHardwareAccelerated() {
18163        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
18164    }
18165
18166    /**
18167     * Sets a rectangular area on this view to which the view will be clipped
18168     * when it is drawn. Setting the value to null will remove the clip bounds
18169     * and the view will draw normally, using its full bounds.
18170     *
18171     * @param clipBounds The rectangular area, in the local coordinates of
18172     * this view, to which future drawing operations will be clipped.
18173     */
18174    public void setClipBounds(Rect clipBounds) {
18175        if (clipBounds == mClipBounds
18176                || (clipBounds != null && clipBounds.equals(mClipBounds))) {
18177            return;
18178        }
18179        if (clipBounds != null) {
18180            if (mClipBounds == null) {
18181                mClipBounds = new Rect(clipBounds);
18182            } else {
18183                mClipBounds.set(clipBounds);
18184            }
18185        } else {
18186            mClipBounds = null;
18187        }
18188        mRenderNode.setClipBounds(mClipBounds);
18189        invalidateViewProperty(false, false);
18190    }
18191
18192    /**
18193     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
18194     *
18195     * @return A copy of the current clip bounds if clip bounds are set,
18196     * otherwise null.
18197     */
18198    public Rect getClipBounds() {
18199        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
18200    }
18201
18202
18203    /**
18204     * Populates an output rectangle with the clip bounds of the view,
18205     * returning {@code true} if successful or {@code false} if the view's
18206     * clip bounds are {@code null}.
18207     *
18208     * @param outRect rectangle in which to place the clip bounds of the view
18209     * @return {@code true} if successful or {@code false} if the view's
18210     *         clip bounds are {@code null}
18211     */
18212    public boolean getClipBounds(Rect outRect) {
18213        if (mClipBounds != null) {
18214            outRect.set(mClipBounds);
18215            return true;
18216        }
18217        return false;
18218    }
18219
18220    /**
18221     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
18222     * case of an active Animation being run on the view.
18223     */
18224    private boolean applyLegacyAnimation(ViewGroup parent, long drawingTime,
18225            Animation a, boolean scalingRequired) {
18226        Transformation invalidationTransform;
18227        final int flags = parent.mGroupFlags;
18228        final boolean initialized = a.isInitialized();
18229        if (!initialized) {
18230            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
18231            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
18232            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
18233            onAnimationStart();
18234        }
18235
18236        final Transformation t = parent.getChildTransformation();
18237        boolean more = a.getTransformation(drawingTime, t, 1f);
18238        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
18239            if (parent.mInvalidationTransformation == null) {
18240                parent.mInvalidationTransformation = new Transformation();
18241            }
18242            invalidationTransform = parent.mInvalidationTransformation;
18243            a.getTransformation(drawingTime, invalidationTransform, 1f);
18244        } else {
18245            invalidationTransform = t;
18246        }
18247
18248        if (more) {
18249            if (!a.willChangeBounds()) {
18250                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
18251                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
18252                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
18253                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
18254                    // The child need to draw an animation, potentially offscreen, so
18255                    // make sure we do not cancel invalidate requests
18256                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
18257                    parent.invalidate(mLeft, mTop, mRight, mBottom);
18258                }
18259            } else {
18260                if (parent.mInvalidateRegion == null) {
18261                    parent.mInvalidateRegion = new RectF();
18262                }
18263                final RectF region = parent.mInvalidateRegion;
18264                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
18265                        invalidationTransform);
18266
18267                // The child need to draw an animation, potentially offscreen, so
18268                // make sure we do not cancel invalidate requests
18269                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
18270
18271                final int left = mLeft + (int) region.left;
18272                final int top = mTop + (int) region.top;
18273                parent.invalidate(left, top, left + (int) (region.width() + .5f),
18274                        top + (int) (region.height() + .5f));
18275            }
18276        }
18277        return more;
18278    }
18279
18280    /**
18281     * This method is called by getDisplayList() when a display list is recorded for a View.
18282     * It pushes any properties to the RenderNode that aren't managed by the RenderNode.
18283     */
18284    void setDisplayListProperties(RenderNode renderNode) {
18285        if (renderNode != null) {
18286            renderNode.setHasOverlappingRendering(getHasOverlappingRendering());
18287            renderNode.setClipToBounds(mParent instanceof ViewGroup
18288                    && ((ViewGroup) mParent).getClipChildren());
18289
18290            float alpha = 1;
18291            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
18292                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
18293                ViewGroup parentVG = (ViewGroup) mParent;
18294                final Transformation t = parentVG.getChildTransformation();
18295                if (parentVG.getChildStaticTransformation(this, t)) {
18296                    final int transformType = t.getTransformationType();
18297                    if (transformType != Transformation.TYPE_IDENTITY) {
18298                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
18299                            alpha = t.getAlpha();
18300                        }
18301                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
18302                            renderNode.setStaticMatrix(t.getMatrix());
18303                        }
18304                    }
18305                }
18306            }
18307            if (mTransformationInfo != null) {
18308                alpha *= getFinalAlpha();
18309                if (alpha < 1) {
18310                    final int multipliedAlpha = (int) (255 * alpha);
18311                    if (onSetAlpha(multipliedAlpha)) {
18312                        alpha = 1;
18313                    }
18314                }
18315                renderNode.setAlpha(alpha);
18316            } else if (alpha < 1) {
18317                renderNode.setAlpha(alpha);
18318            }
18319        }
18320    }
18321
18322    /**
18323     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
18324     *
18325     * This is where the View specializes rendering behavior based on layer type,
18326     * and hardware acceleration.
18327     */
18328    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
18329        final boolean hardwareAcceleratedCanvas = canvas.isHardwareAccelerated();
18330        /* If an attached view draws to a HW canvas, it may use its RenderNode + DisplayList.
18331         *
18332         * If a view is dettached, its DisplayList shouldn't exist. If the canvas isn't
18333         * HW accelerated, it can't handle drawing RenderNodes.
18334         */
18335        boolean drawingWithRenderNode = mAttachInfo != null
18336                && mAttachInfo.mHardwareAccelerated
18337                && hardwareAcceleratedCanvas;
18338
18339        boolean more = false;
18340        final boolean childHasIdentityMatrix = hasIdentityMatrix();
18341        final int parentFlags = parent.mGroupFlags;
18342
18343        if ((parentFlags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) != 0) {
18344            parent.getChildTransformation().clear();
18345            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
18346        }
18347
18348        Transformation transformToApply = null;
18349        boolean concatMatrix = false;
18350        final boolean scalingRequired = mAttachInfo != null && mAttachInfo.mScalingRequired;
18351        final Animation a = getAnimation();
18352        if (a != null) {
18353            more = applyLegacyAnimation(parent, drawingTime, a, scalingRequired);
18354            concatMatrix = a.willChangeTransformationMatrix();
18355            if (concatMatrix) {
18356                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
18357            }
18358            transformToApply = parent.getChildTransformation();
18359        } else {
18360            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) {
18361                // No longer animating: clear out old animation matrix
18362                mRenderNode.setAnimationMatrix(null);
18363                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
18364            }
18365            if (!drawingWithRenderNode
18366                    && (parentFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
18367                final Transformation t = parent.getChildTransformation();
18368                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
18369                if (hasTransform) {
18370                    final int transformType = t.getTransformationType();
18371                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
18372                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
18373                }
18374            }
18375        }
18376
18377        concatMatrix |= !childHasIdentityMatrix;
18378
18379        // Sets the flag as early as possible to allow draw() implementations
18380        // to call invalidate() successfully when doing animations
18381        mPrivateFlags |= PFLAG_DRAWN;
18382
18383        if (!concatMatrix &&
18384                (parentFlags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
18385                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
18386                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
18387                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
18388            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
18389            return more;
18390        }
18391        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
18392
18393        if (hardwareAcceleratedCanvas) {
18394            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
18395            // retain the flag's value temporarily in the mRecreateDisplayList flag
18396            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) != 0;
18397            mPrivateFlags &= ~PFLAG_INVALIDATED;
18398        }
18399
18400        RenderNode renderNode = null;
18401        Bitmap cache = null;
18402        int layerType = getLayerType(); // TODO: signify cache state with just 'cache' local
18403        if (layerType == LAYER_TYPE_SOFTWARE || !drawingWithRenderNode) {
18404             if (layerType != LAYER_TYPE_NONE) {
18405                 // If not drawing with RenderNode, treat HW layers as SW
18406                 layerType = LAYER_TYPE_SOFTWARE;
18407                 buildDrawingCache(true);
18408            }
18409            cache = getDrawingCache(true);
18410        }
18411
18412        if (drawingWithRenderNode) {
18413            // Delay getting the display list until animation-driven alpha values are
18414            // set up and possibly passed on to the view
18415            renderNode = updateDisplayListIfDirty();
18416            if (!renderNode.isValid()) {
18417                // Uncommon, but possible. If a view is removed from the hierarchy during the call
18418                // to getDisplayList(), the display list will be marked invalid and we should not
18419                // try to use it again.
18420                renderNode = null;
18421                drawingWithRenderNode = false;
18422            }
18423        }
18424
18425        int sx = 0;
18426        int sy = 0;
18427        if (!drawingWithRenderNode) {
18428            computeScroll();
18429            sx = mScrollX;
18430            sy = mScrollY;
18431        }
18432
18433        final boolean drawingWithDrawingCache = cache != null && !drawingWithRenderNode;
18434        final boolean offsetForScroll = cache == null && !drawingWithRenderNode;
18435
18436        int restoreTo = -1;
18437        if (!drawingWithRenderNode || transformToApply != null) {
18438            restoreTo = canvas.save();
18439        }
18440        if (offsetForScroll) {
18441            canvas.translate(mLeft - sx, mTop - sy);
18442        } else {
18443            if (!drawingWithRenderNode) {
18444                canvas.translate(mLeft, mTop);
18445            }
18446            if (scalingRequired) {
18447                if (drawingWithRenderNode) {
18448                    // TODO: Might not need this if we put everything inside the DL
18449                    restoreTo = canvas.save();
18450                }
18451                // mAttachInfo cannot be null, otherwise scalingRequired == false
18452                final float scale = 1.0f / mAttachInfo.mApplicationScale;
18453                canvas.scale(scale, scale);
18454            }
18455        }
18456
18457        float alpha = drawingWithRenderNode ? 1 : (getAlpha() * getTransitionAlpha());
18458        if (transformToApply != null
18459                || alpha < 1
18460                || !hasIdentityMatrix()
18461                || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
18462            if (transformToApply != null || !childHasIdentityMatrix) {
18463                int transX = 0;
18464                int transY = 0;
18465
18466                if (offsetForScroll) {
18467                    transX = -sx;
18468                    transY = -sy;
18469                }
18470
18471                if (transformToApply != null) {
18472                    if (concatMatrix) {
18473                        if (drawingWithRenderNode) {
18474                            renderNode.setAnimationMatrix(transformToApply.getMatrix());
18475                        } else {
18476                            // Undo the scroll translation, apply the transformation matrix,
18477                            // then redo the scroll translate to get the correct result.
18478                            canvas.translate(-transX, -transY);
18479                            canvas.concat(transformToApply.getMatrix());
18480                            canvas.translate(transX, transY);
18481                        }
18482                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
18483                    }
18484
18485                    float transformAlpha = transformToApply.getAlpha();
18486                    if (transformAlpha < 1) {
18487                        alpha *= transformAlpha;
18488                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
18489                    }
18490                }
18491
18492                if (!childHasIdentityMatrix && !drawingWithRenderNode) {
18493                    canvas.translate(-transX, -transY);
18494                    canvas.concat(getMatrix());
18495                    canvas.translate(transX, transY);
18496                }
18497            }
18498
18499            // Deal with alpha if it is or used to be <1
18500            if (alpha < 1 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
18501                if (alpha < 1) {
18502                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
18503                } else {
18504                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
18505                }
18506                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
18507                if (!drawingWithDrawingCache) {
18508                    final int multipliedAlpha = (int) (255 * alpha);
18509                    if (!onSetAlpha(multipliedAlpha)) {
18510                        if (drawingWithRenderNode) {
18511                            renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha());
18512                        } else if (layerType == LAYER_TYPE_NONE) {
18513                            canvas.saveLayerAlpha(sx, sy, sx + getWidth(), sy + getHeight(),
18514                                    multipliedAlpha);
18515                        }
18516                    } else {
18517                        // Alpha is handled by the child directly, clobber the layer's alpha
18518                        mPrivateFlags |= PFLAG_ALPHA_SET;
18519                    }
18520                }
18521            }
18522        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
18523            onSetAlpha(255);
18524            mPrivateFlags &= ~PFLAG_ALPHA_SET;
18525        }
18526
18527        if (!drawingWithRenderNode) {
18528            // apply clips directly, since RenderNode won't do it for this draw
18529            if ((parentFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 && cache == null) {
18530                if (offsetForScroll) {
18531                    canvas.clipRect(sx, sy, sx + getWidth(), sy + getHeight());
18532                } else {
18533                    if (!scalingRequired || cache == null) {
18534                        canvas.clipRect(0, 0, getWidth(), getHeight());
18535                    } else {
18536                        canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
18537                    }
18538                }
18539            }
18540
18541            if (mClipBounds != null) {
18542                // clip bounds ignore scroll
18543                canvas.clipRect(mClipBounds);
18544            }
18545        }
18546
18547        if (!drawingWithDrawingCache) {
18548            if (drawingWithRenderNode) {
18549                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
18550                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
18551            } else {
18552                // Fast path for layouts with no backgrounds
18553                if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
18554                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
18555                    dispatchDraw(canvas);
18556                } else {
18557                    draw(canvas);
18558                }
18559            }
18560        } else if (cache != null) {
18561            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
18562            if (layerType == LAYER_TYPE_NONE || mLayerPaint == null) {
18563                // no layer paint, use temporary paint to draw bitmap
18564                Paint cachePaint = parent.mCachePaint;
18565                if (cachePaint == null) {
18566                    cachePaint = new Paint();
18567                    cachePaint.setDither(false);
18568                    parent.mCachePaint = cachePaint;
18569                }
18570                cachePaint.setAlpha((int) (alpha * 255));
18571                canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
18572            } else {
18573                // use layer paint to draw the bitmap, merging the two alphas, but also restore
18574                int layerPaintAlpha = mLayerPaint.getAlpha();
18575                if (alpha < 1) {
18576                    mLayerPaint.setAlpha((int) (alpha * layerPaintAlpha));
18577                }
18578                canvas.drawBitmap(cache, 0.0f, 0.0f, mLayerPaint);
18579                if (alpha < 1) {
18580                    mLayerPaint.setAlpha(layerPaintAlpha);
18581                }
18582            }
18583        }
18584
18585        if (restoreTo >= 0) {
18586            canvas.restoreToCount(restoreTo);
18587        }
18588
18589        if (a != null && !more) {
18590            if (!hardwareAcceleratedCanvas && !a.getFillAfter()) {
18591                onSetAlpha(255);
18592            }
18593            parent.finishAnimatingView(this, a);
18594        }
18595
18596        if (more && hardwareAcceleratedCanvas) {
18597            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
18598                // alpha animations should cause the child to recreate its display list
18599                invalidate(true);
18600            }
18601        }
18602
18603        mRecreateDisplayList = false;
18604
18605        return more;
18606    }
18607
18608    static Paint getDebugPaint() {
18609        if (sDebugPaint == null) {
18610            sDebugPaint = new Paint();
18611            sDebugPaint.setAntiAlias(false);
18612        }
18613        return sDebugPaint;
18614    }
18615
18616    final int dipsToPixels(int dips) {
18617        float scale = getContext().getResources().getDisplayMetrics().density;
18618        return (int) (dips * scale + 0.5f);
18619    }
18620
18621    final private void debugDrawFocus(Canvas canvas) {
18622        if (isFocused()) {
18623            final int cornerSquareSize = dipsToPixels(DEBUG_CORNERS_SIZE_DIP);
18624            final int l = mScrollX;
18625            final int r = l + mRight - mLeft;
18626            final int t = mScrollY;
18627            final int b = t + mBottom - mTop;
18628
18629            final Paint paint = getDebugPaint();
18630            paint.setColor(DEBUG_CORNERS_COLOR);
18631
18632            // Draw squares in corners.
18633            paint.setStyle(Paint.Style.FILL);
18634            canvas.drawRect(l, t, l + cornerSquareSize, t + cornerSquareSize, paint);
18635            canvas.drawRect(r - cornerSquareSize, t, r, t + cornerSquareSize, paint);
18636            canvas.drawRect(l, b - cornerSquareSize, l + cornerSquareSize, b, paint);
18637            canvas.drawRect(r - cornerSquareSize, b - cornerSquareSize, r, b, paint);
18638
18639            // Draw big X across the view.
18640            paint.setStyle(Paint.Style.STROKE);
18641            canvas.drawLine(l, t, r, b, paint);
18642            canvas.drawLine(l, b, r, t, paint);
18643        }
18644    }
18645
18646    /**
18647     * Manually render this view (and all of its children) to the given Canvas.
18648     * The view must have already done a full layout before this function is
18649     * called.  When implementing a view, implement
18650     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
18651     * If you do need to override this method, call the superclass version.
18652     *
18653     * @param canvas The Canvas to which the View is rendered.
18654     */
18655    @CallSuper
18656    public void draw(Canvas canvas) {
18657        final int privateFlags = mPrivateFlags;
18658        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
18659                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
18660        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
18661
18662        /*
18663         * Draw traversal performs several drawing steps which must be executed
18664         * in the appropriate order:
18665         *
18666         *      1. Draw the background
18667         *      2. If necessary, save the canvas' layers to prepare for fading
18668         *      3. Draw view's content
18669         *      4. Draw children
18670         *      5. If necessary, draw the fading edges and restore layers
18671         *      6. Draw decorations (scrollbars for instance)
18672         */
18673
18674        // Step 1, draw the background, if needed
18675        int saveCount;
18676
18677        if (!dirtyOpaque) {
18678            drawBackground(canvas);
18679        }
18680
18681        // skip step 2 & 5 if possible (common case)
18682        final int viewFlags = mViewFlags;
18683        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
18684        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
18685        if (!verticalEdges && !horizontalEdges) {
18686            // Step 3, draw the content
18687            if (!dirtyOpaque) onDraw(canvas);
18688
18689            // Step 4, draw the children
18690            dispatchDraw(canvas);
18691
18692            drawAutofilledHighlight(canvas);
18693
18694            // Overlay is part of the content and draws beneath Foreground
18695            if (mOverlay != null && !mOverlay.isEmpty()) {
18696                mOverlay.getOverlayView().dispatchDraw(canvas);
18697            }
18698
18699            // Step 6, draw decorations (foreground, scrollbars)
18700            onDrawForeground(canvas);
18701
18702            if (debugDraw()) {
18703                debugDrawFocus(canvas);
18704            }
18705
18706            // we're done...
18707            return;
18708        }
18709
18710        /*
18711         * Here we do the full fledged routine...
18712         * (this is an uncommon case where speed matters less,
18713         * this is why we repeat some of the tests that have been
18714         * done above)
18715         */
18716
18717        boolean drawTop = false;
18718        boolean drawBottom = false;
18719        boolean drawLeft = false;
18720        boolean drawRight = false;
18721
18722        float topFadeStrength = 0.0f;
18723        float bottomFadeStrength = 0.0f;
18724        float leftFadeStrength = 0.0f;
18725        float rightFadeStrength = 0.0f;
18726
18727        // Step 2, save the canvas' layers
18728        int paddingLeft = mPaddingLeft;
18729
18730        final boolean offsetRequired = isPaddingOffsetRequired();
18731        if (offsetRequired) {
18732            paddingLeft += getLeftPaddingOffset();
18733        }
18734
18735        int left = mScrollX + paddingLeft;
18736        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
18737        int top = mScrollY + getFadeTop(offsetRequired);
18738        int bottom = top + getFadeHeight(offsetRequired);
18739
18740        if (offsetRequired) {
18741            right += getRightPaddingOffset();
18742            bottom += getBottomPaddingOffset();
18743        }
18744
18745        final ScrollabilityCache scrollabilityCache = mScrollCache;
18746        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
18747        int length = (int) fadeHeight;
18748
18749        // clip the fade length if top and bottom fades overlap
18750        // overlapping fades produce odd-looking artifacts
18751        if (verticalEdges && (top + length > bottom - length)) {
18752            length = (bottom - top) / 2;
18753        }
18754
18755        // also clip horizontal fades if necessary
18756        if (horizontalEdges && (left + length > right - length)) {
18757            length = (right - left) / 2;
18758        }
18759
18760        if (verticalEdges) {
18761            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
18762            drawTop = topFadeStrength * fadeHeight > 1.0f;
18763            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
18764            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
18765        }
18766
18767        if (horizontalEdges) {
18768            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
18769            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
18770            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
18771            drawRight = rightFadeStrength * fadeHeight > 1.0f;
18772        }
18773
18774        saveCount = canvas.getSaveCount();
18775
18776        int solidColor = getSolidColor();
18777        if (solidColor == 0) {
18778            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
18779
18780            if (drawTop) {
18781                canvas.saveLayer(left, top, right, top + length, null, flags);
18782            }
18783
18784            if (drawBottom) {
18785                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
18786            }
18787
18788            if (drawLeft) {
18789                canvas.saveLayer(left, top, left + length, bottom, null, flags);
18790            }
18791
18792            if (drawRight) {
18793                canvas.saveLayer(right - length, top, right, bottom, null, flags);
18794            }
18795        } else {
18796            scrollabilityCache.setFadeColor(solidColor);
18797        }
18798
18799        // Step 3, draw the content
18800        if (!dirtyOpaque) onDraw(canvas);
18801
18802        // Step 4, draw the children
18803        dispatchDraw(canvas);
18804
18805        // Step 5, draw the fade effect and restore layers
18806        final Paint p = scrollabilityCache.paint;
18807        final Matrix matrix = scrollabilityCache.matrix;
18808        final Shader fade = scrollabilityCache.shader;
18809
18810        if (drawTop) {
18811            matrix.setScale(1, fadeHeight * topFadeStrength);
18812            matrix.postTranslate(left, top);
18813            fade.setLocalMatrix(matrix);
18814            p.setShader(fade);
18815            canvas.drawRect(left, top, right, top + length, p);
18816        }
18817
18818        if (drawBottom) {
18819            matrix.setScale(1, fadeHeight * bottomFadeStrength);
18820            matrix.postRotate(180);
18821            matrix.postTranslate(left, bottom);
18822            fade.setLocalMatrix(matrix);
18823            p.setShader(fade);
18824            canvas.drawRect(left, bottom - length, right, bottom, p);
18825        }
18826
18827        if (drawLeft) {
18828            matrix.setScale(1, fadeHeight * leftFadeStrength);
18829            matrix.postRotate(-90);
18830            matrix.postTranslate(left, top);
18831            fade.setLocalMatrix(matrix);
18832            p.setShader(fade);
18833            canvas.drawRect(left, top, left + length, bottom, p);
18834        }
18835
18836        if (drawRight) {
18837            matrix.setScale(1, fadeHeight * rightFadeStrength);
18838            matrix.postRotate(90);
18839            matrix.postTranslate(right, top);
18840            fade.setLocalMatrix(matrix);
18841            p.setShader(fade);
18842            canvas.drawRect(right - length, top, right, bottom, p);
18843        }
18844
18845        canvas.restoreToCount(saveCount);
18846
18847        drawAutofilledHighlight(canvas);
18848
18849        // Overlay is part of the content and draws beneath Foreground
18850        if (mOverlay != null && !mOverlay.isEmpty()) {
18851            mOverlay.getOverlayView().dispatchDraw(canvas);
18852        }
18853
18854        // Step 6, draw decorations (foreground, scrollbars)
18855        onDrawForeground(canvas);
18856
18857        if (debugDraw()) {
18858            debugDrawFocus(canvas);
18859        }
18860    }
18861
18862    /**
18863     * Draws the background onto the specified canvas.
18864     *
18865     * @param canvas Canvas on which to draw the background
18866     */
18867    private void drawBackground(Canvas canvas) {
18868        final Drawable background = mBackground;
18869        if (background == null) {
18870            return;
18871        }
18872
18873        setBackgroundBounds();
18874
18875        // Attempt to use a display list if requested.
18876        if (canvas.isHardwareAccelerated() && mAttachInfo != null
18877                && mAttachInfo.mThreadedRenderer != null) {
18878            mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode);
18879
18880            final RenderNode renderNode = mBackgroundRenderNode;
18881            if (renderNode != null && renderNode.isValid()) {
18882                setBackgroundRenderNodeProperties(renderNode);
18883                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
18884                return;
18885            }
18886        }
18887
18888        final int scrollX = mScrollX;
18889        final int scrollY = mScrollY;
18890        if ((scrollX | scrollY) == 0) {
18891            background.draw(canvas);
18892        } else {
18893            canvas.translate(scrollX, scrollY);
18894            background.draw(canvas);
18895            canvas.translate(-scrollX, -scrollY);
18896        }
18897    }
18898
18899    /**
18900     * Sets the correct background bounds and rebuilds the outline, if needed.
18901     * <p/>
18902     * This is called by LayoutLib.
18903     */
18904    void setBackgroundBounds() {
18905        if (mBackgroundSizeChanged && mBackground != null) {
18906            mBackground.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
18907            mBackgroundSizeChanged = false;
18908            rebuildOutline();
18909        }
18910    }
18911
18912    private void setBackgroundRenderNodeProperties(RenderNode renderNode) {
18913        renderNode.setTranslationX(mScrollX);
18914        renderNode.setTranslationY(mScrollY);
18915    }
18916
18917    /**
18918     * Creates a new display list or updates the existing display list for the
18919     * specified Drawable.
18920     *
18921     * @param drawable Drawable for which to create a display list
18922     * @param renderNode Existing RenderNode, or {@code null}
18923     * @return A valid display list for the specified drawable
18924     */
18925    private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) {
18926        if (renderNode == null) {
18927            renderNode = RenderNode.create(drawable.getClass().getName(), this);
18928        }
18929
18930        final Rect bounds = drawable.getBounds();
18931        final int width = bounds.width();
18932        final int height = bounds.height();
18933        final DisplayListCanvas canvas = renderNode.start(width, height);
18934
18935        // Reverse left/top translation done by drawable canvas, which will
18936        // instead be applied by rendernode's LTRB bounds below. This way, the
18937        // drawable's bounds match with its rendernode bounds and its content
18938        // will lie within those bounds in the rendernode tree.
18939        canvas.translate(-bounds.left, -bounds.top);
18940
18941        try {
18942            drawable.draw(canvas);
18943        } finally {
18944            renderNode.end(canvas);
18945        }
18946
18947        // Set up drawable properties that are view-independent.
18948        renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
18949        renderNode.setProjectBackwards(drawable.isProjected());
18950        renderNode.setProjectionReceiver(true);
18951        renderNode.setClipToBounds(false);
18952        return renderNode;
18953    }
18954
18955    /**
18956     * Returns the overlay for this view, creating it if it does not yet exist.
18957     * Adding drawables to the overlay will cause them to be displayed whenever
18958     * the view itself is redrawn. Objects in the overlay should be actively
18959     * managed: remove them when they should not be displayed anymore. The
18960     * overlay will always have the same size as its host view.
18961     *
18962     * <p>Note: Overlays do not currently work correctly with {@link
18963     * SurfaceView} or {@link TextureView}; contents in overlays for these
18964     * types of views may not display correctly.</p>
18965     *
18966     * @return The ViewOverlay object for this view.
18967     * @see ViewOverlay
18968     */
18969    public ViewOverlay getOverlay() {
18970        if (mOverlay == null) {
18971            mOverlay = new ViewOverlay(mContext, this);
18972        }
18973        return mOverlay;
18974    }
18975
18976    /**
18977     * Override this if your view is known to always be drawn on top of a solid color background,
18978     * and needs to draw fading edges. Returning a non-zero color enables the view system to
18979     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
18980     * should be set to 0xFF.
18981     *
18982     * @see #setVerticalFadingEdgeEnabled(boolean)
18983     * @see #setHorizontalFadingEdgeEnabled(boolean)
18984     *
18985     * @return The known solid color background for this view, or 0 if the color may vary
18986     */
18987    @ViewDebug.ExportedProperty(category = "drawing")
18988    @ColorInt
18989    public int getSolidColor() {
18990        return 0;
18991    }
18992
18993    /**
18994     * Build a human readable string representation of the specified view flags.
18995     *
18996     * @param flags the view flags to convert to a string
18997     * @return a String representing the supplied flags
18998     */
18999    private static String printFlags(int flags) {
19000        String output = "";
19001        int numFlags = 0;
19002        if ((flags & FOCUSABLE) == FOCUSABLE) {
19003            output += "TAKES_FOCUS";
19004            numFlags++;
19005        }
19006
19007        switch (flags & VISIBILITY_MASK) {
19008        case INVISIBLE:
19009            if (numFlags > 0) {
19010                output += " ";
19011            }
19012            output += "INVISIBLE";
19013            // USELESS HERE numFlags++;
19014            break;
19015        case GONE:
19016            if (numFlags > 0) {
19017                output += " ";
19018            }
19019            output += "GONE";
19020            // USELESS HERE numFlags++;
19021            break;
19022        default:
19023            break;
19024        }
19025        return output;
19026    }
19027
19028    /**
19029     * Build a human readable string representation of the specified private
19030     * view flags.
19031     *
19032     * @param privateFlags the private view flags to convert to a string
19033     * @return a String representing the supplied flags
19034     */
19035    private static String printPrivateFlags(int privateFlags) {
19036        String output = "";
19037        int numFlags = 0;
19038
19039        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
19040            output += "WANTS_FOCUS";
19041            numFlags++;
19042        }
19043
19044        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
19045            if (numFlags > 0) {
19046                output += " ";
19047            }
19048            output += "FOCUSED";
19049            numFlags++;
19050        }
19051
19052        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
19053            if (numFlags > 0) {
19054                output += " ";
19055            }
19056            output += "SELECTED";
19057            numFlags++;
19058        }
19059
19060        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
19061            if (numFlags > 0) {
19062                output += " ";
19063            }
19064            output += "IS_ROOT_NAMESPACE";
19065            numFlags++;
19066        }
19067
19068        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
19069            if (numFlags > 0) {
19070                output += " ";
19071            }
19072            output += "HAS_BOUNDS";
19073            numFlags++;
19074        }
19075
19076        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
19077            if (numFlags > 0) {
19078                output += " ";
19079            }
19080            output += "DRAWN";
19081            // USELESS HERE numFlags++;
19082        }
19083        return output;
19084    }
19085
19086    /**
19087     * <p>Indicates whether or not this view's layout will be requested during
19088     * the next hierarchy layout pass.</p>
19089     *
19090     * @return true if the layout will be forced during next layout pass
19091     */
19092    public boolean isLayoutRequested() {
19093        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
19094    }
19095
19096    /**
19097     * Return true if o is a ViewGroup that is laying out using optical bounds.
19098     * @hide
19099     */
19100    public static boolean isLayoutModeOptical(Object o) {
19101        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
19102    }
19103
19104    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
19105        Insets parentInsets = mParent instanceof View ?
19106                ((View) mParent).getOpticalInsets() : Insets.NONE;
19107        Insets childInsets = getOpticalInsets();
19108        return setFrame(
19109                left   + parentInsets.left - childInsets.left,
19110                top    + parentInsets.top  - childInsets.top,
19111                right  + parentInsets.left + childInsets.right,
19112                bottom + parentInsets.top  + childInsets.bottom);
19113    }
19114
19115    /**
19116     * Assign a size and position to a view and all of its
19117     * descendants
19118     *
19119     * <p>This is the second phase of the layout mechanism.
19120     * (The first is measuring). In this phase, each parent calls
19121     * layout on all of its children to position them.
19122     * This is typically done using the child measurements
19123     * that were stored in the measure pass().</p>
19124     *
19125     * <p>Derived classes should not override this method.
19126     * Derived classes with children should override
19127     * onLayout. In that method, they should
19128     * call layout on each of their children.</p>
19129     *
19130     * @param l Left position, relative to parent
19131     * @param t Top position, relative to parent
19132     * @param r Right position, relative to parent
19133     * @param b Bottom position, relative to parent
19134     */
19135    @SuppressWarnings({"unchecked"})
19136    public void layout(int l, int t, int r, int b) {
19137        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
19138            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
19139            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
19140        }
19141
19142        int oldL = mLeft;
19143        int oldT = mTop;
19144        int oldB = mBottom;
19145        int oldR = mRight;
19146
19147        boolean changed = isLayoutModeOptical(mParent) ?
19148                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
19149
19150        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
19151            onLayout(changed, l, t, r, b);
19152
19153            if (shouldDrawRoundScrollbar()) {
19154                if(mRoundScrollbarRenderer == null) {
19155                    mRoundScrollbarRenderer = new RoundScrollbarRenderer(this);
19156                }
19157            } else {
19158                mRoundScrollbarRenderer = null;
19159            }
19160
19161            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
19162
19163            ListenerInfo li = mListenerInfo;
19164            if (li != null && li.mOnLayoutChangeListeners != null) {
19165                ArrayList<OnLayoutChangeListener> listenersCopy =
19166                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
19167                int numListeners = listenersCopy.size();
19168                for (int i = 0; i < numListeners; ++i) {
19169                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
19170                }
19171            }
19172        }
19173
19174        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
19175        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
19176    }
19177
19178    /**
19179     * Called from layout when this view should
19180     * assign a size and position to each of its children.
19181     *
19182     * Derived classes with children should override
19183     * this method and call layout on each of
19184     * their children.
19185     * @param changed This is a new size or position for this view
19186     * @param left Left position, relative to parent
19187     * @param top Top position, relative to parent
19188     * @param right Right position, relative to parent
19189     * @param bottom Bottom position, relative to parent
19190     */
19191    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
19192    }
19193
19194    /**
19195     * Assign a size and position to this view.
19196     *
19197     * This is called from layout.
19198     *
19199     * @param left Left position, relative to parent
19200     * @param top Top position, relative to parent
19201     * @param right Right position, relative to parent
19202     * @param bottom Bottom position, relative to parent
19203     * @return true if the new size and position are different than the
19204     *         previous ones
19205     * {@hide}
19206     */
19207    protected boolean setFrame(int left, int top, int right, int bottom) {
19208        boolean changed = false;
19209
19210        if (DBG) {
19211            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
19212                    + right + "," + bottom + ")");
19213        }
19214
19215        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
19216            changed = true;
19217
19218            // Remember our drawn bit
19219            int drawn = mPrivateFlags & PFLAG_DRAWN;
19220
19221            int oldWidth = mRight - mLeft;
19222            int oldHeight = mBottom - mTop;
19223            int newWidth = right - left;
19224            int newHeight = bottom - top;
19225            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
19226
19227            // Invalidate our old position
19228            invalidate(sizeChanged);
19229
19230            mLeft = left;
19231            mTop = top;
19232            mRight = right;
19233            mBottom = bottom;
19234            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
19235
19236            mPrivateFlags |= PFLAG_HAS_BOUNDS;
19237
19238
19239            if (sizeChanged) {
19240                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
19241            }
19242
19243            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) {
19244                // If we are visible, force the DRAWN bit to on so that
19245                // this invalidate will go through (at least to our parent).
19246                // This is because someone may have invalidated this view
19247                // before this call to setFrame came in, thereby clearing
19248                // the DRAWN bit.
19249                mPrivateFlags |= PFLAG_DRAWN;
19250                invalidate(sizeChanged);
19251                // parent display list may need to be recreated based on a change in the bounds
19252                // of any child
19253                invalidateParentCaches();
19254            }
19255
19256            // Reset drawn bit to original value (invalidate turns it off)
19257            mPrivateFlags |= drawn;
19258
19259            mBackgroundSizeChanged = true;
19260            if (mForegroundInfo != null) {
19261                mForegroundInfo.mBoundsChanged = true;
19262            }
19263
19264            notifySubtreeAccessibilityStateChangedIfNeeded();
19265        }
19266        return changed;
19267    }
19268
19269    /**
19270     * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}.
19271     * @hide
19272     */
19273    public void setLeftTopRightBottom(int left, int top, int right, int bottom) {
19274        setFrame(left, top, right, bottom);
19275    }
19276
19277    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
19278        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
19279        if (mOverlay != null) {
19280            mOverlay.getOverlayView().setRight(newWidth);
19281            mOverlay.getOverlayView().setBottom(newHeight);
19282        }
19283        rebuildOutline();
19284    }
19285
19286    /**
19287     * Finalize inflating a view from XML.  This is called as the last phase
19288     * of inflation, after all child views have been added.
19289     *
19290     * <p>Even if the subclass overrides onFinishInflate, they should always be
19291     * sure to call the super method, so that we get called.
19292     */
19293    @CallSuper
19294    protected void onFinishInflate() {
19295    }
19296
19297    /**
19298     * Returns the resources associated with this view.
19299     *
19300     * @return Resources object.
19301     */
19302    public Resources getResources() {
19303        return mResources;
19304    }
19305
19306    /**
19307     * Invalidates the specified Drawable.
19308     *
19309     * @param drawable the drawable to invalidate
19310     */
19311    @Override
19312    public void invalidateDrawable(@NonNull Drawable drawable) {
19313        if (verifyDrawable(drawable)) {
19314            final Rect dirty = drawable.getDirtyBounds();
19315            final int scrollX = mScrollX;
19316            final int scrollY = mScrollY;
19317
19318            invalidate(dirty.left + scrollX, dirty.top + scrollY,
19319                    dirty.right + scrollX, dirty.bottom + scrollY);
19320            rebuildOutline();
19321        }
19322    }
19323
19324    /**
19325     * Schedules an action on a drawable to occur at a specified time.
19326     *
19327     * @param who the recipient of the action
19328     * @param what the action to run on the drawable
19329     * @param when the time at which the action must occur. Uses the
19330     *        {@link SystemClock#uptimeMillis} timebase.
19331     */
19332    @Override
19333    public void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when) {
19334        if (verifyDrawable(who) && what != null) {
19335            final long delay = when - SystemClock.uptimeMillis();
19336            if (mAttachInfo != null) {
19337                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
19338                        Choreographer.CALLBACK_ANIMATION, what, who,
19339                        Choreographer.subtractFrameDelay(delay));
19340            } else {
19341                // Postpone the runnable until we know
19342                // on which thread it needs to run.
19343                getRunQueue().postDelayed(what, delay);
19344            }
19345        }
19346    }
19347
19348    /**
19349     * Cancels a scheduled action on a drawable.
19350     *
19351     * @param who the recipient of the action
19352     * @param what the action to cancel
19353     */
19354    @Override
19355    public void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what) {
19356        if (verifyDrawable(who) && what != null) {
19357            if (mAttachInfo != null) {
19358                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
19359                        Choreographer.CALLBACK_ANIMATION, what, who);
19360            }
19361            getRunQueue().removeCallbacks(what);
19362        }
19363    }
19364
19365    /**
19366     * Unschedule any events associated with the given Drawable.  This can be
19367     * used when selecting a new Drawable into a view, so that the previous
19368     * one is completely unscheduled.
19369     *
19370     * @param who The Drawable to unschedule.
19371     *
19372     * @see #drawableStateChanged
19373     */
19374    public void unscheduleDrawable(Drawable who) {
19375        if (mAttachInfo != null && who != null) {
19376            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
19377                    Choreographer.CALLBACK_ANIMATION, null, who);
19378        }
19379    }
19380
19381    /**
19382     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
19383     * that the View directionality can and will be resolved before its Drawables.
19384     *
19385     * Will call {@link View#onResolveDrawables} when resolution is done.
19386     *
19387     * @hide
19388     */
19389    protected void resolveDrawables() {
19390        // Drawables resolution may need to happen before resolving the layout direction (which is
19391        // done only during the measure() call).
19392        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
19393        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
19394        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
19395        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
19396        // direction to be resolved as its resolved value will be the same as its raw value.
19397        if (!isLayoutDirectionResolved() &&
19398                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
19399            return;
19400        }
19401
19402        final int layoutDirection = isLayoutDirectionResolved() ?
19403                getLayoutDirection() : getRawLayoutDirection();
19404
19405        if (mBackground != null) {
19406            mBackground.setLayoutDirection(layoutDirection);
19407        }
19408        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
19409            mForegroundInfo.mDrawable.setLayoutDirection(layoutDirection);
19410        }
19411        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
19412        onResolveDrawables(layoutDirection);
19413    }
19414
19415    boolean areDrawablesResolved() {
19416        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
19417    }
19418
19419    /**
19420     * Called when layout direction has been resolved.
19421     *
19422     * The default implementation does nothing.
19423     *
19424     * @param layoutDirection The resolved layout direction.
19425     *
19426     * @see #LAYOUT_DIRECTION_LTR
19427     * @see #LAYOUT_DIRECTION_RTL
19428     *
19429     * @hide
19430     */
19431    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
19432    }
19433
19434    /**
19435     * @hide
19436     */
19437    protected void resetResolvedDrawables() {
19438        resetResolvedDrawablesInternal();
19439    }
19440
19441    void resetResolvedDrawablesInternal() {
19442        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
19443    }
19444
19445    /**
19446     * If your view subclass is displaying its own Drawable objects, it should
19447     * override this function and return true for any Drawable it is
19448     * displaying.  This allows animations for those drawables to be
19449     * scheduled.
19450     *
19451     * <p>Be sure to call through to the super class when overriding this
19452     * function.
19453     *
19454     * @param who The Drawable to verify.  Return true if it is one you are
19455     *            displaying, else return the result of calling through to the
19456     *            super class.
19457     *
19458     * @return boolean If true than the Drawable is being displayed in the
19459     *         view; else false and it is not allowed to animate.
19460     *
19461     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
19462     * @see #drawableStateChanged()
19463     */
19464    @CallSuper
19465    protected boolean verifyDrawable(@NonNull Drawable who) {
19466        // Avoid verifying the scroll bar drawable so that we don't end up in
19467        // an invalidation loop. This effectively prevents the scroll bar
19468        // drawable from triggering invalidations and scheduling runnables.
19469        return who == mBackground || (mForegroundInfo != null && mForegroundInfo.mDrawable == who);
19470    }
19471
19472    /**
19473     * This function is called whenever the state of the view changes in such
19474     * a way that it impacts the state of drawables being shown.
19475     * <p>
19476     * If the View has a StateListAnimator, it will also be called to run necessary state
19477     * change animations.
19478     * <p>
19479     * Be sure to call through to the superclass when overriding this function.
19480     *
19481     * @see Drawable#setState(int[])
19482     */
19483    @CallSuper
19484    protected void drawableStateChanged() {
19485        final int[] state = getDrawableState();
19486        boolean changed = false;
19487
19488        final Drawable bg = mBackground;
19489        if (bg != null && bg.isStateful()) {
19490            changed |= bg.setState(state);
19491        }
19492
19493        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
19494        if (fg != null && fg.isStateful()) {
19495            changed |= fg.setState(state);
19496        }
19497
19498        if (mScrollCache != null) {
19499            final Drawable scrollBar = mScrollCache.scrollBar;
19500            if (scrollBar != null && scrollBar.isStateful()) {
19501                changed |= scrollBar.setState(state)
19502                        && mScrollCache.state != ScrollabilityCache.OFF;
19503            }
19504        }
19505
19506        if (mStateListAnimator != null) {
19507            mStateListAnimator.setState(state);
19508        }
19509
19510        if (changed) {
19511            invalidate();
19512        }
19513    }
19514
19515    /**
19516     * This function is called whenever the view hotspot changes and needs to
19517     * be propagated to drawables or child views managed by the view.
19518     * <p>
19519     * Dispatching to child views is handled by
19520     * {@link #dispatchDrawableHotspotChanged(float, float)}.
19521     * <p>
19522     * Be sure to call through to the superclass when overriding this function.
19523     *
19524     * @param x hotspot x coordinate
19525     * @param y hotspot y coordinate
19526     */
19527    @CallSuper
19528    public void drawableHotspotChanged(float x, float y) {
19529        if (mBackground != null) {
19530            mBackground.setHotspot(x, y);
19531        }
19532        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
19533            mForegroundInfo.mDrawable.setHotspot(x, y);
19534        }
19535
19536        dispatchDrawableHotspotChanged(x, y);
19537    }
19538
19539    /**
19540     * Dispatches drawableHotspotChanged to all of this View's children.
19541     *
19542     * @param x hotspot x coordinate
19543     * @param y hotspot y coordinate
19544     * @see #drawableHotspotChanged(float, float)
19545     */
19546    public void dispatchDrawableHotspotChanged(float x, float y) {
19547    }
19548
19549    /**
19550     * Call this to force a view to update its drawable state. This will cause
19551     * drawableStateChanged to be called on this view. Views that are interested
19552     * in the new state should call getDrawableState.
19553     *
19554     * @see #drawableStateChanged
19555     * @see #getDrawableState
19556     */
19557    public void refreshDrawableState() {
19558        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
19559        drawableStateChanged();
19560
19561        ViewParent parent = mParent;
19562        if (parent != null) {
19563            parent.childDrawableStateChanged(this);
19564        }
19565    }
19566
19567    /**
19568     * Return an array of resource IDs of the drawable states representing the
19569     * current state of the view.
19570     *
19571     * @return The current drawable state
19572     *
19573     * @see Drawable#setState(int[])
19574     * @see #drawableStateChanged()
19575     * @see #onCreateDrawableState(int)
19576     */
19577    public final int[] getDrawableState() {
19578        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
19579            return mDrawableState;
19580        } else {
19581            mDrawableState = onCreateDrawableState(0);
19582            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
19583            return mDrawableState;
19584        }
19585    }
19586
19587    /**
19588     * Generate the new {@link android.graphics.drawable.Drawable} state for
19589     * this view. This is called by the view
19590     * system when the cached Drawable state is determined to be invalid.  To
19591     * retrieve the current state, you should use {@link #getDrawableState}.
19592     *
19593     * @param extraSpace if non-zero, this is the number of extra entries you
19594     * would like in the returned array in which you can place your own
19595     * states.
19596     *
19597     * @return Returns an array holding the current {@link Drawable} state of
19598     * the view.
19599     *
19600     * @see #mergeDrawableStates(int[], int[])
19601     */
19602    protected int[] onCreateDrawableState(int extraSpace) {
19603        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
19604                mParent instanceof View) {
19605            return ((View) mParent).onCreateDrawableState(extraSpace);
19606        }
19607
19608        int[] drawableState;
19609
19610        int privateFlags = mPrivateFlags;
19611
19612        int viewStateIndex = 0;
19613        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= StateSet.VIEW_STATE_PRESSED;
19614        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= StateSet.VIEW_STATE_ENABLED;
19615        if (isFocused()) viewStateIndex |= StateSet.VIEW_STATE_FOCUSED;
19616        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= StateSet.VIEW_STATE_SELECTED;
19617        if (hasWindowFocus()) viewStateIndex |= StateSet.VIEW_STATE_WINDOW_FOCUSED;
19618        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= StateSet.VIEW_STATE_ACTIVATED;
19619        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
19620                ThreadedRenderer.isAvailable()) {
19621            // This is set if HW acceleration is requested, even if the current
19622            // process doesn't allow it.  This is just to allow app preview
19623            // windows to better match their app.
19624            viewStateIndex |= StateSet.VIEW_STATE_ACCELERATED;
19625        }
19626        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= StateSet.VIEW_STATE_HOVERED;
19627
19628        final int privateFlags2 = mPrivateFlags2;
19629        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) {
19630            viewStateIndex |= StateSet.VIEW_STATE_DRAG_CAN_ACCEPT;
19631        }
19632        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) {
19633            viewStateIndex |= StateSet.VIEW_STATE_DRAG_HOVERED;
19634        }
19635
19636        drawableState = StateSet.get(viewStateIndex);
19637
19638        //noinspection ConstantIfStatement
19639        if (false) {
19640            Log.i("View", "drawableStateIndex=" + viewStateIndex);
19641            Log.i("View", toString()
19642                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
19643                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
19644                    + " fo=" + hasFocus()
19645                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
19646                    + " wf=" + hasWindowFocus()
19647                    + ": " + Arrays.toString(drawableState));
19648        }
19649
19650        if (extraSpace == 0) {
19651            return drawableState;
19652        }
19653
19654        final int[] fullState;
19655        if (drawableState != null) {
19656            fullState = new int[drawableState.length + extraSpace];
19657            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
19658        } else {
19659            fullState = new int[extraSpace];
19660        }
19661
19662        return fullState;
19663    }
19664
19665    /**
19666     * Merge your own state values in <var>additionalState</var> into the base
19667     * state values <var>baseState</var> that were returned by
19668     * {@link #onCreateDrawableState(int)}.
19669     *
19670     * @param baseState The base state values returned by
19671     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
19672     * own additional state values.
19673     *
19674     * @param additionalState The additional state values you would like
19675     * added to <var>baseState</var>; this array is not modified.
19676     *
19677     * @return As a convenience, the <var>baseState</var> array you originally
19678     * passed into the function is returned.
19679     *
19680     * @see #onCreateDrawableState(int)
19681     */
19682    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
19683        final int N = baseState.length;
19684        int i = N - 1;
19685        while (i >= 0 && baseState[i] == 0) {
19686            i--;
19687        }
19688        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
19689        return baseState;
19690    }
19691
19692    /**
19693     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
19694     * on all Drawable objects associated with this view.
19695     * <p>
19696     * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator
19697     * attached to this view.
19698     */
19699    @CallSuper
19700    public void jumpDrawablesToCurrentState() {
19701        if (mBackground != null) {
19702            mBackground.jumpToCurrentState();
19703        }
19704        if (mStateListAnimator != null) {
19705            mStateListAnimator.jumpToCurrentState();
19706        }
19707        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
19708            mForegroundInfo.mDrawable.jumpToCurrentState();
19709        }
19710    }
19711
19712    /**
19713     * Sets the background color for this view.
19714     * @param color the color of the background
19715     */
19716    @RemotableViewMethod
19717    public void setBackgroundColor(@ColorInt int color) {
19718        if (mBackground instanceof ColorDrawable) {
19719            ((ColorDrawable) mBackground.mutate()).setColor(color);
19720            computeOpaqueFlags();
19721            mBackgroundResource = 0;
19722        } else {
19723            setBackground(new ColorDrawable(color));
19724        }
19725    }
19726
19727    /**
19728     * Set the background to a given resource. The resource should refer to
19729     * a Drawable object or 0 to remove the background.
19730     * @param resid The identifier of the resource.
19731     *
19732     * @attr ref android.R.styleable#View_background
19733     */
19734    @RemotableViewMethod
19735    public void setBackgroundResource(@DrawableRes int resid) {
19736        if (resid != 0 && resid == mBackgroundResource) {
19737            return;
19738        }
19739
19740        Drawable d = null;
19741        if (resid != 0) {
19742            d = mContext.getDrawable(resid);
19743        }
19744        setBackground(d);
19745
19746        mBackgroundResource = resid;
19747    }
19748
19749    /**
19750     * Set the background to a given Drawable, or remove the background. If the
19751     * background has padding, this View's padding is set to the background's
19752     * padding. However, when a background is removed, this View's padding isn't
19753     * touched. If setting the padding is desired, please use
19754     * {@link #setPadding(int, int, int, int)}.
19755     *
19756     * @param background The Drawable to use as the background, or null to remove the
19757     *        background
19758     */
19759    public void setBackground(Drawable background) {
19760        //noinspection deprecation
19761        setBackgroundDrawable(background);
19762    }
19763
19764    /**
19765     * @deprecated use {@link #setBackground(Drawable)} instead
19766     */
19767    @Deprecated
19768    public void setBackgroundDrawable(Drawable background) {
19769        computeOpaqueFlags();
19770
19771        if (background == mBackground) {
19772            return;
19773        }
19774
19775        boolean requestLayout = false;
19776
19777        mBackgroundResource = 0;
19778
19779        /*
19780         * Regardless of whether we're setting a new background or not, we want
19781         * to clear the previous drawable. setVisible first while we still have the callback set.
19782         */
19783        if (mBackground != null) {
19784            if (isAttachedToWindow()) {
19785                mBackground.setVisible(false, false);
19786            }
19787            mBackground.setCallback(null);
19788            unscheduleDrawable(mBackground);
19789        }
19790
19791        if (background != null) {
19792            Rect padding = sThreadLocal.get();
19793            if (padding == null) {
19794                padding = new Rect();
19795                sThreadLocal.set(padding);
19796            }
19797            resetResolvedDrawablesInternal();
19798            background.setLayoutDirection(getLayoutDirection());
19799            if (background.getPadding(padding)) {
19800                resetResolvedPaddingInternal();
19801                switch (background.getLayoutDirection()) {
19802                    case LAYOUT_DIRECTION_RTL:
19803                        mUserPaddingLeftInitial = padding.right;
19804                        mUserPaddingRightInitial = padding.left;
19805                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
19806                        break;
19807                    case LAYOUT_DIRECTION_LTR:
19808                    default:
19809                        mUserPaddingLeftInitial = padding.left;
19810                        mUserPaddingRightInitial = padding.right;
19811                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
19812                }
19813                mLeftPaddingDefined = false;
19814                mRightPaddingDefined = false;
19815            }
19816
19817            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
19818            // if it has a different minimum size, we should layout again
19819            if (mBackground == null
19820                    || mBackground.getMinimumHeight() != background.getMinimumHeight()
19821                    || mBackground.getMinimumWidth() != background.getMinimumWidth()) {
19822                requestLayout = true;
19823            }
19824
19825            // Set mBackground before we set this as the callback and start making other
19826            // background drawable state change calls. In particular, the setVisible call below
19827            // can result in drawables attempting to start animations or otherwise invalidate,
19828            // which requires the view set as the callback (us) to recognize the drawable as
19829            // belonging to it as per verifyDrawable.
19830            mBackground = background;
19831            if (background.isStateful()) {
19832                background.setState(getDrawableState());
19833            }
19834            if (isAttachedToWindow()) {
19835                background.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
19836            }
19837
19838            applyBackgroundTint();
19839
19840            // Set callback last, since the view may still be initializing.
19841            background.setCallback(this);
19842
19843            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
19844                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
19845                requestLayout = true;
19846            }
19847        } else {
19848            /* Remove the background */
19849            mBackground = null;
19850            if ((mViewFlags & WILL_NOT_DRAW) != 0
19851                    && (mForegroundInfo == null || mForegroundInfo.mDrawable == null)) {
19852                mPrivateFlags |= PFLAG_SKIP_DRAW;
19853            }
19854
19855            /*
19856             * When the background is set, we try to apply its padding to this
19857             * View. When the background is removed, we don't touch this View's
19858             * padding. This is noted in the Javadocs. Hence, we don't need to
19859             * requestLayout(), the invalidate() below is sufficient.
19860             */
19861
19862            // The old background's minimum size could have affected this
19863            // View's layout, so let's requestLayout
19864            requestLayout = true;
19865        }
19866
19867        computeOpaqueFlags();
19868
19869        if (requestLayout) {
19870            requestLayout();
19871        }
19872
19873        mBackgroundSizeChanged = true;
19874        invalidate(true);
19875        invalidateOutline();
19876    }
19877
19878    /**
19879     * Gets the background drawable
19880     *
19881     * @return The drawable used as the background for this view, if any.
19882     *
19883     * @see #setBackground(Drawable)
19884     *
19885     * @attr ref android.R.styleable#View_background
19886     */
19887    public Drawable getBackground() {
19888        return mBackground;
19889    }
19890
19891    /**
19892     * Applies a tint to the background drawable. Does not modify the current tint
19893     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
19894     * <p>
19895     * Subsequent calls to {@link #setBackground(Drawable)} will automatically
19896     * mutate the drawable and apply the specified tint and tint mode using
19897     * {@link Drawable#setTintList(ColorStateList)}.
19898     *
19899     * @param tint the tint to apply, may be {@code null} to clear tint
19900     *
19901     * @attr ref android.R.styleable#View_backgroundTint
19902     * @see #getBackgroundTintList()
19903     * @see Drawable#setTintList(ColorStateList)
19904     */
19905    public void setBackgroundTintList(@Nullable ColorStateList tint) {
19906        if (mBackgroundTint == null) {
19907            mBackgroundTint = new TintInfo();
19908        }
19909        mBackgroundTint.mTintList = tint;
19910        mBackgroundTint.mHasTintList = true;
19911
19912        applyBackgroundTint();
19913    }
19914
19915    /**
19916     * Return the tint applied to the background drawable, if specified.
19917     *
19918     * @return the tint applied to the background drawable
19919     * @attr ref android.R.styleable#View_backgroundTint
19920     * @see #setBackgroundTintList(ColorStateList)
19921     */
19922    @Nullable
19923    public ColorStateList getBackgroundTintList() {
19924        return mBackgroundTint != null ? mBackgroundTint.mTintList : null;
19925    }
19926
19927    /**
19928     * Specifies the blending mode used to apply the tint specified by
19929     * {@link #setBackgroundTintList(ColorStateList)}} to the background
19930     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
19931     *
19932     * @param tintMode the blending mode used to apply the tint, may be
19933     *                 {@code null} to clear tint
19934     * @attr ref android.R.styleable#View_backgroundTintMode
19935     * @see #getBackgroundTintMode()
19936     * @see Drawable#setTintMode(PorterDuff.Mode)
19937     */
19938    public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) {
19939        if (mBackgroundTint == null) {
19940            mBackgroundTint = new TintInfo();
19941        }
19942        mBackgroundTint.mTintMode = tintMode;
19943        mBackgroundTint.mHasTintMode = true;
19944
19945        applyBackgroundTint();
19946    }
19947
19948    /**
19949     * Return the blending mode used to apply the tint to the background
19950     * drawable, if specified.
19951     *
19952     * @return the blending mode used to apply the tint to the background
19953     *         drawable
19954     * @attr ref android.R.styleable#View_backgroundTintMode
19955     * @see #setBackgroundTintMode(PorterDuff.Mode)
19956     */
19957    @Nullable
19958    public PorterDuff.Mode getBackgroundTintMode() {
19959        return mBackgroundTint != null ? mBackgroundTint.mTintMode : null;
19960    }
19961
19962    private void applyBackgroundTint() {
19963        if (mBackground != null && mBackgroundTint != null) {
19964            final TintInfo tintInfo = mBackgroundTint;
19965            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
19966                mBackground = mBackground.mutate();
19967
19968                if (tintInfo.mHasTintList) {
19969                    mBackground.setTintList(tintInfo.mTintList);
19970                }
19971
19972                if (tintInfo.mHasTintMode) {
19973                    mBackground.setTintMode(tintInfo.mTintMode);
19974                }
19975
19976                // The drawable (or one of its children) may not have been
19977                // stateful before applying the tint, so let's try again.
19978                if (mBackground.isStateful()) {
19979                    mBackground.setState(getDrawableState());
19980                }
19981            }
19982        }
19983    }
19984
19985    /**
19986     * Returns the drawable used as the foreground of this View. The
19987     * foreground drawable, if non-null, is always drawn on top of the view's content.
19988     *
19989     * @return a Drawable or null if no foreground was set
19990     *
19991     * @see #onDrawForeground(Canvas)
19992     */
19993    public Drawable getForeground() {
19994        return mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
19995    }
19996
19997    /**
19998     * Supply a Drawable that is to be rendered on top of all of the content in the view.
19999     *
20000     * @param foreground the Drawable to be drawn on top of the children
20001     *
20002     * @attr ref android.R.styleable#View_foreground
20003     */
20004    public void setForeground(Drawable foreground) {
20005        if (mForegroundInfo == null) {
20006            if (foreground == null) {
20007                // Nothing to do.
20008                return;
20009            }
20010            mForegroundInfo = new ForegroundInfo();
20011        }
20012
20013        if (foreground == mForegroundInfo.mDrawable) {
20014            // Nothing to do
20015            return;
20016        }
20017
20018        if (mForegroundInfo.mDrawable != null) {
20019            if (isAttachedToWindow()) {
20020                mForegroundInfo.mDrawable.setVisible(false, false);
20021            }
20022            mForegroundInfo.mDrawable.setCallback(null);
20023            unscheduleDrawable(mForegroundInfo.mDrawable);
20024        }
20025
20026        mForegroundInfo.mDrawable = foreground;
20027        mForegroundInfo.mBoundsChanged = true;
20028        if (foreground != null) {
20029            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
20030                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
20031            }
20032            foreground.setLayoutDirection(getLayoutDirection());
20033            if (foreground.isStateful()) {
20034                foreground.setState(getDrawableState());
20035            }
20036            applyForegroundTint();
20037            if (isAttachedToWindow()) {
20038                foreground.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
20039            }
20040            // Set callback last, since the view may still be initializing.
20041            foreground.setCallback(this);
20042        } else if ((mViewFlags & WILL_NOT_DRAW) != 0 && mBackground == null) {
20043            mPrivateFlags |= PFLAG_SKIP_DRAW;
20044        }
20045        requestLayout();
20046        invalidate();
20047    }
20048
20049    /**
20050     * Magic bit used to support features of framework-internal window decor implementation details.
20051     * This used to live exclusively in FrameLayout.
20052     *
20053     * @return true if the foreground should draw inside the padding region or false
20054     *         if it should draw inset by the view's padding
20055     * @hide internal use only; only used by FrameLayout and internal screen layouts.
20056     */
20057    public boolean isForegroundInsidePadding() {
20058        return mForegroundInfo != null ? mForegroundInfo.mInsidePadding : true;
20059    }
20060
20061    /**
20062     * Describes how the foreground is positioned.
20063     *
20064     * @return foreground gravity.
20065     *
20066     * @see #setForegroundGravity(int)
20067     *
20068     * @attr ref android.R.styleable#View_foregroundGravity
20069     */
20070    public int getForegroundGravity() {
20071        return mForegroundInfo != null ? mForegroundInfo.mGravity
20072                : Gravity.START | Gravity.TOP;
20073    }
20074
20075    /**
20076     * Describes how the foreground is positioned. Defaults to START and TOP.
20077     *
20078     * @param gravity see {@link android.view.Gravity}
20079     *
20080     * @see #getForegroundGravity()
20081     *
20082     * @attr ref android.R.styleable#View_foregroundGravity
20083     */
20084    public void setForegroundGravity(int gravity) {
20085        if (mForegroundInfo == null) {
20086            mForegroundInfo = new ForegroundInfo();
20087        }
20088
20089        if (mForegroundInfo.mGravity != gravity) {
20090            if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) {
20091                gravity |= Gravity.START;
20092            }
20093
20094            if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) {
20095                gravity |= Gravity.TOP;
20096            }
20097
20098            mForegroundInfo.mGravity = gravity;
20099            requestLayout();
20100        }
20101    }
20102
20103    /**
20104     * Applies a tint to the foreground drawable. Does not modify the current tint
20105     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
20106     * <p>
20107     * Subsequent calls to {@link #setForeground(Drawable)} will automatically
20108     * mutate the drawable and apply the specified tint and tint mode using
20109     * {@link Drawable#setTintList(ColorStateList)}.
20110     *
20111     * @param tint the tint to apply, may be {@code null} to clear tint
20112     *
20113     * @attr ref android.R.styleable#View_foregroundTint
20114     * @see #getForegroundTintList()
20115     * @see Drawable#setTintList(ColorStateList)
20116     */
20117    public void setForegroundTintList(@Nullable ColorStateList tint) {
20118        if (mForegroundInfo == null) {
20119            mForegroundInfo = new ForegroundInfo();
20120        }
20121        if (mForegroundInfo.mTintInfo == null) {
20122            mForegroundInfo.mTintInfo = new TintInfo();
20123        }
20124        mForegroundInfo.mTintInfo.mTintList = tint;
20125        mForegroundInfo.mTintInfo.mHasTintList = true;
20126
20127        applyForegroundTint();
20128    }
20129
20130    /**
20131     * Return the tint applied to the foreground drawable, if specified.
20132     *
20133     * @return the tint applied to the foreground drawable
20134     * @attr ref android.R.styleable#View_foregroundTint
20135     * @see #setForegroundTintList(ColorStateList)
20136     */
20137    @Nullable
20138    public ColorStateList getForegroundTintList() {
20139        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
20140                ? mForegroundInfo.mTintInfo.mTintList : null;
20141    }
20142
20143    /**
20144     * Specifies the blending mode used to apply the tint specified by
20145     * {@link #setForegroundTintList(ColorStateList)}} to the background
20146     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
20147     *
20148     * @param tintMode the blending mode used to apply the tint, may be
20149     *                 {@code null} to clear tint
20150     * @attr ref android.R.styleable#View_foregroundTintMode
20151     * @see #getForegroundTintMode()
20152     * @see Drawable#setTintMode(PorterDuff.Mode)
20153     */
20154    public void setForegroundTintMode(@Nullable PorterDuff.Mode tintMode) {
20155        if (mForegroundInfo == null) {
20156            mForegroundInfo = new ForegroundInfo();
20157        }
20158        if (mForegroundInfo.mTintInfo == null) {
20159            mForegroundInfo.mTintInfo = new TintInfo();
20160        }
20161        mForegroundInfo.mTintInfo.mTintMode = tintMode;
20162        mForegroundInfo.mTintInfo.mHasTintMode = true;
20163
20164        applyForegroundTint();
20165    }
20166
20167    /**
20168     * Return the blending mode used to apply the tint to the foreground
20169     * drawable, if specified.
20170     *
20171     * @return the blending mode used to apply the tint to the foreground
20172     *         drawable
20173     * @attr ref android.R.styleable#View_foregroundTintMode
20174     * @see #setForegroundTintMode(PorterDuff.Mode)
20175     */
20176    @Nullable
20177    public PorterDuff.Mode getForegroundTintMode() {
20178        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
20179                ? mForegroundInfo.mTintInfo.mTintMode : null;
20180    }
20181
20182    private void applyForegroundTint() {
20183        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
20184                && mForegroundInfo.mTintInfo != null) {
20185            final TintInfo tintInfo = mForegroundInfo.mTintInfo;
20186            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
20187                mForegroundInfo.mDrawable = mForegroundInfo.mDrawable.mutate();
20188
20189                if (tintInfo.mHasTintList) {
20190                    mForegroundInfo.mDrawable.setTintList(tintInfo.mTintList);
20191                }
20192
20193                if (tintInfo.mHasTintMode) {
20194                    mForegroundInfo.mDrawable.setTintMode(tintInfo.mTintMode);
20195                }
20196
20197                // The drawable (or one of its children) may not have been
20198                // stateful before applying the tint, so let's try again.
20199                if (mForegroundInfo.mDrawable.isStateful()) {
20200                    mForegroundInfo.mDrawable.setState(getDrawableState());
20201                }
20202            }
20203        }
20204    }
20205
20206    /**
20207     * Get the drawable to be overlayed when a view is autofilled
20208     *
20209     * @return The drawable
20210     *
20211     * @throws IllegalStateException if the drawable could not be found.
20212     */
20213    @NonNull private Drawable getAutofilledDrawable() {
20214        // Lazily load the isAutofilled drawable.
20215        if (mAttachInfo.mAutofilledDrawable == null) {
20216            mAttachInfo.mAutofilledDrawable = mContext.getDrawable(R.drawable.autofilled_highlight);
20217
20218            if (mAttachInfo.mAutofilledDrawable == null) {
20219                throw new IllegalStateException(
20220                        "Could not find android:drawable/autofilled_highlight");
20221            }
20222        }
20223
20224        return mAttachInfo.mAutofilledDrawable;
20225    }
20226
20227    /**
20228     * Draw {@link View#isAutofilled()} highlight over view if the view is autofilled.
20229     *
20230     * @param canvas The canvas to draw on
20231     */
20232    private void drawAutofilledHighlight(@NonNull Canvas canvas) {
20233        if (isAutofilled()) {
20234            Drawable autofilledHighlight = getAutofilledDrawable();
20235
20236            autofilledHighlight.setBounds(0, 0, getWidth(), getHeight());
20237            autofilledHighlight.draw(canvas);
20238        }
20239    }
20240
20241    /**
20242     * Draw any foreground content for this view.
20243     *
20244     * <p>Foreground content may consist of scroll bars, a {@link #setForeground foreground}
20245     * drawable or other view-specific decorations. The foreground is drawn on top of the
20246     * primary view content.</p>
20247     *
20248     * @param canvas canvas to draw into
20249     */
20250    public void onDrawForeground(Canvas canvas) {
20251        onDrawScrollIndicators(canvas);
20252        onDrawScrollBars(canvas);
20253
20254        final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
20255        if (foreground != null) {
20256            if (mForegroundInfo.mBoundsChanged) {
20257                mForegroundInfo.mBoundsChanged = false;
20258                final Rect selfBounds = mForegroundInfo.mSelfBounds;
20259                final Rect overlayBounds = mForegroundInfo.mOverlayBounds;
20260
20261                if (mForegroundInfo.mInsidePadding) {
20262                    selfBounds.set(0, 0, getWidth(), getHeight());
20263                } else {
20264                    selfBounds.set(getPaddingLeft(), getPaddingTop(),
20265                            getWidth() - getPaddingRight(), getHeight() - getPaddingBottom());
20266                }
20267
20268                final int ld = getLayoutDirection();
20269                Gravity.apply(mForegroundInfo.mGravity, foreground.getIntrinsicWidth(),
20270                        foreground.getIntrinsicHeight(), selfBounds, overlayBounds, ld);
20271                foreground.setBounds(overlayBounds);
20272            }
20273
20274            foreground.draw(canvas);
20275        }
20276    }
20277
20278    /**
20279     * Sets the padding. The view may add on the space required to display
20280     * the scrollbars, depending on the style and visibility of the scrollbars.
20281     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
20282     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
20283     * from the values set in this call.
20284     *
20285     * @attr ref android.R.styleable#View_padding
20286     * @attr ref android.R.styleable#View_paddingBottom
20287     * @attr ref android.R.styleable#View_paddingLeft
20288     * @attr ref android.R.styleable#View_paddingRight
20289     * @attr ref android.R.styleable#View_paddingTop
20290     * @param left the left padding in pixels
20291     * @param top the top padding in pixels
20292     * @param right the right padding in pixels
20293     * @param bottom the bottom padding in pixels
20294     */
20295    public void setPadding(int left, int top, int right, int bottom) {
20296        resetResolvedPaddingInternal();
20297
20298        mUserPaddingStart = UNDEFINED_PADDING;
20299        mUserPaddingEnd = UNDEFINED_PADDING;
20300
20301        mUserPaddingLeftInitial = left;
20302        mUserPaddingRightInitial = right;
20303
20304        mLeftPaddingDefined = true;
20305        mRightPaddingDefined = true;
20306
20307        internalSetPadding(left, top, right, bottom);
20308    }
20309
20310    /**
20311     * @hide
20312     */
20313    protected void internalSetPadding(int left, int top, int right, int bottom) {
20314        mUserPaddingLeft = left;
20315        mUserPaddingRight = right;
20316        mUserPaddingBottom = bottom;
20317
20318        final int viewFlags = mViewFlags;
20319        boolean changed = false;
20320
20321        // Common case is there are no scroll bars.
20322        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
20323            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
20324                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
20325                        ? 0 : getVerticalScrollbarWidth();
20326                switch (mVerticalScrollbarPosition) {
20327                    case SCROLLBAR_POSITION_DEFAULT:
20328                        if (isLayoutRtl()) {
20329                            left += offset;
20330                        } else {
20331                            right += offset;
20332                        }
20333                        break;
20334                    case SCROLLBAR_POSITION_RIGHT:
20335                        right += offset;
20336                        break;
20337                    case SCROLLBAR_POSITION_LEFT:
20338                        left += offset;
20339                        break;
20340                }
20341            }
20342            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
20343                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
20344                        ? 0 : getHorizontalScrollbarHeight();
20345            }
20346        }
20347
20348        if (mPaddingLeft != left) {
20349            changed = true;
20350            mPaddingLeft = left;
20351        }
20352        if (mPaddingTop != top) {
20353            changed = true;
20354            mPaddingTop = top;
20355        }
20356        if (mPaddingRight != right) {
20357            changed = true;
20358            mPaddingRight = right;
20359        }
20360        if (mPaddingBottom != bottom) {
20361            changed = true;
20362            mPaddingBottom = bottom;
20363        }
20364
20365        if (changed) {
20366            requestLayout();
20367            invalidateOutline();
20368        }
20369    }
20370
20371    /**
20372     * Sets the relative padding. The view may add on the space required to display
20373     * the scrollbars, depending on the style and visibility of the scrollbars.
20374     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
20375     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
20376     * from the values set in this call.
20377     *
20378     * @attr ref android.R.styleable#View_padding
20379     * @attr ref android.R.styleable#View_paddingBottom
20380     * @attr ref android.R.styleable#View_paddingStart
20381     * @attr ref android.R.styleable#View_paddingEnd
20382     * @attr ref android.R.styleable#View_paddingTop
20383     * @param start the start padding in pixels
20384     * @param top the top padding in pixels
20385     * @param end the end padding in pixels
20386     * @param bottom the bottom padding in pixels
20387     */
20388    public void setPaddingRelative(int start, int top, int end, int bottom) {
20389        resetResolvedPaddingInternal();
20390
20391        mUserPaddingStart = start;
20392        mUserPaddingEnd = end;
20393        mLeftPaddingDefined = true;
20394        mRightPaddingDefined = true;
20395
20396        switch(getLayoutDirection()) {
20397            case LAYOUT_DIRECTION_RTL:
20398                mUserPaddingLeftInitial = end;
20399                mUserPaddingRightInitial = start;
20400                internalSetPadding(end, top, start, bottom);
20401                break;
20402            case LAYOUT_DIRECTION_LTR:
20403            default:
20404                mUserPaddingLeftInitial = start;
20405                mUserPaddingRightInitial = end;
20406                internalSetPadding(start, top, end, bottom);
20407        }
20408    }
20409
20410    /**
20411     * Returns the top padding of this view.
20412     *
20413     * @return the top padding in pixels
20414     */
20415    public int getPaddingTop() {
20416        return mPaddingTop;
20417    }
20418
20419    /**
20420     * Returns the bottom padding of this view. If there are inset and enabled
20421     * scrollbars, this value may include the space required to display the
20422     * scrollbars as well.
20423     *
20424     * @return the bottom padding in pixels
20425     */
20426    public int getPaddingBottom() {
20427        return mPaddingBottom;
20428    }
20429
20430    /**
20431     * Returns the left padding of this view. If there are inset and enabled
20432     * scrollbars, this value may include the space required to display the
20433     * scrollbars as well.
20434     *
20435     * @return the left padding in pixels
20436     */
20437    public int getPaddingLeft() {
20438        if (!isPaddingResolved()) {
20439            resolvePadding();
20440        }
20441        return mPaddingLeft;
20442    }
20443
20444    /**
20445     * Returns the start padding of this view depending on its resolved layout direction.
20446     * If there are inset and enabled scrollbars, this value may include the space
20447     * required to display the scrollbars as well.
20448     *
20449     * @return the start padding in pixels
20450     */
20451    public int getPaddingStart() {
20452        if (!isPaddingResolved()) {
20453            resolvePadding();
20454        }
20455        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
20456                mPaddingRight : mPaddingLeft;
20457    }
20458
20459    /**
20460     * Returns the right padding of this view. If there are inset and enabled
20461     * scrollbars, this value may include the space required to display the
20462     * scrollbars as well.
20463     *
20464     * @return the right padding in pixels
20465     */
20466    public int getPaddingRight() {
20467        if (!isPaddingResolved()) {
20468            resolvePadding();
20469        }
20470        return mPaddingRight;
20471    }
20472
20473    /**
20474     * Returns the end padding of this view depending on its resolved layout direction.
20475     * If there are inset and enabled scrollbars, this value may include the space
20476     * required to display the scrollbars as well.
20477     *
20478     * @return the end padding in pixels
20479     */
20480    public int getPaddingEnd() {
20481        if (!isPaddingResolved()) {
20482            resolvePadding();
20483        }
20484        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
20485                mPaddingLeft : mPaddingRight;
20486    }
20487
20488    /**
20489     * Return if the padding has been set through relative values
20490     * {@link #setPaddingRelative(int, int, int, int)} or through
20491     * @attr ref android.R.styleable#View_paddingStart or
20492     * @attr ref android.R.styleable#View_paddingEnd
20493     *
20494     * @return true if the padding is relative or false if it is not.
20495     */
20496    public boolean isPaddingRelative() {
20497        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
20498    }
20499
20500    Insets computeOpticalInsets() {
20501        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
20502    }
20503
20504    /**
20505     * @hide
20506     */
20507    public void resetPaddingToInitialValues() {
20508        if (isRtlCompatibilityMode()) {
20509            mPaddingLeft = mUserPaddingLeftInitial;
20510            mPaddingRight = mUserPaddingRightInitial;
20511            return;
20512        }
20513        if (isLayoutRtl()) {
20514            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
20515            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
20516        } else {
20517            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
20518            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
20519        }
20520    }
20521
20522    /**
20523     * @hide
20524     */
20525    public Insets getOpticalInsets() {
20526        if (mLayoutInsets == null) {
20527            mLayoutInsets = computeOpticalInsets();
20528        }
20529        return mLayoutInsets;
20530    }
20531
20532    /**
20533     * Set this view's optical insets.
20534     *
20535     * <p>This method should be treated similarly to setMeasuredDimension and not as a general
20536     * property. Views that compute their own optical insets should call it as part of measurement.
20537     * This method does not request layout. If you are setting optical insets outside of
20538     * measure/layout itself you will want to call requestLayout() yourself.
20539     * </p>
20540     * @hide
20541     */
20542    public void setOpticalInsets(Insets insets) {
20543        mLayoutInsets = insets;
20544    }
20545
20546    /**
20547     * Changes the selection state of this view. A view can be selected or not.
20548     * Note that selection is not the same as focus. Views are typically
20549     * selected in the context of an AdapterView like ListView or GridView;
20550     * the selected view is the view that is highlighted.
20551     *
20552     * @param selected true if the view must be selected, false otherwise
20553     */
20554    public void setSelected(boolean selected) {
20555        //noinspection DoubleNegation
20556        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
20557            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
20558            if (!selected) resetPressedState();
20559            invalidate(true);
20560            refreshDrawableState();
20561            dispatchSetSelected(selected);
20562            if (selected) {
20563                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
20564            } else {
20565                notifyViewAccessibilityStateChangedIfNeeded(
20566                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
20567            }
20568        }
20569    }
20570
20571    /**
20572     * Dispatch setSelected to all of this View's children.
20573     *
20574     * @see #setSelected(boolean)
20575     *
20576     * @param selected The new selected state
20577     */
20578    protected void dispatchSetSelected(boolean selected) {
20579    }
20580
20581    /**
20582     * Indicates the selection state of this view.
20583     *
20584     * @return true if the view is selected, false otherwise
20585     */
20586    @ViewDebug.ExportedProperty
20587    public boolean isSelected() {
20588        return (mPrivateFlags & PFLAG_SELECTED) != 0;
20589    }
20590
20591    /**
20592     * Changes the activated state of this view. A view can be activated or not.
20593     * Note that activation is not the same as selection.  Selection is
20594     * a transient property, representing the view (hierarchy) the user is
20595     * currently interacting with.  Activation is a longer-term state that the
20596     * user can move views in and out of.  For example, in a list view with
20597     * single or multiple selection enabled, the views in the current selection
20598     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
20599     * here.)  The activated state is propagated down to children of the view it
20600     * is set on.
20601     *
20602     * @param activated true if the view must be activated, false otherwise
20603     */
20604    public void setActivated(boolean activated) {
20605        //noinspection DoubleNegation
20606        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
20607            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
20608            invalidate(true);
20609            refreshDrawableState();
20610            dispatchSetActivated(activated);
20611        }
20612    }
20613
20614    /**
20615     * Dispatch setActivated to all of this View's children.
20616     *
20617     * @see #setActivated(boolean)
20618     *
20619     * @param activated The new activated state
20620     */
20621    protected void dispatchSetActivated(boolean activated) {
20622    }
20623
20624    /**
20625     * Indicates the activation state of this view.
20626     *
20627     * @return true if the view is activated, false otherwise
20628     */
20629    @ViewDebug.ExportedProperty
20630    public boolean isActivated() {
20631        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
20632    }
20633
20634    /**
20635     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
20636     * observer can be used to get notifications when global events, like
20637     * layout, happen.
20638     *
20639     * The returned ViewTreeObserver observer is not guaranteed to remain
20640     * valid for the lifetime of this View. If the caller of this method keeps
20641     * a long-lived reference to ViewTreeObserver, it should always check for
20642     * the return value of {@link ViewTreeObserver#isAlive()}.
20643     *
20644     * @return The ViewTreeObserver for this view's hierarchy.
20645     */
20646    public ViewTreeObserver getViewTreeObserver() {
20647        if (mAttachInfo != null) {
20648            return mAttachInfo.mTreeObserver;
20649        }
20650        if (mFloatingTreeObserver == null) {
20651            mFloatingTreeObserver = new ViewTreeObserver(mContext);
20652        }
20653        return mFloatingTreeObserver;
20654    }
20655
20656    /**
20657     * <p>Finds the topmost view in the current view hierarchy.</p>
20658     *
20659     * @return the topmost view containing this view
20660     */
20661    public View getRootView() {
20662        if (mAttachInfo != null) {
20663            final View v = mAttachInfo.mRootView;
20664            if (v != null) {
20665                return v;
20666            }
20667        }
20668
20669        View parent = this;
20670
20671        while (parent.mParent != null && parent.mParent instanceof View) {
20672            parent = (View) parent.mParent;
20673        }
20674
20675        return parent;
20676    }
20677
20678    /**
20679     * Transforms a motion event from view-local coordinates to on-screen
20680     * coordinates.
20681     *
20682     * @param ev the view-local motion event
20683     * @return false if the transformation could not be applied
20684     * @hide
20685     */
20686    public boolean toGlobalMotionEvent(MotionEvent ev) {
20687        final AttachInfo info = mAttachInfo;
20688        if (info == null) {
20689            return false;
20690        }
20691
20692        final Matrix m = info.mTmpMatrix;
20693        m.set(Matrix.IDENTITY_MATRIX);
20694        transformMatrixToGlobal(m);
20695        ev.transform(m);
20696        return true;
20697    }
20698
20699    /**
20700     * Transforms a motion event from on-screen coordinates to view-local
20701     * coordinates.
20702     *
20703     * @param ev the on-screen motion event
20704     * @return false if the transformation could not be applied
20705     * @hide
20706     */
20707    public boolean toLocalMotionEvent(MotionEvent ev) {
20708        final AttachInfo info = mAttachInfo;
20709        if (info == null) {
20710            return false;
20711        }
20712
20713        final Matrix m = info.mTmpMatrix;
20714        m.set(Matrix.IDENTITY_MATRIX);
20715        transformMatrixToLocal(m);
20716        ev.transform(m);
20717        return true;
20718    }
20719
20720    /**
20721     * Modifies the input matrix such that it maps view-local coordinates to
20722     * on-screen coordinates.
20723     *
20724     * @param m input matrix to modify
20725     * @hide
20726     */
20727    public void transformMatrixToGlobal(Matrix m) {
20728        final ViewParent parent = mParent;
20729        if (parent instanceof View) {
20730            final View vp = (View) parent;
20731            vp.transformMatrixToGlobal(m);
20732            m.preTranslate(-vp.mScrollX, -vp.mScrollY);
20733        } else if (parent instanceof ViewRootImpl) {
20734            final ViewRootImpl vr = (ViewRootImpl) parent;
20735            vr.transformMatrixToGlobal(m);
20736            m.preTranslate(0, -vr.mCurScrollY);
20737        }
20738
20739        m.preTranslate(mLeft, mTop);
20740
20741        if (!hasIdentityMatrix()) {
20742            m.preConcat(getMatrix());
20743        }
20744    }
20745
20746    /**
20747     * Modifies the input matrix such that it maps on-screen coordinates to
20748     * view-local coordinates.
20749     *
20750     * @param m input matrix to modify
20751     * @hide
20752     */
20753    public void transformMatrixToLocal(Matrix m) {
20754        final ViewParent parent = mParent;
20755        if (parent instanceof View) {
20756            final View vp = (View) parent;
20757            vp.transformMatrixToLocal(m);
20758            m.postTranslate(vp.mScrollX, vp.mScrollY);
20759        } else if (parent instanceof ViewRootImpl) {
20760            final ViewRootImpl vr = (ViewRootImpl) parent;
20761            vr.transformMatrixToLocal(m);
20762            m.postTranslate(0, vr.mCurScrollY);
20763        }
20764
20765        m.postTranslate(-mLeft, -mTop);
20766
20767        if (!hasIdentityMatrix()) {
20768            m.postConcat(getInverseMatrix());
20769        }
20770    }
20771
20772    /**
20773     * @hide
20774     */
20775    @ViewDebug.ExportedProperty(category = "layout", indexMapping = {
20776            @ViewDebug.IntToString(from = 0, to = "x"),
20777            @ViewDebug.IntToString(from = 1, to = "y")
20778    })
20779    public int[] getLocationOnScreen() {
20780        int[] location = new int[2];
20781        getLocationOnScreen(location);
20782        return location;
20783    }
20784
20785    /**
20786     * <p>Computes the coordinates of this view on the screen. The argument
20787     * must be an array of two integers. After the method returns, the array
20788     * contains the x and y location in that order.</p>
20789     *
20790     * @param outLocation an array of two integers in which to hold the coordinates
20791     */
20792    public void getLocationOnScreen(@Size(2) int[] outLocation) {
20793        getLocationInWindow(outLocation);
20794
20795        final AttachInfo info = mAttachInfo;
20796        if (info != null) {
20797            outLocation[0] += info.mWindowLeft;
20798            outLocation[1] += info.mWindowTop;
20799        }
20800    }
20801
20802    /**
20803     * <p>Computes the coordinates of this view in its window. The argument
20804     * must be an array of two integers. After the method returns, the array
20805     * contains the x and y location in that order.</p>
20806     *
20807     * @param outLocation an array of two integers in which to hold the coordinates
20808     */
20809    public void getLocationInWindow(@Size(2) int[] outLocation) {
20810        if (outLocation == null || outLocation.length < 2) {
20811            throw new IllegalArgumentException("outLocation must be an array of two integers");
20812        }
20813
20814        outLocation[0] = 0;
20815        outLocation[1] = 0;
20816
20817        transformFromViewToWindowSpace(outLocation);
20818    }
20819
20820    /** @hide */
20821    public void transformFromViewToWindowSpace(@Size(2) int[] inOutLocation) {
20822        if (inOutLocation == null || inOutLocation.length < 2) {
20823            throw new IllegalArgumentException("inOutLocation must be an array of two integers");
20824        }
20825
20826        if (mAttachInfo == null) {
20827            // When the view is not attached to a window, this method does not make sense
20828            inOutLocation[0] = inOutLocation[1] = 0;
20829            return;
20830        }
20831
20832        float position[] = mAttachInfo.mTmpTransformLocation;
20833        position[0] = inOutLocation[0];
20834        position[1] = inOutLocation[1];
20835
20836        if (!hasIdentityMatrix()) {
20837            getMatrix().mapPoints(position);
20838        }
20839
20840        position[0] += mLeft;
20841        position[1] += mTop;
20842
20843        ViewParent viewParent = mParent;
20844        while (viewParent instanceof View) {
20845            final View view = (View) viewParent;
20846
20847            position[0] -= view.mScrollX;
20848            position[1] -= view.mScrollY;
20849
20850            if (!view.hasIdentityMatrix()) {
20851                view.getMatrix().mapPoints(position);
20852            }
20853
20854            position[0] += view.mLeft;
20855            position[1] += view.mTop;
20856
20857            viewParent = view.mParent;
20858         }
20859
20860        if (viewParent instanceof ViewRootImpl) {
20861            // *cough*
20862            final ViewRootImpl vr = (ViewRootImpl) viewParent;
20863            position[1] -= vr.mCurScrollY;
20864        }
20865
20866        inOutLocation[0] = Math.round(position[0]);
20867        inOutLocation[1] = Math.round(position[1]);
20868    }
20869
20870    /**
20871     * @param id the id of the view to be found
20872     * @return the view of the specified id, null if cannot be found
20873     * @hide
20874     */
20875    protected <T extends View> T findViewTraversal(@IdRes int id) {
20876        if (id == mID) {
20877            return (T) this;
20878        }
20879        return null;
20880    }
20881
20882    /**
20883     * @param tag the tag of the view to be found
20884     * @return the view of specified tag, null if cannot be found
20885     * @hide
20886     */
20887    protected <T extends View> T findViewWithTagTraversal(Object tag) {
20888        if (tag != null && tag.equals(mTag)) {
20889            return (T) this;
20890        }
20891        return null;
20892    }
20893
20894    /**
20895     * @param predicate The predicate to evaluate.
20896     * @param childToSkip If not null, ignores this child during the recursive traversal.
20897     * @return The first view that matches the predicate or null.
20898     * @hide
20899     */
20900    protected <T extends View> T findViewByPredicateTraversal(Predicate<View> predicate,
20901            View childToSkip) {
20902        if (predicate.test(this)) {
20903            return (T) this;
20904        }
20905        return null;
20906    }
20907
20908    /**
20909     * Finds the first descendant view with the given ID, the view itself if
20910     * the ID matches {@link #getId()}, or {@code null} if the ID is invalid
20911     * (< 0) or there is no matching view in the hierarchy.
20912     * <p>
20913     * <strong>Note:</strong> In most cases -- depending on compiler support --
20914     * the resulting view is automatically cast to the target class type. If
20915     * the target class type is unconstrained, an explicit cast may be
20916     * necessary.
20917     *
20918     * @param id the ID to search for
20919     * @return a view with given ID if found, or {@code null} otherwise
20920     * @see View#findViewById(int)
20921     */
20922    @Nullable
20923    public final <T extends View> T findViewById(@IdRes int id) {
20924        if (id < 0) {
20925            return null;
20926        }
20927        return findViewTraversal(id);
20928    }
20929
20930    /**
20931     * Finds a view by its unuque and stable accessibility id.
20932     *
20933     * @param accessibilityId The searched accessibility id.
20934     * @return The found view.
20935     */
20936    final <T extends View> T  findViewByAccessibilityId(int accessibilityId) {
20937        if (accessibilityId < 0) {
20938            return null;
20939        }
20940        T view = findViewByAccessibilityIdTraversal(accessibilityId);
20941        if (view != null) {
20942            return view.includeForAccessibility() ? view : null;
20943        }
20944        return null;
20945    }
20946
20947    /**
20948     * Performs the traversal to find a view by its unuque and stable accessibility id.
20949     *
20950     * <strong>Note:</strong>This method does not stop at the root namespace
20951     * boundary since the user can touch the screen at an arbitrary location
20952     * potentially crossing the root namespace bounday which will send an
20953     * accessibility event to accessibility services and they should be able
20954     * to obtain the event source. Also accessibility ids are guaranteed to be
20955     * unique in the window.
20956     *
20957     * @param accessibilityId The accessibility id.
20958     * @return The found view.
20959     * @hide
20960     */
20961    public <T extends View> T findViewByAccessibilityIdTraversal(int accessibilityId) {
20962        if (getAccessibilityViewId() == accessibilityId) {
20963            return (T) this;
20964        }
20965        return null;
20966    }
20967
20968    /**
20969     * Look for a child view with the given tag.  If this view has the given
20970     * tag, return this view.
20971     *
20972     * @param tag The tag to search for, using "tag.equals(getTag())".
20973     * @return The View that has the given tag in the hierarchy or null
20974     */
20975    public final <T extends View> T findViewWithTag(Object tag) {
20976        if (tag == null) {
20977            return null;
20978        }
20979        return findViewWithTagTraversal(tag);
20980    }
20981
20982    /**
20983     * Look for a child view that matches the specified predicate.
20984     * If this view matches the predicate, return this view.
20985     *
20986     * @param predicate The predicate to evaluate.
20987     * @return The first view that matches the predicate or null.
20988     * @hide
20989     */
20990    public final <T extends View> T findViewByPredicate(Predicate<View> predicate) {
20991        return findViewByPredicateTraversal(predicate, null);
20992    }
20993
20994    /**
20995     * Look for a child view that matches the specified predicate,
20996     * starting with the specified view and its descendents and then
20997     * recusively searching the ancestors and siblings of that view
20998     * until this view is reached.
20999     *
21000     * This method is useful in cases where the predicate does not match
21001     * a single unique view (perhaps multiple views use the same id)
21002     * and we are trying to find the view that is "closest" in scope to the
21003     * starting view.
21004     *
21005     * @param start The view to start from.
21006     * @param predicate The predicate to evaluate.
21007     * @return The first view that matches the predicate or null.
21008     * @hide
21009     */
21010    public final <T extends View> T findViewByPredicateInsideOut(
21011            View start, Predicate<View> predicate) {
21012        View childToSkip = null;
21013        for (;;) {
21014            T view = start.findViewByPredicateTraversal(predicate, childToSkip);
21015            if (view != null || start == this) {
21016                return view;
21017            }
21018
21019            ViewParent parent = start.getParent();
21020            if (parent == null || !(parent instanceof View)) {
21021                return null;
21022            }
21023
21024            childToSkip = start;
21025            start = (View) parent;
21026        }
21027    }
21028
21029    /**
21030     * Sets the identifier for this view. The identifier does not have to be
21031     * unique in this view's hierarchy. The identifier should be a positive
21032     * number.
21033     *
21034     * @see #NO_ID
21035     * @see #getId()
21036     * @see #findViewById(int)
21037     *
21038     * @param id a number used to identify the view
21039     *
21040     * @attr ref android.R.styleable#View_id
21041     */
21042    public void setId(@IdRes int id) {
21043        mID = id;
21044        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
21045            mID = generateViewId();
21046        }
21047    }
21048
21049    /**
21050     * {@hide}
21051     *
21052     * @param isRoot true if the view belongs to the root namespace, false
21053     *        otherwise
21054     */
21055    public void setIsRootNamespace(boolean isRoot) {
21056        if (isRoot) {
21057            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
21058        } else {
21059            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
21060        }
21061    }
21062
21063    /**
21064     * {@hide}
21065     *
21066     * @return true if the view belongs to the root namespace, false otherwise
21067     */
21068    public boolean isRootNamespace() {
21069        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
21070    }
21071
21072    /**
21073     * Returns this view's identifier.
21074     *
21075     * @return a positive integer used to identify the view or {@link #NO_ID}
21076     *         if the view has no ID
21077     *
21078     * @see #setId(int)
21079     * @see #findViewById(int)
21080     * @attr ref android.R.styleable#View_id
21081     */
21082    @IdRes
21083    @ViewDebug.CapturedViewProperty
21084    public int getId() {
21085        return mID;
21086    }
21087
21088    /**
21089     * Returns this view's tag.
21090     *
21091     * @return the Object stored in this view as a tag, or {@code null} if not
21092     *         set
21093     *
21094     * @see #setTag(Object)
21095     * @see #getTag(int)
21096     */
21097    @ViewDebug.ExportedProperty
21098    public Object getTag() {
21099        return mTag;
21100    }
21101
21102    /**
21103     * Sets the tag associated with this view. A tag can be used to mark
21104     * a view in its hierarchy and does not have to be unique within the
21105     * hierarchy. Tags can also be used to store data within a view without
21106     * resorting to another data structure.
21107     *
21108     * @param tag an Object to tag the view with
21109     *
21110     * @see #getTag()
21111     * @see #setTag(int, Object)
21112     */
21113    public void setTag(final Object tag) {
21114        mTag = tag;
21115    }
21116
21117    /**
21118     * Returns the tag associated with this view and the specified key.
21119     *
21120     * @param key The key identifying the tag
21121     *
21122     * @return the Object stored in this view as a tag, or {@code null} if not
21123     *         set
21124     *
21125     * @see #setTag(int, Object)
21126     * @see #getTag()
21127     */
21128    public Object getTag(int key) {
21129        if (mKeyedTags != null) return mKeyedTags.get(key);
21130        return null;
21131    }
21132
21133    /**
21134     * Sets a tag associated with this view and a key. A tag can be used
21135     * to mark a view in its hierarchy and does not have to be unique within
21136     * the hierarchy. Tags can also be used to store data within a view
21137     * without resorting to another data structure.
21138     *
21139     * The specified key should be an id declared in the resources of the
21140     * application to ensure it is unique (see the <a
21141     * href="{@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
21142     * Keys identified as belonging to
21143     * the Android framework or not associated with any package will cause
21144     * an {@link IllegalArgumentException} to be thrown.
21145     *
21146     * @param key The key identifying the tag
21147     * @param tag An Object to tag the view with
21148     *
21149     * @throws IllegalArgumentException If they specified key is not valid
21150     *
21151     * @see #setTag(Object)
21152     * @see #getTag(int)
21153     */
21154    public void setTag(int key, final Object tag) {
21155        // If the package id is 0x00 or 0x01, it's either an undefined package
21156        // or a framework id
21157        if ((key >>> 24) < 2) {
21158            throw new IllegalArgumentException("The key must be an application-specific "
21159                    + "resource id.");
21160        }
21161
21162        setKeyedTag(key, tag);
21163    }
21164
21165    /**
21166     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
21167     * framework id.
21168     *
21169     * @hide
21170     */
21171    public void setTagInternal(int key, Object tag) {
21172        if ((key >>> 24) != 0x1) {
21173            throw new IllegalArgumentException("The key must be a framework-specific "
21174                    + "resource id.");
21175        }
21176
21177        setKeyedTag(key, tag);
21178    }
21179
21180    private void setKeyedTag(int key, Object tag) {
21181        if (mKeyedTags == null) {
21182            mKeyedTags = new SparseArray<Object>(2);
21183        }
21184
21185        mKeyedTags.put(key, tag);
21186    }
21187
21188    /**
21189     * Prints information about this view in the log output, with the tag
21190     * {@link #VIEW_LOG_TAG}.
21191     *
21192     * @hide
21193     */
21194    public void debug() {
21195        debug(0);
21196    }
21197
21198    /**
21199     * Prints information about this view in the log output, with the tag
21200     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
21201     * indentation defined by the <code>depth</code>.
21202     *
21203     * @param depth the indentation level
21204     *
21205     * @hide
21206     */
21207    protected void debug(int depth) {
21208        String output = debugIndent(depth - 1);
21209
21210        output += "+ " + this;
21211        int id = getId();
21212        if (id != -1) {
21213            output += " (id=" + id + ")";
21214        }
21215        Object tag = getTag();
21216        if (tag != null) {
21217            output += " (tag=" + tag + ")";
21218        }
21219        Log.d(VIEW_LOG_TAG, output);
21220
21221        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
21222            output = debugIndent(depth) + " FOCUSED";
21223            Log.d(VIEW_LOG_TAG, output);
21224        }
21225
21226        output = debugIndent(depth);
21227        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
21228                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
21229                + "} ";
21230        Log.d(VIEW_LOG_TAG, output);
21231
21232        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
21233                || mPaddingBottom != 0) {
21234            output = debugIndent(depth);
21235            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
21236                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
21237            Log.d(VIEW_LOG_TAG, output);
21238        }
21239
21240        output = debugIndent(depth);
21241        output += "mMeasureWidth=" + mMeasuredWidth +
21242                " mMeasureHeight=" + mMeasuredHeight;
21243        Log.d(VIEW_LOG_TAG, output);
21244
21245        output = debugIndent(depth);
21246        if (mLayoutParams == null) {
21247            output += "BAD! no layout params";
21248        } else {
21249            output = mLayoutParams.debug(output);
21250        }
21251        Log.d(VIEW_LOG_TAG, output);
21252
21253        output = debugIndent(depth);
21254        output += "flags={";
21255        output += View.printFlags(mViewFlags);
21256        output += "}";
21257        Log.d(VIEW_LOG_TAG, output);
21258
21259        output = debugIndent(depth);
21260        output += "privateFlags={";
21261        output += View.printPrivateFlags(mPrivateFlags);
21262        output += "}";
21263        Log.d(VIEW_LOG_TAG, output);
21264    }
21265
21266    /**
21267     * Creates a string of whitespaces used for indentation.
21268     *
21269     * @param depth the indentation level
21270     * @return a String containing (depth * 2 + 3) * 2 white spaces
21271     *
21272     * @hide
21273     */
21274    protected static String debugIndent(int depth) {
21275        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
21276        for (int i = 0; i < (depth * 2) + 3; i++) {
21277            spaces.append(' ').append(' ');
21278        }
21279        return spaces.toString();
21280    }
21281
21282    /**
21283     * <p>Return the offset of the widget's text baseline from the widget's top
21284     * boundary. If this widget does not support baseline alignment, this
21285     * method returns -1. </p>
21286     *
21287     * @return the offset of the baseline within the widget's bounds or -1
21288     *         if baseline alignment is not supported
21289     */
21290    @ViewDebug.ExportedProperty(category = "layout")
21291    public int getBaseline() {
21292        return -1;
21293    }
21294
21295    /**
21296     * Returns whether the view hierarchy is currently undergoing a layout pass. This
21297     * information is useful to avoid situations such as calling {@link #requestLayout()} during
21298     * a layout pass.
21299     *
21300     * @return whether the view hierarchy is currently undergoing a layout pass
21301     */
21302    public boolean isInLayout() {
21303        ViewRootImpl viewRoot = getViewRootImpl();
21304        return (viewRoot != null && viewRoot.isInLayout());
21305    }
21306
21307    /**
21308     * Call this when something has changed which has invalidated the
21309     * layout of this view. This will schedule a layout pass of the view
21310     * tree. This should not be called while the view hierarchy is currently in a layout
21311     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
21312     * end of the current layout pass (and then layout will run again) or after the current
21313     * frame is drawn and the next layout occurs.
21314     *
21315     * <p>Subclasses which override this method should call the superclass method to
21316     * handle possible request-during-layout errors correctly.</p>
21317     */
21318    @CallSuper
21319    public void requestLayout() {
21320        if (mMeasureCache != null) mMeasureCache.clear();
21321
21322        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
21323            // Only trigger request-during-layout logic if this is the view requesting it,
21324            // not the views in its parent hierarchy
21325            ViewRootImpl viewRoot = getViewRootImpl();
21326            if (viewRoot != null && viewRoot.isInLayout()) {
21327                if (!viewRoot.requestLayoutDuringLayout(this)) {
21328                    return;
21329                }
21330            }
21331            mAttachInfo.mViewRequestingLayout = this;
21332        }
21333
21334        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
21335        mPrivateFlags |= PFLAG_INVALIDATED;
21336
21337        if (mParent != null && !mParent.isLayoutRequested()) {
21338            mParent.requestLayout();
21339        }
21340        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
21341            mAttachInfo.mViewRequestingLayout = null;
21342        }
21343    }
21344
21345    /**
21346     * Forces this view to be laid out during the next layout pass.
21347     * This method does not call requestLayout() or forceLayout()
21348     * on the parent.
21349     */
21350    public void forceLayout() {
21351        if (mMeasureCache != null) mMeasureCache.clear();
21352
21353        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
21354        mPrivateFlags |= PFLAG_INVALIDATED;
21355    }
21356
21357    /**
21358     * <p>
21359     * This is called to find out how big a view should be. The parent
21360     * supplies constraint information in the width and height parameters.
21361     * </p>
21362     *
21363     * <p>
21364     * The actual measurement work of a view is performed in
21365     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
21366     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
21367     * </p>
21368     *
21369     *
21370     * @param widthMeasureSpec Horizontal space requirements as imposed by the
21371     *        parent
21372     * @param heightMeasureSpec Vertical space requirements as imposed by the
21373     *        parent
21374     *
21375     * @see #onMeasure(int, int)
21376     */
21377    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
21378        boolean optical = isLayoutModeOptical(this);
21379        if (optical != isLayoutModeOptical(mParent)) {
21380            Insets insets = getOpticalInsets();
21381            int oWidth  = insets.left + insets.right;
21382            int oHeight = insets.top  + insets.bottom;
21383            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
21384            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
21385        }
21386
21387        // Suppress sign extension for the low bytes
21388        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
21389        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
21390
21391        final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
21392
21393        // Optimize layout by avoiding an extra EXACTLY pass when the view is
21394        // already measured as the correct size. In API 23 and below, this
21395        // extra pass is required to make LinearLayout re-distribute weight.
21396        final boolean specChanged = widthMeasureSpec != mOldWidthMeasureSpec
21397                || heightMeasureSpec != mOldHeightMeasureSpec;
21398        final boolean isSpecExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY
21399                && MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY;
21400        final boolean matchesSpecSize = getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec)
21401                && getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec);
21402        final boolean needsLayout = specChanged
21403                && (sAlwaysRemeasureExactly || !isSpecExactly || !matchesSpecSize);
21404
21405        if (forceLayout || needsLayout) {
21406            // first clears the measured dimension flag
21407            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
21408
21409            resolveRtlPropertiesIfNeeded();
21410
21411            int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key);
21412            if (cacheIndex < 0 || sIgnoreMeasureCache) {
21413                // measure ourselves, this should set the measured dimension flag back
21414                onMeasure(widthMeasureSpec, heightMeasureSpec);
21415                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
21416            } else {
21417                long value = mMeasureCache.valueAt(cacheIndex);
21418                // Casting a long to int drops the high 32 bits, no mask needed
21419                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
21420                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
21421            }
21422
21423            // flag not set, setMeasuredDimension() was not invoked, we raise
21424            // an exception to warn the developer
21425            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
21426                throw new IllegalStateException("View with id " + getId() + ": "
21427                        + getClass().getName() + "#onMeasure() did not set the"
21428                        + " measured dimension by calling"
21429                        + " setMeasuredDimension()");
21430            }
21431
21432            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
21433        }
21434
21435        mOldWidthMeasureSpec = widthMeasureSpec;
21436        mOldHeightMeasureSpec = heightMeasureSpec;
21437
21438        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
21439                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
21440    }
21441
21442    /**
21443     * <p>
21444     * Measure the view and its content to determine the measured width and the
21445     * measured height. This method is invoked by {@link #measure(int, int)} and
21446     * should be overridden by subclasses to provide accurate and efficient
21447     * measurement of their contents.
21448     * </p>
21449     *
21450     * <p>
21451     * <strong>CONTRACT:</strong> When overriding this method, you
21452     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
21453     * measured width and height of this view. Failure to do so will trigger an
21454     * <code>IllegalStateException</code>, thrown by
21455     * {@link #measure(int, int)}. Calling the superclass'
21456     * {@link #onMeasure(int, int)} is a valid use.
21457     * </p>
21458     *
21459     * <p>
21460     * The base class implementation of measure defaults to the background size,
21461     * unless a larger size is allowed by the MeasureSpec. Subclasses should
21462     * override {@link #onMeasure(int, int)} to provide better measurements of
21463     * their content.
21464     * </p>
21465     *
21466     * <p>
21467     * If this method is overridden, it is the subclass's responsibility to make
21468     * sure the measured height and width are at least the view's minimum height
21469     * and width ({@link #getSuggestedMinimumHeight()} and
21470     * {@link #getSuggestedMinimumWidth()}).
21471     * </p>
21472     *
21473     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
21474     *                         The requirements are encoded with
21475     *                         {@link android.view.View.MeasureSpec}.
21476     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
21477     *                         The requirements are encoded with
21478     *                         {@link android.view.View.MeasureSpec}.
21479     *
21480     * @see #getMeasuredWidth()
21481     * @see #getMeasuredHeight()
21482     * @see #setMeasuredDimension(int, int)
21483     * @see #getSuggestedMinimumHeight()
21484     * @see #getSuggestedMinimumWidth()
21485     * @see android.view.View.MeasureSpec#getMode(int)
21486     * @see android.view.View.MeasureSpec#getSize(int)
21487     */
21488    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
21489        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
21490                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
21491    }
21492
21493    /**
21494     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
21495     * measured width and measured height. Failing to do so will trigger an
21496     * exception at measurement time.</p>
21497     *
21498     * @param measuredWidth The measured width of this view.  May be a complex
21499     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
21500     * {@link #MEASURED_STATE_TOO_SMALL}.
21501     * @param measuredHeight The measured height of this view.  May be a complex
21502     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
21503     * {@link #MEASURED_STATE_TOO_SMALL}.
21504     */
21505    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
21506        boolean optical = isLayoutModeOptical(this);
21507        if (optical != isLayoutModeOptical(mParent)) {
21508            Insets insets = getOpticalInsets();
21509            int opticalWidth  = insets.left + insets.right;
21510            int opticalHeight = insets.top  + insets.bottom;
21511
21512            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
21513            measuredHeight += optical ? opticalHeight : -opticalHeight;
21514        }
21515        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
21516    }
21517
21518    /**
21519     * Sets the measured dimension without extra processing for things like optical bounds.
21520     * Useful for reapplying consistent values that have already been cooked with adjustments
21521     * for optical bounds, etc. such as those from the measurement cache.
21522     *
21523     * @param measuredWidth The measured width of this view.  May be a complex
21524     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
21525     * {@link #MEASURED_STATE_TOO_SMALL}.
21526     * @param measuredHeight The measured height of this view.  May be a complex
21527     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
21528     * {@link #MEASURED_STATE_TOO_SMALL}.
21529     */
21530    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
21531        mMeasuredWidth = measuredWidth;
21532        mMeasuredHeight = measuredHeight;
21533
21534        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
21535    }
21536
21537    /**
21538     * Merge two states as returned by {@link #getMeasuredState()}.
21539     * @param curState The current state as returned from a view or the result
21540     * of combining multiple views.
21541     * @param newState The new view state to combine.
21542     * @return Returns a new integer reflecting the combination of the two
21543     * states.
21544     */
21545    public static int combineMeasuredStates(int curState, int newState) {
21546        return curState | newState;
21547    }
21548
21549    /**
21550     * Version of {@link #resolveSizeAndState(int, int, int)}
21551     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
21552     */
21553    public static int resolveSize(int size, int measureSpec) {
21554        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
21555    }
21556
21557    /**
21558     * Utility to reconcile a desired size and state, with constraints imposed
21559     * by a MeasureSpec. Will take the desired size, unless a different size
21560     * is imposed by the constraints. The returned value is a compound integer,
21561     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
21562     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the
21563     * resulting size is smaller than the size the view wants to be.
21564     *
21565     * @param size How big the view wants to be.
21566     * @param measureSpec Constraints imposed by the parent.
21567     * @param childMeasuredState Size information bit mask for the view's
21568     *                           children.
21569     * @return Size information bit mask as defined by
21570     *         {@link #MEASURED_SIZE_MASK} and
21571     *         {@link #MEASURED_STATE_TOO_SMALL}.
21572     */
21573    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
21574        final int specMode = MeasureSpec.getMode(measureSpec);
21575        final int specSize = MeasureSpec.getSize(measureSpec);
21576        final int result;
21577        switch (specMode) {
21578            case MeasureSpec.AT_MOST:
21579                if (specSize < size) {
21580                    result = specSize | MEASURED_STATE_TOO_SMALL;
21581                } else {
21582                    result = size;
21583                }
21584                break;
21585            case MeasureSpec.EXACTLY:
21586                result = specSize;
21587                break;
21588            case MeasureSpec.UNSPECIFIED:
21589            default:
21590                result = size;
21591        }
21592        return result | (childMeasuredState & MEASURED_STATE_MASK);
21593    }
21594
21595    /**
21596     * Utility to return a default size. Uses the supplied size if the
21597     * MeasureSpec imposed no constraints. Will get larger if allowed
21598     * by the MeasureSpec.
21599     *
21600     * @param size Default size for this view
21601     * @param measureSpec Constraints imposed by the parent
21602     * @return The size this view should be.
21603     */
21604    public static int getDefaultSize(int size, int measureSpec) {
21605        int result = size;
21606        int specMode = MeasureSpec.getMode(measureSpec);
21607        int specSize = MeasureSpec.getSize(measureSpec);
21608
21609        switch (specMode) {
21610        case MeasureSpec.UNSPECIFIED:
21611            result = size;
21612            break;
21613        case MeasureSpec.AT_MOST:
21614        case MeasureSpec.EXACTLY:
21615            result = specSize;
21616            break;
21617        }
21618        return result;
21619    }
21620
21621    /**
21622     * Returns the suggested minimum height that the view should use. This
21623     * returns the maximum of the view's minimum height
21624     * and the background's minimum height
21625     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
21626     * <p>
21627     * When being used in {@link #onMeasure(int, int)}, the caller should still
21628     * ensure the returned height is within the requirements of the parent.
21629     *
21630     * @return The suggested minimum height of the view.
21631     */
21632    protected int getSuggestedMinimumHeight() {
21633        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
21634
21635    }
21636
21637    /**
21638     * Returns the suggested minimum width that the view should use. This
21639     * returns the maximum of the view's minimum width
21640     * and the background's minimum width
21641     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
21642     * <p>
21643     * When being used in {@link #onMeasure(int, int)}, the caller should still
21644     * ensure the returned width is within the requirements of the parent.
21645     *
21646     * @return The suggested minimum width of the view.
21647     */
21648    protected int getSuggestedMinimumWidth() {
21649        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
21650    }
21651
21652    /**
21653     * Returns the minimum height of the view.
21654     *
21655     * @return the minimum height the view will try to be, in pixels
21656     *
21657     * @see #setMinimumHeight(int)
21658     *
21659     * @attr ref android.R.styleable#View_minHeight
21660     */
21661    public int getMinimumHeight() {
21662        return mMinHeight;
21663    }
21664
21665    /**
21666     * Sets the minimum height of the view. It is not guaranteed the view will
21667     * be able to achieve this minimum height (for example, if its parent layout
21668     * constrains it with less available height).
21669     *
21670     * @param minHeight The minimum height the view will try to be, in pixels
21671     *
21672     * @see #getMinimumHeight()
21673     *
21674     * @attr ref android.R.styleable#View_minHeight
21675     */
21676    @RemotableViewMethod
21677    public void setMinimumHeight(int minHeight) {
21678        mMinHeight = minHeight;
21679        requestLayout();
21680    }
21681
21682    /**
21683     * Returns the minimum width of the view.
21684     *
21685     * @return the minimum width the view will try to be, in pixels
21686     *
21687     * @see #setMinimumWidth(int)
21688     *
21689     * @attr ref android.R.styleable#View_minWidth
21690     */
21691    public int getMinimumWidth() {
21692        return mMinWidth;
21693    }
21694
21695    /**
21696     * Sets the minimum width of the view. It is not guaranteed the view will
21697     * be able to achieve this minimum width (for example, if its parent layout
21698     * constrains it with less available width).
21699     *
21700     * @param minWidth The minimum width the view will try to be, in pixels
21701     *
21702     * @see #getMinimumWidth()
21703     *
21704     * @attr ref android.R.styleable#View_minWidth
21705     */
21706    public void setMinimumWidth(int minWidth) {
21707        mMinWidth = minWidth;
21708        requestLayout();
21709
21710    }
21711
21712    /**
21713     * Get the animation currently associated with this view.
21714     *
21715     * @return The animation that is currently playing or
21716     *         scheduled to play for this view.
21717     */
21718    public Animation getAnimation() {
21719        return mCurrentAnimation;
21720    }
21721
21722    /**
21723     * Start the specified animation now.
21724     *
21725     * @param animation the animation to start now
21726     */
21727    public void startAnimation(Animation animation) {
21728        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
21729        setAnimation(animation);
21730        invalidateParentCaches();
21731        invalidate(true);
21732    }
21733
21734    /**
21735     * Cancels any animations for this view.
21736     */
21737    public void clearAnimation() {
21738        if (mCurrentAnimation != null) {
21739            mCurrentAnimation.detach();
21740        }
21741        mCurrentAnimation = null;
21742        invalidateParentIfNeeded();
21743    }
21744
21745    /**
21746     * Sets the next animation to play for this view.
21747     * If you want the animation to play immediately, use
21748     * {@link #startAnimation(android.view.animation.Animation)} instead.
21749     * This method provides allows fine-grained
21750     * control over the start time and invalidation, but you
21751     * must make sure that 1) the animation has a start time set, and
21752     * 2) the view's parent (which controls animations on its children)
21753     * will be invalidated when the animation is supposed to
21754     * start.
21755     *
21756     * @param animation The next animation, or null.
21757     */
21758    public void setAnimation(Animation animation) {
21759        mCurrentAnimation = animation;
21760
21761        if (animation != null) {
21762            // If the screen is off assume the animation start time is now instead of
21763            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
21764            // would cause the animation to start when the screen turns back on
21765            if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF
21766                    && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
21767                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
21768            }
21769            animation.reset();
21770        }
21771    }
21772
21773    /**
21774     * Invoked by a parent ViewGroup to notify the start of the animation
21775     * currently associated with this view. If you override this method,
21776     * always call super.onAnimationStart();
21777     *
21778     * @see #setAnimation(android.view.animation.Animation)
21779     * @see #getAnimation()
21780     */
21781    @CallSuper
21782    protected void onAnimationStart() {
21783        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
21784    }
21785
21786    /**
21787     * Invoked by a parent ViewGroup to notify the end of the animation
21788     * currently associated with this view. If you override this method,
21789     * always call super.onAnimationEnd();
21790     *
21791     * @see #setAnimation(android.view.animation.Animation)
21792     * @see #getAnimation()
21793     */
21794    @CallSuper
21795    protected void onAnimationEnd() {
21796        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
21797    }
21798
21799    /**
21800     * Invoked if there is a Transform that involves alpha. Subclass that can
21801     * draw themselves with the specified alpha should return true, and then
21802     * respect that alpha when their onDraw() is called. If this returns false
21803     * then the view may be redirected to draw into an offscreen buffer to
21804     * fulfill the request, which will look fine, but may be slower than if the
21805     * subclass handles it internally. The default implementation returns false.
21806     *
21807     * @param alpha The alpha (0..255) to apply to the view's drawing
21808     * @return true if the view can draw with the specified alpha.
21809     */
21810    protected boolean onSetAlpha(int alpha) {
21811        return false;
21812    }
21813
21814    /**
21815     * This is used by the RootView to perform an optimization when
21816     * the view hierarchy contains one or several SurfaceView.
21817     * SurfaceView is always considered transparent, but its children are not,
21818     * therefore all View objects remove themselves from the global transparent
21819     * region (passed as a parameter to this function).
21820     *
21821     * @param region The transparent region for this ViewAncestor (window).
21822     *
21823     * @return Returns true if the effective visibility of the view at this
21824     * point is opaque, regardless of the transparent region; returns false
21825     * if it is possible for underlying windows to be seen behind the view.
21826     *
21827     * {@hide}
21828     */
21829    public boolean gatherTransparentRegion(Region region) {
21830        final AttachInfo attachInfo = mAttachInfo;
21831        if (region != null && attachInfo != null) {
21832            final int pflags = mPrivateFlags;
21833            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
21834                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
21835                // remove it from the transparent region.
21836                final int[] location = attachInfo.mTransparentLocation;
21837                getLocationInWindow(location);
21838                // When a view has Z value, then it will be better to leave some area below the view
21839                // for drawing shadow. The shadow outset is proportional to the Z value. Note that
21840                // the bottom part needs more offset than the left, top and right parts due to the
21841                // spot light effects.
21842                int shadowOffset = getZ() > 0 ? (int) getZ() : 0;
21843                region.op(location[0] - shadowOffset, location[1] - shadowOffset,
21844                        location[0] + mRight - mLeft + shadowOffset,
21845                        location[1] + mBottom - mTop + (shadowOffset * 3), Region.Op.DIFFERENCE);
21846            } else {
21847                if (mBackground != null && mBackground.getOpacity() != PixelFormat.TRANSPARENT) {
21848                    // The SKIP_DRAW flag IS set and the background drawable exists, we remove
21849                    // the background drawable's non-transparent parts from this transparent region.
21850                    applyDrawableToTransparentRegion(mBackground, region);
21851                }
21852                if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
21853                        && mForegroundInfo.mDrawable.getOpacity() != PixelFormat.TRANSPARENT) {
21854                    // Similarly, we remove the foreground drawable's non-transparent parts.
21855                    applyDrawableToTransparentRegion(mForegroundInfo.mDrawable, region);
21856                }
21857            }
21858        }
21859        return true;
21860    }
21861
21862    /**
21863     * Play a sound effect for this view.
21864     *
21865     * <p>The framework will play sound effects for some built in actions, such as
21866     * clicking, but you may wish to play these effects in your widget,
21867     * for instance, for internal navigation.
21868     *
21869     * <p>The sound effect will only be played if sound effects are enabled by the user, and
21870     * {@link #isSoundEffectsEnabled()} is true.
21871     *
21872     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
21873     */
21874    public void playSoundEffect(int soundConstant) {
21875        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
21876            return;
21877        }
21878        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
21879    }
21880
21881    /**
21882     * BZZZTT!!1!
21883     *
21884     * <p>Provide haptic feedback to the user for this view.
21885     *
21886     * <p>The framework will provide haptic feedback for some built in actions,
21887     * such as long presses, but you may wish to provide feedback for your
21888     * own widget.
21889     *
21890     * <p>The feedback will only be performed if
21891     * {@link #isHapticFeedbackEnabled()} is true.
21892     *
21893     * @param feedbackConstant One of the constants defined in
21894     * {@link HapticFeedbackConstants}
21895     */
21896    public boolean performHapticFeedback(int feedbackConstant) {
21897        return performHapticFeedback(feedbackConstant, 0);
21898    }
21899
21900    /**
21901     * BZZZTT!!1!
21902     *
21903     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
21904     *
21905     * @param feedbackConstant One of the constants defined in
21906     * {@link HapticFeedbackConstants}
21907     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
21908     */
21909    public boolean performHapticFeedback(int feedbackConstant, int flags) {
21910        if (mAttachInfo == null) {
21911            return false;
21912        }
21913        //noinspection SimplifiableIfStatement
21914        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
21915                && !isHapticFeedbackEnabled()) {
21916            return false;
21917        }
21918        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
21919                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
21920    }
21921
21922    /**
21923     * Request that the visibility of the status bar or other screen/window
21924     * decorations be changed.
21925     *
21926     * <p>This method is used to put the over device UI into temporary modes
21927     * where the user's attention is focused more on the application content,
21928     * by dimming or hiding surrounding system affordances.  This is typically
21929     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
21930     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
21931     * to be placed behind the action bar (and with these flags other system
21932     * affordances) so that smooth transitions between hiding and showing them
21933     * can be done.
21934     *
21935     * <p>Two representative examples of the use of system UI visibility is
21936     * implementing a content browsing application (like a magazine reader)
21937     * and a video playing application.
21938     *
21939     * <p>The first code shows a typical implementation of a View in a content
21940     * browsing application.  In this implementation, the application goes
21941     * into a content-oriented mode by hiding the status bar and action bar,
21942     * and putting the navigation elements into lights out mode.  The user can
21943     * then interact with content while in this mode.  Such an application should
21944     * provide an easy way for the user to toggle out of the mode (such as to
21945     * check information in the status bar or access notifications).  In the
21946     * implementation here, this is done simply by tapping on the content.
21947     *
21948     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
21949     *      content}
21950     *
21951     * <p>This second code sample shows a typical implementation of a View
21952     * in a video playing application.  In this situation, while the video is
21953     * playing the application would like to go into a complete full-screen mode,
21954     * to use as much of the display as possible for the video.  When in this state
21955     * the user can not interact with the application; the system intercepts
21956     * touching on the screen to pop the UI out of full screen mode.  See
21957     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
21958     *
21959     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
21960     *      content}
21961     *
21962     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
21963     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
21964     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
21965     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
21966     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
21967     */
21968    public void setSystemUiVisibility(int visibility) {
21969        if (visibility != mSystemUiVisibility) {
21970            mSystemUiVisibility = visibility;
21971            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
21972                mParent.recomputeViewAttributes(this);
21973            }
21974        }
21975    }
21976
21977    /**
21978     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
21979     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
21980     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
21981     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
21982     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
21983     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
21984     */
21985    public int getSystemUiVisibility() {
21986        return mSystemUiVisibility;
21987    }
21988
21989    /**
21990     * Returns the current system UI visibility that is currently set for
21991     * the entire window.  This is the combination of the
21992     * {@link #setSystemUiVisibility(int)} values supplied by all of the
21993     * views in the window.
21994     */
21995    public int getWindowSystemUiVisibility() {
21996        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
21997    }
21998
21999    /**
22000     * Override to find out when the window's requested system UI visibility
22001     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
22002     * This is different from the callbacks received through
22003     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
22004     * in that this is only telling you about the local request of the window,
22005     * not the actual values applied by the system.
22006     */
22007    public void onWindowSystemUiVisibilityChanged(int visible) {
22008    }
22009
22010    /**
22011     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
22012     * the view hierarchy.
22013     */
22014    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
22015        onWindowSystemUiVisibilityChanged(visible);
22016    }
22017
22018    /**
22019     * Set a listener to receive callbacks when the visibility of the system bar changes.
22020     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
22021     */
22022    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
22023        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
22024        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
22025            mParent.recomputeViewAttributes(this);
22026        }
22027    }
22028
22029    /**
22030     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
22031     * the view hierarchy.
22032     */
22033    public void dispatchSystemUiVisibilityChanged(int visibility) {
22034        ListenerInfo li = mListenerInfo;
22035        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
22036            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
22037                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
22038        }
22039    }
22040
22041    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
22042        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
22043        if (val != mSystemUiVisibility) {
22044            setSystemUiVisibility(val);
22045            return true;
22046        }
22047        return false;
22048    }
22049
22050    /** @hide */
22051    public void setDisabledSystemUiVisibility(int flags) {
22052        if (mAttachInfo != null) {
22053            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
22054                mAttachInfo.mDisabledSystemUiVisibility = flags;
22055                if (mParent != null) {
22056                    mParent.recomputeViewAttributes(this);
22057                }
22058            }
22059        }
22060    }
22061
22062    /**
22063     * Creates an image that the system displays during the drag and drop
22064     * operation. This is called a &quot;drag shadow&quot;. The default implementation
22065     * for a DragShadowBuilder based on a View returns an image that has exactly the same
22066     * appearance as the given View. The default also positions the center of the drag shadow
22067     * directly under the touch point. If no View is provided (the constructor with no parameters
22068     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
22069     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overridden, then the
22070     * default is an invisible drag shadow.
22071     * <p>
22072     * You are not required to use the View you provide to the constructor as the basis of the
22073     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
22074     * anything you want as the drag shadow.
22075     * </p>
22076     * <p>
22077     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
22078     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
22079     *  size and position of the drag shadow. It uses this data to construct a
22080     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
22081     *  so that your application can draw the shadow image in the Canvas.
22082     * </p>
22083     *
22084     * <div class="special reference">
22085     * <h3>Developer Guides</h3>
22086     * <p>For a guide to implementing drag and drop features, read the
22087     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
22088     * </div>
22089     */
22090    public static class DragShadowBuilder {
22091        private final WeakReference<View> mView;
22092
22093        /**
22094         * Constructs a shadow image builder based on a View. By default, the resulting drag
22095         * shadow will have the same appearance and dimensions as the View, with the touch point
22096         * over the center of the View.
22097         * @param view A View. Any View in scope can be used.
22098         */
22099        public DragShadowBuilder(View view) {
22100            mView = new WeakReference<View>(view);
22101        }
22102
22103        /**
22104         * Construct a shadow builder object with no associated View.  This
22105         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
22106         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
22107         * to supply the drag shadow's dimensions and appearance without
22108         * reference to any View object. If they are not overridden, then the result is an
22109         * invisible drag shadow.
22110         */
22111        public DragShadowBuilder() {
22112            mView = new WeakReference<View>(null);
22113        }
22114
22115        /**
22116         * Returns the View object that had been passed to the
22117         * {@link #View.DragShadowBuilder(View)}
22118         * constructor.  If that View parameter was {@code null} or if the
22119         * {@link #View.DragShadowBuilder()}
22120         * constructor was used to instantiate the builder object, this method will return
22121         * null.
22122         *
22123         * @return The View object associate with this builder object.
22124         */
22125        @SuppressWarnings({"JavadocReference"})
22126        final public View getView() {
22127            return mView.get();
22128        }
22129
22130        /**
22131         * Provides the metrics for the shadow image. These include the dimensions of
22132         * the shadow image, and the point within that shadow that should
22133         * be centered under the touch location while dragging.
22134         * <p>
22135         * The default implementation sets the dimensions of the shadow to be the
22136         * same as the dimensions of the View itself and centers the shadow under
22137         * the touch point.
22138         * </p>
22139         *
22140         * @param outShadowSize A {@link android.graphics.Point} containing the width and height
22141         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
22142         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
22143         * image.
22144         *
22145         * @param outShadowTouchPoint A {@link android.graphics.Point} for the position within the
22146         * shadow image that should be underneath the touch point during the drag and drop
22147         * operation. Your application must set {@link android.graphics.Point#x} to the
22148         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
22149         */
22150        public void onProvideShadowMetrics(Point outShadowSize, Point outShadowTouchPoint) {
22151            final View view = mView.get();
22152            if (view != null) {
22153                outShadowSize.set(view.getWidth(), view.getHeight());
22154                outShadowTouchPoint.set(outShadowSize.x / 2, outShadowSize.y / 2);
22155            } else {
22156                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
22157            }
22158        }
22159
22160        /**
22161         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
22162         * based on the dimensions it received from the
22163         * {@link #onProvideShadowMetrics(Point, Point)} callback.
22164         *
22165         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
22166         */
22167        public void onDrawShadow(Canvas canvas) {
22168            final View view = mView.get();
22169            if (view != null) {
22170                view.draw(canvas);
22171            } else {
22172                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
22173            }
22174        }
22175    }
22176
22177    /**
22178     * @deprecated Use {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)
22179     * startDragAndDrop()} for newer platform versions.
22180     */
22181    @Deprecated
22182    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
22183                                   Object myLocalState, int flags) {
22184        return startDragAndDrop(data, shadowBuilder, myLocalState, flags);
22185    }
22186
22187    /**
22188     * Starts a drag and drop operation. When your application calls this method, it passes a
22189     * {@link android.view.View.DragShadowBuilder} object to the system. The
22190     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
22191     * to get metrics for the drag shadow, and then calls the object's
22192     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
22193     * <p>
22194     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
22195     *  drag events to all the View objects in your application that are currently visible. It does
22196     *  this either by calling the View object's drag listener (an implementation of
22197     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
22198     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
22199     *  Both are passed a {@link android.view.DragEvent} object that has a
22200     *  {@link android.view.DragEvent#getAction()} value of
22201     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
22202     * </p>
22203     * <p>
22204     * Your application can invoke {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object,
22205     * int) startDragAndDrop()} on any attached View object. The View object does not need to be
22206     * the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to be related
22207     * to the View the user selected for dragging.
22208     * </p>
22209     * @param data A {@link android.content.ClipData} object pointing to the data to be
22210     * transferred by the drag and drop operation.
22211     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
22212     * drag shadow.
22213     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
22214     * drop operation. When dispatching drag events to views in the same activity this object
22215     * will be available through {@link android.view.DragEvent#getLocalState()}. Views in other
22216     * activities will not have access to this data ({@link android.view.DragEvent#getLocalState()}
22217     * will return null).
22218     * <p>
22219     * myLocalState is a lightweight mechanism for the sending information from the dragged View
22220     * to the target Views. For example, it can contain flags that differentiate between a
22221     * a copy operation and a move operation.
22222     * </p>
22223     * @param flags Flags that control the drag and drop operation. This can be set to 0 for no
22224     * flags, or any combination of the following:
22225     *     <ul>
22226     *         <li>{@link #DRAG_FLAG_GLOBAL}</li>
22227     *         <li>{@link #DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION}</li>
22228     *         <li>{@link #DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION}</li>
22229     *         <li>{@link #DRAG_FLAG_GLOBAL_URI_READ}</li>
22230     *         <li>{@link #DRAG_FLAG_GLOBAL_URI_WRITE}</li>
22231     *         <li>{@link #DRAG_FLAG_OPAQUE}</li>
22232     *     </ul>
22233     * @return {@code true} if the method completes successfully, or
22234     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
22235     * do a drag, and so no drag operation is in progress.
22236     */
22237    public final boolean startDragAndDrop(ClipData data, DragShadowBuilder shadowBuilder,
22238            Object myLocalState, int flags) {
22239        if (ViewDebug.DEBUG_DRAG) {
22240            Log.d(VIEW_LOG_TAG, "startDragAndDrop: data=" + data + " flags=" + flags);
22241        }
22242        if (mAttachInfo == null) {
22243            Log.w(VIEW_LOG_TAG, "startDragAndDrop called on a detached view.");
22244            return false;
22245        }
22246
22247        if (data != null) {
22248            data.prepareToLeaveProcess((flags & View.DRAG_FLAG_GLOBAL) != 0);
22249        }
22250
22251        boolean okay = false;
22252
22253        Point shadowSize = new Point();
22254        Point shadowTouchPoint = new Point();
22255        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
22256
22257        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
22258                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
22259            throw new IllegalStateException("Drag shadow dimensions must not be negative");
22260        }
22261
22262        if (ViewDebug.DEBUG_DRAG) {
22263            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
22264                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
22265        }
22266        if (mAttachInfo.mDragSurface != null) {
22267            mAttachInfo.mDragSurface.release();
22268        }
22269        mAttachInfo.mDragSurface = new Surface();
22270        try {
22271            mAttachInfo.mDragToken = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
22272                    flags, shadowSize.x, shadowSize.y, mAttachInfo.mDragSurface);
22273            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token="
22274                    + mAttachInfo.mDragToken + " surface=" + mAttachInfo.mDragSurface);
22275            if (mAttachInfo.mDragToken != null) {
22276                Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null);
22277                try {
22278                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
22279                    shadowBuilder.onDrawShadow(canvas);
22280                } finally {
22281                    mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas);
22282                }
22283
22284                final ViewRootImpl root = getViewRootImpl();
22285
22286                // Cache the local state object for delivery with DragEvents
22287                root.setLocalDragState(myLocalState);
22288
22289                // repurpose 'shadowSize' for the last touch point
22290                root.getLastTouchPoint(shadowSize);
22291
22292                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, mAttachInfo.mDragToken,
22293                        root.getLastTouchSource(), shadowSize.x, shadowSize.y,
22294                        shadowTouchPoint.x, shadowTouchPoint.y, data);
22295                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
22296            }
22297        } catch (Exception e) {
22298            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
22299            mAttachInfo.mDragSurface.destroy();
22300            mAttachInfo.mDragSurface = null;
22301        }
22302
22303        return okay;
22304    }
22305
22306    /**
22307     * Cancels an ongoing drag and drop operation.
22308     * <p>
22309     * A {@link android.view.DragEvent} object with
22310     * {@link android.view.DragEvent#getAction()} value of
22311     * {@link android.view.DragEvent#ACTION_DRAG_ENDED} and
22312     * {@link android.view.DragEvent#getResult()} value of {@code false}
22313     * will be sent to every
22314     * View that received {@link android.view.DragEvent#ACTION_DRAG_STARTED}
22315     * even if they are not currently visible.
22316     * </p>
22317     * <p>
22318     * This method can be called on any View in the same window as the View on which
22319     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int) startDragAndDrop}
22320     * was called.
22321     * </p>
22322     */
22323    public final void cancelDragAndDrop() {
22324        if (ViewDebug.DEBUG_DRAG) {
22325            Log.d(VIEW_LOG_TAG, "cancelDragAndDrop");
22326        }
22327        if (mAttachInfo == null) {
22328            Log.w(VIEW_LOG_TAG, "cancelDragAndDrop called on a detached view.");
22329            return;
22330        }
22331        if (mAttachInfo.mDragToken != null) {
22332            try {
22333                mAttachInfo.mSession.cancelDragAndDrop(mAttachInfo.mDragToken);
22334            } catch (Exception e) {
22335                Log.e(VIEW_LOG_TAG, "Unable to cancel drag", e);
22336            }
22337            mAttachInfo.mDragToken = null;
22338        } else {
22339            Log.e(VIEW_LOG_TAG, "No active drag to cancel");
22340        }
22341    }
22342
22343    /**
22344     * Updates the drag shadow for the ongoing drag and drop operation.
22345     *
22346     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
22347     * new drag shadow.
22348     */
22349    public final void updateDragShadow(DragShadowBuilder shadowBuilder) {
22350        if (ViewDebug.DEBUG_DRAG) {
22351            Log.d(VIEW_LOG_TAG, "updateDragShadow");
22352        }
22353        if (mAttachInfo == null) {
22354            Log.w(VIEW_LOG_TAG, "updateDragShadow called on a detached view.");
22355            return;
22356        }
22357        if (mAttachInfo.mDragToken != null) {
22358            try {
22359                Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null);
22360                try {
22361                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
22362                    shadowBuilder.onDrawShadow(canvas);
22363                } finally {
22364                    mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas);
22365                }
22366            } catch (Exception e) {
22367                Log.e(VIEW_LOG_TAG, "Unable to update drag shadow", e);
22368            }
22369        } else {
22370            Log.e(VIEW_LOG_TAG, "No active drag");
22371        }
22372    }
22373
22374    /**
22375     * Starts a move from {startX, startY}, the amount of the movement will be the offset
22376     * between {startX, startY} and the new cursor positon.
22377     * @param startX horizontal coordinate where the move started.
22378     * @param startY vertical coordinate where the move started.
22379     * @return whether moving was started successfully.
22380     * @hide
22381     */
22382    public final boolean startMovingTask(float startX, float startY) {
22383        if (ViewDebug.DEBUG_POSITIONING) {
22384            Log.d(VIEW_LOG_TAG, "startMovingTask: {" + startX + "," + startY + "}");
22385        }
22386        try {
22387            return mAttachInfo.mSession.startMovingTask(mAttachInfo.mWindow, startX, startY);
22388        } catch (RemoteException e) {
22389            Log.e(VIEW_LOG_TAG, "Unable to start moving", e);
22390        }
22391        return false;
22392    }
22393
22394    /**
22395     * Handles drag events sent by the system following a call to
22396     * {@link android.view.View#startDragAndDrop(ClipData,DragShadowBuilder,Object,int)
22397     * startDragAndDrop()}.
22398     *<p>
22399     * When the system calls this method, it passes a
22400     * {@link android.view.DragEvent} object. A call to
22401     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
22402     * in DragEvent. The method uses these to determine what is happening in the drag and drop
22403     * operation.
22404     * @param event The {@link android.view.DragEvent} sent by the system.
22405     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
22406     * in DragEvent, indicating the type of drag event represented by this object.
22407     * @return {@code true} if the method was successful, otherwise {@code false}.
22408     * <p>
22409     *  The method should return {@code true} in response to an action type of
22410     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
22411     *  operation.
22412     * </p>
22413     * <p>
22414     *  The method should also return {@code true} in response to an action type of
22415     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
22416     *  {@code false} if it didn't.
22417     * </p>
22418     * <p>
22419     *  For all other events, the return value is ignored.
22420     * </p>
22421     */
22422    public boolean onDragEvent(DragEvent event) {
22423        return false;
22424    }
22425
22426    // Dispatches ACTION_DRAG_ENTERED and ACTION_DRAG_EXITED events for pre-Nougat apps.
22427    boolean dispatchDragEnterExitInPreN(DragEvent event) {
22428        return callDragEventHandler(event);
22429    }
22430
22431    /**
22432     * Detects if this View is enabled and has a drag event listener.
22433     * If both are true, then it calls the drag event listener with the
22434     * {@link android.view.DragEvent} it received. If the drag event listener returns
22435     * {@code true}, then dispatchDragEvent() returns {@code true}.
22436     * <p>
22437     * For all other cases, the method calls the
22438     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
22439     * method and returns its result.
22440     * </p>
22441     * <p>
22442     * This ensures that a drag event is always consumed, even if the View does not have a drag
22443     * event listener. However, if the View has a listener and the listener returns true, then
22444     * onDragEvent() is not called.
22445     * </p>
22446     */
22447    public boolean dispatchDragEvent(DragEvent event) {
22448        event.mEventHandlerWasCalled = true;
22449        if (event.mAction == DragEvent.ACTION_DRAG_LOCATION ||
22450            event.mAction == DragEvent.ACTION_DROP) {
22451            // About to deliver an event with coordinates to this view. Notify that now this view
22452            // has drag focus. This will send exit/enter events as needed.
22453            getViewRootImpl().setDragFocus(this, event);
22454        }
22455        return callDragEventHandler(event);
22456    }
22457
22458    final boolean callDragEventHandler(DragEvent event) {
22459        final boolean result;
22460
22461        ListenerInfo li = mListenerInfo;
22462        //noinspection SimplifiableIfStatement
22463        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
22464                && li.mOnDragListener.onDrag(this, event)) {
22465            result = true;
22466        } else {
22467            result = onDragEvent(event);
22468        }
22469
22470        switch (event.mAction) {
22471            case DragEvent.ACTION_DRAG_ENTERED: {
22472                mPrivateFlags2 |= View.PFLAG2_DRAG_HOVERED;
22473                refreshDrawableState();
22474            } break;
22475            case DragEvent.ACTION_DRAG_EXITED: {
22476                mPrivateFlags2 &= ~View.PFLAG2_DRAG_HOVERED;
22477                refreshDrawableState();
22478            } break;
22479            case DragEvent.ACTION_DRAG_ENDED: {
22480                mPrivateFlags2 &= ~View.DRAG_MASK;
22481                refreshDrawableState();
22482            } break;
22483        }
22484
22485        return result;
22486    }
22487
22488    boolean canAcceptDrag() {
22489        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
22490    }
22491
22492    /**
22493     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
22494     * it is ever exposed at all.
22495     * @hide
22496     */
22497    public void onCloseSystemDialogs(String reason) {
22498    }
22499
22500    /**
22501     * Given a Drawable whose bounds have been set to draw into this view,
22502     * update a Region being computed for
22503     * {@link #gatherTransparentRegion(android.graphics.Region)} so
22504     * that any non-transparent parts of the Drawable are removed from the
22505     * given transparent region.
22506     *
22507     * @param dr The Drawable whose transparency is to be applied to the region.
22508     * @param region A Region holding the current transparency information,
22509     * where any parts of the region that are set are considered to be
22510     * transparent.  On return, this region will be modified to have the
22511     * transparency information reduced by the corresponding parts of the
22512     * Drawable that are not transparent.
22513     * {@hide}
22514     */
22515    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
22516        if (DBG) {
22517            Log.i("View", "Getting transparent region for: " + this);
22518        }
22519        final Region r = dr.getTransparentRegion();
22520        final Rect db = dr.getBounds();
22521        final AttachInfo attachInfo = mAttachInfo;
22522        if (r != null && attachInfo != null) {
22523            final int w = getRight()-getLeft();
22524            final int h = getBottom()-getTop();
22525            if (db.left > 0) {
22526                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
22527                r.op(0, 0, db.left, h, Region.Op.UNION);
22528            }
22529            if (db.right < w) {
22530                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
22531                r.op(db.right, 0, w, h, Region.Op.UNION);
22532            }
22533            if (db.top > 0) {
22534                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
22535                r.op(0, 0, w, db.top, Region.Op.UNION);
22536            }
22537            if (db.bottom < h) {
22538                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
22539                r.op(0, db.bottom, w, h, Region.Op.UNION);
22540            }
22541            final int[] location = attachInfo.mTransparentLocation;
22542            getLocationInWindow(location);
22543            r.translate(location[0], location[1]);
22544            region.op(r, Region.Op.INTERSECT);
22545        } else {
22546            region.op(db, Region.Op.DIFFERENCE);
22547        }
22548    }
22549
22550    private void checkForLongClick(int delayOffset, float x, float y) {
22551        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE || (mViewFlags & TOOLTIP) == TOOLTIP) {
22552            mHasPerformedLongPress = false;
22553
22554            if (mPendingCheckForLongPress == null) {
22555                mPendingCheckForLongPress = new CheckForLongPress();
22556            }
22557            mPendingCheckForLongPress.setAnchor(x, y);
22558            mPendingCheckForLongPress.rememberWindowAttachCount();
22559            mPendingCheckForLongPress.rememberPressedState();
22560            postDelayed(mPendingCheckForLongPress,
22561                    ViewConfiguration.getLongPressTimeout() - delayOffset);
22562        }
22563    }
22564
22565    /**
22566     * Inflate a view from an XML resource.  This convenience method wraps the {@link
22567     * LayoutInflater} class, which provides a full range of options for view inflation.
22568     *
22569     * @param context The Context object for your activity or application.
22570     * @param resource The resource ID to inflate
22571     * @param root A view group that will be the parent.  Used to properly inflate the
22572     * layout_* parameters.
22573     * @see LayoutInflater
22574     */
22575    public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
22576        LayoutInflater factory = LayoutInflater.from(context);
22577        return factory.inflate(resource, root);
22578    }
22579
22580    /**
22581     * Scroll the view with standard behavior for scrolling beyond the normal
22582     * content boundaries. Views that call this method should override
22583     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
22584     * results of an over-scroll operation.
22585     *
22586     * Views can use this method to handle any touch or fling-based scrolling.
22587     *
22588     * @param deltaX Change in X in pixels
22589     * @param deltaY Change in Y in pixels
22590     * @param scrollX Current X scroll value in pixels before applying deltaX
22591     * @param scrollY Current Y scroll value in pixels before applying deltaY
22592     * @param scrollRangeX Maximum content scroll range along the X axis
22593     * @param scrollRangeY Maximum content scroll range along the Y axis
22594     * @param maxOverScrollX Number of pixels to overscroll by in either direction
22595     *          along the X axis.
22596     * @param maxOverScrollY Number of pixels to overscroll by in either direction
22597     *          along the Y axis.
22598     * @param isTouchEvent true if this scroll operation is the result of a touch event.
22599     * @return true if scrolling was clamped to an over-scroll boundary along either
22600     *          axis, false otherwise.
22601     */
22602    @SuppressWarnings({"UnusedParameters"})
22603    protected boolean overScrollBy(int deltaX, int deltaY,
22604            int scrollX, int scrollY,
22605            int scrollRangeX, int scrollRangeY,
22606            int maxOverScrollX, int maxOverScrollY,
22607            boolean isTouchEvent) {
22608        final int overScrollMode = mOverScrollMode;
22609        final boolean canScrollHorizontal =
22610                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
22611        final boolean canScrollVertical =
22612                computeVerticalScrollRange() > computeVerticalScrollExtent();
22613        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
22614                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
22615        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
22616                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
22617
22618        int newScrollX = scrollX + deltaX;
22619        if (!overScrollHorizontal) {
22620            maxOverScrollX = 0;
22621        }
22622
22623        int newScrollY = scrollY + deltaY;
22624        if (!overScrollVertical) {
22625            maxOverScrollY = 0;
22626        }
22627
22628        // Clamp values if at the limits and record
22629        final int left = -maxOverScrollX;
22630        final int right = maxOverScrollX + scrollRangeX;
22631        final int top = -maxOverScrollY;
22632        final int bottom = maxOverScrollY + scrollRangeY;
22633
22634        boolean clampedX = false;
22635        if (newScrollX > right) {
22636            newScrollX = right;
22637            clampedX = true;
22638        } else if (newScrollX < left) {
22639            newScrollX = left;
22640            clampedX = true;
22641        }
22642
22643        boolean clampedY = false;
22644        if (newScrollY > bottom) {
22645            newScrollY = bottom;
22646            clampedY = true;
22647        } else if (newScrollY < top) {
22648            newScrollY = top;
22649            clampedY = true;
22650        }
22651
22652        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
22653
22654        return clampedX || clampedY;
22655    }
22656
22657    /**
22658     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
22659     * respond to the results of an over-scroll operation.
22660     *
22661     * @param scrollX New X scroll value in pixels
22662     * @param scrollY New Y scroll value in pixels
22663     * @param clampedX True if scrollX was clamped to an over-scroll boundary
22664     * @param clampedY True if scrollY was clamped to an over-scroll boundary
22665     */
22666    protected void onOverScrolled(int scrollX, int scrollY,
22667            boolean clampedX, boolean clampedY) {
22668        // Intentionally empty.
22669    }
22670
22671    /**
22672     * Returns the over-scroll mode for this view. The result will be
22673     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
22674     * (allow over-scrolling only if the view content is larger than the container),
22675     * or {@link #OVER_SCROLL_NEVER}.
22676     *
22677     * @return This view's over-scroll mode.
22678     */
22679    public int getOverScrollMode() {
22680        return mOverScrollMode;
22681    }
22682
22683    /**
22684     * Set the over-scroll mode for this view. Valid over-scroll modes are
22685     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
22686     * (allow over-scrolling only if the view content is larger than the container),
22687     * or {@link #OVER_SCROLL_NEVER}.
22688     *
22689     * Setting the over-scroll mode of a view will have an effect only if the
22690     * view is capable of scrolling.
22691     *
22692     * @param overScrollMode The new over-scroll mode for this view.
22693     */
22694    public void setOverScrollMode(int overScrollMode) {
22695        if (overScrollMode != OVER_SCROLL_ALWAYS &&
22696                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
22697                overScrollMode != OVER_SCROLL_NEVER) {
22698            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
22699        }
22700        mOverScrollMode = overScrollMode;
22701    }
22702
22703    /**
22704     * Enable or disable nested scrolling for this view.
22705     *
22706     * <p>If this property is set to true the view will be permitted to initiate nested
22707     * scrolling operations with a compatible parent view in the current hierarchy. If this
22708     * view does not implement nested scrolling this will have no effect. Disabling nested scrolling
22709     * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping}
22710     * the nested scroll.</p>
22711     *
22712     * @param enabled true to enable nested scrolling, false to disable
22713     *
22714     * @see #isNestedScrollingEnabled()
22715     */
22716    public void setNestedScrollingEnabled(boolean enabled) {
22717        if (enabled) {
22718            mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED;
22719        } else {
22720            stopNestedScroll();
22721            mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED;
22722        }
22723    }
22724
22725    /**
22726     * Returns true if nested scrolling is enabled for this view.
22727     *
22728     * <p>If nested scrolling is enabled and this View class implementation supports it,
22729     * this view will act as a nested scrolling child view when applicable, forwarding data
22730     * about the scroll operation in progress to a compatible and cooperating nested scrolling
22731     * parent.</p>
22732     *
22733     * @return true if nested scrolling is enabled
22734     *
22735     * @see #setNestedScrollingEnabled(boolean)
22736     */
22737    public boolean isNestedScrollingEnabled() {
22738        return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) ==
22739                PFLAG3_NESTED_SCROLLING_ENABLED;
22740    }
22741
22742    /**
22743     * Begin a nestable scroll operation along the given axes.
22744     *
22745     * <p>A view starting a nested scroll promises to abide by the following contract:</p>
22746     *
22747     * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case
22748     * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}.
22749     * In the case of touch scrolling the nested scroll will be terminated automatically in
22750     * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}.
22751     * In the event of programmatic scrolling the caller must explicitly call
22752     * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p>
22753     *
22754     * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found.
22755     * If it returns false the caller may ignore the rest of this contract until the next scroll.
22756     * Calling startNestedScroll while a nested scroll is already in progress will return true.</p>
22757     *
22758     * <p>At each incremental step of the scroll the caller should invoke
22759     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll}
22760     * once it has calculated the requested scrolling delta. If it returns true the nested scrolling
22761     * parent at least partially consumed the scroll and the caller should adjust the amount it
22762     * scrolls by.</p>
22763     *
22764     * <p>After applying the remainder of the scroll delta the caller should invoke
22765     * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing
22766     * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat
22767     * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}.
22768     * </p>
22769     *
22770     * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or
22771     *             {@link #SCROLL_AXIS_VERTICAL}.
22772     * @return true if a cooperative parent was found and nested scrolling has been enabled for
22773     *         the current gesture.
22774     *
22775     * @see #stopNestedScroll()
22776     * @see #dispatchNestedPreScroll(int, int, int[], int[])
22777     * @see #dispatchNestedScroll(int, int, int, int, int[])
22778     */
22779    public boolean startNestedScroll(int axes) {
22780        if (hasNestedScrollingParent()) {
22781            // Already in progress
22782            return true;
22783        }
22784        if (isNestedScrollingEnabled()) {
22785            ViewParent p = getParent();
22786            View child = this;
22787            while (p != null) {
22788                try {
22789                    if (p.onStartNestedScroll(child, this, axes)) {
22790                        mNestedScrollingParent = p;
22791                        p.onNestedScrollAccepted(child, this, axes);
22792                        return true;
22793                    }
22794                } catch (AbstractMethodError e) {
22795                    Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " +
22796                            "method onStartNestedScroll", e);
22797                    // Allow the search upward to continue
22798                }
22799                if (p instanceof View) {
22800                    child = (View) p;
22801                }
22802                p = p.getParent();
22803            }
22804        }
22805        return false;
22806    }
22807
22808    /**
22809     * Stop a nested scroll in progress.
22810     *
22811     * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p>
22812     *
22813     * @see #startNestedScroll(int)
22814     */
22815    public void stopNestedScroll() {
22816        if (mNestedScrollingParent != null) {
22817            mNestedScrollingParent.onStopNestedScroll(this);
22818            mNestedScrollingParent = null;
22819        }
22820    }
22821
22822    /**
22823     * Returns true if this view has a nested scrolling parent.
22824     *
22825     * <p>The presence of a nested scrolling parent indicates that this view has initiated
22826     * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p>
22827     *
22828     * @return whether this view has a nested scrolling parent
22829     */
22830    public boolean hasNestedScrollingParent() {
22831        return mNestedScrollingParent != null;
22832    }
22833
22834    /**
22835     * Dispatch one step of a nested scroll in progress.
22836     *
22837     * <p>Implementations of views that support nested scrolling should call this to report
22838     * info about a scroll in progress to the current nested scrolling parent. If a nested scroll
22839     * is not currently in progress or nested scrolling is not
22840     * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p>
22841     *
22842     * <p>Compatible View implementations should also call
22843     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before
22844     * consuming a component of the scroll event themselves.</p>
22845     *
22846     * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step
22847     * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step
22848     * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view
22849     * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view
22850     * @param offsetInWindow Optional. If not null, on return this will contain the offset
22851     *                       in local view coordinates of this view from before this operation
22852     *                       to after it completes. View implementations may use this to adjust
22853     *                       expected input coordinate tracking.
22854     * @return true if the event was dispatched, false if it could not be dispatched.
22855     * @see #dispatchNestedPreScroll(int, int, int[], int[])
22856     */
22857    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed,
22858            int dxUnconsumed, int dyUnconsumed, @Nullable @Size(2) int[] offsetInWindow) {
22859        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
22860            if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) {
22861                int startX = 0;
22862                int startY = 0;
22863                if (offsetInWindow != null) {
22864                    getLocationInWindow(offsetInWindow);
22865                    startX = offsetInWindow[0];
22866                    startY = offsetInWindow[1];
22867                }
22868
22869                mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed,
22870                        dxUnconsumed, dyUnconsumed);
22871
22872                if (offsetInWindow != null) {
22873                    getLocationInWindow(offsetInWindow);
22874                    offsetInWindow[0] -= startX;
22875                    offsetInWindow[1] -= startY;
22876                }
22877                return true;
22878            } else if (offsetInWindow != null) {
22879                // No motion, no dispatch. Keep offsetInWindow up to date.
22880                offsetInWindow[0] = 0;
22881                offsetInWindow[1] = 0;
22882            }
22883        }
22884        return false;
22885    }
22886
22887    /**
22888     * Dispatch one step of a nested scroll in progress before this view consumes any portion of it.
22889     *
22890     * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch.
22891     * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested
22892     * scrolling operation to consume some or all of the scroll operation before the child view
22893     * consumes it.</p>
22894     *
22895     * @param dx Horizontal scroll distance in pixels
22896     * @param dy Vertical scroll distance in pixels
22897     * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx
22898     *                 and consumed[1] the consumed dy.
22899     * @param offsetInWindow Optional. If not null, on return this will contain the offset
22900     *                       in local view coordinates of this view from before this operation
22901     *                       to after it completes. View implementations may use this to adjust
22902     *                       expected input coordinate tracking.
22903     * @return true if the parent consumed some or all of the scroll delta
22904     * @see #dispatchNestedScroll(int, int, int, int, int[])
22905     */
22906    public boolean dispatchNestedPreScroll(int dx, int dy,
22907            @Nullable @Size(2) int[] consumed, @Nullable @Size(2) int[] offsetInWindow) {
22908        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
22909            if (dx != 0 || dy != 0) {
22910                int startX = 0;
22911                int startY = 0;
22912                if (offsetInWindow != null) {
22913                    getLocationInWindow(offsetInWindow);
22914                    startX = offsetInWindow[0];
22915                    startY = offsetInWindow[1];
22916                }
22917
22918                if (consumed == null) {
22919                    if (mTempNestedScrollConsumed == null) {
22920                        mTempNestedScrollConsumed = new int[2];
22921                    }
22922                    consumed = mTempNestedScrollConsumed;
22923                }
22924                consumed[0] = 0;
22925                consumed[1] = 0;
22926                mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed);
22927
22928                if (offsetInWindow != null) {
22929                    getLocationInWindow(offsetInWindow);
22930                    offsetInWindow[0] -= startX;
22931                    offsetInWindow[1] -= startY;
22932                }
22933                return consumed[0] != 0 || consumed[1] != 0;
22934            } else if (offsetInWindow != null) {
22935                offsetInWindow[0] = 0;
22936                offsetInWindow[1] = 0;
22937            }
22938        }
22939        return false;
22940    }
22941
22942    /**
22943     * Dispatch a fling to a nested scrolling parent.
22944     *
22945     * <p>This method should be used to indicate that a nested scrolling child has detected
22946     * suitable conditions for a fling. Generally this means that a touch scroll has ended with a
22947     * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds
22948     * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity}
22949     * along a scrollable axis.</p>
22950     *
22951     * <p>If a nested scrolling child view would normally fling but it is at the edge of
22952     * its own content, it can use this method to delegate the fling to its nested scrolling
22953     * parent instead. The parent may optionally consume the fling or observe a child fling.</p>
22954     *
22955     * @param velocityX Horizontal fling velocity in pixels per second
22956     * @param velocityY Vertical fling velocity in pixels per second
22957     * @param consumed true if the child consumed the fling, false otherwise
22958     * @return true if the nested scrolling parent consumed or otherwise reacted to the fling
22959     */
22960    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
22961        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
22962            return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed);
22963        }
22964        return false;
22965    }
22966
22967    /**
22968     * Dispatch a fling to a nested scrolling parent before it is processed by this view.
22969     *
22970     * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch
22971     * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code>
22972     * offsets an opportunity for the parent view in a nested fling to fully consume the fling
22973     * before the child view consumes it. If this method returns <code>true</code>, a nested
22974     * parent view consumed the fling and this view should not scroll as a result.</p>
22975     *
22976     * <p>For a better user experience, only one view in a nested scrolling chain should consume
22977     * the fling at a time. If a parent view consumed the fling this method will return false.
22978     * Custom view implementations should account for this in two ways:</p>
22979     *
22980     * <ul>
22981     *     <li>If a custom view is paged and needs to settle to a fixed page-point, do not
22982     *     call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid
22983     *     position regardless.</li>
22984     *     <li>If a nested parent does consume the fling, this view should not scroll at all,
22985     *     even to settle back to a valid idle position.</li>
22986     * </ul>
22987     *
22988     * <p>Views should also not offer fling velocities to nested parent views along an axis
22989     * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView}
22990     * should not offer a horizontal fling velocity to its parents since scrolling along that
22991     * axis is not permitted and carrying velocity along that motion does not make sense.</p>
22992     *
22993     * @param velocityX Horizontal fling velocity in pixels per second
22994     * @param velocityY Vertical fling velocity in pixels per second
22995     * @return true if a nested scrolling parent consumed the fling
22996     */
22997    public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
22998        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
22999            return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY);
23000        }
23001        return false;
23002    }
23003
23004    /**
23005     * Gets a scale factor that determines the distance the view should scroll
23006     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
23007     * @return The vertical scroll scale factor.
23008     * @hide
23009     */
23010    protected float getVerticalScrollFactor() {
23011        if (mVerticalScrollFactor == 0) {
23012            TypedValue outValue = new TypedValue();
23013            if (!mContext.getTheme().resolveAttribute(
23014                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
23015                throw new IllegalStateException(
23016                        "Expected theme to define listPreferredItemHeight.");
23017            }
23018            mVerticalScrollFactor = outValue.getDimension(
23019                    mContext.getResources().getDisplayMetrics());
23020        }
23021        return mVerticalScrollFactor;
23022    }
23023
23024    /**
23025     * Gets a scale factor that determines the distance the view should scroll
23026     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
23027     * @return The horizontal scroll scale factor.
23028     * @hide
23029     */
23030    protected float getHorizontalScrollFactor() {
23031        // TODO: Should use something else.
23032        return getVerticalScrollFactor();
23033    }
23034
23035    /**
23036     * Return the value specifying the text direction or policy that was set with
23037     * {@link #setTextDirection(int)}.
23038     *
23039     * @return the defined text direction. It can be one of:
23040     *
23041     * {@link #TEXT_DIRECTION_INHERIT},
23042     * {@link #TEXT_DIRECTION_FIRST_STRONG},
23043     * {@link #TEXT_DIRECTION_ANY_RTL},
23044     * {@link #TEXT_DIRECTION_LTR},
23045     * {@link #TEXT_DIRECTION_RTL},
23046     * {@link #TEXT_DIRECTION_LOCALE},
23047     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
23048     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
23049     *
23050     * @attr ref android.R.styleable#View_textDirection
23051     *
23052     * @hide
23053     */
23054    @ViewDebug.ExportedProperty(category = "text", mapping = {
23055            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
23056            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
23057            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
23058            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
23059            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
23060            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
23061            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
23062            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
23063    })
23064    public int getRawTextDirection() {
23065        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
23066    }
23067
23068    /**
23069     * Set the text direction.
23070     *
23071     * @param textDirection the direction to set. Should be one of:
23072     *
23073     * {@link #TEXT_DIRECTION_INHERIT},
23074     * {@link #TEXT_DIRECTION_FIRST_STRONG},
23075     * {@link #TEXT_DIRECTION_ANY_RTL},
23076     * {@link #TEXT_DIRECTION_LTR},
23077     * {@link #TEXT_DIRECTION_RTL},
23078     * {@link #TEXT_DIRECTION_LOCALE}
23079     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
23080     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL},
23081     *
23082     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
23083     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
23084     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
23085     *
23086     * @attr ref android.R.styleable#View_textDirection
23087     */
23088    public void setTextDirection(int textDirection) {
23089        if (getRawTextDirection() != textDirection) {
23090            // Reset the current text direction and the resolved one
23091            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
23092            resetResolvedTextDirection();
23093            // Set the new text direction
23094            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
23095            // Do resolution
23096            resolveTextDirection();
23097            // Notify change
23098            onRtlPropertiesChanged(getLayoutDirection());
23099            // Refresh
23100            requestLayout();
23101            invalidate(true);
23102        }
23103    }
23104
23105    /**
23106     * Return the resolved text direction.
23107     *
23108     * @return the resolved text direction. Returns one of:
23109     *
23110     * {@link #TEXT_DIRECTION_FIRST_STRONG},
23111     * {@link #TEXT_DIRECTION_ANY_RTL},
23112     * {@link #TEXT_DIRECTION_LTR},
23113     * {@link #TEXT_DIRECTION_RTL},
23114     * {@link #TEXT_DIRECTION_LOCALE},
23115     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
23116     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
23117     *
23118     * @attr ref android.R.styleable#View_textDirection
23119     */
23120    @ViewDebug.ExportedProperty(category = "text", mapping = {
23121            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
23122            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
23123            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
23124            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
23125            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
23126            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
23127            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
23128            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
23129    })
23130    public int getTextDirection() {
23131        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
23132    }
23133
23134    /**
23135     * Resolve the text direction.
23136     *
23137     * @return true if resolution has been done, false otherwise.
23138     *
23139     * @hide
23140     */
23141    public boolean resolveTextDirection() {
23142        // Reset any previous text direction resolution
23143        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
23144
23145        if (hasRtlSupport()) {
23146            // Set resolved text direction flag depending on text direction flag
23147            final int textDirection = getRawTextDirection();
23148            switch(textDirection) {
23149                case TEXT_DIRECTION_INHERIT:
23150                    if (!canResolveTextDirection()) {
23151                        // We cannot do the resolution if there is no parent, so use the default one
23152                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
23153                        // Resolution will need to happen again later
23154                        return false;
23155                    }
23156
23157                    // Parent has not yet resolved, so we still return the default
23158                    try {
23159                        if (!mParent.isTextDirectionResolved()) {
23160                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
23161                            // Resolution will need to happen again later
23162                            return false;
23163                        }
23164                    } catch (AbstractMethodError e) {
23165                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
23166                                " does not fully implement ViewParent", e);
23167                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
23168                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
23169                        return true;
23170                    }
23171
23172                    // Set current resolved direction to the same value as the parent's one
23173                    int parentResolvedDirection;
23174                    try {
23175                        parentResolvedDirection = mParent.getTextDirection();
23176                    } catch (AbstractMethodError e) {
23177                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
23178                                " does not fully implement ViewParent", e);
23179                        parentResolvedDirection = TEXT_DIRECTION_LTR;
23180                    }
23181                    switch (parentResolvedDirection) {
23182                        case TEXT_DIRECTION_FIRST_STRONG:
23183                        case TEXT_DIRECTION_ANY_RTL:
23184                        case TEXT_DIRECTION_LTR:
23185                        case TEXT_DIRECTION_RTL:
23186                        case TEXT_DIRECTION_LOCALE:
23187                        case TEXT_DIRECTION_FIRST_STRONG_LTR:
23188                        case TEXT_DIRECTION_FIRST_STRONG_RTL:
23189                            mPrivateFlags2 |=
23190                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
23191                            break;
23192                        default:
23193                            // Default resolved direction is "first strong" heuristic
23194                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
23195                    }
23196                    break;
23197                case TEXT_DIRECTION_FIRST_STRONG:
23198                case TEXT_DIRECTION_ANY_RTL:
23199                case TEXT_DIRECTION_LTR:
23200                case TEXT_DIRECTION_RTL:
23201                case TEXT_DIRECTION_LOCALE:
23202                case TEXT_DIRECTION_FIRST_STRONG_LTR:
23203                case TEXT_DIRECTION_FIRST_STRONG_RTL:
23204                    // Resolved direction is the same as text direction
23205                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
23206                    break;
23207                default:
23208                    // Default resolved direction is "first strong" heuristic
23209                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
23210            }
23211        } else {
23212            // Default resolved direction is "first strong" heuristic
23213            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
23214        }
23215
23216        // Set to resolved
23217        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
23218        return true;
23219    }
23220
23221    /**
23222     * Check if text direction resolution can be done.
23223     *
23224     * @return true if text direction resolution can be done otherwise return false.
23225     */
23226    public boolean canResolveTextDirection() {
23227        switch (getRawTextDirection()) {
23228            case TEXT_DIRECTION_INHERIT:
23229                if (mParent != null) {
23230                    try {
23231                        return mParent.canResolveTextDirection();
23232                    } catch (AbstractMethodError e) {
23233                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
23234                                " does not fully implement ViewParent", e);
23235                    }
23236                }
23237                return false;
23238
23239            default:
23240                return true;
23241        }
23242    }
23243
23244    /**
23245     * Reset resolved text direction. Text direction will be resolved during a call to
23246     * {@link #onMeasure(int, int)}.
23247     *
23248     * @hide
23249     */
23250    public void resetResolvedTextDirection() {
23251        // Reset any previous text direction resolution
23252        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
23253        // Set to default value
23254        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
23255    }
23256
23257    /**
23258     * @return true if text direction is inherited.
23259     *
23260     * @hide
23261     */
23262    public boolean isTextDirectionInherited() {
23263        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
23264    }
23265
23266    /**
23267     * @return true if text direction is resolved.
23268     */
23269    public boolean isTextDirectionResolved() {
23270        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
23271    }
23272
23273    /**
23274     * Return the value specifying the text alignment or policy that was set with
23275     * {@link #setTextAlignment(int)}.
23276     *
23277     * @return the defined text alignment. It can be one of:
23278     *
23279     * {@link #TEXT_ALIGNMENT_INHERIT},
23280     * {@link #TEXT_ALIGNMENT_GRAVITY},
23281     * {@link #TEXT_ALIGNMENT_CENTER},
23282     * {@link #TEXT_ALIGNMENT_TEXT_START},
23283     * {@link #TEXT_ALIGNMENT_TEXT_END},
23284     * {@link #TEXT_ALIGNMENT_VIEW_START},
23285     * {@link #TEXT_ALIGNMENT_VIEW_END}
23286     *
23287     * @attr ref android.R.styleable#View_textAlignment
23288     *
23289     * @hide
23290     */
23291    @ViewDebug.ExportedProperty(category = "text", mapping = {
23292            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
23293            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
23294            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
23295            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
23296            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
23297            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
23298            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
23299    })
23300    @TextAlignment
23301    public int getRawTextAlignment() {
23302        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
23303    }
23304
23305    /**
23306     * Set the text alignment.
23307     *
23308     * @param textAlignment The text alignment to set. Should be one of
23309     *
23310     * {@link #TEXT_ALIGNMENT_INHERIT},
23311     * {@link #TEXT_ALIGNMENT_GRAVITY},
23312     * {@link #TEXT_ALIGNMENT_CENTER},
23313     * {@link #TEXT_ALIGNMENT_TEXT_START},
23314     * {@link #TEXT_ALIGNMENT_TEXT_END},
23315     * {@link #TEXT_ALIGNMENT_VIEW_START},
23316     * {@link #TEXT_ALIGNMENT_VIEW_END}
23317     *
23318     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
23319     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
23320     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
23321     *
23322     * @attr ref android.R.styleable#View_textAlignment
23323     */
23324    public void setTextAlignment(@TextAlignment int textAlignment) {
23325        if (textAlignment != getRawTextAlignment()) {
23326            // Reset the current and resolved text alignment
23327            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
23328            resetResolvedTextAlignment();
23329            // Set the new text alignment
23330            mPrivateFlags2 |=
23331                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
23332            // Do resolution
23333            resolveTextAlignment();
23334            // Notify change
23335            onRtlPropertiesChanged(getLayoutDirection());
23336            // Refresh
23337            requestLayout();
23338            invalidate(true);
23339        }
23340    }
23341
23342    /**
23343     * Return the resolved text alignment.
23344     *
23345     * @return the resolved text alignment. Returns one of:
23346     *
23347     * {@link #TEXT_ALIGNMENT_GRAVITY},
23348     * {@link #TEXT_ALIGNMENT_CENTER},
23349     * {@link #TEXT_ALIGNMENT_TEXT_START},
23350     * {@link #TEXT_ALIGNMENT_TEXT_END},
23351     * {@link #TEXT_ALIGNMENT_VIEW_START},
23352     * {@link #TEXT_ALIGNMENT_VIEW_END}
23353     *
23354     * @attr ref android.R.styleable#View_textAlignment
23355     */
23356    @ViewDebug.ExportedProperty(category = "text", mapping = {
23357            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
23358            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
23359            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
23360            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
23361            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
23362            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
23363            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
23364    })
23365    @TextAlignment
23366    public int getTextAlignment() {
23367        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
23368                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
23369    }
23370
23371    /**
23372     * Resolve the text alignment.
23373     *
23374     * @return true if resolution has been done, false otherwise.
23375     *
23376     * @hide
23377     */
23378    public boolean resolveTextAlignment() {
23379        // Reset any previous text alignment resolution
23380        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
23381
23382        if (hasRtlSupport()) {
23383            // Set resolved text alignment flag depending on text alignment flag
23384            final int textAlignment = getRawTextAlignment();
23385            switch (textAlignment) {
23386                case TEXT_ALIGNMENT_INHERIT:
23387                    // Check if we can resolve the text alignment
23388                    if (!canResolveTextAlignment()) {
23389                        // We cannot do the resolution if there is no parent so use the default
23390                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
23391                        // Resolution will need to happen again later
23392                        return false;
23393                    }
23394
23395                    // Parent has not yet resolved, so we still return the default
23396                    try {
23397                        if (!mParent.isTextAlignmentResolved()) {
23398                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
23399                            // Resolution will need to happen again later
23400                            return false;
23401                        }
23402                    } catch (AbstractMethodError e) {
23403                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
23404                                " does not fully implement ViewParent", e);
23405                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
23406                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
23407                        return true;
23408                    }
23409
23410                    int parentResolvedTextAlignment;
23411                    try {
23412                        parentResolvedTextAlignment = mParent.getTextAlignment();
23413                    } catch (AbstractMethodError e) {
23414                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
23415                                " does not fully implement ViewParent", e);
23416                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
23417                    }
23418                    switch (parentResolvedTextAlignment) {
23419                        case TEXT_ALIGNMENT_GRAVITY:
23420                        case TEXT_ALIGNMENT_TEXT_START:
23421                        case TEXT_ALIGNMENT_TEXT_END:
23422                        case TEXT_ALIGNMENT_CENTER:
23423                        case TEXT_ALIGNMENT_VIEW_START:
23424                        case TEXT_ALIGNMENT_VIEW_END:
23425                            // Resolved text alignment is the same as the parent resolved
23426                            // text alignment
23427                            mPrivateFlags2 |=
23428                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
23429                            break;
23430                        default:
23431                            // Use default resolved text alignment
23432                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
23433                    }
23434                    break;
23435                case TEXT_ALIGNMENT_GRAVITY:
23436                case TEXT_ALIGNMENT_TEXT_START:
23437                case TEXT_ALIGNMENT_TEXT_END:
23438                case TEXT_ALIGNMENT_CENTER:
23439                case TEXT_ALIGNMENT_VIEW_START:
23440                case TEXT_ALIGNMENT_VIEW_END:
23441                    // Resolved text alignment is the same as text alignment
23442                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
23443                    break;
23444                default:
23445                    // Use default resolved text alignment
23446                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
23447            }
23448        } else {
23449            // Use default resolved text alignment
23450            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
23451        }
23452
23453        // Set the resolved
23454        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
23455        return true;
23456    }
23457
23458    /**
23459     * Check if text alignment resolution can be done.
23460     *
23461     * @return true if text alignment resolution can be done otherwise return false.
23462     */
23463    public boolean canResolveTextAlignment() {
23464        switch (getRawTextAlignment()) {
23465            case TEXT_DIRECTION_INHERIT:
23466                if (mParent != null) {
23467                    try {
23468                        return mParent.canResolveTextAlignment();
23469                    } catch (AbstractMethodError e) {
23470                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
23471                                " does not fully implement ViewParent", e);
23472                    }
23473                }
23474                return false;
23475
23476            default:
23477                return true;
23478        }
23479    }
23480
23481    /**
23482     * Reset resolved text alignment. Text alignment will be resolved during a call to
23483     * {@link #onMeasure(int, int)}.
23484     *
23485     * @hide
23486     */
23487    public void resetResolvedTextAlignment() {
23488        // Reset any previous text alignment resolution
23489        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
23490        // Set to default
23491        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
23492    }
23493
23494    /**
23495     * @return true if text alignment is inherited.
23496     *
23497     * @hide
23498     */
23499    public boolean isTextAlignmentInherited() {
23500        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
23501    }
23502
23503    /**
23504     * @return true if text alignment is resolved.
23505     */
23506    public boolean isTextAlignmentResolved() {
23507        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
23508    }
23509
23510    /**
23511     * Generate a value suitable for use in {@link #setId(int)}.
23512     * This value will not collide with ID values generated at build time by aapt for R.id.
23513     *
23514     * @return a generated ID value
23515     */
23516    public static int generateViewId() {
23517        for (;;) {
23518            final int result = sNextGeneratedId.get();
23519            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
23520            int newValue = result + 1;
23521            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
23522            if (sNextGeneratedId.compareAndSet(result, newValue)) {
23523                return result;
23524            }
23525        }
23526    }
23527
23528    private static boolean isViewIdGenerated(int id) {
23529        return (id & 0xFF000000) == 0 && (id & 0x00FFFFFF) != 0;
23530    }
23531
23532    /**
23533     * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions.
23534     * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and
23535     *                           a normal View or a ViewGroup with
23536     *                           {@link android.view.ViewGroup#isTransitionGroup()} true.
23537     * @hide
23538     */
23539    public void captureTransitioningViews(List<View> transitioningViews) {
23540        if (getVisibility() == View.VISIBLE) {
23541            transitioningViews.add(this);
23542        }
23543    }
23544
23545    /**
23546     * Adds all Views that have {@link #getTransitionName()} non-null to namedElements.
23547     * @param namedElements Will contain all Views in the hierarchy having a transitionName.
23548     * @hide
23549     */
23550    public void findNamedViews(Map<String, View> namedElements) {
23551        if (getVisibility() == VISIBLE || mGhostView != null) {
23552            String transitionName = getTransitionName();
23553            if (transitionName != null) {
23554                namedElements.put(transitionName, this);
23555            }
23556        }
23557    }
23558
23559    /**
23560     * Returns the pointer icon for the motion event, or null if it doesn't specify the icon.
23561     * The default implementation does not care the location or event types, but some subclasses
23562     * may use it (such as WebViews).
23563     * @param event The MotionEvent from a mouse
23564     * @param pointerIndex The index of the pointer for which to retrieve the {@link PointerIcon}.
23565     *                     This will be between 0 and {@link MotionEvent#getPointerCount()}.
23566     * @see PointerIcon
23567     */
23568    public PointerIcon onResolvePointerIcon(MotionEvent event, int pointerIndex) {
23569        final float x = event.getX(pointerIndex);
23570        final float y = event.getY(pointerIndex);
23571        if (isDraggingScrollBar() || isOnScrollbarThumb(x, y)) {
23572            return PointerIcon.getSystemIcon(mContext, PointerIcon.TYPE_ARROW);
23573        }
23574        return mPointerIcon;
23575    }
23576
23577    /**
23578     * Set the pointer icon for the current view.
23579     * Passing {@code null} will restore the pointer icon to its default value.
23580     * @param pointerIcon A PointerIcon instance which will be shown when the mouse hovers.
23581     */
23582    public void setPointerIcon(PointerIcon pointerIcon) {
23583        mPointerIcon = pointerIcon;
23584        if (mAttachInfo == null || mAttachInfo.mHandlingPointerEvent) {
23585            return;
23586        }
23587        try {
23588            mAttachInfo.mSession.updatePointerIcon(mAttachInfo.mWindow);
23589        } catch (RemoteException e) {
23590        }
23591    }
23592
23593    /**
23594     * Gets the pointer icon for the current view.
23595     */
23596    public PointerIcon getPointerIcon() {
23597        return mPointerIcon;
23598    }
23599
23600    /**
23601     * Checks pointer capture status.
23602     *
23603     * @return true if the view has pointer capture.
23604     * @see #requestPointerCapture()
23605     * @see #hasPointerCapture()
23606     */
23607    public boolean hasPointerCapture() {
23608        final ViewRootImpl viewRootImpl = getViewRootImpl();
23609        if (viewRootImpl == null) {
23610            return false;
23611        }
23612        return viewRootImpl.hasPointerCapture();
23613    }
23614
23615    /**
23616     * Requests pointer capture mode.
23617     * <p>
23618     * When the window has pointer capture, the mouse pointer icon will disappear and will not
23619     * change its position. Further mouse will be dispatched with the source
23620     * {@link InputDevice#SOURCE_MOUSE_RELATIVE}, and relative position changes will be available
23621     * through {@link MotionEvent#getX} and {@link MotionEvent#getY}. Non-mouse events
23622     * (touchscreens, or stylus) will not be affected.
23623     * <p>
23624     * If the window already has pointer capture, this call does nothing.
23625     * <p>
23626     * The capture may be released through {@link #releasePointerCapture()}, or will be lost
23627     * automatically when the window loses focus.
23628     *
23629     * @see #releasePointerCapture()
23630     * @see #hasPointerCapture()
23631     */
23632    public void requestPointerCapture() {
23633        final ViewRootImpl viewRootImpl = getViewRootImpl();
23634        if (viewRootImpl != null) {
23635            viewRootImpl.requestPointerCapture(true);
23636        }
23637    }
23638
23639
23640    /**
23641     * Releases the pointer capture.
23642     * <p>
23643     * If the window does not have pointer capture, this call will do nothing.
23644     * @see #requestPointerCapture()
23645     * @see #hasPointerCapture()
23646     */
23647    public void releasePointerCapture() {
23648        final ViewRootImpl viewRootImpl = getViewRootImpl();
23649        if (viewRootImpl != null) {
23650            viewRootImpl.requestPointerCapture(false);
23651        }
23652    }
23653
23654    /**
23655     * Called when the window has just acquired or lost pointer capture.
23656     *
23657     * @param hasCapture True if the view now has pointerCapture, false otherwise.
23658     */
23659    @CallSuper
23660    public void onPointerCaptureChange(boolean hasCapture) {
23661    }
23662
23663    /**
23664     * @see #onPointerCaptureChange
23665     */
23666    public void dispatchPointerCaptureChanged(boolean hasCapture) {
23667        onPointerCaptureChange(hasCapture);
23668    }
23669
23670    /**
23671     * Implement this method to handle captured pointer events
23672     *
23673     * @param event The captured pointer event.
23674     * @return True if the event was handled, false otherwise.
23675     * @see #requestPointerCapture()
23676     */
23677    public boolean onCapturedPointerEvent(MotionEvent event) {
23678        return false;
23679    }
23680
23681    /**
23682     * Interface definition for a callback to be invoked when a captured pointer event
23683     * is being dispatched this view. The callback will be invoked before the event is
23684     * given to the view.
23685     */
23686    public interface OnCapturedPointerListener {
23687        /**
23688         * Called when a captured pointer event is dispatched to a view.
23689         * @param view The view this event has been dispatched to.
23690         * @param event The captured event.
23691         * @return True if the listener has consumed the event, false otherwise.
23692         */
23693        boolean onCapturedPointer(View view, MotionEvent event);
23694    }
23695
23696    /**
23697     * Set a listener to receive callbacks when the pointer capture state of a view changes.
23698     * @param l  The {@link OnCapturedPointerListener} to receive callbacks.
23699     */
23700    public void setOnCapturedPointerListener(OnCapturedPointerListener l) {
23701        getListenerInfo().mOnCapturedPointerListener = l;
23702    }
23703
23704    // Properties
23705    //
23706    /**
23707     * A Property wrapper around the <code>alpha</code> functionality handled by the
23708     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
23709     */
23710    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
23711        @Override
23712        public void setValue(View object, float value) {
23713            object.setAlpha(value);
23714        }
23715
23716        @Override
23717        public Float get(View object) {
23718            return object.getAlpha();
23719        }
23720    };
23721
23722    /**
23723     * A Property wrapper around the <code>translationX</code> functionality handled by the
23724     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
23725     */
23726    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
23727        @Override
23728        public void setValue(View object, float value) {
23729            object.setTranslationX(value);
23730        }
23731
23732                @Override
23733        public Float get(View object) {
23734            return object.getTranslationX();
23735        }
23736    };
23737
23738    /**
23739     * A Property wrapper around the <code>translationY</code> functionality handled by the
23740     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
23741     */
23742    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
23743        @Override
23744        public void setValue(View object, float value) {
23745            object.setTranslationY(value);
23746        }
23747
23748        @Override
23749        public Float get(View object) {
23750            return object.getTranslationY();
23751        }
23752    };
23753
23754    /**
23755     * A Property wrapper around the <code>translationZ</code> functionality handled by the
23756     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
23757     */
23758    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
23759        @Override
23760        public void setValue(View object, float value) {
23761            object.setTranslationZ(value);
23762        }
23763
23764        @Override
23765        public Float get(View object) {
23766            return object.getTranslationZ();
23767        }
23768    };
23769
23770    /**
23771     * A Property wrapper around the <code>x</code> functionality handled by the
23772     * {@link View#setX(float)} and {@link View#getX()} methods.
23773     */
23774    public static final Property<View, Float> X = new FloatProperty<View>("x") {
23775        @Override
23776        public void setValue(View object, float value) {
23777            object.setX(value);
23778        }
23779
23780        @Override
23781        public Float get(View object) {
23782            return object.getX();
23783        }
23784    };
23785
23786    /**
23787     * A Property wrapper around the <code>y</code> functionality handled by the
23788     * {@link View#setY(float)} and {@link View#getY()} methods.
23789     */
23790    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
23791        @Override
23792        public void setValue(View object, float value) {
23793            object.setY(value);
23794        }
23795
23796        @Override
23797        public Float get(View object) {
23798            return object.getY();
23799        }
23800    };
23801
23802    /**
23803     * A Property wrapper around the <code>z</code> functionality handled by the
23804     * {@link View#setZ(float)} and {@link View#getZ()} methods.
23805     */
23806    public static final Property<View, Float> Z = new FloatProperty<View>("z") {
23807        @Override
23808        public void setValue(View object, float value) {
23809            object.setZ(value);
23810        }
23811
23812        @Override
23813        public Float get(View object) {
23814            return object.getZ();
23815        }
23816    };
23817
23818    /**
23819     * A Property wrapper around the <code>rotation</code> functionality handled by the
23820     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
23821     */
23822    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
23823        @Override
23824        public void setValue(View object, float value) {
23825            object.setRotation(value);
23826        }
23827
23828        @Override
23829        public Float get(View object) {
23830            return object.getRotation();
23831        }
23832    };
23833
23834    /**
23835     * A Property wrapper around the <code>rotationX</code> functionality handled by the
23836     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
23837     */
23838    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
23839        @Override
23840        public void setValue(View object, float value) {
23841            object.setRotationX(value);
23842        }
23843
23844        @Override
23845        public Float get(View object) {
23846            return object.getRotationX();
23847        }
23848    };
23849
23850    /**
23851     * A Property wrapper around the <code>rotationY</code> functionality handled by the
23852     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
23853     */
23854    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
23855        @Override
23856        public void setValue(View object, float value) {
23857            object.setRotationY(value);
23858        }
23859
23860        @Override
23861        public Float get(View object) {
23862            return object.getRotationY();
23863        }
23864    };
23865
23866    /**
23867     * A Property wrapper around the <code>scaleX</code> functionality handled by the
23868     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
23869     */
23870    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
23871        @Override
23872        public void setValue(View object, float value) {
23873            object.setScaleX(value);
23874        }
23875
23876        @Override
23877        public Float get(View object) {
23878            return object.getScaleX();
23879        }
23880    };
23881
23882    /**
23883     * A Property wrapper around the <code>scaleY</code> functionality handled by the
23884     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
23885     */
23886    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
23887        @Override
23888        public void setValue(View object, float value) {
23889            object.setScaleY(value);
23890        }
23891
23892        @Override
23893        public Float get(View object) {
23894            return object.getScaleY();
23895        }
23896    };
23897
23898    /**
23899     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
23900     * Each MeasureSpec represents a requirement for either the width or the height.
23901     * A MeasureSpec is comprised of a size and a mode. There are three possible
23902     * modes:
23903     * <dl>
23904     * <dt>UNSPECIFIED</dt>
23905     * <dd>
23906     * The parent has not imposed any constraint on the child. It can be whatever size
23907     * it wants.
23908     * </dd>
23909     *
23910     * <dt>EXACTLY</dt>
23911     * <dd>
23912     * The parent has determined an exact size for the child. The child is going to be
23913     * given those bounds regardless of how big it wants to be.
23914     * </dd>
23915     *
23916     * <dt>AT_MOST</dt>
23917     * <dd>
23918     * The child can be as large as it wants up to the specified size.
23919     * </dd>
23920     * </dl>
23921     *
23922     * MeasureSpecs are implemented as ints to reduce object allocation. This class
23923     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
23924     */
23925    public static class MeasureSpec {
23926        private static final int MODE_SHIFT = 30;
23927        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
23928
23929        /** @hide */
23930        @IntDef({UNSPECIFIED, EXACTLY, AT_MOST})
23931        @Retention(RetentionPolicy.SOURCE)
23932        public @interface MeasureSpecMode {}
23933
23934        /**
23935         * Measure specification mode: The parent has not imposed any constraint
23936         * on the child. It can be whatever size it wants.
23937         */
23938        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
23939
23940        /**
23941         * Measure specification mode: The parent has determined an exact size
23942         * for the child. The child is going to be given those bounds regardless
23943         * of how big it wants to be.
23944         */
23945        public static final int EXACTLY     = 1 << MODE_SHIFT;
23946
23947        /**
23948         * Measure specification mode: The child can be as large as it wants up
23949         * to the specified size.
23950         */
23951        public static final int AT_MOST     = 2 << MODE_SHIFT;
23952
23953        /**
23954         * Creates a measure specification based on the supplied size and mode.
23955         *
23956         * The mode must always be one of the following:
23957         * <ul>
23958         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
23959         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
23960         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
23961         * </ul>
23962         *
23963         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
23964         * implementation was such that the order of arguments did not matter
23965         * and overflow in either value could impact the resulting MeasureSpec.
23966         * {@link android.widget.RelativeLayout} was affected by this bug.
23967         * Apps targeting API levels greater than 17 will get the fixed, more strict
23968         * behavior.</p>
23969         *
23970         * @param size the size of the measure specification
23971         * @param mode the mode of the measure specification
23972         * @return the measure specification based on size and mode
23973         */
23974        public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size,
23975                                          @MeasureSpecMode int mode) {
23976            if (sUseBrokenMakeMeasureSpec) {
23977                return size + mode;
23978            } else {
23979                return (size & ~MODE_MASK) | (mode & MODE_MASK);
23980            }
23981        }
23982
23983        /**
23984         * Like {@link #makeMeasureSpec(int, int)}, but any spec with a mode of UNSPECIFIED
23985         * will automatically get a size of 0. Older apps expect this.
23986         *
23987         * @hide internal use only for compatibility with system widgets and older apps
23988         */
23989        public static int makeSafeMeasureSpec(int size, int mode) {
23990            if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) {
23991                return 0;
23992            }
23993            return makeMeasureSpec(size, mode);
23994        }
23995
23996        /**
23997         * Extracts the mode from the supplied measure specification.
23998         *
23999         * @param measureSpec the measure specification to extract the mode from
24000         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
24001         *         {@link android.view.View.MeasureSpec#AT_MOST} or
24002         *         {@link android.view.View.MeasureSpec#EXACTLY}
24003         */
24004        @MeasureSpecMode
24005        public static int getMode(int measureSpec) {
24006            //noinspection ResourceType
24007            return (measureSpec & MODE_MASK);
24008        }
24009
24010        /**
24011         * Extracts the size from the supplied measure specification.
24012         *
24013         * @param measureSpec the measure specification to extract the size from
24014         * @return the size in pixels defined in the supplied measure specification
24015         */
24016        public static int getSize(int measureSpec) {
24017            return (measureSpec & ~MODE_MASK);
24018        }
24019
24020        static int adjust(int measureSpec, int delta) {
24021            final int mode = getMode(measureSpec);
24022            int size = getSize(measureSpec);
24023            if (mode == UNSPECIFIED) {
24024                // No need to adjust size for UNSPECIFIED mode.
24025                return makeMeasureSpec(size, UNSPECIFIED);
24026            }
24027            size += delta;
24028            if (size < 0) {
24029                Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
24030                        ") spec: " + toString(measureSpec) + " delta: " + delta);
24031                size = 0;
24032            }
24033            return makeMeasureSpec(size, mode);
24034        }
24035
24036        /**
24037         * Returns a String representation of the specified measure
24038         * specification.
24039         *
24040         * @param measureSpec the measure specification to convert to a String
24041         * @return a String with the following format: "MeasureSpec: MODE SIZE"
24042         */
24043        public static String toString(int measureSpec) {
24044            int mode = getMode(measureSpec);
24045            int size = getSize(measureSpec);
24046
24047            StringBuilder sb = new StringBuilder("MeasureSpec: ");
24048
24049            if (mode == UNSPECIFIED)
24050                sb.append("UNSPECIFIED ");
24051            else if (mode == EXACTLY)
24052                sb.append("EXACTLY ");
24053            else if (mode == AT_MOST)
24054                sb.append("AT_MOST ");
24055            else
24056                sb.append(mode).append(" ");
24057
24058            sb.append(size);
24059            return sb.toString();
24060        }
24061    }
24062
24063    private final class CheckForLongPress implements Runnable {
24064        private int mOriginalWindowAttachCount;
24065        private float mX;
24066        private float mY;
24067        private boolean mOriginalPressedState;
24068
24069        @Override
24070        public void run() {
24071            if ((mOriginalPressedState == isPressed()) && (mParent != null)
24072                    && mOriginalWindowAttachCount == mWindowAttachCount) {
24073                if (performLongClick(mX, mY)) {
24074                    mHasPerformedLongPress = true;
24075                }
24076            }
24077        }
24078
24079        public void setAnchor(float x, float y) {
24080            mX = x;
24081            mY = y;
24082        }
24083
24084        public void rememberWindowAttachCount() {
24085            mOriginalWindowAttachCount = mWindowAttachCount;
24086        }
24087
24088        public void rememberPressedState() {
24089            mOriginalPressedState = isPressed();
24090        }
24091    }
24092
24093    private final class CheckForTap implements Runnable {
24094        public float x;
24095        public float y;
24096
24097        @Override
24098        public void run() {
24099            mPrivateFlags &= ~PFLAG_PREPRESSED;
24100            setPressed(true, x, y);
24101            checkForLongClick(ViewConfiguration.getTapTimeout(), x, y);
24102        }
24103    }
24104
24105    private final class PerformClick implements Runnable {
24106        @Override
24107        public void run() {
24108            performClick();
24109        }
24110    }
24111
24112    /**
24113     * This method returns a ViewPropertyAnimator object, which can be used to animate
24114     * specific properties on this View.
24115     *
24116     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
24117     */
24118    public ViewPropertyAnimator animate() {
24119        if (mAnimator == null) {
24120            mAnimator = new ViewPropertyAnimator(this);
24121        }
24122        return mAnimator;
24123    }
24124
24125    /**
24126     * Sets the name of the View to be used to identify Views in Transitions.
24127     * Names should be unique in the View hierarchy.
24128     *
24129     * @param transitionName The name of the View to uniquely identify it for Transitions.
24130     */
24131    public final void setTransitionName(String transitionName) {
24132        mTransitionName = transitionName;
24133    }
24134
24135    /**
24136     * Returns the name of the View to be used to identify Views in Transitions.
24137     * Names should be unique in the View hierarchy.
24138     *
24139     * <p>This returns null if the View has not been given a name.</p>
24140     *
24141     * @return The name used of the View to be used to identify Views in Transitions or null
24142     * if no name has been given.
24143     */
24144    @ViewDebug.ExportedProperty
24145    public String getTransitionName() {
24146        return mTransitionName;
24147    }
24148
24149    /**
24150     * @hide
24151     */
24152    public void requestKeyboardShortcuts(List<KeyboardShortcutGroup> data, int deviceId) {
24153        // Do nothing.
24154    }
24155
24156    /**
24157     * Interface definition for a callback to be invoked when a hardware key event is
24158     * dispatched to this view. The callback will be invoked before the key event is
24159     * given to the view. This is only useful for hardware keyboards; a software input
24160     * method has no obligation to trigger this listener.
24161     */
24162    public interface OnKeyListener {
24163        /**
24164         * Called when a hardware key is dispatched to a view. This allows listeners to
24165         * get a chance to respond before the target view.
24166         * <p>Key presses in software keyboards will generally NOT trigger this method,
24167         * although some may elect to do so in some situations. Do not assume a
24168         * software input method has to be key-based; even if it is, it may use key presses
24169         * in a different way than you expect, so there is no way to reliably catch soft
24170         * input key presses.
24171         *
24172         * @param v The view the key has been dispatched to.
24173         * @param keyCode The code for the physical key that was pressed
24174         * @param event The KeyEvent object containing full information about
24175         *        the event.
24176         * @return True if the listener has consumed the event, false otherwise.
24177         */
24178        boolean onKey(View v, int keyCode, KeyEvent event);
24179    }
24180
24181    /**
24182     * Interface definition for a callback to be invoked when a touch event is
24183     * dispatched to this view. The callback will be invoked before the touch
24184     * event is given to the view.
24185     */
24186    public interface OnTouchListener {
24187        /**
24188         * Called when a touch event is dispatched to a view. This allows listeners to
24189         * get a chance to respond before the target view.
24190         *
24191         * @param v The view the touch event has been dispatched to.
24192         * @param event The MotionEvent object containing full information about
24193         *        the event.
24194         * @return True if the listener has consumed the event, false otherwise.
24195         */
24196        boolean onTouch(View v, MotionEvent event);
24197    }
24198
24199    /**
24200     * Interface definition for a callback to be invoked when a hover event is
24201     * dispatched to this view. The callback will be invoked before the hover
24202     * event is given to the view.
24203     */
24204    public interface OnHoverListener {
24205        /**
24206         * Called when a hover event is dispatched to a view. This allows listeners to
24207         * get a chance to respond before the target view.
24208         *
24209         * @param v The view the hover event has been dispatched to.
24210         * @param event The MotionEvent object containing full information about
24211         *        the event.
24212         * @return True if the listener has consumed the event, false otherwise.
24213         */
24214        boolean onHover(View v, MotionEvent event);
24215    }
24216
24217    /**
24218     * Interface definition for a callback to be invoked when a generic motion event is
24219     * dispatched to this view. The callback will be invoked before the generic motion
24220     * event is given to the view.
24221     */
24222    public interface OnGenericMotionListener {
24223        /**
24224         * Called when a generic motion event is dispatched to a view. This allows listeners to
24225         * get a chance to respond before the target view.
24226         *
24227         * @param v The view the generic motion event has been dispatched to.
24228         * @param event The MotionEvent object containing full information about
24229         *        the event.
24230         * @return True if the listener has consumed the event, false otherwise.
24231         */
24232        boolean onGenericMotion(View v, MotionEvent event);
24233    }
24234
24235    /**
24236     * Interface definition for a callback to be invoked when a view has been clicked and held.
24237     */
24238    public interface OnLongClickListener {
24239        /**
24240         * Called when a view has been clicked and held.
24241         *
24242         * @param v The view that was clicked and held.
24243         *
24244         * @return true if the callback consumed the long click, false otherwise.
24245         */
24246        boolean onLongClick(View v);
24247    }
24248
24249    /**
24250     * Interface definition for a callback to be invoked when a drag is being dispatched
24251     * to this view.  The callback will be invoked before the hosting view's own
24252     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
24253     * onDrag(event) behavior, it should return 'false' from this callback.
24254     *
24255     * <div class="special reference">
24256     * <h3>Developer Guides</h3>
24257     * <p>For a guide to implementing drag and drop features, read the
24258     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
24259     * </div>
24260     */
24261    public interface OnDragListener {
24262        /**
24263         * Called when a drag event is dispatched to a view. This allows listeners
24264         * to get a chance to override base View behavior.
24265         *
24266         * @param v The View that received the drag event.
24267         * @param event The {@link android.view.DragEvent} object for the drag event.
24268         * @return {@code true} if the drag event was handled successfully, or {@code false}
24269         * if the drag event was not handled. Note that {@code false} will trigger the View
24270         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
24271         */
24272        boolean onDrag(View v, DragEvent event);
24273    }
24274
24275    /**
24276     * Interface definition for a callback to be invoked when the focus state of
24277     * a view changed.
24278     */
24279    public interface OnFocusChangeListener {
24280        /**
24281         * Called when the focus state of a view has changed.
24282         *
24283         * @param v The view whose state has changed.
24284         * @param hasFocus The new focus state of v.
24285         */
24286        void onFocusChange(View v, boolean hasFocus);
24287    }
24288
24289    /**
24290     * Interface definition for a callback to be invoked when a view is clicked.
24291     */
24292    public interface OnClickListener {
24293        /**
24294         * Called when a view has been clicked.
24295         *
24296         * @param v The view that was clicked.
24297         */
24298        void onClick(View v);
24299    }
24300
24301    /**
24302     * Interface definition for a callback to be invoked when a view is context clicked.
24303     */
24304    public interface OnContextClickListener {
24305        /**
24306         * Called when a view is context clicked.
24307         *
24308         * @param v The view that has been context clicked.
24309         * @return true if the callback consumed the context click, false otherwise.
24310         */
24311        boolean onContextClick(View v);
24312    }
24313
24314    /**
24315     * Interface definition for a callback to be invoked when the context menu
24316     * for this view is being built.
24317     */
24318    public interface OnCreateContextMenuListener {
24319        /**
24320         * Called when the context menu for this view is being built. It is not
24321         * safe to hold onto the menu after this method returns.
24322         *
24323         * @param menu The context menu that is being built
24324         * @param v The view for which the context menu is being built
24325         * @param menuInfo Extra information about the item for which the
24326         *            context menu should be shown. This information will vary
24327         *            depending on the class of v.
24328         */
24329        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
24330    }
24331
24332    /**
24333     * Interface definition for a callback to be invoked when the status bar changes
24334     * visibility.  This reports <strong>global</strong> changes to the system UI
24335     * state, not what the application is requesting.
24336     *
24337     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
24338     */
24339    public interface OnSystemUiVisibilityChangeListener {
24340        /**
24341         * Called when the status bar changes visibility because of a call to
24342         * {@link View#setSystemUiVisibility(int)}.
24343         *
24344         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
24345         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
24346         * This tells you the <strong>global</strong> state of these UI visibility
24347         * flags, not what your app is currently applying.
24348         */
24349        public void onSystemUiVisibilityChange(int visibility);
24350    }
24351
24352    /**
24353     * Interface definition for a callback to be invoked when this view is attached
24354     * or detached from its window.
24355     */
24356    public interface OnAttachStateChangeListener {
24357        /**
24358         * Called when the view is attached to a window.
24359         * @param v The view that was attached
24360         */
24361        public void onViewAttachedToWindow(View v);
24362        /**
24363         * Called when the view is detached from a window.
24364         * @param v The view that was detached
24365         */
24366        public void onViewDetachedFromWindow(View v);
24367    }
24368
24369    /**
24370     * Listener for applying window insets on a view in a custom way.
24371     *
24372     * <p>Apps may choose to implement this interface if they want to apply custom policy
24373     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
24374     * is set, its
24375     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
24376     * method will be called instead of the View's own
24377     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
24378     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
24379     * the View's normal behavior as part of its own.</p>
24380     */
24381    public interface OnApplyWindowInsetsListener {
24382        /**
24383         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
24384         * on a View, this listener method will be called instead of the view's own
24385         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
24386         *
24387         * @param v The view applying window insets
24388         * @param insets The insets to apply
24389         * @return The insets supplied, minus any insets that were consumed
24390         */
24391        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
24392    }
24393
24394    private final class UnsetPressedState implements Runnable {
24395        @Override
24396        public void run() {
24397            setPressed(false);
24398        }
24399    }
24400
24401    /**
24402     * Base class for derived classes that want to save and restore their own
24403     * state in {@link android.view.View#onSaveInstanceState()}.
24404     */
24405    public static class BaseSavedState extends AbsSavedState {
24406        static final int START_ACTIVITY_REQUESTED_WHO_SAVED = 0b1;
24407        static final int IS_AUTOFILLED = 0b10;
24408
24409        // Flags that describe what data in this state is valid
24410        int mSavedData;
24411        String mStartActivityRequestWhoSaved;
24412        boolean mIsAutofilled;
24413
24414        /**
24415         * Constructor used when reading from a parcel. Reads the state of the superclass.
24416         *
24417         * @param source parcel to read from
24418         */
24419        public BaseSavedState(Parcel source) {
24420            this(source, null);
24421        }
24422
24423        /**
24424         * Constructor used when reading from a parcel using a given class loader.
24425         * Reads the state of the superclass.
24426         *
24427         * @param source parcel to read from
24428         * @param loader ClassLoader to use for reading
24429         */
24430        public BaseSavedState(Parcel source, ClassLoader loader) {
24431            super(source, loader);
24432            mSavedData = source.readInt();
24433            mStartActivityRequestWhoSaved = source.readString();
24434            mIsAutofilled = source.readBoolean();
24435        }
24436
24437        /**
24438         * Constructor called by derived classes when creating their SavedState objects
24439         *
24440         * @param superState The state of the superclass of this view
24441         */
24442        public BaseSavedState(Parcelable superState) {
24443            super(superState);
24444        }
24445
24446        @Override
24447        public void writeToParcel(Parcel out, int flags) {
24448            super.writeToParcel(out, flags);
24449
24450            out.writeInt(mSavedData);
24451            out.writeString(mStartActivityRequestWhoSaved);
24452            out.writeBoolean(mIsAutofilled);
24453        }
24454
24455        public static final Parcelable.Creator<BaseSavedState> CREATOR
24456                = new Parcelable.ClassLoaderCreator<BaseSavedState>() {
24457            @Override
24458            public BaseSavedState createFromParcel(Parcel in) {
24459                return new BaseSavedState(in);
24460            }
24461
24462            @Override
24463            public BaseSavedState createFromParcel(Parcel in, ClassLoader loader) {
24464                return new BaseSavedState(in, loader);
24465            }
24466
24467            @Override
24468            public BaseSavedState[] newArray(int size) {
24469                return new BaseSavedState[size];
24470            }
24471        };
24472    }
24473
24474    /**
24475     * A set of information given to a view when it is attached to its parent
24476     * window.
24477     */
24478    final static class AttachInfo {
24479        interface Callbacks {
24480            void playSoundEffect(int effectId);
24481            boolean performHapticFeedback(int effectId, boolean always);
24482        }
24483
24484        /**
24485         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
24486         * to a Handler. This class contains the target (View) to invalidate and
24487         * the coordinates of the dirty rectangle.
24488         *
24489         * For performance purposes, this class also implements a pool of up to
24490         * POOL_LIMIT objects that get reused. This reduces memory allocations
24491         * whenever possible.
24492         */
24493        static class InvalidateInfo {
24494            private static final int POOL_LIMIT = 10;
24495
24496            private static final SynchronizedPool<InvalidateInfo> sPool =
24497                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
24498
24499            View target;
24500
24501            int left;
24502            int top;
24503            int right;
24504            int bottom;
24505
24506            public static InvalidateInfo obtain() {
24507                InvalidateInfo instance = sPool.acquire();
24508                return (instance != null) ? instance : new InvalidateInfo();
24509            }
24510
24511            public void recycle() {
24512                target = null;
24513                sPool.release(this);
24514            }
24515        }
24516
24517        final IWindowSession mSession;
24518
24519        final IWindow mWindow;
24520
24521        final IBinder mWindowToken;
24522
24523        Display mDisplay;
24524
24525        final Callbacks mRootCallbacks;
24526
24527        IWindowId mIWindowId;
24528        WindowId mWindowId;
24529
24530        /**
24531         * The top view of the hierarchy.
24532         */
24533        View mRootView;
24534
24535        IBinder mPanelParentWindowToken;
24536
24537        boolean mHardwareAccelerated;
24538        boolean mHardwareAccelerationRequested;
24539        ThreadedRenderer mThreadedRenderer;
24540        List<RenderNode> mPendingAnimatingRenderNodes;
24541
24542        /**
24543         * The state of the display to which the window is attached, as reported
24544         * by {@link Display#getState()}.  Note that the display state constants
24545         * declared by {@link Display} do not exactly line up with the screen state
24546         * constants declared by {@link View} (there are more display states than
24547         * screen states).
24548         */
24549        int mDisplayState = Display.STATE_UNKNOWN;
24550
24551        /**
24552         * Scale factor used by the compatibility mode
24553         */
24554        float mApplicationScale;
24555
24556        /**
24557         * Indicates whether the application is in compatibility mode
24558         */
24559        boolean mScalingRequired;
24560
24561        /**
24562         * Left position of this view's window
24563         */
24564        int mWindowLeft;
24565
24566        /**
24567         * Top position of this view's window
24568         */
24569        int mWindowTop;
24570
24571        /**
24572         * Indicates whether views need to use 32-bit drawing caches
24573         */
24574        boolean mUse32BitDrawingCache;
24575
24576        /**
24577         * For windows that are full-screen but using insets to layout inside
24578         * of the screen areas, these are the current insets to appear inside
24579         * the overscan area of the display.
24580         */
24581        final Rect mOverscanInsets = new Rect();
24582
24583        /**
24584         * For windows that are full-screen but using insets to layout inside
24585         * of the screen decorations, these are the current insets for the
24586         * content of the window.
24587         */
24588        final Rect mContentInsets = new Rect();
24589
24590        /**
24591         * For windows that are full-screen but using insets to layout inside
24592         * of the screen decorations, these are the current insets for the
24593         * actual visible parts of the window.
24594         */
24595        final Rect mVisibleInsets = new Rect();
24596
24597        /**
24598         * For windows that are full-screen but using insets to layout inside
24599         * of the screen decorations, these are the current insets for the
24600         * stable system windows.
24601         */
24602        final Rect mStableInsets = new Rect();
24603
24604        /**
24605         * For windows that include areas that are not covered by real surface these are the outsets
24606         * for real surface.
24607         */
24608        final Rect mOutsets = new Rect();
24609
24610        /**
24611         * In multi-window we force show the navigation bar. Because we don't want that the surface
24612         * size changes in this mode, we instead have a flag whether the navigation bar size should
24613         * always be consumed, so the app is treated like there is no virtual navigation bar at all.
24614         */
24615        boolean mAlwaysConsumeNavBar;
24616
24617        /**
24618         * The internal insets given by this window.  This value is
24619         * supplied by the client (through
24620         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
24621         * be given to the window manager when changed to be used in laying
24622         * out windows behind it.
24623         */
24624        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
24625                = new ViewTreeObserver.InternalInsetsInfo();
24626
24627        /**
24628         * Set to true when mGivenInternalInsets is non-empty.
24629         */
24630        boolean mHasNonEmptyGivenInternalInsets;
24631
24632        /**
24633         * All views in the window's hierarchy that serve as scroll containers,
24634         * used to determine if the window can be resized or must be panned
24635         * to adjust for a soft input area.
24636         */
24637        final ArrayList<View> mScrollContainers = new ArrayList<View>();
24638
24639        final KeyEvent.DispatcherState mKeyDispatchState
24640                = new KeyEvent.DispatcherState();
24641
24642        /**
24643         * Indicates whether the view's window currently has the focus.
24644         */
24645        boolean mHasWindowFocus;
24646
24647        /**
24648         * The current visibility of the window.
24649         */
24650        int mWindowVisibility;
24651
24652        /**
24653         * Indicates the time at which drawing started to occur.
24654         */
24655        long mDrawingTime;
24656
24657        /**
24658         * Indicates whether or not ignoring the DIRTY_MASK flags.
24659         */
24660        boolean mIgnoreDirtyState;
24661
24662        /**
24663         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
24664         * to avoid clearing that flag prematurely.
24665         */
24666        boolean mSetIgnoreDirtyState = false;
24667
24668        /**
24669         * Indicates whether the view's window is currently in touch mode.
24670         */
24671        boolean mInTouchMode;
24672
24673        /**
24674         * Indicates whether the view has requested unbuffered input dispatching for the current
24675         * event stream.
24676         */
24677        boolean mUnbufferedDispatchRequested;
24678
24679        /**
24680         * Indicates that ViewAncestor should trigger a global layout change
24681         * the next time it performs a traversal
24682         */
24683        boolean mRecomputeGlobalAttributes;
24684
24685        /**
24686         * Always report new attributes at next traversal.
24687         */
24688        boolean mForceReportNewAttributes;
24689
24690        /**
24691         * Set during a traveral if any views want to keep the screen on.
24692         */
24693        boolean mKeepScreenOn;
24694
24695        /**
24696         * Set during a traveral if the light center needs to be updated.
24697         */
24698        boolean mNeedsUpdateLightCenter;
24699
24700        /**
24701         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
24702         */
24703        int mSystemUiVisibility;
24704
24705        /**
24706         * Hack to force certain system UI visibility flags to be cleared.
24707         */
24708        int mDisabledSystemUiVisibility;
24709
24710        /**
24711         * Last global system UI visibility reported by the window manager.
24712         */
24713        int mGlobalSystemUiVisibility = -1;
24714
24715        /**
24716         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
24717         * attached.
24718         */
24719        boolean mHasSystemUiListeners;
24720
24721        /**
24722         * Set if the window has requested to extend into the overscan region
24723         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
24724         */
24725        boolean mOverscanRequested;
24726
24727        /**
24728         * Set if the visibility of any views has changed.
24729         */
24730        boolean mViewVisibilityChanged;
24731
24732        /**
24733         * Set to true if a view has been scrolled.
24734         */
24735        boolean mViewScrollChanged;
24736
24737        /**
24738         * Set to true if high contrast mode enabled
24739         */
24740        boolean mHighContrastText;
24741
24742        /**
24743         * Set to true if a pointer event is currently being handled.
24744         */
24745        boolean mHandlingPointerEvent;
24746
24747        /**
24748         * Global to the view hierarchy used as a temporary for dealing with
24749         * x/y points in the transparent region computations.
24750         */
24751        final int[] mTransparentLocation = new int[2];
24752
24753        /**
24754         * Global to the view hierarchy used as a temporary for dealing with
24755         * x/y points in the ViewGroup.invalidateChild implementation.
24756         */
24757        final int[] mInvalidateChildLocation = new int[2];
24758
24759        /**
24760         * Global to the view hierarchy used as a temporary for dealing with
24761         * computing absolute on-screen location.
24762         */
24763        final int[] mTmpLocation = new int[2];
24764
24765        /**
24766         * Global to the view hierarchy used as a temporary for dealing with
24767         * x/y location when view is transformed.
24768         */
24769        final float[] mTmpTransformLocation = new float[2];
24770
24771        /**
24772         * The view tree observer used to dispatch global events like
24773         * layout, pre-draw, touch mode change, etc.
24774         */
24775        final ViewTreeObserver mTreeObserver;
24776
24777        /**
24778         * A Canvas used by the view hierarchy to perform bitmap caching.
24779         */
24780        Canvas mCanvas;
24781
24782        /**
24783         * The view root impl.
24784         */
24785        final ViewRootImpl mViewRootImpl;
24786
24787        /**
24788         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
24789         * handler can be used to pump events in the UI events queue.
24790         */
24791        final Handler mHandler;
24792
24793        /**
24794         * Temporary for use in computing invalidate rectangles while
24795         * calling up the hierarchy.
24796         */
24797        final Rect mTmpInvalRect = new Rect();
24798
24799        /**
24800         * Temporary for use in computing hit areas with transformed views
24801         */
24802        final RectF mTmpTransformRect = new RectF();
24803
24804        /**
24805         * Temporary for use in computing hit areas with transformed views
24806         */
24807        final RectF mTmpTransformRect1 = new RectF();
24808
24809        /**
24810         * Temporary list of rectanges.
24811         */
24812        final List<RectF> mTmpRectList = new ArrayList<>();
24813
24814        /**
24815         * Temporary for use in transforming invalidation rect
24816         */
24817        final Matrix mTmpMatrix = new Matrix();
24818
24819        /**
24820         * Temporary for use in transforming invalidation rect
24821         */
24822        final Transformation mTmpTransformation = new Transformation();
24823
24824        /**
24825         * Temporary for use in querying outlines from OutlineProviders
24826         */
24827        final Outline mTmpOutline = new Outline();
24828
24829        /**
24830         * Temporary list for use in collecting focusable descendents of a view.
24831         */
24832        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
24833
24834        /**
24835         * The id of the window for accessibility purposes.
24836         */
24837        int mAccessibilityWindowId = AccessibilityWindowInfo.UNDEFINED_WINDOW_ID;
24838
24839        /**
24840         * Flags related to accessibility processing.
24841         *
24842         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
24843         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
24844         */
24845        int mAccessibilityFetchFlags;
24846
24847        /**
24848         * The drawable for highlighting accessibility focus.
24849         */
24850        Drawable mAccessibilityFocusDrawable;
24851
24852        /**
24853         * The drawable for highlighting autofilled views.
24854         *
24855         * @see #isAutofilled()
24856         */
24857        Drawable mAutofilledDrawable;
24858
24859        /**
24860         * Show where the margins, bounds and layout bounds are for each view.
24861         */
24862        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
24863
24864        /**
24865         * Point used to compute visible regions.
24866         */
24867        final Point mPoint = new Point();
24868
24869        /**
24870         * Used to track which View originated a requestLayout() call, used when
24871         * requestLayout() is called during layout.
24872         */
24873        View mViewRequestingLayout;
24874
24875        /**
24876         * Used to track views that need (at least) a partial relayout at their current size
24877         * during the next traversal.
24878         */
24879        List<View> mPartialLayoutViews = new ArrayList<>();
24880
24881        /**
24882         * Swapped with mPartialLayoutViews during layout to avoid concurrent
24883         * modification. Lazily assigned during ViewRootImpl layout.
24884         */
24885        List<View> mEmptyPartialLayoutViews;
24886
24887        /**
24888         * Used to track the identity of the current drag operation.
24889         */
24890        IBinder mDragToken;
24891
24892        /**
24893         * The drag shadow surface for the current drag operation.
24894         */
24895        public Surface mDragSurface;
24896
24897
24898        /**
24899         * The view that currently has a tooltip displayed.
24900         */
24901        View mTooltipHost;
24902
24903        /**
24904         * Creates a new set of attachment information with the specified
24905         * events handler and thread.
24906         *
24907         * @param handler the events handler the view must use
24908         */
24909        AttachInfo(IWindowSession session, IWindow window, Display display,
24910                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer,
24911                Context context) {
24912            mSession = session;
24913            mWindow = window;
24914            mWindowToken = window.asBinder();
24915            mDisplay = display;
24916            mViewRootImpl = viewRootImpl;
24917            mHandler = handler;
24918            mRootCallbacks = effectPlayer;
24919            mTreeObserver = new ViewTreeObserver(context);
24920        }
24921    }
24922
24923    /**
24924     * <p>ScrollabilityCache holds various fields used by a View when scrolling
24925     * is supported. This avoids keeping too many unused fields in most
24926     * instances of View.</p>
24927     */
24928    private static class ScrollabilityCache implements Runnable {
24929
24930        /**
24931         * Scrollbars are not visible
24932         */
24933        public static final int OFF = 0;
24934
24935        /**
24936         * Scrollbars are visible
24937         */
24938        public static final int ON = 1;
24939
24940        /**
24941         * Scrollbars are fading away
24942         */
24943        public static final int FADING = 2;
24944
24945        public boolean fadeScrollBars;
24946
24947        public int fadingEdgeLength;
24948        public int scrollBarDefaultDelayBeforeFade;
24949        public int scrollBarFadeDuration;
24950
24951        public int scrollBarSize;
24952        public int scrollBarMinTouchTarget;
24953        public ScrollBarDrawable scrollBar;
24954        public float[] interpolatorValues;
24955        public View host;
24956
24957        public final Paint paint;
24958        public final Matrix matrix;
24959        public Shader shader;
24960
24961        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
24962
24963        private static final float[] OPAQUE = { 255 };
24964        private static final float[] TRANSPARENT = { 0.0f };
24965
24966        /**
24967         * When fading should start. This time moves into the future every time
24968         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
24969         */
24970        public long fadeStartTime;
24971
24972
24973        /**
24974         * The current state of the scrollbars: ON, OFF, or FADING
24975         */
24976        public int state = OFF;
24977
24978        private int mLastColor;
24979
24980        public final Rect mScrollBarBounds = new Rect();
24981        public final Rect mScrollBarTouchBounds = new Rect();
24982
24983        public static final int NOT_DRAGGING = 0;
24984        public static final int DRAGGING_VERTICAL_SCROLL_BAR = 1;
24985        public static final int DRAGGING_HORIZONTAL_SCROLL_BAR = 2;
24986        public int mScrollBarDraggingState = NOT_DRAGGING;
24987
24988        public float mScrollBarDraggingPos = 0;
24989
24990        public ScrollabilityCache(ViewConfiguration configuration, View host) {
24991            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
24992            scrollBarSize = configuration.getScaledScrollBarSize();
24993            scrollBarMinTouchTarget = configuration.getScaledMinScrollbarTouchTarget();
24994            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
24995            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
24996
24997            paint = new Paint();
24998            matrix = new Matrix();
24999            // use use a height of 1, and then wack the matrix each time we
25000            // actually use it.
25001            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
25002            paint.setShader(shader);
25003            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
25004
25005            this.host = host;
25006        }
25007
25008        public void setFadeColor(int color) {
25009            if (color != mLastColor) {
25010                mLastColor = color;
25011
25012                if (color != 0) {
25013                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
25014                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
25015                    paint.setShader(shader);
25016                    // Restore the default transfer mode (src_over)
25017                    paint.setXfermode(null);
25018                } else {
25019                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
25020                    paint.setShader(shader);
25021                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
25022                }
25023            }
25024        }
25025
25026        public void run() {
25027            long now = AnimationUtils.currentAnimationTimeMillis();
25028            if (now >= fadeStartTime) {
25029
25030                // the animation fades the scrollbars out by changing
25031                // the opacity (alpha) from fully opaque to fully
25032                // transparent
25033                int nextFrame = (int) now;
25034                int framesCount = 0;
25035
25036                Interpolator interpolator = scrollBarInterpolator;
25037
25038                // Start opaque
25039                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
25040
25041                // End transparent
25042                nextFrame += scrollBarFadeDuration;
25043                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
25044
25045                state = FADING;
25046
25047                // Kick off the fade animation
25048                host.invalidate(true);
25049            }
25050        }
25051    }
25052
25053    /**
25054     * Resuable callback for sending
25055     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
25056     */
25057    private class SendViewScrolledAccessibilityEvent implements Runnable {
25058        public volatile boolean mIsPending;
25059
25060        public void run() {
25061            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
25062            mIsPending = false;
25063        }
25064    }
25065
25066    /**
25067     * <p>
25068     * This class represents a delegate that can be registered in a {@link View}
25069     * to enhance accessibility support via composition rather via inheritance.
25070     * It is specifically targeted to widget developers that extend basic View
25071     * classes i.e. classes in package android.view, that would like their
25072     * applications to be backwards compatible.
25073     * </p>
25074     * <div class="special reference">
25075     * <h3>Developer Guides</h3>
25076     * <p>For more information about making applications accessible, read the
25077     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
25078     * developer guide.</p>
25079     * </div>
25080     * <p>
25081     * A scenario in which a developer would like to use an accessibility delegate
25082     * is overriding a method introduced in a later API version than the minimal API
25083     * version supported by the application. For example, the method
25084     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
25085     * in API version 4 when the accessibility APIs were first introduced. If a
25086     * developer would like his application to run on API version 4 devices (assuming
25087     * all other APIs used by the application are version 4 or lower) and take advantage
25088     * of this method, instead of overriding the method which would break the application's
25089     * backwards compatibility, he can override the corresponding method in this
25090     * delegate and register the delegate in the target View if the API version of
25091     * the system is high enough, i.e. the API version is the same as or higher than the API
25092     * version that introduced
25093     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
25094     * </p>
25095     * <p>
25096     * Here is an example implementation:
25097     * </p>
25098     * <code><pre><p>
25099     * if (Build.VERSION.SDK_INT >= 14) {
25100     *     // If the API version is equal of higher than the version in
25101     *     // which onInitializeAccessibilityNodeInfo was introduced we
25102     *     // register a delegate with a customized implementation.
25103     *     View view = findViewById(R.id.view_id);
25104     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
25105     *         public void onInitializeAccessibilityNodeInfo(View host,
25106     *                 AccessibilityNodeInfo info) {
25107     *             // Let the default implementation populate the info.
25108     *             super.onInitializeAccessibilityNodeInfo(host, info);
25109     *             // Set some other information.
25110     *             info.setEnabled(host.isEnabled());
25111     *         }
25112     *     });
25113     * }
25114     * </code></pre></p>
25115     * <p>
25116     * This delegate contains methods that correspond to the accessibility methods
25117     * in View. If a delegate has been specified the implementation in View hands
25118     * off handling to the corresponding method in this delegate. The default
25119     * implementation the delegate methods behaves exactly as the corresponding
25120     * method in View for the case of no accessibility delegate been set. Hence,
25121     * to customize the behavior of a View method, clients can override only the
25122     * corresponding delegate method without altering the behavior of the rest
25123     * accessibility related methods of the host view.
25124     * </p>
25125     * <p>
25126     * <strong>Note:</strong> On platform versions prior to
25127     * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on
25128     * views in the {@code android.widget.*} package are called <i>before</i>
25129     * host methods. This prevents certain properties such as class name from
25130     * being modified by overriding
25131     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)},
25132     * as any changes will be overwritten by the host class.
25133     * <p>
25134     * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate
25135     * methods are called <i>after</i> host methods, which all properties to be
25136     * modified without being overwritten by the host class.
25137     */
25138    public static class AccessibilityDelegate {
25139
25140        /**
25141         * Sends an accessibility event of the given type. If accessibility is not
25142         * enabled this method has no effect.
25143         * <p>
25144         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
25145         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
25146         * been set.
25147         * </p>
25148         *
25149         * @param host The View hosting the delegate.
25150         * @param eventType The type of the event to send.
25151         *
25152         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
25153         */
25154        public void sendAccessibilityEvent(View host, int eventType) {
25155            host.sendAccessibilityEventInternal(eventType);
25156        }
25157
25158        /**
25159         * Performs the specified accessibility action on the view. For
25160         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
25161         * <p>
25162         * The default implementation behaves as
25163         * {@link View#performAccessibilityAction(int, Bundle)
25164         *  View#performAccessibilityAction(int, Bundle)} for the case of
25165         *  no accessibility delegate been set.
25166         * </p>
25167         *
25168         * @param action The action to perform.
25169         * @return Whether the action was performed.
25170         *
25171         * @see View#performAccessibilityAction(int, Bundle)
25172         *      View#performAccessibilityAction(int, Bundle)
25173         */
25174        public boolean performAccessibilityAction(View host, int action, Bundle args) {
25175            return host.performAccessibilityActionInternal(action, args);
25176        }
25177
25178        /**
25179         * Sends an accessibility event. This method behaves exactly as
25180         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
25181         * empty {@link AccessibilityEvent} and does not perform a check whether
25182         * accessibility is enabled.
25183         * <p>
25184         * The default implementation behaves as
25185         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
25186         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
25187         * the case of no accessibility delegate been set.
25188         * </p>
25189         *
25190         * @param host The View hosting the delegate.
25191         * @param event The event to send.
25192         *
25193         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
25194         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
25195         */
25196        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
25197            host.sendAccessibilityEventUncheckedInternal(event);
25198        }
25199
25200        /**
25201         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
25202         * to its children for adding their text content to the event.
25203         * <p>
25204         * The default implementation behaves as
25205         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
25206         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
25207         * the case of no accessibility delegate been set.
25208         * </p>
25209         *
25210         * @param host The View hosting the delegate.
25211         * @param event The event.
25212         * @return True if the event population was completed.
25213         *
25214         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
25215         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
25216         */
25217        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
25218            return host.dispatchPopulateAccessibilityEventInternal(event);
25219        }
25220
25221        /**
25222         * Gives a chance to the host View to populate the accessibility event with its
25223         * text content.
25224         * <p>
25225         * The default implementation behaves as
25226         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
25227         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
25228         * the case of no accessibility delegate been set.
25229         * </p>
25230         *
25231         * @param host The View hosting the delegate.
25232         * @param event The accessibility event which to populate.
25233         *
25234         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
25235         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
25236         */
25237        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
25238            host.onPopulateAccessibilityEventInternal(event);
25239        }
25240
25241        /**
25242         * Initializes an {@link AccessibilityEvent} with information about the
25243         * the host View which is the event source.
25244         * <p>
25245         * The default implementation behaves as
25246         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
25247         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
25248         * the case of no accessibility delegate been set.
25249         * </p>
25250         *
25251         * @param host The View hosting the delegate.
25252         * @param event The event to initialize.
25253         *
25254         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
25255         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
25256         */
25257        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
25258            host.onInitializeAccessibilityEventInternal(event);
25259        }
25260
25261        /**
25262         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
25263         * <p>
25264         * The default implementation behaves as
25265         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
25266         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
25267         * the case of no accessibility delegate been set.
25268         * </p>
25269         *
25270         * @param host The View hosting the delegate.
25271         * @param info The instance to initialize.
25272         *
25273         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
25274         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
25275         */
25276        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
25277            host.onInitializeAccessibilityNodeInfoInternal(info);
25278        }
25279
25280        /**
25281         * Adds extra data to an {@link AccessibilityNodeInfo} based on an explicit request for the
25282         * additional data.
25283         * <p>
25284         * This method only needs to be implemented if the View offers to provide additional data.
25285         * </p>
25286         * <p>
25287         * The default implementation behaves as
25288         * {@link View#addExtraDataToAccessibilityNodeInfo(AccessibilityNodeInfo, int) for
25289         * the case where no accessibility delegate is set.
25290         * </p>
25291         *
25292         * @param host The View hosting the delegate. Never {@code null}.
25293         * @param info The info to which to add the extra data. Never {@code null}.
25294         * @param extraDataKey A key specifying the type of extra data to add to the info. The
25295         *                     extra data should be added to the {@link Bundle} returned by
25296         *                     the info's {@link AccessibilityNodeInfo#getExtras} method.  Never
25297         *                     {@code null}.
25298         * @param arguments A {@link Bundle} holding any arguments relevant for this request.
25299         *                  May be {@code null} if the if the service provided no arguments.
25300         *
25301         * @see AccessibilityNodeInfo#setExtraAvailableData
25302         */
25303        public void addExtraDataToAccessibilityNodeInfo(@NonNull View host,
25304                @NonNull AccessibilityNodeInfo info, @NonNull String extraDataKey,
25305                @Nullable Bundle arguments) {
25306            host.addExtraDataToAccessibilityNodeInfo(info, extraDataKey, arguments);
25307        }
25308
25309        /**
25310         * Called when a child of the host View has requested sending an
25311         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
25312         * to augment the event.
25313         * <p>
25314         * The default implementation behaves as
25315         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
25316         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
25317         * the case of no accessibility delegate been set.
25318         * </p>
25319         *
25320         * @param host The View hosting the delegate.
25321         * @param child The child which requests sending the event.
25322         * @param event The event to be sent.
25323         * @return True if the event should be sent
25324         *
25325         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
25326         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
25327         */
25328        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
25329                AccessibilityEvent event) {
25330            return host.onRequestSendAccessibilityEventInternal(child, event);
25331        }
25332
25333        /**
25334         * Gets the provider for managing a virtual view hierarchy rooted at this View
25335         * and reported to {@link android.accessibilityservice.AccessibilityService}s
25336         * that explore the window content.
25337         * <p>
25338         * The default implementation behaves as
25339         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
25340         * the case of no accessibility delegate been set.
25341         * </p>
25342         *
25343         * @return The provider.
25344         *
25345         * @see AccessibilityNodeProvider
25346         */
25347        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
25348            return null;
25349        }
25350
25351        /**
25352         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
25353         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
25354         * This method is responsible for obtaining an accessibility node info from a
25355         * pool of reusable instances and calling
25356         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
25357         * view to initialize the former.
25358         * <p>
25359         * <strong>Note:</strong> The client is responsible for recycling the obtained
25360         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
25361         * creation.
25362         * </p>
25363         * <p>
25364         * The default implementation behaves as
25365         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
25366         * the case of no accessibility delegate been set.
25367         * </p>
25368         * @return A populated {@link AccessibilityNodeInfo}.
25369         *
25370         * @see AccessibilityNodeInfo
25371         *
25372         * @hide
25373         */
25374        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
25375            return host.createAccessibilityNodeInfoInternal();
25376        }
25377    }
25378
25379    private static class MatchIdPredicate implements Predicate<View> {
25380        public int mId;
25381
25382        @Override
25383        public boolean test(View view) {
25384            return (view.mID == mId);
25385        }
25386    }
25387
25388    private static class MatchLabelForPredicate implements Predicate<View> {
25389        private int mLabeledId;
25390
25391        @Override
25392        public boolean test(View view) {
25393            return (view.mLabelForId == mLabeledId);
25394        }
25395    }
25396
25397    private class SendViewStateChangedAccessibilityEvent implements Runnable {
25398        private int mChangeTypes = 0;
25399        private boolean mPosted;
25400        private boolean mPostedWithDelay;
25401        private long mLastEventTimeMillis;
25402
25403        @Override
25404        public void run() {
25405            mPosted = false;
25406            mPostedWithDelay = false;
25407            mLastEventTimeMillis = SystemClock.uptimeMillis();
25408            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
25409                final AccessibilityEvent event = AccessibilityEvent.obtain();
25410                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
25411                event.setContentChangeTypes(mChangeTypes);
25412                sendAccessibilityEventUnchecked(event);
25413            }
25414            mChangeTypes = 0;
25415        }
25416
25417        public void runOrPost(int changeType) {
25418            mChangeTypes |= changeType;
25419
25420            // If this is a live region or the child of a live region, collect
25421            // all events from this frame and send them on the next frame.
25422            if (inLiveRegion()) {
25423                // If we're already posted with a delay, remove that.
25424                if (mPostedWithDelay) {
25425                    removeCallbacks(this);
25426                    mPostedWithDelay = false;
25427                }
25428                // Only post if we're not already posted.
25429                if (!mPosted) {
25430                    post(this);
25431                    mPosted = true;
25432                }
25433                return;
25434            }
25435
25436            if (mPosted) {
25437                return;
25438            }
25439
25440            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
25441            final long minEventIntevalMillis =
25442                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
25443            if (timeSinceLastMillis >= minEventIntevalMillis) {
25444                removeCallbacks(this);
25445                run();
25446            } else {
25447                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
25448                mPostedWithDelay = true;
25449            }
25450        }
25451    }
25452
25453    private boolean inLiveRegion() {
25454        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
25455            return true;
25456        }
25457
25458        ViewParent parent = getParent();
25459        while (parent instanceof View) {
25460            if (((View) parent).getAccessibilityLiveRegion()
25461                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
25462                return true;
25463            }
25464            parent = parent.getParent();
25465        }
25466
25467        return false;
25468    }
25469
25470    /**
25471     * Dump all private flags in readable format, useful for documentation and
25472     * sanity checking.
25473     */
25474    private static void dumpFlags() {
25475        final HashMap<String, String> found = Maps.newHashMap();
25476        try {
25477            for (Field field : View.class.getDeclaredFields()) {
25478                final int modifiers = field.getModifiers();
25479                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
25480                    if (field.getType().equals(int.class)) {
25481                        final int value = field.getInt(null);
25482                        dumpFlag(found, field.getName(), value);
25483                    } else if (field.getType().equals(int[].class)) {
25484                        final int[] values = (int[]) field.get(null);
25485                        for (int i = 0; i < values.length; i++) {
25486                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
25487                        }
25488                    }
25489                }
25490            }
25491        } catch (IllegalAccessException e) {
25492            throw new RuntimeException(e);
25493        }
25494
25495        final ArrayList<String> keys = Lists.newArrayList();
25496        keys.addAll(found.keySet());
25497        Collections.sort(keys);
25498        for (String key : keys) {
25499            Log.d(VIEW_LOG_TAG, found.get(key));
25500        }
25501    }
25502
25503    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
25504        // Sort flags by prefix, then by bits, always keeping unique keys
25505        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
25506        final int prefix = name.indexOf('_');
25507        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
25508        final String output = bits + " " + name;
25509        found.put(key, output);
25510    }
25511
25512    /** {@hide} */
25513    public void encode(@NonNull ViewHierarchyEncoder stream) {
25514        stream.beginObject(this);
25515        encodeProperties(stream);
25516        stream.endObject();
25517    }
25518
25519    /** {@hide} */
25520    @CallSuper
25521    protected void encodeProperties(@NonNull ViewHierarchyEncoder stream) {
25522        Object resolveId = ViewDebug.resolveId(getContext(), mID);
25523        if (resolveId instanceof String) {
25524            stream.addProperty("id", (String) resolveId);
25525        } else {
25526            stream.addProperty("id", mID);
25527        }
25528
25529        stream.addProperty("misc:transformation.alpha",
25530                mTransformationInfo != null ? mTransformationInfo.mAlpha : 0);
25531        stream.addProperty("misc:transitionName", getTransitionName());
25532
25533        // layout
25534        stream.addProperty("layout:left", mLeft);
25535        stream.addProperty("layout:right", mRight);
25536        stream.addProperty("layout:top", mTop);
25537        stream.addProperty("layout:bottom", mBottom);
25538        stream.addProperty("layout:width", getWidth());
25539        stream.addProperty("layout:height", getHeight());
25540        stream.addProperty("layout:layoutDirection", getLayoutDirection());
25541        stream.addProperty("layout:layoutRtl", isLayoutRtl());
25542        stream.addProperty("layout:hasTransientState", hasTransientState());
25543        stream.addProperty("layout:baseline", getBaseline());
25544
25545        // layout params
25546        ViewGroup.LayoutParams layoutParams = getLayoutParams();
25547        if (layoutParams != null) {
25548            stream.addPropertyKey("layoutParams");
25549            layoutParams.encode(stream);
25550        }
25551
25552        // scrolling
25553        stream.addProperty("scrolling:scrollX", mScrollX);
25554        stream.addProperty("scrolling:scrollY", mScrollY);
25555
25556        // padding
25557        stream.addProperty("padding:paddingLeft", mPaddingLeft);
25558        stream.addProperty("padding:paddingRight", mPaddingRight);
25559        stream.addProperty("padding:paddingTop", mPaddingTop);
25560        stream.addProperty("padding:paddingBottom", mPaddingBottom);
25561        stream.addProperty("padding:userPaddingRight", mUserPaddingRight);
25562        stream.addProperty("padding:userPaddingLeft", mUserPaddingLeft);
25563        stream.addProperty("padding:userPaddingBottom", mUserPaddingBottom);
25564        stream.addProperty("padding:userPaddingStart", mUserPaddingStart);
25565        stream.addProperty("padding:userPaddingEnd", mUserPaddingEnd);
25566
25567        // measurement
25568        stream.addProperty("measurement:minHeight", mMinHeight);
25569        stream.addProperty("measurement:minWidth", mMinWidth);
25570        stream.addProperty("measurement:measuredWidth", mMeasuredWidth);
25571        stream.addProperty("measurement:measuredHeight", mMeasuredHeight);
25572
25573        // drawing
25574        stream.addProperty("drawing:elevation", getElevation());
25575        stream.addProperty("drawing:translationX", getTranslationX());
25576        stream.addProperty("drawing:translationY", getTranslationY());
25577        stream.addProperty("drawing:translationZ", getTranslationZ());
25578        stream.addProperty("drawing:rotation", getRotation());
25579        stream.addProperty("drawing:rotationX", getRotationX());
25580        stream.addProperty("drawing:rotationY", getRotationY());
25581        stream.addProperty("drawing:scaleX", getScaleX());
25582        stream.addProperty("drawing:scaleY", getScaleY());
25583        stream.addProperty("drawing:pivotX", getPivotX());
25584        stream.addProperty("drawing:pivotY", getPivotY());
25585        stream.addProperty("drawing:opaque", isOpaque());
25586        stream.addProperty("drawing:alpha", getAlpha());
25587        stream.addProperty("drawing:transitionAlpha", getTransitionAlpha());
25588        stream.addProperty("drawing:shadow", hasShadow());
25589        stream.addProperty("drawing:solidColor", getSolidColor());
25590        stream.addProperty("drawing:layerType", mLayerType);
25591        stream.addProperty("drawing:willNotDraw", willNotDraw());
25592        stream.addProperty("drawing:hardwareAccelerated", isHardwareAccelerated());
25593        stream.addProperty("drawing:willNotCacheDrawing", willNotCacheDrawing());
25594        stream.addProperty("drawing:drawingCacheEnabled", isDrawingCacheEnabled());
25595        stream.addProperty("drawing:overlappingRendering", hasOverlappingRendering());
25596
25597        // focus
25598        stream.addProperty("focus:hasFocus", hasFocus());
25599        stream.addProperty("focus:isFocused", isFocused());
25600        stream.addProperty("focus:isFocusable", isFocusable());
25601        stream.addProperty("focus:isFocusableInTouchMode", isFocusableInTouchMode());
25602
25603        stream.addProperty("misc:clickable", isClickable());
25604        stream.addProperty("misc:pressed", isPressed());
25605        stream.addProperty("misc:selected", isSelected());
25606        stream.addProperty("misc:touchMode", isInTouchMode());
25607        stream.addProperty("misc:hovered", isHovered());
25608        stream.addProperty("misc:activated", isActivated());
25609
25610        stream.addProperty("misc:visibility", getVisibility());
25611        stream.addProperty("misc:fitsSystemWindows", getFitsSystemWindows());
25612        stream.addProperty("misc:filterTouchesWhenObscured", getFilterTouchesWhenObscured());
25613
25614        stream.addProperty("misc:enabled", isEnabled());
25615        stream.addProperty("misc:soundEffectsEnabled", isSoundEffectsEnabled());
25616        stream.addProperty("misc:hapticFeedbackEnabled", isHapticFeedbackEnabled());
25617
25618        // theme attributes
25619        Resources.Theme theme = getContext().getTheme();
25620        if (theme != null) {
25621            stream.addPropertyKey("theme");
25622            theme.encode(stream);
25623        }
25624
25625        // view attribute information
25626        int n = mAttributes != null ? mAttributes.length : 0;
25627        stream.addProperty("meta:__attrCount__", n/2);
25628        for (int i = 0; i < n; i += 2) {
25629            stream.addProperty("meta:__attr__" + mAttributes[i], mAttributes[i+1]);
25630        }
25631
25632        stream.addProperty("misc:scrollBarStyle", getScrollBarStyle());
25633
25634        // text
25635        stream.addProperty("text:textDirection", getTextDirection());
25636        stream.addProperty("text:textAlignment", getTextAlignment());
25637
25638        // accessibility
25639        CharSequence contentDescription = getContentDescription();
25640        stream.addProperty("accessibility:contentDescription",
25641                contentDescription == null ? "" : contentDescription.toString());
25642        stream.addProperty("accessibility:labelFor", getLabelFor());
25643        stream.addProperty("accessibility:importantForAccessibility", getImportantForAccessibility());
25644    }
25645
25646    /**
25647     * Determine if this view is rendered on a round wearable device and is the main view
25648     * on the screen.
25649     */
25650    boolean shouldDrawRoundScrollbar() {
25651        if (!mResources.getConfiguration().isScreenRound() || mAttachInfo == null) {
25652            return false;
25653        }
25654
25655        final View rootView = getRootView();
25656        final WindowInsets insets = getRootWindowInsets();
25657
25658        int height = getHeight();
25659        int width = getWidth();
25660        int displayHeight = rootView.getHeight();
25661        int displayWidth = rootView.getWidth();
25662
25663        if (height != displayHeight || width != displayWidth) {
25664            return false;
25665        }
25666
25667        getLocationInWindow(mAttachInfo.mTmpLocation);
25668        return mAttachInfo.mTmpLocation[0] == insets.getStableInsetLeft()
25669                && mAttachInfo.mTmpLocation[1] == insets.getStableInsetTop();
25670    }
25671
25672    /**
25673     * Sets the tooltip text which will be displayed in a small popup next to the view.
25674     * <p>
25675     * The tooltip will be displayed:
25676     * <ul>
25677     * <li>On long click, unless it is handled otherwise (by OnLongClickListener or a context
25678     * menu). </li>
25679     * <li>On hover, after a brief delay since the pointer has stopped moving </li>
25680     * </ul>
25681     * <p>
25682     * <strong>Note:</strong> Do not override this method, as it will have no
25683     * effect on the text displayed in the tooltip.
25684     *
25685     * @param tooltipText the tooltip text, or null if no tooltip is required
25686     * @see #getTooltipText()
25687     * @attr ref android.R.styleable#View_tooltipText
25688     */
25689    public void setTooltipText(@Nullable CharSequence tooltipText) {
25690        if (TextUtils.isEmpty(tooltipText)) {
25691            setFlags(0, TOOLTIP);
25692            hideTooltip();
25693            mTooltipInfo = null;
25694        } else {
25695            setFlags(TOOLTIP, TOOLTIP);
25696            if (mTooltipInfo == null) {
25697                mTooltipInfo = new TooltipInfo();
25698                mTooltipInfo.mShowTooltipRunnable = this::showHoverTooltip;
25699                mTooltipInfo.mHideTooltipRunnable = this::hideTooltip;
25700            }
25701            mTooltipInfo.mTooltipText = tooltipText;
25702            if (mTooltipInfo.mTooltipPopup != null && mTooltipInfo.mTooltipPopup.isShowing()) {
25703                mTooltipInfo.mTooltipPopup.updateContent(mTooltipInfo.mTooltipText);
25704            }
25705        }
25706    }
25707
25708    /**
25709     * @hide Binary compatibility stub. To be removed when we finalize O APIs.
25710     */
25711    public void setTooltip(@Nullable CharSequence tooltipText) {
25712        setTooltipText(tooltipText);
25713    }
25714
25715    /**
25716     * Returns the view's tooltip text.
25717     *
25718     * <strong>Note:</strong> Do not override this method, as it will have no
25719     * effect on the text displayed in the tooltip. You must call
25720     * {@link #setTooltipText(CharSequence)} to modify the tooltip text.
25721     *
25722     * @return the tooltip text
25723     * @see #setTooltipText(CharSequence)
25724     * @attr ref android.R.styleable#View_tooltipText
25725     */
25726    @Nullable
25727    public CharSequence getTooltipText() {
25728        return mTooltipInfo != null ? mTooltipInfo.mTooltipText : null;
25729    }
25730
25731    /**
25732     * @hide Binary compatibility stub. To be removed when we finalize O APIs.
25733     */
25734    @Nullable
25735    public CharSequence getTooltip() {
25736        return getTooltipText();
25737    }
25738
25739    private boolean showTooltip(int x, int y, boolean fromLongClick) {
25740        if (mAttachInfo == null || mTooltipInfo == null) {
25741            return false;
25742        }
25743        if ((mViewFlags & ENABLED_MASK) != ENABLED) {
25744            return false;
25745        }
25746        if (TextUtils.isEmpty(mTooltipInfo.mTooltipText)) {
25747            return false;
25748        }
25749        hideTooltip();
25750        mTooltipInfo.mTooltipFromLongClick = fromLongClick;
25751        mTooltipInfo.mTooltipPopup = new TooltipPopup(getContext());
25752        final boolean fromTouch = (mPrivateFlags3 & PFLAG3_FINGER_DOWN) == PFLAG3_FINGER_DOWN;
25753        mTooltipInfo.mTooltipPopup.show(this, x, y, fromTouch, mTooltipInfo.mTooltipText);
25754        mAttachInfo.mTooltipHost = this;
25755        return true;
25756    }
25757
25758    void hideTooltip() {
25759        if (mTooltipInfo == null) {
25760            return;
25761        }
25762        removeCallbacks(mTooltipInfo.mShowTooltipRunnable);
25763        if (mTooltipInfo.mTooltipPopup == null) {
25764            return;
25765        }
25766        mTooltipInfo.mTooltipPopup.hide();
25767        mTooltipInfo.mTooltipPopup = null;
25768        mTooltipInfo.mTooltipFromLongClick = false;
25769        if (mAttachInfo != null) {
25770            mAttachInfo.mTooltipHost = null;
25771        }
25772    }
25773
25774    private boolean showLongClickTooltip(int x, int y) {
25775        removeCallbacks(mTooltipInfo.mShowTooltipRunnable);
25776        removeCallbacks(mTooltipInfo.mHideTooltipRunnable);
25777        return showTooltip(x, y, true);
25778    }
25779
25780    private void showHoverTooltip() {
25781        showTooltip(mTooltipInfo.mAnchorX, mTooltipInfo.mAnchorY, false);
25782    }
25783
25784    boolean dispatchTooltipHoverEvent(MotionEvent event) {
25785        if (mTooltipInfo == null) {
25786            return false;
25787        }
25788        switch(event.getAction()) {
25789            case MotionEvent.ACTION_HOVER_MOVE:
25790                if ((mViewFlags & TOOLTIP) != TOOLTIP || (mViewFlags & ENABLED_MASK) != ENABLED) {
25791                    break;
25792                }
25793                if (!mTooltipInfo.mTooltipFromLongClick) {
25794                    if (mTooltipInfo.mTooltipPopup == null) {
25795                        // Schedule showing the tooltip after a timeout.
25796                        mTooltipInfo.mAnchorX = (int) event.getX();
25797                        mTooltipInfo.mAnchorY = (int) event.getY();
25798                        removeCallbacks(mTooltipInfo.mShowTooltipRunnable);
25799                        postDelayed(mTooltipInfo.mShowTooltipRunnable,
25800                                ViewConfiguration.getHoverTooltipShowTimeout());
25801                    }
25802
25803                    // Hide hover-triggered tooltip after a period of inactivity.
25804                    // Match the timeout used by NativeInputManager to hide the mouse pointer
25805                    // (depends on SYSTEM_UI_FLAG_LOW_PROFILE being set).
25806                    final int timeout;
25807                    if ((getWindowSystemUiVisibility() & SYSTEM_UI_FLAG_LOW_PROFILE)
25808                            == SYSTEM_UI_FLAG_LOW_PROFILE) {
25809                        timeout = ViewConfiguration.getHoverTooltipHideShortTimeout();
25810                    } else {
25811                        timeout = ViewConfiguration.getHoverTooltipHideTimeout();
25812                    }
25813                    removeCallbacks(mTooltipInfo.mHideTooltipRunnable);
25814                    postDelayed(mTooltipInfo.mHideTooltipRunnable, timeout);
25815                }
25816                return true;
25817
25818            case MotionEvent.ACTION_HOVER_EXIT:
25819                if (!mTooltipInfo.mTooltipFromLongClick) {
25820                    hideTooltip();
25821                }
25822                break;
25823        }
25824        return false;
25825    }
25826
25827    void handleTooltipKey(KeyEvent event) {
25828        switch (event.getAction()) {
25829            case KeyEvent.ACTION_DOWN:
25830                if (event.getRepeatCount() == 0) {
25831                    hideTooltip();
25832                }
25833                break;
25834
25835            case KeyEvent.ACTION_UP:
25836                handleTooltipUp();
25837                break;
25838        }
25839    }
25840
25841    private void handleTooltipUp() {
25842        if (mTooltipInfo == null || mTooltipInfo.mTooltipPopup == null) {
25843            return;
25844        }
25845        removeCallbacks(mTooltipInfo.mHideTooltipRunnable);
25846        postDelayed(mTooltipInfo.mHideTooltipRunnable,
25847                ViewConfiguration.getLongPressTooltipHideTimeout());
25848    }
25849
25850    private int getFocusableAttribute(TypedArray attributes) {
25851        TypedValue val = new TypedValue();
25852        if (attributes.getValue(com.android.internal.R.styleable.View_focusable, val)) {
25853            if (val.type == TypedValue.TYPE_INT_BOOLEAN) {
25854                return (val.data == 0 ? NOT_FOCUSABLE : FOCUSABLE);
25855            } else {
25856                return val.data;
25857            }
25858        } else {
25859            return FOCUSABLE_AUTO;
25860        }
25861    }
25862
25863    /**
25864     * @return The content view of the tooltip popup currently being shown, or null if the tooltip
25865     * is not showing.
25866     * @hide
25867     */
25868    @TestApi
25869    public View getTooltipView() {
25870        if (mTooltipInfo == null || mTooltipInfo.mTooltipPopup == null) {
25871            return null;
25872        }
25873        return mTooltipInfo.mTooltipPopup.getContentView();
25874    }
25875}
25876