View.java revision 2ae1bf568b68ea18431ab10aceeff3ec62aedb7b
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.Message;
70import android.os.Parcel;
71import android.os.Parcelable;
72import android.os.RemoteException;
73import android.os.SystemClock;
74import android.os.SystemProperties;
75import android.os.Trace;
76import android.text.TextUtils;
77import android.util.AttributeSet;
78import android.util.FloatProperty;
79import android.util.LayoutDirection;
80import android.util.Log;
81import android.util.LongSparseLongArray;
82import android.util.Pools.SynchronizedPool;
83import android.util.Property;
84import android.util.SparseArray;
85import android.util.StateSet;
86import android.util.SuperNotCalledException;
87import android.util.TypedValue;
88import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
89import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
90import android.view.AccessibilityIterators.TextSegmentIterator;
91import android.view.AccessibilityIterators.WordTextSegmentIterator;
92import android.view.ContextMenu.ContextMenuInfo;
93import android.view.accessibility.AccessibilityEvent;
94import android.view.accessibility.AccessibilityEventSource;
95import android.view.accessibility.AccessibilityManager;
96import android.view.accessibility.AccessibilityNodeInfo;
97import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction;
98import android.view.accessibility.AccessibilityNodeProvider;
99import android.view.accessibility.AccessibilityWindowInfo;
100import android.view.animation.Animation;
101import android.view.animation.AnimationUtils;
102import android.view.animation.Transformation;
103import android.view.autofill.AutofillId;
104import android.view.autofill.AutofillManager;
105import android.view.autofill.AutofillValue;
106import android.view.inputmethod.EditorInfo;
107import android.view.inputmethod.InputConnection;
108import android.view.inputmethod.InputMethodManager;
109import android.widget.Checkable;
110import android.widget.FrameLayout;
111import android.widget.ScrollBarDrawable;
112
113import com.android.internal.R;
114import com.android.internal.view.TooltipPopup;
115import com.android.internal.view.menu.MenuBuilder;
116import com.android.internal.widget.ScrollBarUtils;
117
118import com.google.android.collect.Lists;
119import com.google.android.collect.Maps;
120
121import java.lang.annotation.Retention;
122import java.lang.annotation.RetentionPolicy;
123import java.lang.ref.WeakReference;
124import java.lang.reflect.Field;
125import java.lang.reflect.InvocationTargetException;
126import java.lang.reflect.Method;
127import java.lang.reflect.Modifier;
128import java.util.ArrayList;
129import java.util.Arrays;
130import java.util.Collection;
131import java.util.Collections;
132import java.util.HashMap;
133import java.util.List;
134import java.util.Locale;
135import java.util.Map;
136import java.util.concurrent.CopyOnWriteArrayList;
137import java.util.concurrent.atomic.AtomicInteger;
138import java.util.function.Predicate;
139
140/**
141 * <p>
142 * This class represents the basic building block for user interface components. A View
143 * occupies a rectangular area on the screen and is responsible for drawing and
144 * event handling. View is the base class for <em>widgets</em>, which are
145 * used to create interactive UI components (buttons, text fields, etc.). The
146 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
147 * are invisible containers that hold other Views (or other ViewGroups) and define
148 * their layout properties.
149 * </p>
150 *
151 * <div class="special reference">
152 * <h3>Developer Guides</h3>
153 * <p>For information about using this class to develop your application's user interface,
154 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
155 * </div>
156 *
157 * <a name="Using"></a>
158 * <h3>Using Views</h3>
159 * <p>
160 * All of the views in a window are arranged in a single tree. You can add views
161 * either from code or by specifying a tree of views in one or more XML layout
162 * files. There are many specialized subclasses of views that act as controls or
163 * are capable of displaying text, images, or other content.
164 * </p>
165 * <p>
166 * Once you have created a tree of views, there are typically a few types of
167 * common operations you may wish to perform:
168 * <ul>
169 * <li><strong>Set properties:</strong> for example setting the text of a
170 * {@link android.widget.TextView}. The available properties and the methods
171 * that set them will vary among the different subclasses of views. Note that
172 * properties that are known at build time can be set in the XML layout
173 * files.</li>
174 * <li><strong>Set focus:</strong> The framework will handle moving focus in
175 * response to user input. To force focus to a specific view, call
176 * {@link #requestFocus}.</li>
177 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
178 * that will be notified when something interesting happens to the view. For
179 * example, all views will let you set a listener to be notified when the view
180 * gains or loses focus. You can register such a listener using
181 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
182 * Other view subclasses offer more specialized listeners. For example, a Button
183 * exposes a listener to notify clients when the button is clicked.</li>
184 * <li><strong>Set visibility:</strong> You can hide or show views using
185 * {@link #setVisibility(int)}.</li>
186 * </ul>
187 * </p>
188 * <p><em>
189 * Note: The Android framework is responsible for measuring, laying out and
190 * drawing views. You should not call methods that perform these actions on
191 * views yourself unless you are actually implementing a
192 * {@link android.view.ViewGroup}.
193 * </em></p>
194 *
195 * <a name="Lifecycle"></a>
196 * <h3>Implementing a Custom View</h3>
197 *
198 * <p>
199 * To implement a custom view, you will usually begin by providing overrides for
200 * some of the standard methods that the framework calls on all views. You do
201 * not need to override all of these methods. In fact, you can start by just
202 * overriding {@link #onDraw(android.graphics.Canvas)}.
203 * <table border="2" width="85%" align="center" cellpadding="5">
204 *     <thead>
205 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
206 *     </thead>
207 *
208 *     <tbody>
209 *     <tr>
210 *         <td rowspan="2">Creation</td>
211 *         <td>Constructors</td>
212 *         <td>There is a form of the constructor that are called when the view
213 *         is created from code and a form that is called when the view is
214 *         inflated from a layout file. The second form should parse and apply
215 *         any attributes defined in the layout file.
216 *         </td>
217 *     </tr>
218 *     <tr>
219 *         <td><code>{@link #onFinishInflate()}</code></td>
220 *         <td>Called after a view and all of its children has been inflated
221 *         from XML.</td>
222 *     </tr>
223 *
224 *     <tr>
225 *         <td rowspan="3">Layout</td>
226 *         <td><code>{@link #onMeasure(int, int)}</code></td>
227 *         <td>Called to determine the size requirements for this view and all
228 *         of its children.
229 *         </td>
230 *     </tr>
231 *     <tr>
232 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
233 *         <td>Called when this view should assign a size and position to all
234 *         of its children.
235 *         </td>
236 *     </tr>
237 *     <tr>
238 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
239 *         <td>Called when the size of this view has changed.
240 *         </td>
241 *     </tr>
242 *
243 *     <tr>
244 *         <td>Drawing</td>
245 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
246 *         <td>Called when the view should render its content.
247 *         </td>
248 *     </tr>
249 *
250 *     <tr>
251 *         <td rowspan="4">Event processing</td>
252 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
253 *         <td>Called when a new hardware key event occurs.
254 *         </td>
255 *     </tr>
256 *     <tr>
257 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
258 *         <td>Called when a hardware key up event occurs.
259 *         </td>
260 *     </tr>
261 *     <tr>
262 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
263 *         <td>Called when a trackball motion event occurs.
264 *         </td>
265 *     </tr>
266 *     <tr>
267 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
268 *         <td>Called when a touch screen motion event occurs.
269 *         </td>
270 *     </tr>
271 *
272 *     <tr>
273 *         <td rowspan="2">Focus</td>
274 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
275 *         <td>Called when the view gains or loses focus.
276 *         </td>
277 *     </tr>
278 *
279 *     <tr>
280 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
281 *         <td>Called when the window containing the view gains or loses focus.
282 *         </td>
283 *     </tr>
284 *
285 *     <tr>
286 *         <td rowspan="3">Attaching</td>
287 *         <td><code>{@link #onAttachedToWindow()}</code></td>
288 *         <td>Called when the view is attached to a window.
289 *         </td>
290 *     </tr>
291 *
292 *     <tr>
293 *         <td><code>{@link #onDetachedFromWindow}</code></td>
294 *         <td>Called when the view is detached from its window.
295 *         </td>
296 *     </tr>
297 *
298 *     <tr>
299 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
300 *         <td>Called when the visibility of the window containing the view
301 *         has changed.
302 *         </td>
303 *     </tr>
304 *     </tbody>
305 *
306 * </table>
307 * </p>
308 *
309 * <a name="IDs"></a>
310 * <h3>IDs</h3>
311 * Views may have an integer id associated with them. These ids are typically
312 * assigned in the layout XML files, and are used to find specific views within
313 * the view tree. A common pattern is to:
314 * <ul>
315 * <li>Define a Button in the layout file and assign it a unique ID.
316 * <pre>
317 * &lt;Button
318 *     android:id="@+id/my_button"
319 *     android:layout_width="wrap_content"
320 *     android:layout_height="wrap_content"
321 *     android:text="@string/my_button_text"/&gt;
322 * </pre></li>
323 * <li>From the onCreate method of an Activity, find the Button
324 * <pre class="prettyprint">
325 *      Button myButton = findViewById(R.id.my_button);
326 * </pre></li>
327 * </ul>
328 * <p>
329 * View IDs need not be unique throughout the tree, but it is good practice to
330 * ensure that they are at least unique within the part of the tree you are
331 * searching.
332 * </p>
333 *
334 * <a name="Position"></a>
335 * <h3>Position</h3>
336 * <p>
337 * The geometry of a view is that of a rectangle. A view has a location,
338 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
339 * two dimensions, expressed as a width and a height. The unit for location
340 * and dimensions is the pixel.
341 * </p>
342 *
343 * <p>
344 * It is possible to retrieve the location of a view by invoking the methods
345 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
346 * coordinate of the rectangle representing the view. The latter returns the
347 * top, or Y, coordinate of the rectangle representing the view. These methods
348 * both return the location of the view relative to its parent. For instance,
349 * when getLeft() returns 20, that means the view is located 20 pixels to the
350 * right of the left edge of its direct parent.
351 * </p>
352 *
353 * <p>
354 * In addition, several convenience methods are offered to avoid unnecessary
355 * computations, namely {@link #getRight()} and {@link #getBottom()}.
356 * These methods return the coordinates of the right and bottom edges of the
357 * rectangle representing the view. For instance, calling {@link #getRight()}
358 * is similar to the following computation: <code>getLeft() + getWidth()</code>
359 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
360 * </p>
361 *
362 * <a name="SizePaddingMargins"></a>
363 * <h3>Size, padding and margins</h3>
364 * <p>
365 * The size of a view is expressed with a width and a height. A view actually
366 * possess two pairs of width and height values.
367 * </p>
368 *
369 * <p>
370 * The first pair is known as <em>measured width</em> and
371 * <em>measured height</em>. These dimensions define how big a view wants to be
372 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
373 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
374 * and {@link #getMeasuredHeight()}.
375 * </p>
376 *
377 * <p>
378 * The second pair is simply known as <em>width</em> and <em>height</em>, or
379 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
380 * dimensions define the actual size of the view on screen, at drawing time and
381 * after layout. These values may, but do not have to, be different from the
382 * measured width and height. The width and height can be obtained by calling
383 * {@link #getWidth()} and {@link #getHeight()}.
384 * </p>
385 *
386 * <p>
387 * To measure its dimensions, a view takes into account its padding. The padding
388 * is expressed in pixels for the left, top, right and bottom parts of the view.
389 * Padding can be used to offset the content of the view by a specific amount of
390 * pixels. For instance, a left padding of 2 will push the view's content by
391 * 2 pixels to the right of the left edge. Padding can be set using the
392 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
393 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
394 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
395 * {@link #getPaddingEnd()}.
396 * </p>
397 *
398 * <p>
399 * Even though a view can define a padding, it does not provide any support for
400 * margins. However, view groups provide such a support. Refer to
401 * {@link android.view.ViewGroup} and
402 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
403 * </p>
404 *
405 * <a name="Layout"></a>
406 * <h3>Layout</h3>
407 * <p>
408 * Layout is a two pass process: a measure pass and a layout pass. The measuring
409 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
410 * of the view tree. Each view pushes dimension specifications down the tree
411 * during the recursion. At the end of the measure pass, every view has stored
412 * its measurements. The second pass happens in
413 * {@link #layout(int,int,int,int)} and is also top-down. During
414 * this pass each parent is responsible for positioning all of its children
415 * using the sizes computed in the measure pass.
416 * </p>
417 *
418 * <p>
419 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
420 * {@link #getMeasuredHeight()} values must be set, along with those for all of
421 * that view's descendants. A view's measured width and measured height values
422 * must respect the constraints imposed by the view's parents. This guarantees
423 * that at the end of the measure pass, all parents accept all of their
424 * children's measurements. A parent view may call measure() more than once on
425 * its children. For example, the parent may measure each child once with
426 * unspecified dimensions to find out how big they want to be, then call
427 * measure() on them again with actual numbers if the sum of all the children's
428 * unconstrained sizes is too big or too small.
429 * </p>
430 *
431 * <p>
432 * The measure pass uses two classes to communicate dimensions. The
433 * {@link MeasureSpec} class is used by views to tell their parents how they
434 * want to be measured and positioned. The base LayoutParams class just
435 * describes how big the view wants to be for both width and height. For each
436 * dimension, it can specify one of:
437 * <ul>
438 * <li> an exact number
439 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
440 * (minus padding)
441 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
442 * enclose its content (plus padding).
443 * </ul>
444 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
445 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
446 * an X and Y value.
447 * </p>
448 *
449 * <p>
450 * MeasureSpecs are used to push requirements down the tree from parent to
451 * child. A MeasureSpec can be in one of three modes:
452 * <ul>
453 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
454 * of a child view. For example, a LinearLayout may call measure() on its child
455 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
456 * tall the child view wants to be given a width of 240 pixels.
457 * <li>EXACTLY: This is used by the parent to impose an exact size on the
458 * child. The child must use this size, and guarantee that all of its
459 * descendants will fit within this size.
460 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
461 * child. The child must guarantee that it and all of its descendants will fit
462 * within this size.
463 * </ul>
464 * </p>
465 *
466 * <p>
467 * To initiate a layout, call {@link #requestLayout}. This method is typically
468 * called by a view on itself when it believes that is can no longer fit within
469 * its current bounds.
470 * </p>
471 *
472 * <a name="Drawing"></a>
473 * <h3>Drawing</h3>
474 * <p>
475 * Drawing is handled by walking the tree and recording the drawing commands of
476 * any View that needs to update. After this, the drawing commands of the
477 * entire tree are issued to screen, clipped to the newly damaged area.
478 * </p>
479 *
480 * <p>
481 * The tree is largely recorded and drawn in order, with parents drawn before
482 * (i.e., behind) their children, with siblings drawn in the order they appear
483 * in the tree. If you set a background drawable for a View, then the View will
484 * draw it before calling back to its <code>onDraw()</code> method. The child
485 * drawing order can be overridden with
486 * {@link ViewGroup#setChildrenDrawingOrderEnabled(boolean) custom child drawing order}
487 * in a ViewGroup, and with {@link #setZ(float)} custom Z values} set on Views.
488 * </p>
489 *
490 * <p>
491 * To force a view to draw, call {@link #invalidate()}.
492 * </p>
493 *
494 * <a name="EventHandlingThreading"></a>
495 * <h3>Event Handling and Threading</h3>
496 * <p>
497 * The basic cycle of a view is as follows:
498 * <ol>
499 * <li>An event comes in and is dispatched to the appropriate view. The view
500 * handles the event and notifies any listeners.</li>
501 * <li>If in the course of processing the event, the view's bounds may need
502 * to be changed, the view will call {@link #requestLayout()}.</li>
503 * <li>Similarly, if in the course of processing the event the view's appearance
504 * may need to be changed, the view will call {@link #invalidate()}.</li>
505 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
506 * the framework will take care of measuring, laying out, and drawing the tree
507 * as appropriate.</li>
508 * </ol>
509 * </p>
510 *
511 * <p><em>Note: The entire view tree is single threaded. You must always be on
512 * the UI thread when calling any method on any view.</em>
513 * If you are doing work on other threads and want to update the state of a view
514 * from that thread, you should use a {@link Handler}.
515 * </p>
516 *
517 * <a name="FocusHandling"></a>
518 * <h3>Focus Handling</h3>
519 * <p>
520 * The framework will handle routine focus movement in response to user input.
521 * This includes changing the focus as views are removed or hidden, or as new
522 * views become available. Views indicate their willingness to take focus
523 * through the {@link #isFocusable} method. To change whether a view can take
524 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
525 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
526 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
527 * </p>
528 * <p>
529 * Focus movement is based on an algorithm which finds the nearest neighbor in a
530 * given direction. In rare cases, the default algorithm may not match the
531 * intended behavior of the developer. In these situations, you can provide
532 * explicit overrides by using these XML attributes in the layout file:
533 * <pre>
534 * nextFocusDown
535 * nextFocusLeft
536 * nextFocusRight
537 * nextFocusUp
538 * </pre>
539 * </p>
540 *
541 *
542 * <p>
543 * To get a particular view to take focus, call {@link #requestFocus()}.
544 * </p>
545 *
546 * <a name="TouchMode"></a>
547 * <h3>Touch Mode</h3>
548 * <p>
549 * When a user is navigating a user interface via directional keys such as a D-pad, it is
550 * necessary to give focus to actionable items such as buttons so the user can see
551 * what will take input.  If the device has touch capabilities, however, and the user
552 * begins interacting with the interface by touching it, it is no longer necessary to
553 * always highlight, or give focus to, a particular view.  This motivates a mode
554 * for interaction named 'touch mode'.
555 * </p>
556 * <p>
557 * For a touch capable device, once the user touches the screen, the device
558 * will enter touch mode.  From this point onward, only views for which
559 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
560 * Other views that are touchable, like buttons, will not take focus when touched; they will
561 * only fire the on click listeners.
562 * </p>
563 * <p>
564 * Any time a user hits a directional key, such as a D-pad direction, the view device will
565 * exit touch mode, and find a view to take focus, so that the user may resume interacting
566 * with the user interface without touching the screen again.
567 * </p>
568 * <p>
569 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
570 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
571 * </p>
572 *
573 * <a name="Scrolling"></a>
574 * <h3>Scrolling</h3>
575 * <p>
576 * The framework provides basic support for views that wish to internally
577 * scroll their content. This includes keeping track of the X and Y scroll
578 * offset as well as mechanisms for drawing scrollbars. See
579 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
580 * {@link #awakenScrollBars()} for more details.
581 * </p>
582 *
583 * <a name="Tags"></a>
584 * <h3>Tags</h3>
585 * <p>
586 * Unlike IDs, tags are not used to identify views. Tags are essentially an
587 * extra piece of information that can be associated with a view. They are most
588 * often used as a convenience to store data related to views in the views
589 * themselves rather than by putting them in a separate structure.
590 * </p>
591 * <p>
592 * Tags may be specified with character sequence values in layout XML as either
593 * a single tag using the {@link android.R.styleable#View_tag android:tag}
594 * attribute or multiple tags using the {@code <tag>} child element:
595 * <pre>
596 *     &ltView ...
597 *           android:tag="@string/mytag_value" /&gt;
598 *     &ltView ...&gt;
599 *         &lttag android:id="@+id/mytag"
600 *              android:value="@string/mytag_value" /&gt;
601 *     &lt/View>
602 * </pre>
603 * </p>
604 * <p>
605 * Tags may also be specified with arbitrary objects from code using
606 * {@link #setTag(Object)} or {@link #setTag(int, Object)}.
607 * </p>
608 *
609 * <a name="Themes"></a>
610 * <h3>Themes</h3>
611 * <p>
612 * By default, Views are created using the theme of the Context object supplied
613 * to their constructor; however, a different theme may be specified by using
614 * the {@link android.R.styleable#View_theme android:theme} attribute in layout
615 * XML or by passing a {@link ContextThemeWrapper} to the constructor from
616 * code.
617 * </p>
618 * <p>
619 * When the {@link android.R.styleable#View_theme android:theme} attribute is
620 * used in XML, the specified theme is applied on top of the inflation
621 * context's theme (see {@link LayoutInflater}) and used for the view itself as
622 * well as any child elements.
623 * </p>
624 * <p>
625 * In the following example, both views will be created using the Material dark
626 * color scheme; however, because an overlay theme is used which only defines a
627 * subset of attributes, the value of
628 * {@link android.R.styleable#Theme_colorAccent android:colorAccent} defined on
629 * the inflation context's theme (e.g. the Activity theme) will be preserved.
630 * <pre>
631 *     &ltLinearLayout
632 *             ...
633 *             android:theme="@android:theme/ThemeOverlay.Material.Dark"&gt;
634 *         &ltView ...&gt;
635 *     &lt/LinearLayout&gt;
636 * </pre>
637 * </p>
638 *
639 * <a name="Properties"></a>
640 * <h3>Properties</h3>
641 * <p>
642 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
643 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
644 * available both in the {@link Property} form as well as in similarly-named setter/getter
645 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
646 * be used to set persistent state associated with these rendering-related properties on the view.
647 * The properties and methods can also be used in conjunction with
648 * {@link android.animation.Animator Animator}-based animations, described more in the
649 * <a href="#Animation">Animation</a> section.
650 * </p>
651 *
652 * <a name="Animation"></a>
653 * <h3>Animation</h3>
654 * <p>
655 * Starting with Android 3.0, the preferred way of animating views is to use the
656 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
657 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
658 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
659 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
660 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
661 * makes animating these View properties particularly easy and efficient.
662 * </p>
663 * <p>
664 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
665 * You can attach an {@link Animation} object to a view using
666 * {@link #setAnimation(Animation)} or
667 * {@link #startAnimation(Animation)}. The animation can alter the scale,
668 * rotation, translation and alpha of a view over time. If the animation is
669 * attached to a view that has children, the animation will affect the entire
670 * subtree rooted by that node. When an animation is started, the framework will
671 * take care of redrawing the appropriate views until the animation completes.
672 * </p>
673 *
674 * <a name="Security"></a>
675 * <h3>Security</h3>
676 * <p>
677 * Sometimes it is essential that an application be able to verify that an action
678 * is being performed with the full knowledge and consent of the user, such as
679 * granting a permission request, making a purchase or clicking on an advertisement.
680 * Unfortunately, a malicious application could try to spoof the user into
681 * performing these actions, unaware, by concealing the intended purpose of the view.
682 * As a remedy, the framework offers a touch filtering mechanism that can be used to
683 * improve the security of views that provide access to sensitive functionality.
684 * </p><p>
685 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
686 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
687 * will discard touches that are received whenever the view's window is obscured by
688 * another visible window.  As a result, the view will not receive touches whenever a
689 * toast, dialog or other window appears above the view's window.
690 * </p><p>
691 * For more fine-grained control over security, consider overriding the
692 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
693 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
694 * </p>
695 *
696 * @attr ref android.R.styleable#View_alpha
697 * @attr ref android.R.styleable#View_background
698 * @attr ref android.R.styleable#View_clickable
699 * @attr ref android.R.styleable#View_contentDescription
700 * @attr ref android.R.styleable#View_drawingCacheQuality
701 * @attr ref android.R.styleable#View_duplicateParentState
702 * @attr ref android.R.styleable#View_id
703 * @attr ref android.R.styleable#View_requiresFadingEdge
704 * @attr ref android.R.styleable#View_fadeScrollbars
705 * @attr ref android.R.styleable#View_fadingEdgeLength
706 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
707 * @attr ref android.R.styleable#View_fitsSystemWindows
708 * @attr ref android.R.styleable#View_isScrollContainer
709 * @attr ref android.R.styleable#View_focusable
710 * @attr ref android.R.styleable#View_focusableInTouchMode
711 * @attr ref android.R.styleable#View_focusedByDefault
712 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
713 * @attr ref android.R.styleable#View_keepScreenOn
714 * @attr ref android.R.styleable#View_keyboardNavigationCluster
715 * @attr ref android.R.styleable#View_layerType
716 * @attr ref android.R.styleable#View_layoutDirection
717 * @attr ref android.R.styleable#View_longClickable
718 * @attr ref android.R.styleable#View_minHeight
719 * @attr ref android.R.styleable#View_minWidth
720 * @attr ref android.R.styleable#View_nextClusterForward
721 * @attr ref android.R.styleable#View_nextFocusDown
722 * @attr ref android.R.styleable#View_nextFocusLeft
723 * @attr ref android.R.styleable#View_nextFocusRight
724 * @attr ref android.R.styleable#View_nextFocusUp
725 * @attr ref android.R.styleable#View_onClick
726 * @attr ref android.R.styleable#View_padding
727 * @attr ref android.R.styleable#View_paddingBottom
728 * @attr ref android.R.styleable#View_paddingLeft
729 * @attr ref android.R.styleable#View_paddingRight
730 * @attr ref android.R.styleable#View_paddingTop
731 * @attr ref android.R.styleable#View_paddingStart
732 * @attr ref android.R.styleable#View_paddingEnd
733 * @attr ref android.R.styleable#View_saveEnabled
734 * @attr ref android.R.styleable#View_rotation
735 * @attr ref android.R.styleable#View_rotationX
736 * @attr ref android.R.styleable#View_rotationY
737 * @attr ref android.R.styleable#View_scaleX
738 * @attr ref android.R.styleable#View_scaleY
739 * @attr ref android.R.styleable#View_scrollX
740 * @attr ref android.R.styleable#View_scrollY
741 * @attr ref android.R.styleable#View_scrollbarSize
742 * @attr ref android.R.styleable#View_scrollbarStyle
743 * @attr ref android.R.styleable#View_scrollbars
744 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
745 * @attr ref android.R.styleable#View_scrollbarFadeDuration
746 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
747 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
748 * @attr ref android.R.styleable#View_scrollbarThumbVertical
749 * @attr ref android.R.styleable#View_scrollbarTrackVertical
750 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
751 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
752 * @attr ref android.R.styleable#View_stateListAnimator
753 * @attr ref android.R.styleable#View_transitionName
754 * @attr ref android.R.styleable#View_soundEffectsEnabled
755 * @attr ref android.R.styleable#View_tag
756 * @attr ref android.R.styleable#View_textAlignment
757 * @attr ref android.R.styleable#View_textDirection
758 * @attr ref android.R.styleable#View_transformPivotX
759 * @attr ref android.R.styleable#View_transformPivotY
760 * @attr ref android.R.styleable#View_translationX
761 * @attr ref android.R.styleable#View_translationY
762 * @attr ref android.R.styleable#View_translationZ
763 * @attr ref android.R.styleable#View_visibility
764 * @attr ref android.R.styleable#View_theme
765 *
766 * @see android.view.ViewGroup
767 */
768@UiThread
769public class View implements Drawable.Callback, KeyEvent.Callback,
770        AccessibilityEventSource {
771    private static final boolean DBG = false;
772
773    /** @hide */
774    public static boolean DEBUG_DRAW = false;
775
776    /**
777     * The logging tag used by this class with android.util.Log.
778     */
779    protected static final String VIEW_LOG_TAG = "View";
780
781    /**
782     * When set to true, apps will draw debugging information about their layouts.
783     *
784     * @hide
785     */
786    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
787
788    /**
789     * When set to true, this view will save its attribute data.
790     *
791     * @hide
792     */
793    public static boolean mDebugViewAttributes = false;
794
795    /**
796     * Used to mark a View that has no ID.
797     */
798    public static final int NO_ID = -1;
799
800    /**
801     * Last ID that is given to Views that are no part of activities.
802     *
803     * {@hide}
804     */
805    public static final int LAST_APP_ACCESSIBILITY_ID = Integer.MAX_VALUE / 2;
806
807    /**
808     * Attribute to find the autofilled highlight
809     *
810     * @see #getAutofilledDrawable()
811     */
812    private static final int[] AUTOFILL_HIGHLIGHT_ATTR =
813            new int[]{android.R.attr.autofilledHighlight};
814
815    /**
816     * Signals that compatibility booleans have been initialized according to
817     * target SDK versions.
818     */
819    private static boolean sCompatibilityDone = false;
820
821    /**
822     * Use the old (broken) way of building MeasureSpecs.
823     */
824    private static boolean sUseBrokenMakeMeasureSpec = false;
825
826    /**
827     * Always return a size of 0 for MeasureSpec values with a mode of UNSPECIFIED
828     */
829    static boolean sUseZeroUnspecifiedMeasureSpec = false;
830
831    /**
832     * Ignore any optimizations using the measure cache.
833     */
834    private static boolean sIgnoreMeasureCache = false;
835
836    /**
837     * Ignore an optimization that skips unnecessary EXACTLY layout passes.
838     */
839    private static boolean sAlwaysRemeasureExactly = false;
840
841    /**
842     * Relax constraints around whether setLayoutParams() must be called after
843     * modifying the layout params.
844     */
845    private static boolean sLayoutParamsAlwaysChanged = false;
846
847    /**
848     * Allow setForeground/setBackground to be called (and ignored) on a textureview,
849     * without throwing
850     */
851    static boolean sTextureViewIgnoresDrawableSetters = false;
852
853    /**
854     * Prior to N, some ViewGroups would not convert LayoutParams properly even though both extend
855     * MarginLayoutParams. For instance, converting LinearLayout.LayoutParams to
856     * RelativeLayout.LayoutParams would lose margin information. This is fixed on N but target API
857     * check is implemented for backwards compatibility.
858     *
859     * {@hide}
860     */
861    protected static boolean sPreserveMarginParamsInLayoutParamConversion;
862
863    /**
864     * Prior to N, when drag enters into child of a view that has already received an
865     * ACTION_DRAG_ENTERED event, the parent doesn't get a ACTION_DRAG_EXITED event.
866     * ACTION_DRAG_LOCATION and ACTION_DROP were delivered to the parent of a view that returned
867     * false from its event handler for these events.
868     * Starting from N, the parent will get ACTION_DRAG_EXITED event before the child gets its
869     * ACTION_DRAG_ENTERED. ACTION_DRAG_LOCATION and ACTION_DROP are never propagated to the parent.
870     * sCascadedDragDrop is true for pre-N apps for backwards compatibility implementation.
871     */
872    static boolean sCascadedDragDrop;
873
874    /**
875     * Prior to O, auto-focusable didn't exist and widgets such as ListView use hasFocusable
876     * to determine things like whether or not to permit item click events. We can't break
877     * apps that do this just because more things (clickable things) are now auto-focusable
878     * and they would get different results, so give old behavior to old apps.
879     */
880    static boolean sHasFocusableExcludeAutoFocusable;
881
882    /**
883     * Prior to O, auto-focusable didn't exist and views marked as clickable weren't implicitly
884     * made focusable by default. As a result, apps could (incorrectly) change the clickable
885     * setting of views off the UI thread. Now that clickable can effect the focusable state,
886     * changing the clickable attribute off the UI thread will cause an exception (since changing
887     * the focusable state checks). In order to prevent apps from crashing, we will handle this
888     * specific case and just not notify parents on new focusables resulting from marking views
889     * clickable from outside the UI thread.
890     */
891    private static boolean sAutoFocusableOffUIThreadWontNotifyParents;
892
893    /** @hide */
894    @IntDef({NOT_FOCUSABLE, FOCUSABLE, FOCUSABLE_AUTO})
895    @Retention(RetentionPolicy.SOURCE)
896    public @interface Focusable {}
897
898    /**
899     * This view does not want keystrokes.
900     * <p>
901     * Use with {@link #setFocusable(int)} and <a href="#attr_android:focusable">{@code
902     * android:focusable}.
903     */
904    public static final int NOT_FOCUSABLE = 0x00000000;
905
906    /**
907     * This view wants keystrokes.
908     * <p>
909     * Use with {@link #setFocusable(int)} and <a href="#attr_android:focusable">{@code
910     * android:focusable}.
911     */
912    public static final int FOCUSABLE = 0x00000001;
913
914    /**
915     * This view determines focusability automatically. This is the default.
916     * <p>
917     * Use with {@link #setFocusable(int)} and <a href="#attr_android:focusable">{@code
918     * android:focusable}.
919     */
920    public static final int FOCUSABLE_AUTO = 0x00000010;
921
922    /**
923     * Mask for use with setFlags indicating bits used for focus.
924     */
925    private static final int FOCUSABLE_MASK = 0x00000011;
926
927    /**
928     * This view will adjust its padding to fit sytem windows (e.g. status bar)
929     */
930    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
931
932    /** @hide */
933    @IntDef({VISIBLE, INVISIBLE, GONE})
934    @Retention(RetentionPolicy.SOURCE)
935    public @interface Visibility {}
936
937    /**
938     * This view is visible.
939     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
940     * android:visibility}.
941     */
942    public static final int VISIBLE = 0x00000000;
943
944    /**
945     * This view is invisible, but it still takes up space for layout purposes.
946     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
947     * android:visibility}.
948     */
949    public static final int INVISIBLE = 0x00000004;
950
951    /**
952     * This view is invisible, and it doesn't take any space for layout
953     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
954     * android:visibility}.
955     */
956    public static final int GONE = 0x00000008;
957
958    /**
959     * Mask for use with setFlags indicating bits used for visibility.
960     * {@hide}
961     */
962    static final int VISIBILITY_MASK = 0x0000000C;
963
964    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
965
966    /**
967     * This view contains an email address.
968     *
969     * Use with {@link #setAutofillHints(String[])}, or set "{@value #AUTOFILL_HINT_EMAIL_ADDRESS}"
970     * to <a href="#attr_android:autofillHint"> {@code android:autofillHint}.
971     */
972    public static final String AUTOFILL_HINT_EMAIL_ADDRESS = "emailAddress";
973
974    /**
975     * The view contains a real name.
976     *
977     * Use with {@link #setAutofillHints(String[])}, or set "{@value #AUTOFILL_HINT_NAME}" to
978     * <a href="#attr_android:autofillHint"> {@code android:autofillHint}.
979     */
980    public static final String AUTOFILL_HINT_NAME = "name";
981
982    /**
983     * The view contains a user name.
984     *
985     * Use with {@link #setAutofillHints(String[])}, or set "{@value #AUTOFILL_HINT_USERNAME}" to
986     * <a href="#attr_android:autofillHint"> {@code android:autofillHint}.
987     */
988    public static final String AUTOFILL_HINT_USERNAME = "username";
989
990    /**
991     * The view contains a password.
992     *
993     * Use with {@link #setAutofillHints(String[])}, or set "{@value #AUTOFILL_HINT_PASSWORD}" to
994     * <a href="#attr_android:autofillHint"> {@code android:autofillHint}.
995     */
996    public static final String AUTOFILL_HINT_PASSWORD = "password";
997
998    /**
999     * The view contains a phone number.
1000     *
1001     * Use with {@link #setAutofillHints(String[])}, or set "{@value #AUTOFILL_HINT_PHONE}" to
1002     * <a href="#attr_android:autofillHint"> {@code android:autofillHint}.
1003     */
1004    public static final String AUTOFILL_HINT_PHONE = "phone";
1005
1006    /**
1007     * The view contains a postal address.
1008     *
1009     * Use with {@link #setAutofillHints(String[])}, or set "{@value #AUTOFILL_HINT_POSTAL_ADDRESS}"
1010     * to <a href="#attr_android:autofillHint"> {@code android:autofillHint}.
1011     */
1012    public static final String AUTOFILL_HINT_POSTAL_ADDRESS = "postalAddress";
1013
1014    /**
1015     * The view contains a postal code.
1016     *
1017     * Use with {@link #setAutofillHints(String[])}, or set "{@value #AUTOFILL_HINT_POSTAL_CODE}" to
1018     * <a href="#attr_android:autofillHint"> {@code android:autofillHint}.
1019     */
1020    public static final String AUTOFILL_HINT_POSTAL_CODE = "postalCode";
1021
1022    /**
1023     * The view contains a credit card number.
1024     *
1025     * Use with {@link #setAutofillHints(String[])}, or set "{@value
1026     * #AUTOFILL_HINT_CREDIT_CARD_NUMBER}" to <a href="#attr_android:autofillHint"> {@code
1027     * android:autofillHint}.
1028     */
1029    public static final String AUTOFILL_HINT_CREDIT_CARD_NUMBER = "creditCardNumber";
1030
1031    /**
1032     * The view contains a credit card security code.
1033     *
1034     * Use with {@link #setAutofillHints(String[])}, or set "{@value
1035     * #AUTOFILL_HINT_CREDIT_CARD_SECURITY_CODE}" to <a href="#attr_android:autofillHint"> {@code
1036     * android:autofillHint}.
1037     */
1038    public static final String AUTOFILL_HINT_CREDIT_CARD_SECURITY_CODE = "creditCardSecurityCode";
1039
1040    /**
1041     * The view contains a credit card expiration date.
1042     *
1043     * Use with {@link #setAutofillHints(String[])}, or set "{@value
1044     * #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DATE}" to <a href="#attr_android:autofillHint"> {@code
1045     * android:autofillHint}.
1046     */
1047    public static final String AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DATE =
1048            "creditCardExpirationDate";
1049
1050    /**
1051     * The view contains the month a credit card expires.
1052     *
1053     * Use with {@link #setAutofillHints(String[])}, or set "{@value
1054     * #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_MONTH}" to <a href="#attr_android:autofillHint"> {@code
1055     * android:autofillHint}.
1056     */
1057    public static final String AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_MONTH =
1058            "creditCardExpirationMonth";
1059
1060    /**
1061     * The view contains the year a credit card expires.
1062     *
1063     * Use with {@link #setAutofillHints(String[])}, or set "{@value
1064     * #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_YEAR}" to <a href="#attr_android:autofillHint"> {@code
1065     * android:autofillHint}.
1066     */
1067    public static final String AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_YEAR =
1068            "creditCardExpirationYear";
1069
1070    /**
1071     * The view contains the day a credit card expires.
1072     *
1073     * Use with {@link #setAutofillHints(String[])}, or set "{@value
1074     * #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DAY}" to <a href="#attr_android:autofillHint"> {@code
1075     * android:autofillHint}.
1076     */
1077    public static final String AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DAY = "creditCardExpirationDay";
1078
1079    /**
1080     * Hints for the autofill services that describes the content of the view.
1081     */
1082    private @Nullable String[] mAutofillHints;
1083
1084    /**
1085     * Autofill id, lazily created on calls to {@link #getAutofillId()}.
1086     */
1087    private AutofillId mAutofillId;
1088
1089    /** @hide */
1090    @IntDef({
1091            AUTOFILL_TYPE_NONE,
1092            AUTOFILL_TYPE_TEXT,
1093            AUTOFILL_TYPE_TOGGLE,
1094            AUTOFILL_TYPE_LIST,
1095            AUTOFILL_TYPE_DATE
1096    })
1097    @Retention(RetentionPolicy.SOURCE)
1098    public @interface AutofillType {}
1099
1100    /**
1101     * Autofill type for views that cannot be autofilled.
1102     */
1103    public static final int AUTOFILL_TYPE_NONE = 0;
1104
1105    /**
1106     * Autofill type for a text field, which is filled by a {@link CharSequence}.
1107     *
1108     * <p>{@link AutofillValue} instances for autofilling a {@link View} can be obtained through
1109     * {@link AutofillValue#forText(CharSequence)}, and the value passed to autofill a
1110     * {@link View} can be fetched through {@link AutofillValue#getTextValue()}.
1111     */
1112    public static final int AUTOFILL_TYPE_TEXT = 1;
1113
1114    /**
1115     * Autofill type for a togglable field, which is filled by a {@code boolean}.
1116     *
1117     * <p>{@link AutofillValue} instances for autofilling a {@link View} can be obtained through
1118     * {@link AutofillValue#forToggle(boolean)}, and the value passed to autofill a
1119     * {@link View} can be fetched through {@link AutofillValue#getToggleValue()}.
1120     */
1121    public static final int AUTOFILL_TYPE_TOGGLE = 2;
1122
1123    /**
1124     * Autofill type for a selection list field, which is filled by an {@code int}
1125     * representing the element index inside the list (starting at {@code 0}).
1126     *
1127     * <p>{@link AutofillValue} instances for autofilling a {@link View} can be obtained through
1128     * {@link AutofillValue#forList(int)}, and the value passed to autofill a
1129     * {@link View} can be fetched through {@link AutofillValue#getListValue()}.
1130     *
1131     * <p>The available options in the selection list are typically provided by
1132     * {@link android.app.assist.AssistStructure.ViewNode#getAutofillOptions()}.
1133     */
1134    public static final int AUTOFILL_TYPE_LIST = 3;
1135
1136
1137    /**
1138     * Autofill type for a field that contains a date, which is represented by a long representing
1139     * the number of milliseconds since the standard base time known as "the epoch", namely
1140     * January 1, 1970, 00:00:00 GMT (see {@link java.util.Date#getTime()}.
1141     *
1142     * <p>{@link AutofillValue} instances for autofilling a {@link View} can be obtained through
1143     * {@link AutofillValue#forDate(long)}, and the values passed to
1144     * autofill a {@link View} can be fetched through {@link AutofillValue#getDateValue()}.
1145     */
1146    public static final int AUTOFILL_TYPE_DATE = 4;
1147
1148    /** @hide */
1149    @IntDef({
1150            IMPORTANT_FOR_AUTOFILL_AUTO,
1151            IMPORTANT_FOR_AUTOFILL_YES,
1152            IMPORTANT_FOR_AUTOFILL_NO,
1153            IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS,
1154            IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS
1155    })
1156    @Retention(RetentionPolicy.SOURCE)
1157    public @interface AutofillImportance {}
1158
1159    /**
1160     * Automatically determine whether a view is important for autofill.
1161     */
1162    public static final int IMPORTANT_FOR_AUTOFILL_AUTO = 0x0;
1163
1164    /**
1165     * The view is important for autofill, and its children (if any) will be traversed.
1166     */
1167    public static final int IMPORTANT_FOR_AUTOFILL_YES = 0x1;
1168
1169    /**
1170     * The view is not important for autofill, but its children (if any) will be traversed.
1171     */
1172    public static final int IMPORTANT_FOR_AUTOFILL_NO = 0x2;
1173
1174    /**
1175     * The view is important for autofill, but its children (if any) will not be traversed.
1176     */
1177    public static final int IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS = 0x4;
1178
1179    /**
1180     * The view is not important for autofill, and its children (if any) will not be traversed.
1181     */
1182    public static final int IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS = 0x8;
1183
1184    /** @hide */
1185    @IntDef(
1186            flag = true,
1187            value = {AUTOFILL_FLAG_INCLUDE_NOT_IMPORTANT_VIEWS})
1188    @Retention(RetentionPolicy.SOURCE)
1189    public @interface AutofillFlags {}
1190
1191    /**
1192     * Flag requesting you to add views not-important for autofill to the assist data.
1193     */
1194    public static final int AUTOFILL_FLAG_INCLUDE_NOT_IMPORTANT_VIEWS = 0x1;
1195
1196    /**
1197     * This view is enabled. Interpretation varies by subclass.
1198     * Use with ENABLED_MASK when calling setFlags.
1199     * {@hide}
1200     */
1201    static final int ENABLED = 0x00000000;
1202
1203    /**
1204     * This view is disabled. Interpretation varies by subclass.
1205     * Use with ENABLED_MASK when calling setFlags.
1206     * {@hide}
1207     */
1208    static final int DISABLED = 0x00000020;
1209
1210   /**
1211    * Mask for use with setFlags indicating bits used for indicating whether
1212    * this view is enabled
1213    * {@hide}
1214    */
1215    static final int ENABLED_MASK = 0x00000020;
1216
1217    /**
1218     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
1219     * called and further optimizations will be performed. It is okay to have
1220     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
1221     * {@hide}
1222     */
1223    static final int WILL_NOT_DRAW = 0x00000080;
1224
1225    /**
1226     * Mask for use with setFlags indicating bits used for indicating whether
1227     * this view is will draw
1228     * {@hide}
1229     */
1230    static final int DRAW_MASK = 0x00000080;
1231
1232    /**
1233     * <p>This view doesn't show scrollbars.</p>
1234     * {@hide}
1235     */
1236    static final int SCROLLBARS_NONE = 0x00000000;
1237
1238    /**
1239     * <p>This view shows horizontal scrollbars.</p>
1240     * {@hide}
1241     */
1242    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
1243
1244    /**
1245     * <p>This view shows vertical scrollbars.</p>
1246     * {@hide}
1247     */
1248    static final int SCROLLBARS_VERTICAL = 0x00000200;
1249
1250    /**
1251     * <p>Mask for use with setFlags indicating bits used for indicating which
1252     * scrollbars are enabled.</p>
1253     * {@hide}
1254     */
1255    static final int SCROLLBARS_MASK = 0x00000300;
1256
1257    /**
1258     * Indicates that the view should filter touches when its window is obscured.
1259     * Refer to the class comments for more information about this security feature.
1260     * {@hide}
1261     */
1262    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
1263
1264    /**
1265     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
1266     * that they are optional and should be skipped if the window has
1267     * requested system UI flags that ignore those insets for layout.
1268     */
1269    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
1270
1271    /**
1272     * <p>This view doesn't show fading edges.</p>
1273     * {@hide}
1274     */
1275    static final int FADING_EDGE_NONE = 0x00000000;
1276
1277    /**
1278     * <p>This view shows horizontal fading edges.</p>
1279     * {@hide}
1280     */
1281    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
1282
1283    /**
1284     * <p>This view shows vertical fading edges.</p>
1285     * {@hide}
1286     */
1287    static final int FADING_EDGE_VERTICAL = 0x00002000;
1288
1289    /**
1290     * <p>Mask for use with setFlags indicating bits used for indicating which
1291     * fading edges are enabled.</p>
1292     * {@hide}
1293     */
1294    static final int FADING_EDGE_MASK = 0x00003000;
1295
1296    /**
1297     * <p>Indicates this view can be clicked. When clickable, a View reacts
1298     * to clicks by notifying the OnClickListener.<p>
1299     * {@hide}
1300     */
1301    static final int CLICKABLE = 0x00004000;
1302
1303    /**
1304     * <p>Indicates this view is caching its drawing into a bitmap.</p>
1305     * {@hide}
1306     */
1307    static final int DRAWING_CACHE_ENABLED = 0x00008000;
1308
1309    /**
1310     * <p>Indicates that no icicle should be saved for this view.<p>
1311     * {@hide}
1312     */
1313    static final int SAVE_DISABLED = 0x000010000;
1314
1315    /**
1316     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
1317     * property.</p>
1318     * {@hide}
1319     */
1320    static final int SAVE_DISABLED_MASK = 0x000010000;
1321
1322    /**
1323     * <p>Indicates that no drawing cache should ever be created for this view.<p>
1324     * {@hide}
1325     */
1326    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
1327
1328    /**
1329     * <p>Indicates this view can take / keep focus when int touch mode.</p>
1330     * {@hide}
1331     */
1332    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
1333
1334    /** @hide */
1335    @Retention(RetentionPolicy.SOURCE)
1336    @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO})
1337    public @interface DrawingCacheQuality {}
1338
1339    /**
1340     * <p>Enables low quality mode for the drawing cache.</p>
1341     */
1342    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
1343
1344    /**
1345     * <p>Enables high quality mode for the drawing cache.</p>
1346     */
1347    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
1348
1349    /**
1350     * <p>Enables automatic quality mode for the drawing cache.</p>
1351     */
1352    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
1353
1354    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
1355            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
1356    };
1357
1358    /**
1359     * <p>Mask for use with setFlags indicating bits used for the cache
1360     * quality property.</p>
1361     * {@hide}
1362     */
1363    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
1364
1365    /**
1366     * <p>
1367     * Indicates this view can be long clicked. When long clickable, a View
1368     * reacts to long clicks by notifying the OnLongClickListener or showing a
1369     * context menu.
1370     * </p>
1371     * {@hide}
1372     */
1373    static final int LONG_CLICKABLE = 0x00200000;
1374
1375    /**
1376     * <p>Indicates that this view gets its drawable states from its direct parent
1377     * and ignores its original internal states.</p>
1378     *
1379     * @hide
1380     */
1381    static final int DUPLICATE_PARENT_STATE = 0x00400000;
1382
1383    /**
1384     * <p>
1385     * Indicates this view can be context clicked. When context clickable, a View reacts to a
1386     * context click (e.g. a primary stylus button press or right mouse click) by notifying the
1387     * OnContextClickListener.
1388     * </p>
1389     * {@hide}
1390     */
1391    static final int CONTEXT_CLICKABLE = 0x00800000;
1392
1393
1394    /** @hide */
1395    @IntDef({
1396        SCROLLBARS_INSIDE_OVERLAY,
1397        SCROLLBARS_INSIDE_INSET,
1398        SCROLLBARS_OUTSIDE_OVERLAY,
1399        SCROLLBARS_OUTSIDE_INSET
1400    })
1401    @Retention(RetentionPolicy.SOURCE)
1402    public @interface ScrollBarStyle {}
1403
1404    /**
1405     * The scrollbar style to display the scrollbars inside the content area,
1406     * without increasing the padding. The scrollbars will be overlaid with
1407     * translucency on the view's content.
1408     */
1409    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
1410
1411    /**
1412     * The scrollbar style to display the scrollbars inside the padded area,
1413     * increasing the padding of the view. The scrollbars will not overlap the
1414     * content area of the view.
1415     */
1416    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
1417
1418    /**
1419     * The scrollbar style to display the scrollbars at the edge of the view,
1420     * without increasing the padding. The scrollbars will be overlaid with
1421     * translucency.
1422     */
1423    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
1424
1425    /**
1426     * The scrollbar style to display the scrollbars at the edge of the view,
1427     * increasing the padding of the view. The scrollbars will only overlap the
1428     * background, if any.
1429     */
1430    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
1431
1432    /**
1433     * Mask to check if the scrollbar style is overlay or inset.
1434     * {@hide}
1435     */
1436    static final int SCROLLBARS_INSET_MASK = 0x01000000;
1437
1438    /**
1439     * Mask to check if the scrollbar style is inside or outside.
1440     * {@hide}
1441     */
1442    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
1443
1444    /**
1445     * Mask for scrollbar style.
1446     * {@hide}
1447     */
1448    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
1449
1450    /**
1451     * View flag indicating that the screen should remain on while the
1452     * window containing this view is visible to the user.  This effectively
1453     * takes care of automatically setting the WindowManager's
1454     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
1455     */
1456    public static final int KEEP_SCREEN_ON = 0x04000000;
1457
1458    /**
1459     * View flag indicating whether this view should have sound effects enabled
1460     * for events such as clicking and touching.
1461     */
1462    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
1463
1464    /**
1465     * View flag indicating whether this view should have haptic feedback
1466     * enabled for events such as long presses.
1467     */
1468    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
1469
1470    /**
1471     * <p>Indicates that the view hierarchy should stop saving state when
1472     * it reaches this view.  If state saving is initiated immediately at
1473     * the view, it will be allowed.
1474     * {@hide}
1475     */
1476    static final int PARENT_SAVE_DISABLED = 0x20000000;
1477
1478    /**
1479     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1480     * {@hide}
1481     */
1482    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1483
1484    private static Paint sDebugPaint;
1485
1486    /**
1487     * <p>Indicates this view can display a tooltip on hover or long press.</p>
1488     * {@hide}
1489     */
1490    static final int TOOLTIP = 0x40000000;
1491
1492    /** @hide */
1493    @IntDef(flag = true,
1494            value = {
1495                FOCUSABLES_ALL,
1496                FOCUSABLES_TOUCH_MODE
1497            })
1498    @Retention(RetentionPolicy.SOURCE)
1499    public @interface FocusableMode {}
1500
1501    /**
1502     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1503     * should add all focusable Views regardless if they are focusable in touch mode.
1504     */
1505    public static final int FOCUSABLES_ALL = 0x00000000;
1506
1507    /**
1508     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1509     * should add only Views focusable in touch mode.
1510     */
1511    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1512
1513    /** @hide */
1514    @IntDef({
1515            FOCUS_BACKWARD,
1516            FOCUS_FORWARD,
1517            FOCUS_LEFT,
1518            FOCUS_UP,
1519            FOCUS_RIGHT,
1520            FOCUS_DOWN
1521    })
1522    @Retention(RetentionPolicy.SOURCE)
1523    public @interface FocusDirection {}
1524
1525    /** @hide */
1526    @IntDef({
1527            FOCUS_LEFT,
1528            FOCUS_UP,
1529            FOCUS_RIGHT,
1530            FOCUS_DOWN
1531    })
1532    @Retention(RetentionPolicy.SOURCE)
1533    public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward
1534
1535    /**
1536     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1537     * item.
1538     */
1539    public static final int FOCUS_BACKWARD = 0x00000001;
1540
1541    /**
1542     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1543     * item.
1544     */
1545    public static final int FOCUS_FORWARD = 0x00000002;
1546
1547    /**
1548     * Use with {@link #focusSearch(int)}. Move focus to the left.
1549     */
1550    public static final int FOCUS_LEFT = 0x00000011;
1551
1552    /**
1553     * Use with {@link #focusSearch(int)}. Move focus up.
1554     */
1555    public static final int FOCUS_UP = 0x00000021;
1556
1557    /**
1558     * Use with {@link #focusSearch(int)}. Move focus to the right.
1559     */
1560    public static final int FOCUS_RIGHT = 0x00000042;
1561
1562    /**
1563     * Use with {@link #focusSearch(int)}. Move focus down.
1564     */
1565    public static final int FOCUS_DOWN = 0x00000082;
1566
1567    /**
1568     * Bits of {@link #getMeasuredWidthAndState()} and
1569     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1570     */
1571    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1572
1573    /**
1574     * Bits of {@link #getMeasuredWidthAndState()} and
1575     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1576     */
1577    public static final int MEASURED_STATE_MASK = 0xff000000;
1578
1579    /**
1580     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1581     * for functions that combine both width and height into a single int,
1582     * such as {@link #getMeasuredState()} and the childState argument of
1583     * {@link #resolveSizeAndState(int, int, int)}.
1584     */
1585    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1586
1587    /**
1588     * Bit of {@link #getMeasuredWidthAndState()} and
1589     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1590     * is smaller that the space the view would like to have.
1591     */
1592    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1593
1594    /**
1595     * Base View state sets
1596     */
1597    // Singles
1598    /**
1599     * Indicates the view has no states set. States are used with
1600     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1601     * view depending on its state.
1602     *
1603     * @see android.graphics.drawable.Drawable
1604     * @see #getDrawableState()
1605     */
1606    protected static final int[] EMPTY_STATE_SET;
1607    /**
1608     * Indicates the view is enabled. States are used with
1609     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1610     * view depending on its state.
1611     *
1612     * @see android.graphics.drawable.Drawable
1613     * @see #getDrawableState()
1614     */
1615    protected static final int[] ENABLED_STATE_SET;
1616    /**
1617     * Indicates the view is focused. States are used with
1618     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1619     * view depending on its state.
1620     *
1621     * @see android.graphics.drawable.Drawable
1622     * @see #getDrawableState()
1623     */
1624    protected static final int[] FOCUSED_STATE_SET;
1625    /**
1626     * Indicates the view is selected. States are used with
1627     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1628     * view depending on its state.
1629     *
1630     * @see android.graphics.drawable.Drawable
1631     * @see #getDrawableState()
1632     */
1633    protected static final int[] SELECTED_STATE_SET;
1634    /**
1635     * Indicates the view is pressed. States are used with
1636     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1637     * view depending on its state.
1638     *
1639     * @see android.graphics.drawable.Drawable
1640     * @see #getDrawableState()
1641     */
1642    protected static final int[] PRESSED_STATE_SET;
1643    /**
1644     * Indicates the view's window has focus. States are used with
1645     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1646     * view depending on its state.
1647     *
1648     * @see android.graphics.drawable.Drawable
1649     * @see #getDrawableState()
1650     */
1651    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1652    // Doubles
1653    /**
1654     * Indicates the view is enabled and has the focus.
1655     *
1656     * @see #ENABLED_STATE_SET
1657     * @see #FOCUSED_STATE_SET
1658     */
1659    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1660    /**
1661     * Indicates the view is enabled and selected.
1662     *
1663     * @see #ENABLED_STATE_SET
1664     * @see #SELECTED_STATE_SET
1665     */
1666    protected static final int[] ENABLED_SELECTED_STATE_SET;
1667    /**
1668     * Indicates the view is enabled and that its window has focus.
1669     *
1670     * @see #ENABLED_STATE_SET
1671     * @see #WINDOW_FOCUSED_STATE_SET
1672     */
1673    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1674    /**
1675     * Indicates the view is focused and selected.
1676     *
1677     * @see #FOCUSED_STATE_SET
1678     * @see #SELECTED_STATE_SET
1679     */
1680    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1681    /**
1682     * Indicates the view has the focus and that its window has the focus.
1683     *
1684     * @see #FOCUSED_STATE_SET
1685     * @see #WINDOW_FOCUSED_STATE_SET
1686     */
1687    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1688    /**
1689     * Indicates the view is selected and that its window has the focus.
1690     *
1691     * @see #SELECTED_STATE_SET
1692     * @see #WINDOW_FOCUSED_STATE_SET
1693     */
1694    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1695    // Triples
1696    /**
1697     * Indicates the view is enabled, focused and selected.
1698     *
1699     * @see #ENABLED_STATE_SET
1700     * @see #FOCUSED_STATE_SET
1701     * @see #SELECTED_STATE_SET
1702     */
1703    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1704    /**
1705     * Indicates the view is enabled, focused and its window has the focus.
1706     *
1707     * @see #ENABLED_STATE_SET
1708     * @see #FOCUSED_STATE_SET
1709     * @see #WINDOW_FOCUSED_STATE_SET
1710     */
1711    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1712    /**
1713     * Indicates the view is enabled, selected and its window has the focus.
1714     *
1715     * @see #ENABLED_STATE_SET
1716     * @see #SELECTED_STATE_SET
1717     * @see #WINDOW_FOCUSED_STATE_SET
1718     */
1719    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1720    /**
1721     * Indicates the view is focused, selected and its window has the focus.
1722     *
1723     * @see #FOCUSED_STATE_SET
1724     * @see #SELECTED_STATE_SET
1725     * @see #WINDOW_FOCUSED_STATE_SET
1726     */
1727    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1728    /**
1729     * Indicates the view is enabled, focused, selected and its window
1730     * has the focus.
1731     *
1732     * @see #ENABLED_STATE_SET
1733     * @see #FOCUSED_STATE_SET
1734     * @see #SELECTED_STATE_SET
1735     * @see #WINDOW_FOCUSED_STATE_SET
1736     */
1737    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1738    /**
1739     * Indicates the view is pressed and its window has the focus.
1740     *
1741     * @see #PRESSED_STATE_SET
1742     * @see #WINDOW_FOCUSED_STATE_SET
1743     */
1744    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1745    /**
1746     * Indicates the view is pressed and selected.
1747     *
1748     * @see #PRESSED_STATE_SET
1749     * @see #SELECTED_STATE_SET
1750     */
1751    protected static final int[] PRESSED_SELECTED_STATE_SET;
1752    /**
1753     * Indicates the view is pressed, selected and its window has the focus.
1754     *
1755     * @see #PRESSED_STATE_SET
1756     * @see #SELECTED_STATE_SET
1757     * @see #WINDOW_FOCUSED_STATE_SET
1758     */
1759    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1760    /**
1761     * Indicates the view is pressed and focused.
1762     *
1763     * @see #PRESSED_STATE_SET
1764     * @see #FOCUSED_STATE_SET
1765     */
1766    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1767    /**
1768     * Indicates the view is pressed, focused and its window has the focus.
1769     *
1770     * @see #PRESSED_STATE_SET
1771     * @see #FOCUSED_STATE_SET
1772     * @see #WINDOW_FOCUSED_STATE_SET
1773     */
1774    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1775    /**
1776     * Indicates the view is pressed, focused and selected.
1777     *
1778     * @see #PRESSED_STATE_SET
1779     * @see #SELECTED_STATE_SET
1780     * @see #FOCUSED_STATE_SET
1781     */
1782    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1783    /**
1784     * Indicates the view is pressed, focused, selected and its window has the focus.
1785     *
1786     * @see #PRESSED_STATE_SET
1787     * @see #FOCUSED_STATE_SET
1788     * @see #SELECTED_STATE_SET
1789     * @see #WINDOW_FOCUSED_STATE_SET
1790     */
1791    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1792    /**
1793     * Indicates the view is pressed and enabled.
1794     *
1795     * @see #PRESSED_STATE_SET
1796     * @see #ENABLED_STATE_SET
1797     */
1798    protected static final int[] PRESSED_ENABLED_STATE_SET;
1799    /**
1800     * Indicates the view is pressed, enabled and its window has the focus.
1801     *
1802     * @see #PRESSED_STATE_SET
1803     * @see #ENABLED_STATE_SET
1804     * @see #WINDOW_FOCUSED_STATE_SET
1805     */
1806    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1807    /**
1808     * Indicates the view is pressed, enabled and selected.
1809     *
1810     * @see #PRESSED_STATE_SET
1811     * @see #ENABLED_STATE_SET
1812     * @see #SELECTED_STATE_SET
1813     */
1814    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1815    /**
1816     * Indicates the view is pressed, enabled, selected and its window has the
1817     * focus.
1818     *
1819     * @see #PRESSED_STATE_SET
1820     * @see #ENABLED_STATE_SET
1821     * @see #SELECTED_STATE_SET
1822     * @see #WINDOW_FOCUSED_STATE_SET
1823     */
1824    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1825    /**
1826     * Indicates the view is pressed, enabled and focused.
1827     *
1828     * @see #PRESSED_STATE_SET
1829     * @see #ENABLED_STATE_SET
1830     * @see #FOCUSED_STATE_SET
1831     */
1832    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1833    /**
1834     * Indicates the view is pressed, enabled, focused and its window has the
1835     * focus.
1836     *
1837     * @see #PRESSED_STATE_SET
1838     * @see #ENABLED_STATE_SET
1839     * @see #FOCUSED_STATE_SET
1840     * @see #WINDOW_FOCUSED_STATE_SET
1841     */
1842    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1843    /**
1844     * Indicates the view is pressed, enabled, focused and selected.
1845     *
1846     * @see #PRESSED_STATE_SET
1847     * @see #ENABLED_STATE_SET
1848     * @see #SELECTED_STATE_SET
1849     * @see #FOCUSED_STATE_SET
1850     */
1851    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1852    /**
1853     * Indicates the view is pressed, enabled, focused, selected and its window
1854     * has the focus.
1855     *
1856     * @see #PRESSED_STATE_SET
1857     * @see #ENABLED_STATE_SET
1858     * @see #SELECTED_STATE_SET
1859     * @see #FOCUSED_STATE_SET
1860     * @see #WINDOW_FOCUSED_STATE_SET
1861     */
1862    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1863
1864    static {
1865        EMPTY_STATE_SET = StateSet.get(0);
1866
1867        WINDOW_FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_WINDOW_FOCUSED);
1868
1869        SELECTED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_SELECTED);
1870        SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1871                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED);
1872
1873        FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_FOCUSED);
1874        FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1875                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED);
1876        FOCUSED_SELECTED_STATE_SET = StateSet.get(
1877                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED);
1878        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1879                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1880                        | StateSet.VIEW_STATE_FOCUSED);
1881
1882        ENABLED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_ENABLED);
1883        ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1884                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED);
1885        ENABLED_SELECTED_STATE_SET = StateSet.get(
1886                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED);
1887        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1888                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1889                        | StateSet.VIEW_STATE_ENABLED);
1890        ENABLED_FOCUSED_STATE_SET = StateSet.get(
1891                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED);
1892        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1893                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1894                        | StateSet.VIEW_STATE_ENABLED);
1895        ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1896                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1897                        | StateSet.VIEW_STATE_ENABLED);
1898        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1899                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1900                        | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED);
1901
1902        PRESSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_PRESSED);
1903        PRESSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1904                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1905        PRESSED_SELECTED_STATE_SET = StateSet.get(
1906                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_PRESSED);
1907        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1908                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1909                        | StateSet.VIEW_STATE_PRESSED);
1910        PRESSED_FOCUSED_STATE_SET = StateSet.get(
1911                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1912        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1913                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1914                        | StateSet.VIEW_STATE_PRESSED);
1915        PRESSED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1916                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1917                        | StateSet.VIEW_STATE_PRESSED);
1918        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1919                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1920                        | StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1921        PRESSED_ENABLED_STATE_SET = StateSet.get(
1922                StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1923        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1924                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED
1925                        | StateSet.VIEW_STATE_PRESSED);
1926        PRESSED_ENABLED_SELECTED_STATE_SET = StateSet.get(
1927                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED
1928                        | StateSet.VIEW_STATE_PRESSED);
1929        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1930                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1931                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1932        PRESSED_ENABLED_FOCUSED_STATE_SET = StateSet.get(
1933                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED
1934                        | StateSet.VIEW_STATE_PRESSED);
1935        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1936                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1937                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1938        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1939                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1940                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1941        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1942                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1943                        | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED
1944                        | StateSet.VIEW_STATE_PRESSED);
1945    }
1946
1947    /**
1948     * Accessibility event types that are dispatched for text population.
1949     */
1950    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1951            AccessibilityEvent.TYPE_VIEW_CLICKED
1952            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1953            | AccessibilityEvent.TYPE_VIEW_SELECTED
1954            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1955            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1956            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1957            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1958            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1959            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1960            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1961            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1962
1963    static final int DEBUG_CORNERS_COLOR = Color.rgb(63, 127, 255);
1964
1965    static final int DEBUG_CORNERS_SIZE_DIP = 8;
1966
1967    /**
1968     * Temporary Rect currently for use in setBackground().  This will probably
1969     * be extended in the future to hold our own class with more than just
1970     * a Rect. :)
1971     */
1972    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1973
1974    /**
1975     * Map used to store views' tags.
1976     */
1977    private SparseArray<Object> mKeyedTags;
1978
1979    /**
1980     * The animation currently associated with this view.
1981     * @hide
1982     */
1983    protected Animation mCurrentAnimation = null;
1984
1985    /**
1986     * Width as measured during measure pass.
1987     * {@hide}
1988     */
1989    @ViewDebug.ExportedProperty(category = "measurement")
1990    int mMeasuredWidth;
1991
1992    /**
1993     * Height as measured during measure pass.
1994     * {@hide}
1995     */
1996    @ViewDebug.ExportedProperty(category = "measurement")
1997    int mMeasuredHeight;
1998
1999    /**
2000     * Flag to indicate that this view was marked INVALIDATED, or had its display list
2001     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
2002     * its display list. This flag, used only when hw accelerated, allows us to clear the
2003     * flag while retaining this information until it's needed (at getDisplayList() time and
2004     * in drawChild(), when we decide to draw a view's children's display lists into our own).
2005     *
2006     * {@hide}
2007     */
2008    boolean mRecreateDisplayList = false;
2009
2010    /**
2011     * The view's identifier.
2012     * {@hide}
2013     *
2014     * @see #setId(int)
2015     * @see #getId()
2016     */
2017    @IdRes
2018    @ViewDebug.ExportedProperty(resolveId = true)
2019    int mID = NO_ID;
2020
2021    /** The ID of this view for accessibility and autofill purposes.
2022     * <ul>
2023     *     <li>== {@link #NO_ID}: ID has not been assigned yet
2024     *     <li>&le; {@link #LAST_APP_ACCESSIBILITY_ID}: View is not part of a activity. The ID is
2025     *                                                  unique in the process. This might change
2026     *                                                  over activity lifecycle events.
2027     *     <li>&gt; {@link #LAST_APP_ACCESSIBILITY_ID}: View is part of a activity. The ID is
2028     *                                                  unique in the activity. This stays the same
2029     *                                                  over activity lifecycle events.
2030     */
2031    private int mAccessibilityViewId = NO_ID;
2032
2033    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
2034
2035    SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent;
2036
2037    /**
2038     * The view's tag.
2039     * {@hide}
2040     *
2041     * @see #setTag(Object)
2042     * @see #getTag()
2043     */
2044    protected Object mTag = null;
2045
2046    // for mPrivateFlags:
2047    /** {@hide} */
2048    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
2049    /** {@hide} */
2050    static final int PFLAG_FOCUSED                     = 0x00000002;
2051    /** {@hide} */
2052    static final int PFLAG_SELECTED                    = 0x00000004;
2053    /** {@hide} */
2054    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
2055    /** {@hide} */
2056    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
2057    /** {@hide} */
2058    static final int PFLAG_DRAWN                       = 0x00000020;
2059    /**
2060     * When this flag is set, this view is running an animation on behalf of its
2061     * children and should therefore not cancel invalidate requests, even if they
2062     * lie outside of this view's bounds.
2063     *
2064     * {@hide}
2065     */
2066    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
2067    /** {@hide} */
2068    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
2069    /** {@hide} */
2070    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
2071    /** {@hide} */
2072    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
2073    /** {@hide} */
2074    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
2075    /** {@hide} */
2076    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
2077    /** {@hide} */
2078    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
2079
2080    private static final int PFLAG_PRESSED             = 0x00004000;
2081
2082    /** {@hide} */
2083    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
2084    /**
2085     * Flag used to indicate that this view should be drawn once more (and only once
2086     * more) after its animation has completed.
2087     * {@hide}
2088     */
2089    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
2090
2091    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
2092
2093    /**
2094     * Indicates that the View returned true when onSetAlpha() was called and that
2095     * the alpha must be restored.
2096     * {@hide}
2097     */
2098    static final int PFLAG_ALPHA_SET                   = 0x00040000;
2099
2100    /**
2101     * Set by {@link #setScrollContainer(boolean)}.
2102     */
2103    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
2104
2105    /**
2106     * Set by {@link #setScrollContainer(boolean)}.
2107     */
2108    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
2109
2110    /**
2111     * View flag indicating whether this view was invalidated (fully or partially.)
2112     *
2113     * @hide
2114     */
2115    static final int PFLAG_DIRTY                       = 0x00200000;
2116
2117    /**
2118     * View flag indicating whether this view was invalidated by an opaque
2119     * invalidate request.
2120     *
2121     * @hide
2122     */
2123    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
2124
2125    /**
2126     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
2127     *
2128     * @hide
2129     */
2130    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
2131
2132    /**
2133     * Indicates whether the background is opaque.
2134     *
2135     * @hide
2136     */
2137    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
2138
2139    /**
2140     * Indicates whether the scrollbars are opaque.
2141     *
2142     * @hide
2143     */
2144    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
2145
2146    /**
2147     * Indicates whether the view is opaque.
2148     *
2149     * @hide
2150     */
2151    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
2152
2153    /**
2154     * Indicates a prepressed state;
2155     * the short time between ACTION_DOWN and recognizing
2156     * a 'real' press. Prepressed is used to recognize quick taps
2157     * even when they are shorter than ViewConfiguration.getTapTimeout().
2158     *
2159     * @hide
2160     */
2161    private static final int PFLAG_PREPRESSED          = 0x02000000;
2162
2163    /**
2164     * Indicates whether the view is temporarily detached.
2165     *
2166     * @hide
2167     */
2168    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
2169
2170    /**
2171     * Indicates that we should awaken scroll bars once attached
2172     *
2173     * PLEASE NOTE: This flag is now unused as we now send onVisibilityChanged
2174     * during window attachment and it is no longer needed. Feel free to repurpose it.
2175     *
2176     * @hide
2177     */
2178    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
2179
2180    /**
2181     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
2182     * @hide
2183     */
2184    private static final int PFLAG_HOVERED             = 0x10000000;
2185
2186    /**
2187     * no longer needed, should be reused
2188     */
2189    private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000;
2190
2191    /** {@hide} */
2192    static final int PFLAG_ACTIVATED                   = 0x40000000;
2193
2194    /**
2195     * Indicates that this view was specifically invalidated, not just dirtied because some
2196     * child view was invalidated. The flag is used to determine when we need to recreate
2197     * a view's display list (as opposed to just returning a reference to its existing
2198     * display list).
2199     *
2200     * @hide
2201     */
2202    static final int PFLAG_INVALIDATED                 = 0x80000000;
2203
2204    /**
2205     * Masks for mPrivateFlags2, as generated by dumpFlags():
2206     *
2207     * |-------|-------|-------|-------|
2208     *                                 1 PFLAG2_DRAG_CAN_ACCEPT
2209     *                                1  PFLAG2_DRAG_HOVERED
2210     *                              11   PFLAG2_LAYOUT_DIRECTION_MASK
2211     *                             1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
2212     *                            1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
2213     *                            11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
2214     *                           1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
2215     *                          1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
2216     *                          11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
2217     *                         1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
2218     *                         1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
2219     *                         11        PFLAG2_TEXT_DIRECTION_FLAGS[6]
2220     *                         111       PFLAG2_TEXT_DIRECTION_FLAGS[7]
2221     *                         111       PFLAG2_TEXT_DIRECTION_MASK
2222     *                        1          PFLAG2_TEXT_DIRECTION_RESOLVED
2223     *                       1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
2224     *                     111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
2225     *                    1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
2226     *                   1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
2227     *                   11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
2228     *                  1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
2229     *                  1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
2230     *                  11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
2231     *                  111              PFLAG2_TEXT_ALIGNMENT_MASK
2232     *                 1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
2233     *                1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
2234     *              111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
2235     *           111                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
2236     *         11                        PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK
2237     *       1                           PFLAG2_ACCESSIBILITY_FOCUSED
2238     *      1                            PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED
2239     *     1                             PFLAG2_VIEW_QUICK_REJECTED
2240     *    1                              PFLAG2_PADDING_RESOLVED
2241     *   1                               PFLAG2_DRAWABLE_RESOLVED
2242     *  1                                PFLAG2_HAS_TRANSIENT_STATE
2243     * |-------|-------|-------|-------|
2244     */
2245
2246    /**
2247     * Indicates that this view has reported that it can accept the current drag's content.
2248     * Cleared when the drag operation concludes.
2249     * @hide
2250     */
2251    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
2252
2253    /**
2254     * Indicates that this view is currently directly under the drag location in a
2255     * drag-and-drop operation involving content that it can accept.  Cleared when
2256     * the drag exits the view, or when the drag operation concludes.
2257     * @hide
2258     */
2259    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
2260
2261    /** @hide */
2262    @IntDef({
2263        LAYOUT_DIRECTION_LTR,
2264        LAYOUT_DIRECTION_RTL,
2265        LAYOUT_DIRECTION_INHERIT,
2266        LAYOUT_DIRECTION_LOCALE
2267    })
2268    @Retention(RetentionPolicy.SOURCE)
2269    // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection
2270    public @interface LayoutDir {}
2271
2272    /** @hide */
2273    @IntDef({
2274        LAYOUT_DIRECTION_LTR,
2275        LAYOUT_DIRECTION_RTL
2276    })
2277    @Retention(RetentionPolicy.SOURCE)
2278    public @interface ResolvedLayoutDir {}
2279
2280    /**
2281     * A flag to indicate that the layout direction of this view has not been defined yet.
2282     * @hide
2283     */
2284    public static final int LAYOUT_DIRECTION_UNDEFINED = LayoutDirection.UNDEFINED;
2285
2286    /**
2287     * Horizontal layout direction of this view is from Left to Right.
2288     * Use with {@link #setLayoutDirection}.
2289     */
2290    public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR;
2291
2292    /**
2293     * Horizontal layout direction of this view is from Right to Left.
2294     * Use with {@link #setLayoutDirection}.
2295     */
2296    public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL;
2297
2298    /**
2299     * Horizontal layout direction of this view is inherited from its parent.
2300     * Use with {@link #setLayoutDirection}.
2301     */
2302    public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT;
2303
2304    /**
2305     * Horizontal layout direction of this view is from deduced from the default language
2306     * script for the locale. Use with {@link #setLayoutDirection}.
2307     */
2308    public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE;
2309
2310    /**
2311     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2312     * @hide
2313     */
2314    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
2315
2316    /**
2317     * Mask for use with private flags indicating bits used for horizontal layout direction.
2318     * @hide
2319     */
2320    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2321
2322    /**
2323     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
2324     * right-to-left direction.
2325     * @hide
2326     */
2327    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2328
2329    /**
2330     * Indicates whether the view horizontal layout direction has been resolved.
2331     * @hide
2332     */
2333    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2334
2335    /**
2336     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
2337     * @hide
2338     */
2339    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
2340            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2341
2342    /*
2343     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
2344     * flag value.
2345     * @hide
2346     */
2347    private static final int[] LAYOUT_DIRECTION_FLAGS = {
2348            LAYOUT_DIRECTION_LTR,
2349            LAYOUT_DIRECTION_RTL,
2350            LAYOUT_DIRECTION_INHERIT,
2351            LAYOUT_DIRECTION_LOCALE
2352    };
2353
2354    /**
2355     * Default horizontal layout direction.
2356     */
2357    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
2358
2359    /**
2360     * Default horizontal layout direction.
2361     * @hide
2362     */
2363    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
2364
2365    /**
2366     * Text direction is inherited through {@link ViewGroup}
2367     */
2368    public static final int TEXT_DIRECTION_INHERIT = 0;
2369
2370    /**
2371     * Text direction is using "first strong algorithm". The first strong directional character
2372     * determines the paragraph direction. If there is no strong directional character, the
2373     * paragraph direction is the view's resolved layout direction.
2374     */
2375    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
2376
2377    /**
2378     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
2379     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
2380     * If there are neither, the paragraph direction is the view's resolved layout direction.
2381     */
2382    public static final int TEXT_DIRECTION_ANY_RTL = 2;
2383
2384    /**
2385     * Text direction is forced to LTR.
2386     */
2387    public static final int TEXT_DIRECTION_LTR = 3;
2388
2389    /**
2390     * Text direction is forced to RTL.
2391     */
2392    public static final int TEXT_DIRECTION_RTL = 4;
2393
2394    /**
2395     * Text direction is coming from the system Locale.
2396     */
2397    public static final int TEXT_DIRECTION_LOCALE = 5;
2398
2399    /**
2400     * Text direction is using "first strong algorithm". The first strong directional character
2401     * determines the paragraph direction. If there is no strong directional character, the
2402     * paragraph direction is LTR.
2403     */
2404    public static final int TEXT_DIRECTION_FIRST_STRONG_LTR = 6;
2405
2406    /**
2407     * Text direction is using "first strong algorithm". The first strong directional character
2408     * determines the paragraph direction. If there is no strong directional character, the
2409     * paragraph direction is RTL.
2410     */
2411    public static final int TEXT_DIRECTION_FIRST_STRONG_RTL = 7;
2412
2413    /**
2414     * Default text direction is inherited
2415     */
2416    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
2417
2418    /**
2419     * Default resolved text direction
2420     * @hide
2421     */
2422    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
2423
2424    /**
2425     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
2426     * @hide
2427     */
2428    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
2429
2430    /**
2431     * Mask for use with private flags indicating bits used for text direction.
2432     * @hide
2433     */
2434    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
2435            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2436
2437    /**
2438     * Array of text direction flags for mapping attribute "textDirection" to correct
2439     * flag value.
2440     * @hide
2441     */
2442    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
2443            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2444            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2445            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2446            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2447            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2448            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2449            TEXT_DIRECTION_FIRST_STRONG_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2450            TEXT_DIRECTION_FIRST_STRONG_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
2451    };
2452
2453    /**
2454     * Indicates whether the view text direction has been resolved.
2455     * @hide
2456     */
2457    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
2458            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2459
2460    /**
2461     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2462     * @hide
2463     */
2464    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
2465
2466    /**
2467     * Mask for use with private flags indicating bits used for resolved text direction.
2468     * @hide
2469     */
2470    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
2471            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2472
2473    /**
2474     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
2475     * @hide
2476     */
2477    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
2478            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2479
2480    /** @hide */
2481    @IntDef({
2482        TEXT_ALIGNMENT_INHERIT,
2483        TEXT_ALIGNMENT_GRAVITY,
2484        TEXT_ALIGNMENT_CENTER,
2485        TEXT_ALIGNMENT_TEXT_START,
2486        TEXT_ALIGNMENT_TEXT_END,
2487        TEXT_ALIGNMENT_VIEW_START,
2488        TEXT_ALIGNMENT_VIEW_END
2489    })
2490    @Retention(RetentionPolicy.SOURCE)
2491    public @interface TextAlignment {}
2492
2493    /**
2494     * Default text alignment. The text alignment of this View is inherited from its parent.
2495     * Use with {@link #setTextAlignment(int)}
2496     */
2497    public static final int TEXT_ALIGNMENT_INHERIT = 0;
2498
2499    /**
2500     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
2501     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
2502     *
2503     * Use with {@link #setTextAlignment(int)}
2504     */
2505    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
2506
2507    /**
2508     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2509     *
2510     * Use with {@link #setTextAlignment(int)}
2511     */
2512    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2513
2514    /**
2515     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2516     *
2517     * Use with {@link #setTextAlignment(int)}
2518     */
2519    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2520
2521    /**
2522     * Center the paragraph, e.g. ALIGN_CENTER.
2523     *
2524     * Use with {@link #setTextAlignment(int)}
2525     */
2526    public static final int TEXT_ALIGNMENT_CENTER = 4;
2527
2528    /**
2529     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2530     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2531     *
2532     * Use with {@link #setTextAlignment(int)}
2533     */
2534    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2535
2536    /**
2537     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2538     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2539     *
2540     * Use with {@link #setTextAlignment(int)}
2541     */
2542    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2543
2544    /**
2545     * Default text alignment is inherited
2546     */
2547    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2548
2549    /**
2550     * Default resolved text alignment
2551     * @hide
2552     */
2553    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2554
2555    /**
2556      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2557      * @hide
2558      */
2559    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2560
2561    /**
2562      * Mask for use with private flags indicating bits used for text alignment.
2563      * @hide
2564      */
2565    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2566
2567    /**
2568     * Array of text direction flags for mapping attribute "textAlignment" to correct
2569     * flag value.
2570     * @hide
2571     */
2572    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2573            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2574            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2575            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2576            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2577            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2578            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2579            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2580    };
2581
2582    /**
2583     * Indicates whether the view text alignment has been resolved.
2584     * @hide
2585     */
2586    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2587
2588    /**
2589     * Bit shift to get the resolved text alignment.
2590     * @hide
2591     */
2592    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2593
2594    /**
2595     * Mask for use with private flags indicating bits used for text alignment.
2596     * @hide
2597     */
2598    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2599            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2600
2601    /**
2602     * Indicates whether if the view text alignment has been resolved to gravity
2603     */
2604    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2605            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2606
2607    // Accessiblity constants for mPrivateFlags2
2608
2609    /**
2610     * Shift for the bits in {@link #mPrivateFlags2} related to the
2611     * "importantForAccessibility" attribute.
2612     */
2613    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2614
2615    /**
2616     * Automatically determine whether a view is important for accessibility.
2617     */
2618    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2619
2620    /**
2621     * The view is important for accessibility.
2622     */
2623    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2624
2625    /**
2626     * The view is not important for accessibility.
2627     */
2628    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2629
2630    /**
2631     * The view is not important for accessibility, nor are any of its
2632     * descendant views.
2633     */
2634    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004;
2635
2636    /**
2637     * The default whether the view is important for accessibility.
2638     */
2639    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2640
2641    /**
2642     * Mask for obtaining the bits which specify how to determine
2643     * whether a view is important for accessibility.
2644     */
2645    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2646        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO
2647        | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS)
2648        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2649
2650    /**
2651     * Shift for the bits in {@link #mPrivateFlags2} related to the
2652     * "accessibilityLiveRegion" attribute.
2653     */
2654    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23;
2655
2656    /**
2657     * Live region mode specifying that accessibility services should not
2658     * automatically announce changes to this view. This is the default live
2659     * region mode for most views.
2660     * <p>
2661     * Use with {@link #setAccessibilityLiveRegion(int)}.
2662     */
2663    public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000;
2664
2665    /**
2666     * Live region mode specifying that accessibility services should announce
2667     * changes to this view.
2668     * <p>
2669     * Use with {@link #setAccessibilityLiveRegion(int)}.
2670     */
2671    public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001;
2672
2673    /**
2674     * Live region mode specifying that accessibility services should interrupt
2675     * ongoing speech to immediately announce changes to this view.
2676     * <p>
2677     * Use with {@link #setAccessibilityLiveRegion(int)}.
2678     */
2679    public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002;
2680
2681    /**
2682     * The default whether the view is important for accessibility.
2683     */
2684    static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE;
2685
2686    /**
2687     * Mask for obtaining the bits which specify a view's accessibility live
2688     * region mode.
2689     */
2690    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE
2691            | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE)
2692            << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
2693
2694    /**
2695     * Flag indicating whether a view has accessibility focus.
2696     */
2697    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000;
2698
2699    /**
2700     * Flag whether the accessibility state of the subtree rooted at this view changed.
2701     */
2702    static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000;
2703
2704    /**
2705     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2706     * is used to check whether later changes to the view's transform should invalidate the
2707     * view to force the quickReject test to run again.
2708     */
2709    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2710
2711    /**
2712     * Flag indicating that start/end padding has been resolved into left/right padding
2713     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2714     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2715     * during measurement. In some special cases this is required such as when an adapter-based
2716     * view measures prospective children without attaching them to a window.
2717     */
2718    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2719
2720    /**
2721     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2722     */
2723    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2724
2725    /**
2726     * Indicates that the view is tracking some sort of transient state
2727     * that the app should not need to be aware of, but that the framework
2728     * should take special care to preserve.
2729     */
2730    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000;
2731
2732    /**
2733     * Group of bits indicating that RTL properties resolution is done.
2734     */
2735    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2736            PFLAG2_TEXT_DIRECTION_RESOLVED |
2737            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2738            PFLAG2_PADDING_RESOLVED |
2739            PFLAG2_DRAWABLE_RESOLVED;
2740
2741    // There are a couple of flags left in mPrivateFlags2
2742
2743    /* End of masks for mPrivateFlags2 */
2744
2745    /**
2746     * Masks for mPrivateFlags3, as generated by dumpFlags():
2747     *
2748     * |-------|-------|-------|-------|
2749     *                                 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM
2750     *                                1  PFLAG3_VIEW_IS_ANIMATING_ALPHA
2751     *                               1   PFLAG3_IS_LAID_OUT
2752     *                              1    PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT
2753     *                             1     PFLAG3_CALLED_SUPER
2754     *                            1      PFLAG3_APPLYING_INSETS
2755     *                           1       PFLAG3_FITTING_SYSTEM_WINDOWS
2756     *                          1        PFLAG3_NESTED_SCROLLING_ENABLED
2757     *                         1         PFLAG3_SCROLL_INDICATOR_TOP
2758     *                        1          PFLAG3_SCROLL_INDICATOR_BOTTOM
2759     *                       1           PFLAG3_SCROLL_INDICATOR_LEFT
2760     *                      1            PFLAG3_SCROLL_INDICATOR_RIGHT
2761     *                     1             PFLAG3_SCROLL_INDICATOR_START
2762     *                    1              PFLAG3_SCROLL_INDICATOR_END
2763     *                   1               PFLAG3_ASSIST_BLOCKED
2764     *                  1                PFLAG3_CLUSTER
2765     *                 1                 PFLAG3_IS_AUTOFILLED
2766     *                1                  PFLAG3_FINGER_DOWN
2767     *               1                   PFLAG3_FOCUSED_BY_DEFAULT
2768     *           1111                    PFLAG3_IMPORTANT_FOR_AUTOFILL
2769     *          1                        PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE
2770     *         1                         PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED
2771     *        1                          PFLAG3_TEMPORARY_DETACH
2772     *       1                           PFLAG3_NO_REVEAL_ON_FOCUS
2773     * |-------|-------|-------|-------|
2774     */
2775
2776    /**
2777     * Flag indicating that view has a transform animation set on it. This is used to track whether
2778     * an animation is cleared between successive frames, in order to tell the associated
2779     * DisplayList to clear its animation matrix.
2780     */
2781    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2782
2783    /**
2784     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2785     * animation is cleared between successive frames, in order to tell the associated
2786     * DisplayList to restore its alpha value.
2787     */
2788    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2789
2790    /**
2791     * Flag indicating that the view has been through at least one layout since it
2792     * was last attached to a window.
2793     */
2794    static final int PFLAG3_IS_LAID_OUT = 0x4;
2795
2796    /**
2797     * Flag indicating that a call to measure() was skipped and should be done
2798     * instead when layout() is invoked.
2799     */
2800    static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8;
2801
2802    /**
2803     * Flag indicating that an overridden method correctly called down to
2804     * the superclass implementation as required by the API spec.
2805     */
2806    static final int PFLAG3_CALLED_SUPER = 0x10;
2807
2808    /**
2809     * Flag indicating that we're in the process of applying window insets.
2810     */
2811    static final int PFLAG3_APPLYING_INSETS = 0x20;
2812
2813    /**
2814     * Flag indicating that we're in the process of fitting system windows using the old method.
2815     */
2816    static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40;
2817
2818    /**
2819     * Flag indicating that nested scrolling is enabled for this view.
2820     * The view will optionally cooperate with views up its parent chain to allow for
2821     * integrated nested scrolling along the same axis.
2822     */
2823    static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80;
2824
2825    /**
2826     * Flag indicating that the bottom scroll indicator should be displayed
2827     * when this view can scroll up.
2828     */
2829    static final int PFLAG3_SCROLL_INDICATOR_TOP = 0x0100;
2830
2831    /**
2832     * Flag indicating that the bottom scroll indicator should be displayed
2833     * when this view can scroll down.
2834     */
2835    static final int PFLAG3_SCROLL_INDICATOR_BOTTOM = 0x0200;
2836
2837    /**
2838     * Flag indicating that the left scroll indicator should be displayed
2839     * when this view can scroll left.
2840     */
2841    static final int PFLAG3_SCROLL_INDICATOR_LEFT = 0x0400;
2842
2843    /**
2844     * Flag indicating that the right scroll indicator should be displayed
2845     * when this view can scroll right.
2846     */
2847    static final int PFLAG3_SCROLL_INDICATOR_RIGHT = 0x0800;
2848
2849    /**
2850     * Flag indicating that the start scroll indicator should be displayed
2851     * when this view can scroll in the start direction.
2852     */
2853    static final int PFLAG3_SCROLL_INDICATOR_START = 0x1000;
2854
2855    /**
2856     * Flag indicating that the end scroll indicator should be displayed
2857     * when this view can scroll in the end direction.
2858     */
2859    static final int PFLAG3_SCROLL_INDICATOR_END = 0x2000;
2860
2861    /**
2862     * Flag indicating that when layout is completed we should notify
2863     * that the view was entered for autofill purposes. To minimize
2864     * showing autofill for views not visible to the user we evaluate
2865     * user visibility which cannot be done until the view is laid out.
2866     */
2867    static final int PFLAG3_NOTIFY_AUTOFILL_ENTER_ON_LAYOUT = 0x4000;
2868
2869    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2870
2871    static final int SCROLL_INDICATORS_NONE = 0x0000;
2872
2873    /**
2874     * Mask for use with setFlags indicating bits used for indicating which
2875     * scroll indicators are enabled.
2876     */
2877    static final int SCROLL_INDICATORS_PFLAG3_MASK = PFLAG3_SCROLL_INDICATOR_TOP
2878            | PFLAG3_SCROLL_INDICATOR_BOTTOM | PFLAG3_SCROLL_INDICATOR_LEFT
2879            | PFLAG3_SCROLL_INDICATOR_RIGHT | PFLAG3_SCROLL_INDICATOR_START
2880            | PFLAG3_SCROLL_INDICATOR_END;
2881
2882    /**
2883     * Left-shift required to translate between public scroll indicator flags
2884     * and internal PFLAGS3 flags. When used as a right-shift, translates
2885     * PFLAGS3 flags to public flags.
2886     */
2887    static final int SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT = 8;
2888
2889    /** @hide */
2890    @Retention(RetentionPolicy.SOURCE)
2891    @IntDef(flag = true,
2892            value = {
2893                    SCROLL_INDICATOR_TOP,
2894                    SCROLL_INDICATOR_BOTTOM,
2895                    SCROLL_INDICATOR_LEFT,
2896                    SCROLL_INDICATOR_RIGHT,
2897                    SCROLL_INDICATOR_START,
2898                    SCROLL_INDICATOR_END,
2899            })
2900    public @interface ScrollIndicators {}
2901
2902    /**
2903     * Scroll indicator direction for the top edge of the view.
2904     *
2905     * @see #setScrollIndicators(int)
2906     * @see #setScrollIndicators(int, int)
2907     * @see #getScrollIndicators()
2908     */
2909    public static final int SCROLL_INDICATOR_TOP =
2910            PFLAG3_SCROLL_INDICATOR_TOP >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2911
2912    /**
2913     * Scroll indicator direction for the bottom edge of the view.
2914     *
2915     * @see #setScrollIndicators(int)
2916     * @see #setScrollIndicators(int, int)
2917     * @see #getScrollIndicators()
2918     */
2919    public static final int SCROLL_INDICATOR_BOTTOM =
2920            PFLAG3_SCROLL_INDICATOR_BOTTOM >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2921
2922    /**
2923     * Scroll indicator direction for the left edge of the view.
2924     *
2925     * @see #setScrollIndicators(int)
2926     * @see #setScrollIndicators(int, int)
2927     * @see #getScrollIndicators()
2928     */
2929    public static final int SCROLL_INDICATOR_LEFT =
2930            PFLAG3_SCROLL_INDICATOR_LEFT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2931
2932    /**
2933     * Scroll indicator direction for the right edge of the view.
2934     *
2935     * @see #setScrollIndicators(int)
2936     * @see #setScrollIndicators(int, int)
2937     * @see #getScrollIndicators()
2938     */
2939    public static final int SCROLL_INDICATOR_RIGHT =
2940            PFLAG3_SCROLL_INDICATOR_RIGHT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2941
2942    /**
2943     * Scroll indicator direction for the starting edge of the view.
2944     * <p>
2945     * Resolved according to the view's layout direction, see
2946     * {@link #getLayoutDirection()} for more information.
2947     *
2948     * @see #setScrollIndicators(int)
2949     * @see #setScrollIndicators(int, int)
2950     * @see #getScrollIndicators()
2951     */
2952    public static final int SCROLL_INDICATOR_START =
2953            PFLAG3_SCROLL_INDICATOR_START >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2954
2955    /**
2956     * Scroll indicator direction for the ending edge of the view.
2957     * <p>
2958     * Resolved according to the view's layout direction, see
2959     * {@link #getLayoutDirection()} for more information.
2960     *
2961     * @see #setScrollIndicators(int)
2962     * @see #setScrollIndicators(int, int)
2963     * @see #getScrollIndicators()
2964     */
2965    public static final int SCROLL_INDICATOR_END =
2966            PFLAG3_SCROLL_INDICATOR_END >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2967
2968    /**
2969     * <p>Indicates that we are allowing {@link ViewStructure} to traverse
2970     * into this view.<p>
2971     */
2972    static final int PFLAG3_ASSIST_BLOCKED = 0x4000;
2973
2974    /**
2975     * Flag indicating that the view is a root of a keyboard navigation cluster.
2976     *
2977     * @see #isKeyboardNavigationCluster()
2978     * @see #setKeyboardNavigationCluster(boolean)
2979     */
2980    private static final int PFLAG3_CLUSTER = 0x8000;
2981
2982    /**
2983     * Flag indicating that the view is autofilled
2984     *
2985     * @see #isAutofilled()
2986     * @see #setAutofilled(boolean)
2987     */
2988    private static final int PFLAG3_IS_AUTOFILLED = 0x10000;
2989
2990    /**
2991     * Indicates that the user is currently touching the screen.
2992     * Currently used for the tooltip positioning only.
2993     */
2994    private static final int PFLAG3_FINGER_DOWN = 0x20000;
2995
2996    /**
2997     * Flag indicating that this view is the default-focus view.
2998     *
2999     * @see #isFocusedByDefault()
3000     * @see #setFocusedByDefault(boolean)
3001     */
3002    private static final int PFLAG3_FOCUSED_BY_DEFAULT = 0x40000;
3003
3004    /**
3005     * Shift for the bits in {@link #mPrivateFlags3} related to the
3006     * "importantForAutofill" attribute.
3007     */
3008    static final int PFLAG3_IMPORTANT_FOR_AUTOFILL_SHIFT = 19;
3009
3010    /**
3011     * Mask for obtaining the bits which specify how to determine
3012     * whether a view is important for autofill.
3013     */
3014    static final int PFLAG3_IMPORTANT_FOR_AUTOFILL_MASK = (IMPORTANT_FOR_AUTOFILL_AUTO
3015            | IMPORTANT_FOR_AUTOFILL_YES | IMPORTANT_FOR_AUTOFILL_NO
3016            | IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS
3017            | IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS)
3018            << PFLAG3_IMPORTANT_FOR_AUTOFILL_SHIFT;
3019
3020    /**
3021     * Whether this view has rendered elements that overlap (see {@link
3022     * #hasOverlappingRendering()}, {@link #forceHasOverlappingRendering(boolean)}, and
3023     * {@link #getHasOverlappingRendering()} ). The value in this bit is only valid when
3024     * PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED has been set. Otherwise, the value is
3025     * determined by whatever {@link #hasOverlappingRendering()} returns.
3026     */
3027    private static final int PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE = 0x800000;
3028
3029    /**
3030     * Whether {@link #forceHasOverlappingRendering(boolean)} has been called. When true, value
3031     * in PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE is valid.
3032     */
3033    private static final int PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED = 0x1000000;
3034
3035    /**
3036     * Flag indicating that the view is temporarily detached from the parent view.
3037     *
3038     * @see #onStartTemporaryDetach()
3039     * @see #onFinishTemporaryDetach()
3040     */
3041    static final int PFLAG3_TEMPORARY_DETACH = 0x2000000;
3042
3043    /**
3044     * Flag indicating that the view does not wish to be revealed within its parent
3045     * hierarchy when it gains focus. Expressed in the negative since the historical
3046     * default behavior is to reveal on focus; this flag suppresses that behavior.
3047     *
3048     * @see #setRevealOnFocusHint(boolean)
3049     * @see #getRevealOnFocusHint()
3050     */
3051    private static final int PFLAG3_NO_REVEAL_ON_FOCUS = 0x4000000;
3052
3053    /* End of masks for mPrivateFlags3 */
3054
3055    /**
3056     * Always allow a user to over-scroll this view, provided it is a
3057     * view that can scroll.
3058     *
3059     * @see #getOverScrollMode()
3060     * @see #setOverScrollMode(int)
3061     */
3062    public static final int OVER_SCROLL_ALWAYS = 0;
3063
3064    /**
3065     * Allow a user to over-scroll this view only if the content is large
3066     * enough to meaningfully scroll, provided it is a view that can scroll.
3067     *
3068     * @see #getOverScrollMode()
3069     * @see #setOverScrollMode(int)
3070     */
3071    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
3072
3073    /**
3074     * Never allow a user to over-scroll this view.
3075     *
3076     * @see #getOverScrollMode()
3077     * @see #setOverScrollMode(int)
3078     */
3079    public static final int OVER_SCROLL_NEVER = 2;
3080
3081    /**
3082     * Special constant for {@link #setSystemUiVisibility(int)}: View has
3083     * requested the system UI (status bar) to be visible (the default).
3084     *
3085     * @see #setSystemUiVisibility(int)
3086     */
3087    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
3088
3089    /**
3090     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
3091     * system UI to enter an unobtrusive "low profile" mode.
3092     *
3093     * <p>This is for use in games, book readers, video players, or any other
3094     * "immersive" application where the usual system chrome is deemed too distracting.
3095     *
3096     * <p>In low profile mode, the status bar and/or navigation icons may dim.
3097     *
3098     * @see #setSystemUiVisibility(int)
3099     */
3100    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
3101
3102    /**
3103     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
3104     * system navigation be temporarily hidden.
3105     *
3106     * <p>This is an even less obtrusive state than that called for by
3107     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
3108     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
3109     * those to disappear. This is useful (in conjunction with the
3110     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
3111     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
3112     * window flags) for displaying content using every last pixel on the display.
3113     *
3114     * <p>There is a limitation: because navigation controls are so important, the least user
3115     * interaction will cause them to reappear immediately.  When this happens, both
3116     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
3117     * so that both elements reappear at the same time.
3118     *
3119     * @see #setSystemUiVisibility(int)
3120     */
3121    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
3122
3123    /**
3124     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
3125     * into the normal fullscreen mode so that its content can take over the screen
3126     * while still allowing the user to interact with the application.
3127     *
3128     * <p>This has the same visual effect as
3129     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
3130     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
3131     * meaning that non-critical screen decorations (such as the status bar) will be
3132     * hidden while the user is in the View's window, focusing the experience on
3133     * that content.  Unlike the window flag, if you are using ActionBar in
3134     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
3135     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
3136     * hide the action bar.
3137     *
3138     * <p>This approach to going fullscreen is best used over the window flag when
3139     * it is a transient state -- that is, the application does this at certain
3140     * points in its user interaction where it wants to allow the user to focus
3141     * on content, but not as a continuous state.  For situations where the application
3142     * would like to simply stay full screen the entire time (such as a game that
3143     * wants to take over the screen), the
3144     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
3145     * is usually a better approach.  The state set here will be removed by the system
3146     * in various situations (such as the user moving to another application) like
3147     * the other system UI states.
3148     *
3149     * <p>When using this flag, the application should provide some easy facility
3150     * for the user to go out of it.  A common example would be in an e-book
3151     * reader, where tapping on the screen brings back whatever screen and UI
3152     * decorations that had been hidden while the user was immersed in reading
3153     * the book.
3154     *
3155     * @see #setSystemUiVisibility(int)
3156     */
3157    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
3158
3159    /**
3160     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
3161     * flags, we would like a stable view of the content insets given to
3162     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
3163     * will always represent the worst case that the application can expect
3164     * as a continuous state.  In the stock Android UI this is the space for
3165     * the system bar, nav bar, and status bar, but not more transient elements
3166     * such as an input method.
3167     *
3168     * The stable layout your UI sees is based on the system UI modes you can
3169     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
3170     * then you will get a stable layout for changes of the
3171     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
3172     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
3173     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
3174     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
3175     * with a stable layout.  (Note that you should avoid using
3176     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
3177     *
3178     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
3179     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
3180     * then a hidden status bar will be considered a "stable" state for purposes
3181     * here.  This allows your UI to continually hide the status bar, while still
3182     * using the system UI flags to hide the action bar while still retaining
3183     * a stable layout.  Note that changing the window fullscreen flag will never
3184     * provide a stable layout for a clean transition.
3185     *
3186     * <p>If you are using ActionBar in
3187     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
3188     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
3189     * insets it adds to those given to the application.
3190     */
3191    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
3192
3193    /**
3194     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
3195     * to be laid out as if it has requested
3196     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
3197     * allows it to avoid artifacts when switching in and out of that mode, at
3198     * the expense that some of its user interface may be covered by screen
3199     * decorations when they are shown.  You can perform layout of your inner
3200     * UI elements to account for the navigation system UI through the
3201     * {@link #fitSystemWindows(Rect)} method.
3202     */
3203    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
3204
3205    /**
3206     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
3207     * to be laid out as if it has requested
3208     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
3209     * allows it to avoid artifacts when switching in and out of that mode, at
3210     * the expense that some of its user interface may be covered by screen
3211     * decorations when they are shown.  You can perform layout of your inner
3212     * UI elements to account for non-fullscreen system UI through the
3213     * {@link #fitSystemWindows(Rect)} method.
3214     */
3215    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
3216
3217    /**
3218     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
3219     * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  If this flag is
3220     * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any
3221     * user interaction.
3222     * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only
3223     * has an effect when used in combination with that flag.</p>
3224     */
3225    public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800;
3226
3227    /**
3228     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
3229     * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation
3230     * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  Use this flag to create an immersive
3231     * experience while also hiding the system bars.  If this flag is not set,
3232     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user
3233     * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system
3234     * if the user swipes from the top of the screen.
3235     * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with
3236     * system gestures, such as swiping from the top of the screen.  These transient system bars
3237     * will overlay app’s content, may have some degree of transparency, and will automatically
3238     * hide after a short timeout.
3239     * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and
3240     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination
3241     * with one or both of those flags.</p>
3242     */
3243    public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000;
3244
3245    /**
3246     * Flag for {@link #setSystemUiVisibility(int)}: Requests the status bar to draw in a mode that
3247     * is compatible with light status bar backgrounds.
3248     *
3249     * <p>For this to take effect, the window must request
3250     * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS
3251     *         FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not
3252     * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_STATUS
3253     *         FLAG_TRANSLUCENT_STATUS}.
3254     *
3255     * @see android.R.attr#windowLightStatusBar
3256     */
3257    public static final int SYSTEM_UI_FLAG_LIGHT_STATUS_BAR = 0x00002000;
3258
3259    /**
3260     * This flag was previously used for a private API. DO NOT reuse it for a public API as it might
3261     * trigger undefined behavior on older platforms with apps compiled against a new SDK.
3262     */
3263    private static final int SYSTEM_UI_RESERVED_LEGACY1 = 0x00004000;
3264
3265    /**
3266     * This flag was previously used for a private API. DO NOT reuse it for a public API as it might
3267     * trigger undefined behavior on older platforms with apps compiled against a new SDK.
3268     */
3269    private static final int SYSTEM_UI_RESERVED_LEGACY2 = 0x00010000;
3270
3271    /**
3272     * Flag for {@link #setSystemUiVisibility(int)}: Requests the navigation bar to draw in a mode
3273     * that is compatible with light navigation bar backgrounds.
3274     *
3275     * <p>For this to take effect, the window must request
3276     * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS
3277     *         FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not
3278     * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_NAVIGATION
3279     *         FLAG_TRANSLUCENT_NAVIGATION}.
3280     */
3281    public static final int SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR = 0x00000010;
3282
3283    /**
3284     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
3285     */
3286    @Deprecated
3287    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
3288
3289    /**
3290     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
3291     */
3292    @Deprecated
3293    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
3294
3295    /**
3296     * @hide
3297     *
3298     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3299     * out of the public fields to keep the undefined bits out of the developer's way.
3300     *
3301     * Flag to make the status bar not expandable.  Unless you also
3302     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
3303     */
3304    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
3305
3306    /**
3307     * @hide
3308     *
3309     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3310     * out of the public fields to keep the undefined bits out of the developer's way.
3311     *
3312     * Flag to hide notification icons and scrolling ticker text.
3313     */
3314    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
3315
3316    /**
3317     * @hide
3318     *
3319     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3320     * out of the public fields to keep the undefined bits out of the developer's way.
3321     *
3322     * Flag to disable incoming notification alerts.  This will not block
3323     * icons, but it will block sound, vibrating and other visual or aural notifications.
3324     */
3325    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
3326
3327    /**
3328     * @hide
3329     *
3330     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3331     * out of the public fields to keep the undefined bits out of the developer's way.
3332     *
3333     * Flag to hide only the scrolling ticker.  Note that
3334     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
3335     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
3336     */
3337    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
3338
3339    /**
3340     * @hide
3341     *
3342     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3343     * out of the public fields to keep the undefined bits out of the developer's way.
3344     *
3345     * Flag to hide the center system info area.
3346     */
3347    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
3348
3349    /**
3350     * @hide
3351     *
3352     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3353     * out of the public fields to keep the undefined bits out of the developer's way.
3354     *
3355     * Flag to hide only the home button.  Don't use this
3356     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3357     */
3358    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
3359
3360    /**
3361     * @hide
3362     *
3363     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3364     * out of the public fields to keep the undefined bits out of the developer's way.
3365     *
3366     * Flag to hide only the back button. Don't use this
3367     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3368     */
3369    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
3370
3371    /**
3372     * @hide
3373     *
3374     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3375     * out of the public fields to keep the undefined bits out of the developer's way.
3376     *
3377     * Flag to hide only the clock.  You might use this if your activity has
3378     * its own clock making the status bar's clock redundant.
3379     */
3380    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
3381
3382    /**
3383     * @hide
3384     *
3385     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3386     * out of the public fields to keep the undefined bits out of the developer's way.
3387     *
3388     * Flag to hide only the recent apps button. Don't use this
3389     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3390     */
3391    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
3392
3393    /**
3394     * @hide
3395     *
3396     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3397     * out of the public fields to keep the undefined bits out of the developer's way.
3398     *
3399     * Flag to disable the global search gesture. Don't use this
3400     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3401     */
3402    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
3403
3404    /**
3405     * @hide
3406     *
3407     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3408     * out of the public fields to keep the undefined bits out of the developer's way.
3409     *
3410     * Flag to specify that the status bar is displayed in transient mode.
3411     */
3412    public static final int STATUS_BAR_TRANSIENT = 0x04000000;
3413
3414    /**
3415     * @hide
3416     *
3417     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3418     * out of the public fields to keep the undefined bits out of the developer's way.
3419     *
3420     * Flag to specify that the navigation bar is displayed in transient mode.
3421     */
3422    public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000;
3423
3424    /**
3425     * @hide
3426     *
3427     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3428     * out of the public fields to keep the undefined bits out of the developer's way.
3429     *
3430     * Flag to specify that the hidden status bar would like to be shown.
3431     */
3432    public static final int STATUS_BAR_UNHIDE = 0x10000000;
3433
3434    /**
3435     * @hide
3436     *
3437     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3438     * out of the public fields to keep the undefined bits out of the developer's way.
3439     *
3440     * Flag to specify that the hidden navigation bar would like to be shown.
3441     */
3442    public static final int NAVIGATION_BAR_UNHIDE = 0x20000000;
3443
3444    /**
3445     * @hide
3446     *
3447     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3448     * out of the public fields to keep the undefined bits out of the developer's way.
3449     *
3450     * Flag to specify that the status bar is displayed in translucent mode.
3451     */
3452    public static final int STATUS_BAR_TRANSLUCENT = 0x40000000;
3453
3454    /**
3455     * @hide
3456     *
3457     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3458     * out of the public fields to keep the undefined bits out of the developer's way.
3459     *
3460     * Flag to specify that the navigation bar is displayed in translucent mode.
3461     */
3462    public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000;
3463
3464    /**
3465     * @hide
3466     *
3467     * Makes navigation bar transparent (but not the status bar).
3468     */
3469    public static final int NAVIGATION_BAR_TRANSPARENT = 0x00008000;
3470
3471    /**
3472     * @hide
3473     *
3474     * Makes status bar transparent (but not the navigation bar).
3475     */
3476    public static final int STATUS_BAR_TRANSPARENT = 0x00000008;
3477
3478    /**
3479     * @hide
3480     *
3481     * Makes both status bar and navigation bar transparent.
3482     */
3483    public static final int SYSTEM_UI_TRANSPARENT = NAVIGATION_BAR_TRANSPARENT
3484            | STATUS_BAR_TRANSPARENT;
3485
3486    /**
3487     * @hide
3488     */
3489    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FF7;
3490
3491    /**
3492     * These are the system UI flags that can be cleared by events outside
3493     * of an application.  Currently this is just the ability to tap on the
3494     * screen while hiding the navigation bar to have it return.
3495     * @hide
3496     */
3497    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
3498            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
3499            | SYSTEM_UI_FLAG_FULLSCREEN;
3500
3501    /**
3502     * Flags that can impact the layout in relation to system UI.
3503     */
3504    public static final int SYSTEM_UI_LAYOUT_FLAGS =
3505            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
3506            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
3507
3508    /** @hide */
3509    @IntDef(flag = true,
3510            value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION })
3511    @Retention(RetentionPolicy.SOURCE)
3512    public @interface FindViewFlags {}
3513
3514    /**
3515     * Find views that render the specified text.
3516     *
3517     * @see #findViewsWithText(ArrayList, CharSequence, int)
3518     */
3519    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
3520
3521    /**
3522     * Find find views that contain the specified content description.
3523     *
3524     * @see #findViewsWithText(ArrayList, CharSequence, int)
3525     */
3526    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
3527
3528    /**
3529     * Find views that contain {@link AccessibilityNodeProvider}. Such
3530     * a View is a root of virtual view hierarchy and may contain the searched
3531     * text. If this flag is set Views with providers are automatically
3532     * added and it is a responsibility of the client to call the APIs of
3533     * the provider to determine whether the virtual tree rooted at this View
3534     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
3535     * representing the virtual views with this text.
3536     *
3537     * @see #findViewsWithText(ArrayList, CharSequence, int)
3538     *
3539     * @hide
3540     */
3541    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
3542
3543    /**
3544     * The undefined cursor position.
3545     *
3546     * @hide
3547     */
3548    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
3549
3550    /**
3551     * Indicates that the screen has changed state and is now off.
3552     *
3553     * @see #onScreenStateChanged(int)
3554     */
3555    public static final int SCREEN_STATE_OFF = 0x0;
3556
3557    /**
3558     * Indicates that the screen has changed state and is now on.
3559     *
3560     * @see #onScreenStateChanged(int)
3561     */
3562    public static final int SCREEN_STATE_ON = 0x1;
3563
3564    /**
3565     * Indicates no axis of view scrolling.
3566     */
3567    public static final int SCROLL_AXIS_NONE = 0;
3568
3569    /**
3570     * Indicates scrolling along the horizontal axis.
3571     */
3572    public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0;
3573
3574    /**
3575     * Indicates scrolling along the vertical axis.
3576     */
3577    public static final int SCROLL_AXIS_VERTICAL = 1 << 1;
3578
3579    /**
3580     * Controls the over-scroll mode for this view.
3581     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
3582     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
3583     * and {@link #OVER_SCROLL_NEVER}.
3584     */
3585    private int mOverScrollMode;
3586
3587    /**
3588     * The parent this view is attached to.
3589     * {@hide}
3590     *
3591     * @see #getParent()
3592     */
3593    protected ViewParent mParent;
3594
3595    /**
3596     * {@hide}
3597     */
3598    AttachInfo mAttachInfo;
3599
3600    /**
3601     * {@hide}
3602     */
3603    @ViewDebug.ExportedProperty(flagMapping = {
3604        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
3605                name = "FORCE_LAYOUT"),
3606        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
3607                name = "LAYOUT_REQUIRED"),
3608        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
3609            name = "DRAWING_CACHE_INVALID", outputIf = false),
3610        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
3611        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
3612        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
3613        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
3614    }, formatToHexString = true)
3615
3616    /* @hide */
3617    public int mPrivateFlags;
3618    int mPrivateFlags2;
3619    int mPrivateFlags3;
3620
3621    /**
3622     * This view's request for the visibility of the status bar.
3623     * @hide
3624     */
3625    @ViewDebug.ExportedProperty(flagMapping = {
3626        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
3627                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
3628                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
3629        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
3630                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
3631                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
3632        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
3633                                equals = SYSTEM_UI_FLAG_VISIBLE,
3634                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
3635    }, formatToHexString = true)
3636    int mSystemUiVisibility;
3637
3638    /**
3639     * Reference count for transient state.
3640     * @see #setHasTransientState(boolean)
3641     */
3642    int mTransientStateCount = 0;
3643
3644    /**
3645     * Count of how many windows this view has been attached to.
3646     */
3647    int mWindowAttachCount;
3648
3649    /**
3650     * The layout parameters associated with this view and used by the parent
3651     * {@link android.view.ViewGroup} to determine how this view should be
3652     * laid out.
3653     * {@hide}
3654     */
3655    protected ViewGroup.LayoutParams mLayoutParams;
3656
3657    /**
3658     * The view flags hold various views states.
3659     * {@hide}
3660     */
3661    @ViewDebug.ExportedProperty(formatToHexString = true)
3662    int mViewFlags;
3663
3664    static class TransformationInfo {
3665        /**
3666         * The transform matrix for the View. This transform is calculated internally
3667         * based on the translation, rotation, and scale properties.
3668         *
3669         * Do *not* use this variable directly; instead call getMatrix(), which will
3670         * load the value from the View's RenderNode.
3671         */
3672        private final Matrix mMatrix = new Matrix();
3673
3674        /**
3675         * The inverse transform matrix for the View. This transform is calculated
3676         * internally based on the translation, rotation, and scale properties.
3677         *
3678         * Do *not* use this variable directly; instead call getInverseMatrix(),
3679         * which will load the value from the View's RenderNode.
3680         */
3681        private Matrix mInverseMatrix;
3682
3683        /**
3684         * The opacity of the View. This is a value from 0 to 1, where 0 means
3685         * completely transparent and 1 means completely opaque.
3686         */
3687        @ViewDebug.ExportedProperty
3688        float mAlpha = 1f;
3689
3690        /**
3691         * The opacity of the view as manipulated by the Fade transition. This is a hidden
3692         * property only used by transitions, which is composited with the other alpha
3693         * values to calculate the final visual alpha value.
3694         */
3695        float mTransitionAlpha = 1f;
3696    }
3697
3698    /** @hide */
3699    public TransformationInfo mTransformationInfo;
3700
3701    /**
3702     * Current clip bounds. to which all drawing of this view are constrained.
3703     */
3704    Rect mClipBounds = null;
3705
3706    private boolean mLastIsOpaque;
3707
3708    /**
3709     * The distance in pixels from the left edge of this view's parent
3710     * to the left edge of this view.
3711     * {@hide}
3712     */
3713    @ViewDebug.ExportedProperty(category = "layout")
3714    protected int mLeft;
3715    /**
3716     * The distance in pixels from the left edge of this view's parent
3717     * to the right edge of this view.
3718     * {@hide}
3719     */
3720    @ViewDebug.ExportedProperty(category = "layout")
3721    protected int mRight;
3722    /**
3723     * The distance in pixels from the top edge of this view's parent
3724     * to the top edge of this view.
3725     * {@hide}
3726     */
3727    @ViewDebug.ExportedProperty(category = "layout")
3728    protected int mTop;
3729    /**
3730     * The distance in pixels from the top edge of this view's parent
3731     * to the bottom edge of this view.
3732     * {@hide}
3733     */
3734    @ViewDebug.ExportedProperty(category = "layout")
3735    protected int mBottom;
3736
3737    /**
3738     * The offset, in pixels, by which the content of this view is scrolled
3739     * horizontally.
3740     * {@hide}
3741     */
3742    @ViewDebug.ExportedProperty(category = "scrolling")
3743    protected int mScrollX;
3744    /**
3745     * The offset, in pixels, by which the content of this view is scrolled
3746     * vertically.
3747     * {@hide}
3748     */
3749    @ViewDebug.ExportedProperty(category = "scrolling")
3750    protected int mScrollY;
3751
3752    /**
3753     * The left padding in pixels, that is the distance in pixels between the
3754     * left edge of this view and the left edge of its content.
3755     * {@hide}
3756     */
3757    @ViewDebug.ExportedProperty(category = "padding")
3758    protected int mPaddingLeft = 0;
3759    /**
3760     * The right padding in pixels, that is the distance in pixels between the
3761     * right edge of this view and the right edge of its content.
3762     * {@hide}
3763     */
3764    @ViewDebug.ExportedProperty(category = "padding")
3765    protected int mPaddingRight = 0;
3766    /**
3767     * The top padding in pixels, that is the distance in pixels between the
3768     * top edge of this view and the top edge of its content.
3769     * {@hide}
3770     */
3771    @ViewDebug.ExportedProperty(category = "padding")
3772    protected int mPaddingTop;
3773    /**
3774     * The bottom padding in pixels, that is the distance in pixels between the
3775     * bottom edge of this view and the bottom edge of its content.
3776     * {@hide}
3777     */
3778    @ViewDebug.ExportedProperty(category = "padding")
3779    protected int mPaddingBottom;
3780
3781    /**
3782     * The layout insets in pixels, that is the distance in pixels between the
3783     * visible edges of this view its bounds.
3784     */
3785    private Insets mLayoutInsets;
3786
3787    /**
3788     * Briefly describes the view and is primarily used for accessibility support.
3789     */
3790    private CharSequence mContentDescription;
3791
3792    /**
3793     * Specifies the id of a view for which this view serves as a label for
3794     * accessibility purposes.
3795     */
3796    private int mLabelForId = View.NO_ID;
3797
3798    /**
3799     * Predicate for matching labeled view id with its label for
3800     * accessibility purposes.
3801     */
3802    private MatchLabelForPredicate mMatchLabelForPredicate;
3803
3804    /**
3805     * Specifies a view before which this one is visited in accessibility traversal.
3806     */
3807    private int mAccessibilityTraversalBeforeId = NO_ID;
3808
3809    /**
3810     * Specifies a view after which this one is visited in accessibility traversal.
3811     */
3812    private int mAccessibilityTraversalAfterId = NO_ID;
3813
3814    /**
3815     * Predicate for matching a view by its id.
3816     */
3817    private MatchIdPredicate mMatchIdPredicate;
3818
3819    /**
3820     * Cache the paddingRight set by the user to append to the scrollbar's size.
3821     *
3822     * @hide
3823     */
3824    @ViewDebug.ExportedProperty(category = "padding")
3825    protected int mUserPaddingRight;
3826
3827    /**
3828     * Cache the paddingBottom set by the user to append to the scrollbar's size.
3829     *
3830     * @hide
3831     */
3832    @ViewDebug.ExportedProperty(category = "padding")
3833    protected int mUserPaddingBottom;
3834
3835    /**
3836     * Cache the paddingLeft set by the user to append to the scrollbar's size.
3837     *
3838     * @hide
3839     */
3840    @ViewDebug.ExportedProperty(category = "padding")
3841    protected int mUserPaddingLeft;
3842
3843    /**
3844     * Cache the paddingStart set by the user to append to the scrollbar's size.
3845     *
3846     */
3847    @ViewDebug.ExportedProperty(category = "padding")
3848    int mUserPaddingStart;
3849
3850    /**
3851     * Cache the paddingEnd set by the user to append to the scrollbar's size.
3852     *
3853     */
3854    @ViewDebug.ExportedProperty(category = "padding")
3855    int mUserPaddingEnd;
3856
3857    /**
3858     * Cache initial left padding.
3859     *
3860     * @hide
3861     */
3862    int mUserPaddingLeftInitial;
3863
3864    /**
3865     * Cache initial right padding.
3866     *
3867     * @hide
3868     */
3869    int mUserPaddingRightInitial;
3870
3871    /**
3872     * Default undefined padding
3873     */
3874    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
3875
3876    /**
3877     * Cache if a left padding has been defined
3878     */
3879    private boolean mLeftPaddingDefined = false;
3880
3881    /**
3882     * Cache if a right padding has been defined
3883     */
3884    private boolean mRightPaddingDefined = false;
3885
3886    /**
3887     * @hide
3888     */
3889    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
3890    /**
3891     * @hide
3892     */
3893    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
3894
3895    private LongSparseLongArray mMeasureCache;
3896
3897    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
3898    private Drawable mBackground;
3899    private TintInfo mBackgroundTint;
3900
3901    @ViewDebug.ExportedProperty(deepExport = true, prefix = "fg_")
3902    private ForegroundInfo mForegroundInfo;
3903
3904    private Drawable mScrollIndicatorDrawable;
3905
3906    /**
3907     * RenderNode used for backgrounds.
3908     * <p>
3909     * When non-null and valid, this is expected to contain an up-to-date copy
3910     * of the background drawable. It is cleared on temporary detach, and reset
3911     * on cleanup.
3912     */
3913    private RenderNode mBackgroundRenderNode;
3914
3915    private int mBackgroundResource;
3916    private boolean mBackgroundSizeChanged;
3917
3918    /** The default focus highlight.
3919     * @see #mDefaultFocusHighlightEnabled
3920     * @see Drawable#hasFocusStateSpecified()
3921     */
3922    private Drawable mDefaultFocusHighlight;
3923    private Drawable mDefaultFocusHighlightCache;
3924    private boolean mDefaultFocusHighlightSizeChanged;
3925    /**
3926     * True if the default focus highlight is needed on the target device.
3927     */
3928    private static boolean sUseDefaultFocusHighlight;
3929
3930    private String mTransitionName;
3931
3932    static class TintInfo {
3933        ColorStateList mTintList;
3934        PorterDuff.Mode mTintMode;
3935        boolean mHasTintMode;
3936        boolean mHasTintList;
3937    }
3938
3939    private static class ForegroundInfo {
3940        private Drawable mDrawable;
3941        private TintInfo mTintInfo;
3942        private int mGravity = Gravity.FILL;
3943        private boolean mInsidePadding = true;
3944        private boolean mBoundsChanged = true;
3945        private final Rect mSelfBounds = new Rect();
3946        private final Rect mOverlayBounds = new Rect();
3947    }
3948
3949    static class ListenerInfo {
3950        /**
3951         * Listener used to dispatch focus change events.
3952         * This field should be made private, so it is hidden from the SDK.
3953         * {@hide}
3954         */
3955        protected OnFocusChangeListener mOnFocusChangeListener;
3956
3957        /**
3958         * Listeners for layout change events.
3959         */
3960        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
3961
3962        protected OnScrollChangeListener mOnScrollChangeListener;
3963
3964        /**
3965         * Listeners for attach events.
3966         */
3967        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
3968
3969        /**
3970         * Listener used to dispatch click events.
3971         * This field should be made private, so it is hidden from the SDK.
3972         * {@hide}
3973         */
3974        public OnClickListener mOnClickListener;
3975
3976        /**
3977         * Listener used to dispatch long click events.
3978         * This field should be made private, so it is hidden from the SDK.
3979         * {@hide}
3980         */
3981        protected OnLongClickListener mOnLongClickListener;
3982
3983        /**
3984         * Listener used to dispatch context click events. This field should be made private, so it
3985         * is hidden from the SDK.
3986         * {@hide}
3987         */
3988        protected OnContextClickListener mOnContextClickListener;
3989
3990        /**
3991         * Listener used to build the context menu.
3992         * This field should be made private, so it is hidden from the SDK.
3993         * {@hide}
3994         */
3995        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
3996
3997        private OnKeyListener mOnKeyListener;
3998
3999        private OnTouchListener mOnTouchListener;
4000
4001        private OnHoverListener mOnHoverListener;
4002
4003        private OnGenericMotionListener mOnGenericMotionListener;
4004
4005        private OnDragListener mOnDragListener;
4006
4007        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
4008
4009        OnApplyWindowInsetsListener mOnApplyWindowInsetsListener;
4010
4011        OnCapturedPointerListener mOnCapturedPointerListener;
4012    }
4013
4014    ListenerInfo mListenerInfo;
4015
4016    private static class TooltipInfo {
4017        /**
4018         * Text to be displayed in a tooltip popup.
4019         */
4020        @Nullable
4021        CharSequence mTooltipText;
4022
4023        /**
4024         * View-relative position of the tooltip anchor point.
4025         */
4026        int mAnchorX;
4027        int mAnchorY;
4028
4029        /**
4030         * The tooltip popup.
4031         */
4032        @Nullable
4033        TooltipPopup mTooltipPopup;
4034
4035        /**
4036         * Set to true if the tooltip was shown as a result of a long click.
4037         */
4038        boolean mTooltipFromLongClick;
4039
4040        /**
4041         * Keep these Runnables so that they can be used to reschedule.
4042         */
4043        Runnable mShowTooltipRunnable;
4044        Runnable mHideTooltipRunnable;
4045    }
4046
4047    TooltipInfo mTooltipInfo;
4048
4049    // Temporary values used to hold (x,y) coordinates when delegating from the
4050    // two-arg performLongClick() method to the legacy no-arg version.
4051    private float mLongClickX = Float.NaN;
4052    private float mLongClickY = Float.NaN;
4053
4054    /**
4055     * The application environment this view lives in.
4056     * This field should be made private, so it is hidden from the SDK.
4057     * {@hide}
4058     */
4059    @ViewDebug.ExportedProperty(deepExport = true)
4060    protected Context mContext;
4061
4062    private final Resources mResources;
4063
4064    private ScrollabilityCache mScrollCache;
4065
4066    private int[] mDrawableState = null;
4067
4068    ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND;
4069
4070    /**
4071     * Animator that automatically runs based on state changes.
4072     */
4073    private StateListAnimator mStateListAnimator;
4074
4075    /**
4076     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
4077     * the user may specify which view to go to next.
4078     */
4079    private int mNextFocusLeftId = View.NO_ID;
4080
4081    /**
4082     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
4083     * the user may specify which view to go to next.
4084     */
4085    private int mNextFocusRightId = View.NO_ID;
4086
4087    /**
4088     * When this view has focus and the next focus is {@link #FOCUS_UP},
4089     * the user may specify which view to go to next.
4090     */
4091    private int mNextFocusUpId = View.NO_ID;
4092
4093    /**
4094     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
4095     * the user may specify which view to go to next.
4096     */
4097    private int mNextFocusDownId = View.NO_ID;
4098
4099    /**
4100     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
4101     * the user may specify which view to go to next.
4102     */
4103    int mNextFocusForwardId = View.NO_ID;
4104
4105    /**
4106     * User-specified next keyboard navigation cluster in the {@link #FOCUS_FORWARD} direction.
4107     *
4108     * @see #findUserSetNextKeyboardNavigationCluster(View, int)
4109     */
4110    int mNextClusterForwardId = View.NO_ID;
4111
4112    /**
4113     * Whether this View should use a default focus highlight when it gets focused but doesn't
4114     * have {@link android.R.attr#state_focused} defined in its background.
4115     */
4116    boolean mDefaultFocusHighlightEnabled = true;
4117
4118    private CheckForLongPress mPendingCheckForLongPress;
4119    private CheckForTap mPendingCheckForTap = null;
4120    private PerformClick mPerformClick;
4121    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
4122
4123    private UnsetPressedState mUnsetPressedState;
4124
4125    /**
4126     * Whether the long press's action has been invoked.  The tap's action is invoked on the
4127     * up event while a long press is invoked as soon as the long press duration is reached, so
4128     * a long press could be performed before the tap is checked, in which case the tap's action
4129     * should not be invoked.
4130     */
4131    private boolean mHasPerformedLongPress;
4132
4133    /**
4134     * Whether a context click button is currently pressed down. This is true when the stylus is
4135     * touching the screen and the primary button has been pressed, or if a mouse's right button is
4136     * pressed. This is false once the button is released or if the stylus has been lifted.
4137     */
4138    private boolean mInContextButtonPress;
4139
4140    /**
4141     * Whether the next up event should be ignored for the purposes of gesture recognition. This is
4142     * true after a stylus button press has occured, when the next up event should not be recognized
4143     * as a tap.
4144     */
4145    private boolean mIgnoreNextUpEvent;
4146
4147    /**
4148     * The minimum height of the view. We'll try our best to have the height
4149     * of this view to at least this amount.
4150     */
4151    @ViewDebug.ExportedProperty(category = "measurement")
4152    private int mMinHeight;
4153
4154    /**
4155     * The minimum width of the view. We'll try our best to have the width
4156     * of this view to at least this amount.
4157     */
4158    @ViewDebug.ExportedProperty(category = "measurement")
4159    private int mMinWidth;
4160
4161    /**
4162     * The delegate to handle touch events that are physically in this view
4163     * but should be handled by another view.
4164     */
4165    private TouchDelegate mTouchDelegate = null;
4166
4167    /**
4168     * Solid color to use as a background when creating the drawing cache. Enables
4169     * the cache to use 16 bit bitmaps instead of 32 bit.
4170     */
4171    private int mDrawingCacheBackgroundColor = 0;
4172
4173    /**
4174     * Special tree observer used when mAttachInfo is null.
4175     */
4176    private ViewTreeObserver mFloatingTreeObserver;
4177
4178    /**
4179     * Cache the touch slop from the context that created the view.
4180     */
4181    private int mTouchSlop;
4182
4183    /**
4184     * Object that handles automatic animation of view properties.
4185     */
4186    private ViewPropertyAnimator mAnimator = null;
4187
4188    /**
4189     * List of registered FrameMetricsObservers.
4190     */
4191    private ArrayList<FrameMetricsObserver> mFrameMetricsObservers;
4192
4193    /**
4194     * Flag indicating that a drag can cross window boundaries.  When
4195     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called
4196     * with this flag set, all visible applications with targetSdkVersion >=
4197     * {@link android.os.Build.VERSION_CODES#N API 24} will be able to participate
4198     * in the drag operation and receive the dragged content.
4199     *
4200     * <p>If this is the only flag set, then the drag recipient will only have access to text data
4201     * and intents contained in the {@link ClipData} object. Access to URIs contained in the
4202     * {@link ClipData} is determined by other DRAG_FLAG_GLOBAL_* flags</p>
4203     */
4204    public static final int DRAG_FLAG_GLOBAL = 1 << 8;  // 256
4205
4206    /**
4207     * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to
4208     * request read access to the content URI(s) contained in the {@link ClipData} object.
4209     * @see android.content.Intent#FLAG_GRANT_READ_URI_PERMISSION
4210     */
4211    public static final int DRAG_FLAG_GLOBAL_URI_READ = Intent.FLAG_GRANT_READ_URI_PERMISSION;
4212
4213    /**
4214     * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to
4215     * request write access to the content URI(s) contained in the {@link ClipData} object.
4216     * @see android.content.Intent#FLAG_GRANT_WRITE_URI_PERMISSION
4217     */
4218    public static final int DRAG_FLAG_GLOBAL_URI_WRITE = Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
4219
4220    /**
4221     * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link
4222     * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant can be persisted across device
4223     * reboots until explicitly revoked with
4224     * {@link android.content.Context#revokeUriPermission(Uri, int)} Context.revokeUriPermission}.
4225     * @see android.content.Intent#FLAG_GRANT_PERSISTABLE_URI_PERMISSION
4226     */
4227    public static final int DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION =
4228            Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION;
4229
4230    /**
4231     * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link
4232     * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant applies to any URI that is a prefix
4233     * match against the original granted URI.
4234     * @see android.content.Intent#FLAG_GRANT_PREFIX_URI_PERMISSION
4235     */
4236    public static final int DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION =
4237            Intent.FLAG_GRANT_PREFIX_URI_PERMISSION;
4238
4239    /**
4240     * Flag indicating that the drag shadow will be opaque.  When
4241     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called
4242     * with this flag set, the drag shadow will be opaque, otherwise, it will be semitransparent.
4243     */
4244    public static final int DRAG_FLAG_OPAQUE = 1 << 9;
4245
4246    /**
4247     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
4248     */
4249    private float mVerticalScrollFactor;
4250
4251    /**
4252     * Position of the vertical scroll bar.
4253     */
4254    private int mVerticalScrollbarPosition;
4255
4256    /**
4257     * Position the scroll bar at the default position as determined by the system.
4258     */
4259    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
4260
4261    /**
4262     * Position the scroll bar along the left edge.
4263     */
4264    public static final int SCROLLBAR_POSITION_LEFT = 1;
4265
4266    /**
4267     * Position the scroll bar along the right edge.
4268     */
4269    public static final int SCROLLBAR_POSITION_RIGHT = 2;
4270
4271    /**
4272     * Indicates that the view does not have a layer.
4273     *
4274     * @see #getLayerType()
4275     * @see #setLayerType(int, android.graphics.Paint)
4276     * @see #LAYER_TYPE_SOFTWARE
4277     * @see #LAYER_TYPE_HARDWARE
4278     */
4279    public static final int LAYER_TYPE_NONE = 0;
4280
4281    /**
4282     * <p>Indicates that the view has a software layer. A software layer is backed
4283     * by a bitmap and causes the view to be rendered using Android's software
4284     * rendering pipeline, even if hardware acceleration is enabled.</p>
4285     *
4286     * <p>Software layers have various usages:</p>
4287     * <p>When the application is not using hardware acceleration, a software layer
4288     * is useful to apply a specific color filter and/or blending mode and/or
4289     * translucency to a view and all its children.</p>
4290     * <p>When the application is using hardware acceleration, a software layer
4291     * is useful to render drawing primitives not supported by the hardware
4292     * accelerated pipeline. It can also be used to cache a complex view tree
4293     * into a texture and reduce the complexity of drawing operations. For instance,
4294     * when animating a complex view tree with a translation, a software layer can
4295     * be used to render the view tree only once.</p>
4296     * <p>Software layers should be avoided when the affected view tree updates
4297     * often. Every update will require to re-render the software layer, which can
4298     * potentially be slow (particularly when hardware acceleration is turned on
4299     * since the layer will have to be uploaded into a hardware texture after every
4300     * update.)</p>
4301     *
4302     * @see #getLayerType()
4303     * @see #setLayerType(int, android.graphics.Paint)
4304     * @see #LAYER_TYPE_NONE
4305     * @see #LAYER_TYPE_HARDWARE
4306     */
4307    public static final int LAYER_TYPE_SOFTWARE = 1;
4308
4309    /**
4310     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
4311     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
4312     * OpenGL hardware) and causes the view to be rendered using Android's hardware
4313     * rendering pipeline, but only if hardware acceleration is turned on for the
4314     * view hierarchy. When hardware acceleration is turned off, hardware layers
4315     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
4316     *
4317     * <p>A hardware layer is useful to apply a specific color filter and/or
4318     * blending mode and/or translucency to a view and all its children.</p>
4319     * <p>A hardware layer can be used to cache a complex view tree into a
4320     * texture and reduce the complexity of drawing operations. For instance,
4321     * when animating a complex view tree with a translation, a hardware layer can
4322     * be used to render the view tree only once.</p>
4323     * <p>A hardware layer can also be used to increase the rendering quality when
4324     * rotation transformations are applied on a view. It can also be used to
4325     * prevent potential clipping issues when applying 3D transforms on a view.</p>
4326     *
4327     * @see #getLayerType()
4328     * @see #setLayerType(int, android.graphics.Paint)
4329     * @see #LAYER_TYPE_NONE
4330     * @see #LAYER_TYPE_SOFTWARE
4331     */
4332    public static final int LAYER_TYPE_HARDWARE = 2;
4333
4334    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
4335            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
4336            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
4337            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
4338    })
4339    int mLayerType = LAYER_TYPE_NONE;
4340    Paint mLayerPaint;
4341
4342    /**
4343     * Set to true when drawing cache is enabled and cannot be created.
4344     *
4345     * @hide
4346     */
4347    public boolean mCachingFailed;
4348    private Bitmap mDrawingCache;
4349    private Bitmap mUnscaledDrawingCache;
4350
4351    /**
4352     * RenderNode holding View properties, potentially holding a DisplayList of View content.
4353     * <p>
4354     * When non-null and valid, this is expected to contain an up-to-date copy
4355     * of the View content. Its DisplayList content is cleared on temporary detach and reset on
4356     * cleanup.
4357     */
4358    final RenderNode mRenderNode;
4359
4360    /**
4361     * Set to true when the view is sending hover accessibility events because it
4362     * is the innermost hovered view.
4363     */
4364    private boolean mSendingHoverAccessibilityEvents;
4365
4366    /**
4367     * Delegate for injecting accessibility functionality.
4368     */
4369    AccessibilityDelegate mAccessibilityDelegate;
4370
4371    /**
4372     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
4373     * and add/remove objects to/from the overlay directly through the Overlay methods.
4374     */
4375    ViewOverlay mOverlay;
4376
4377    /**
4378     * The currently active parent view for receiving delegated nested scrolling events.
4379     * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared
4380     * by {@link #stopNestedScroll()} at the same point where we clear
4381     * requestDisallowInterceptTouchEvent.
4382     */
4383    private ViewParent mNestedScrollingParent;
4384
4385    /**
4386     * Consistency verifier for debugging purposes.
4387     * @hide
4388     */
4389    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
4390            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
4391                    new InputEventConsistencyVerifier(this, 0) : null;
4392
4393    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
4394
4395    private int[] mTempNestedScrollConsumed;
4396
4397    /**
4398     * An overlay is going to draw this View instead of being drawn as part of this
4399     * View's parent. mGhostView is the View in the Overlay that must be invalidated
4400     * when this view is invalidated.
4401     */
4402    GhostView mGhostView;
4403
4404    /**
4405     * Holds pairs of adjacent attribute data: attribute name followed by its value.
4406     * @hide
4407     */
4408    @ViewDebug.ExportedProperty(category = "attributes", hasAdjacentMapping = true)
4409    public String[] mAttributes;
4410
4411    /**
4412     * Maps a Resource id to its name.
4413     */
4414    private static SparseArray<String> mAttributeMap;
4415
4416    /**
4417     * Queue of pending runnables. Used to postpone calls to post() until this
4418     * view is attached and has a handler.
4419     */
4420    private HandlerActionQueue mRunQueue;
4421
4422    /**
4423     * The pointer icon when the mouse hovers on this view. The default is null.
4424     */
4425    private PointerIcon mPointerIcon;
4426
4427    /**
4428     * @hide
4429     */
4430    String mStartActivityRequestWho;
4431
4432    @Nullable
4433    private RoundScrollbarRenderer mRoundScrollbarRenderer;
4434
4435    /** Used to delay visibility updates sent to the autofill manager */
4436    private Handler mVisibilityChangeForAutofillHandler;
4437
4438    /**
4439     * Simple constructor to use when creating a view from code.
4440     *
4441     * @param context The Context the view is running in, through which it can
4442     *        access the current theme, resources, etc.
4443     */
4444    public View(Context context) {
4445        mContext = context;
4446        mResources = context != null ? context.getResources() : null;
4447        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED | FOCUSABLE_AUTO;
4448        // Set some flags defaults
4449        mPrivateFlags2 =
4450                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
4451                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
4452                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
4453                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
4454                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
4455                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
4456        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
4457        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
4458        mUserPaddingStart = UNDEFINED_PADDING;
4459        mUserPaddingEnd = UNDEFINED_PADDING;
4460        mRenderNode = RenderNode.create(getClass().getName(), this);
4461
4462        if (!sCompatibilityDone && context != null) {
4463            final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
4464
4465            // Older apps may need this compatibility hack for measurement.
4466            sUseBrokenMakeMeasureSpec = targetSdkVersion <= Build.VERSION_CODES.JELLY_BEAN_MR1;
4467
4468            // Older apps expect onMeasure() to always be called on a layout pass, regardless
4469            // of whether a layout was requested on that View.
4470            sIgnoreMeasureCache = targetSdkVersion < Build.VERSION_CODES.KITKAT;
4471
4472            Canvas.sCompatibilityRestore = targetSdkVersion < Build.VERSION_CODES.M;
4473            Canvas.sCompatibilitySetBitmap = targetSdkVersion < Build.VERSION_CODES.O;
4474
4475            // In M and newer, our widgets can pass a "hint" value in the size
4476            // for UNSPECIFIED MeasureSpecs. This lets child views of scrolling containers
4477            // know what the expected parent size is going to be, so e.g. list items can size
4478            // themselves at 1/3 the size of their container. It breaks older apps though,
4479            // specifically apps that use some popular open source libraries.
4480            sUseZeroUnspecifiedMeasureSpec = targetSdkVersion < Build.VERSION_CODES.M;
4481
4482            // Old versions of the platform would give different results from
4483            // LinearLayout measurement passes using EXACTLY and non-EXACTLY
4484            // modes, so we always need to run an additional EXACTLY pass.
4485            sAlwaysRemeasureExactly = targetSdkVersion <= Build.VERSION_CODES.M;
4486
4487            // Prior to N, layout params could change without requiring a
4488            // subsequent call to setLayoutParams() and they would usually
4489            // work. Partial layout breaks this assumption.
4490            sLayoutParamsAlwaysChanged = targetSdkVersion <= Build.VERSION_CODES.M;
4491
4492            // Prior to N, TextureView would silently ignore calls to setBackground/setForeground.
4493            // On N+, we throw, but that breaks compatibility with apps that use these methods.
4494            sTextureViewIgnoresDrawableSetters = targetSdkVersion <= Build.VERSION_CODES.M;
4495
4496            // Prior to N, we would drop margins in LayoutParam conversions. The fix triggers bugs
4497            // in apps so we target check it to avoid breaking existing apps.
4498            sPreserveMarginParamsInLayoutParamConversion =
4499                    targetSdkVersion >= Build.VERSION_CODES.N;
4500
4501            sCascadedDragDrop = targetSdkVersion < Build.VERSION_CODES.N;
4502
4503            sHasFocusableExcludeAutoFocusable = targetSdkVersion < Build.VERSION_CODES.O;
4504
4505            sAutoFocusableOffUIThreadWontNotifyParents = targetSdkVersion < Build.VERSION_CODES.O;
4506
4507            sUseDefaultFocusHighlight = context.getResources().getBoolean(
4508                    com.android.internal.R.bool.config_useDefaultFocusHighlight);
4509
4510            sCompatibilityDone = true;
4511        }
4512    }
4513
4514    /**
4515     * Constructor that is called when inflating a view from XML. This is called
4516     * when a view is being constructed from an XML file, supplying attributes
4517     * that were specified in the XML file. This version uses a default style of
4518     * 0, so the only attribute values applied are those in the Context's Theme
4519     * and the given AttributeSet.
4520     *
4521     * <p>
4522     * The method onFinishInflate() will be called after all children have been
4523     * added.
4524     *
4525     * @param context The Context the view is running in, through which it can
4526     *        access the current theme, resources, etc.
4527     * @param attrs The attributes of the XML tag that is inflating the view.
4528     * @see #View(Context, AttributeSet, int)
4529     */
4530    public View(Context context, @Nullable AttributeSet attrs) {
4531        this(context, attrs, 0);
4532    }
4533
4534    /**
4535     * Perform inflation from XML and apply a class-specific base style from a
4536     * theme attribute. This constructor of View allows subclasses to use their
4537     * own base style when they are inflating. For example, a Button class's
4538     * constructor would call this version of the super class constructor and
4539     * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this
4540     * allows the theme's button style to modify all of the base view attributes
4541     * (in particular its background) as well as the Button class's attributes.
4542     *
4543     * @param context The Context the view is running in, through which it can
4544     *        access the current theme, resources, etc.
4545     * @param attrs The attributes of the XML tag that is inflating the view.
4546     * @param defStyleAttr An attribute in the current theme that contains a
4547     *        reference to a style resource that supplies default values for
4548     *        the view. Can be 0 to not look for defaults.
4549     * @see #View(Context, AttributeSet)
4550     */
4551    public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
4552        this(context, attrs, defStyleAttr, 0);
4553    }
4554
4555    /**
4556     * Perform inflation from XML and apply a class-specific base style from a
4557     * theme attribute or style resource. This constructor of View allows
4558     * subclasses to use their own base style when they are inflating.
4559     * <p>
4560     * When determining the final value of a particular attribute, there are
4561     * four inputs that come into play:
4562     * <ol>
4563     * <li>Any attribute values in the given AttributeSet.
4564     * <li>The style resource specified in the AttributeSet (named "style").
4565     * <li>The default style specified by <var>defStyleAttr</var>.
4566     * <li>The default style specified by <var>defStyleRes</var>.
4567     * <li>The base values in this theme.
4568     * </ol>
4569     * <p>
4570     * Each of these inputs is considered in-order, with the first listed taking
4571     * precedence over the following ones. In other words, if in the
4572     * AttributeSet you have supplied <code>&lt;Button * textColor="#ff000000"&gt;</code>
4573     * , then the button's text will <em>always</em> be black, regardless of
4574     * what is specified in any of the styles.
4575     *
4576     * @param context The Context the view is running in, through which it can
4577     *        access the current theme, resources, etc.
4578     * @param attrs The attributes of the XML tag that is inflating the view.
4579     * @param defStyleAttr An attribute in the current theme that contains a
4580     *        reference to a style resource that supplies default values for
4581     *        the view. Can be 0 to not look for defaults.
4582     * @param defStyleRes A resource identifier of a style resource that
4583     *        supplies default values for the view, used only if
4584     *        defStyleAttr is 0 or can not be found in the theme. Can be 0
4585     *        to not look for defaults.
4586     * @see #View(Context, AttributeSet, int)
4587     */
4588    public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
4589        this(context);
4590
4591        final TypedArray a = context.obtainStyledAttributes(
4592                attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes);
4593
4594        if (mDebugViewAttributes) {
4595            saveAttributeData(attrs, a);
4596        }
4597
4598        Drawable background = null;
4599
4600        int leftPadding = -1;
4601        int topPadding = -1;
4602        int rightPadding = -1;
4603        int bottomPadding = -1;
4604        int startPadding = UNDEFINED_PADDING;
4605        int endPadding = UNDEFINED_PADDING;
4606
4607        int padding = -1;
4608        int paddingHorizontal = -1;
4609        int paddingVertical = -1;
4610
4611        int viewFlagValues = 0;
4612        int viewFlagMasks = 0;
4613
4614        boolean setScrollContainer = false;
4615
4616        int x = 0;
4617        int y = 0;
4618
4619        float tx = 0;
4620        float ty = 0;
4621        float tz = 0;
4622        float elevation = 0;
4623        float rotation = 0;
4624        float rotationX = 0;
4625        float rotationY = 0;
4626        float sx = 1f;
4627        float sy = 1f;
4628        boolean transformSet = false;
4629
4630        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
4631        int overScrollMode = mOverScrollMode;
4632        boolean initializeScrollbars = false;
4633        boolean initializeScrollIndicators = false;
4634
4635        boolean startPaddingDefined = false;
4636        boolean endPaddingDefined = false;
4637        boolean leftPaddingDefined = false;
4638        boolean rightPaddingDefined = false;
4639
4640        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
4641
4642        // Set default values.
4643        viewFlagValues |= FOCUSABLE_AUTO;
4644        viewFlagMasks |= FOCUSABLE_AUTO;
4645
4646        final int N = a.getIndexCount();
4647        for (int i = 0; i < N; i++) {
4648            int attr = a.getIndex(i);
4649            switch (attr) {
4650                case com.android.internal.R.styleable.View_background:
4651                    background = a.getDrawable(attr);
4652                    break;
4653                case com.android.internal.R.styleable.View_padding:
4654                    padding = a.getDimensionPixelSize(attr, -1);
4655                    mUserPaddingLeftInitial = padding;
4656                    mUserPaddingRightInitial = padding;
4657                    leftPaddingDefined = true;
4658                    rightPaddingDefined = true;
4659                    break;
4660                case com.android.internal.R.styleable.View_paddingHorizontal:
4661                    paddingHorizontal = a.getDimensionPixelSize(attr, -1);
4662                    mUserPaddingLeftInitial = paddingHorizontal;
4663                    mUserPaddingRightInitial = paddingHorizontal;
4664                    leftPaddingDefined = true;
4665                    rightPaddingDefined = true;
4666                    break;
4667                case com.android.internal.R.styleable.View_paddingVertical:
4668                    paddingVertical = a.getDimensionPixelSize(attr, -1);
4669                    break;
4670                 case com.android.internal.R.styleable.View_paddingLeft:
4671                    leftPadding = a.getDimensionPixelSize(attr, -1);
4672                    mUserPaddingLeftInitial = leftPadding;
4673                    leftPaddingDefined = true;
4674                    break;
4675                case com.android.internal.R.styleable.View_paddingTop:
4676                    topPadding = a.getDimensionPixelSize(attr, -1);
4677                    break;
4678                case com.android.internal.R.styleable.View_paddingRight:
4679                    rightPadding = a.getDimensionPixelSize(attr, -1);
4680                    mUserPaddingRightInitial = rightPadding;
4681                    rightPaddingDefined = true;
4682                    break;
4683                case com.android.internal.R.styleable.View_paddingBottom:
4684                    bottomPadding = a.getDimensionPixelSize(attr, -1);
4685                    break;
4686                case com.android.internal.R.styleable.View_paddingStart:
4687                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
4688                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
4689                    break;
4690                case com.android.internal.R.styleable.View_paddingEnd:
4691                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
4692                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
4693                    break;
4694                case com.android.internal.R.styleable.View_scrollX:
4695                    x = a.getDimensionPixelOffset(attr, 0);
4696                    break;
4697                case com.android.internal.R.styleable.View_scrollY:
4698                    y = a.getDimensionPixelOffset(attr, 0);
4699                    break;
4700                case com.android.internal.R.styleable.View_alpha:
4701                    setAlpha(a.getFloat(attr, 1f));
4702                    break;
4703                case com.android.internal.R.styleable.View_transformPivotX:
4704                    setPivotX(a.getDimension(attr, 0));
4705                    break;
4706                case com.android.internal.R.styleable.View_transformPivotY:
4707                    setPivotY(a.getDimension(attr, 0));
4708                    break;
4709                case com.android.internal.R.styleable.View_translationX:
4710                    tx = a.getDimension(attr, 0);
4711                    transformSet = true;
4712                    break;
4713                case com.android.internal.R.styleable.View_translationY:
4714                    ty = a.getDimension(attr, 0);
4715                    transformSet = true;
4716                    break;
4717                case com.android.internal.R.styleable.View_translationZ:
4718                    tz = a.getDimension(attr, 0);
4719                    transformSet = true;
4720                    break;
4721                case com.android.internal.R.styleable.View_elevation:
4722                    elevation = a.getDimension(attr, 0);
4723                    transformSet = true;
4724                    break;
4725                case com.android.internal.R.styleable.View_rotation:
4726                    rotation = a.getFloat(attr, 0);
4727                    transformSet = true;
4728                    break;
4729                case com.android.internal.R.styleable.View_rotationX:
4730                    rotationX = a.getFloat(attr, 0);
4731                    transformSet = true;
4732                    break;
4733                case com.android.internal.R.styleable.View_rotationY:
4734                    rotationY = a.getFloat(attr, 0);
4735                    transformSet = true;
4736                    break;
4737                case com.android.internal.R.styleable.View_scaleX:
4738                    sx = a.getFloat(attr, 1f);
4739                    transformSet = true;
4740                    break;
4741                case com.android.internal.R.styleable.View_scaleY:
4742                    sy = a.getFloat(attr, 1f);
4743                    transformSet = true;
4744                    break;
4745                case com.android.internal.R.styleable.View_id:
4746                    mID = a.getResourceId(attr, NO_ID);
4747                    break;
4748                case com.android.internal.R.styleable.View_tag:
4749                    mTag = a.getText(attr);
4750                    break;
4751                case com.android.internal.R.styleable.View_fitsSystemWindows:
4752                    if (a.getBoolean(attr, false)) {
4753                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
4754                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
4755                    }
4756                    break;
4757                case com.android.internal.R.styleable.View_focusable:
4758                    viewFlagValues = (viewFlagValues & ~FOCUSABLE_MASK) | getFocusableAttribute(a);
4759                    if ((viewFlagValues & FOCUSABLE_AUTO) == 0) {
4760                        viewFlagMasks |= FOCUSABLE_MASK;
4761                    }
4762                    break;
4763                case com.android.internal.R.styleable.View_focusableInTouchMode:
4764                    if (a.getBoolean(attr, false)) {
4765                        // unset auto focus since focusableInTouchMode implies explicit focusable
4766                        viewFlagValues &= ~FOCUSABLE_AUTO;
4767                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
4768                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
4769                    }
4770                    break;
4771                case com.android.internal.R.styleable.View_clickable:
4772                    if (a.getBoolean(attr, false)) {
4773                        viewFlagValues |= CLICKABLE;
4774                        viewFlagMasks |= CLICKABLE;
4775                    }
4776                    break;
4777                case com.android.internal.R.styleable.View_longClickable:
4778                    if (a.getBoolean(attr, false)) {
4779                        viewFlagValues |= LONG_CLICKABLE;
4780                        viewFlagMasks |= LONG_CLICKABLE;
4781                    }
4782                    break;
4783                case com.android.internal.R.styleable.View_contextClickable:
4784                    if (a.getBoolean(attr, false)) {
4785                        viewFlagValues |= CONTEXT_CLICKABLE;
4786                        viewFlagMasks |= CONTEXT_CLICKABLE;
4787                    }
4788                    break;
4789                case com.android.internal.R.styleable.View_saveEnabled:
4790                    if (!a.getBoolean(attr, true)) {
4791                        viewFlagValues |= SAVE_DISABLED;
4792                        viewFlagMasks |= SAVE_DISABLED_MASK;
4793                    }
4794                    break;
4795                case com.android.internal.R.styleable.View_duplicateParentState:
4796                    if (a.getBoolean(attr, false)) {
4797                        viewFlagValues |= DUPLICATE_PARENT_STATE;
4798                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
4799                    }
4800                    break;
4801                case com.android.internal.R.styleable.View_visibility:
4802                    final int visibility = a.getInt(attr, 0);
4803                    if (visibility != 0) {
4804                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
4805                        viewFlagMasks |= VISIBILITY_MASK;
4806                    }
4807                    break;
4808                case com.android.internal.R.styleable.View_layoutDirection:
4809                    // Clear any layout direction flags (included resolved bits) already set
4810                    mPrivateFlags2 &=
4811                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
4812                    // Set the layout direction flags depending on the value of the attribute
4813                    final int layoutDirection = a.getInt(attr, -1);
4814                    final int value = (layoutDirection != -1) ?
4815                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
4816                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
4817                    break;
4818                case com.android.internal.R.styleable.View_drawingCacheQuality:
4819                    final int cacheQuality = a.getInt(attr, 0);
4820                    if (cacheQuality != 0) {
4821                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
4822                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
4823                    }
4824                    break;
4825                case com.android.internal.R.styleable.View_contentDescription:
4826                    setContentDescription(a.getString(attr));
4827                    break;
4828                case com.android.internal.R.styleable.View_accessibilityTraversalBefore:
4829                    setAccessibilityTraversalBefore(a.getResourceId(attr, NO_ID));
4830                    break;
4831                case com.android.internal.R.styleable.View_accessibilityTraversalAfter:
4832                    setAccessibilityTraversalAfter(a.getResourceId(attr, NO_ID));
4833                    break;
4834                case com.android.internal.R.styleable.View_labelFor:
4835                    setLabelFor(a.getResourceId(attr, NO_ID));
4836                    break;
4837                case com.android.internal.R.styleable.View_soundEffectsEnabled:
4838                    if (!a.getBoolean(attr, true)) {
4839                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
4840                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
4841                    }
4842                    break;
4843                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
4844                    if (!a.getBoolean(attr, true)) {
4845                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
4846                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
4847                    }
4848                    break;
4849                case R.styleable.View_scrollbars:
4850                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
4851                    if (scrollbars != SCROLLBARS_NONE) {
4852                        viewFlagValues |= scrollbars;
4853                        viewFlagMasks |= SCROLLBARS_MASK;
4854                        initializeScrollbars = true;
4855                    }
4856                    break;
4857                //noinspection deprecation
4858                case R.styleable.View_fadingEdge:
4859                    if (targetSdkVersion >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
4860                        // Ignore the attribute starting with ICS
4861                        break;
4862                    }
4863                    // With builds < ICS, fall through and apply fading edges
4864                case R.styleable.View_requiresFadingEdge:
4865                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
4866                    if (fadingEdge != FADING_EDGE_NONE) {
4867                        viewFlagValues |= fadingEdge;
4868                        viewFlagMasks |= FADING_EDGE_MASK;
4869                        initializeFadingEdgeInternal(a);
4870                    }
4871                    break;
4872                case R.styleable.View_scrollbarStyle:
4873                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
4874                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4875                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
4876                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
4877                    }
4878                    break;
4879                case R.styleable.View_isScrollContainer:
4880                    setScrollContainer = true;
4881                    if (a.getBoolean(attr, false)) {
4882                        setScrollContainer(true);
4883                    }
4884                    break;
4885                case com.android.internal.R.styleable.View_keepScreenOn:
4886                    if (a.getBoolean(attr, false)) {
4887                        viewFlagValues |= KEEP_SCREEN_ON;
4888                        viewFlagMasks |= KEEP_SCREEN_ON;
4889                    }
4890                    break;
4891                case R.styleable.View_filterTouchesWhenObscured:
4892                    if (a.getBoolean(attr, false)) {
4893                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
4894                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
4895                    }
4896                    break;
4897                case R.styleable.View_nextFocusLeft:
4898                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
4899                    break;
4900                case R.styleable.View_nextFocusRight:
4901                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
4902                    break;
4903                case R.styleable.View_nextFocusUp:
4904                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
4905                    break;
4906                case R.styleable.View_nextFocusDown:
4907                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
4908                    break;
4909                case R.styleable.View_nextFocusForward:
4910                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
4911                    break;
4912                case R.styleable.View_nextClusterForward:
4913                    mNextClusterForwardId = a.getResourceId(attr, View.NO_ID);
4914                    break;
4915                case R.styleable.View_minWidth:
4916                    mMinWidth = a.getDimensionPixelSize(attr, 0);
4917                    break;
4918                case R.styleable.View_minHeight:
4919                    mMinHeight = a.getDimensionPixelSize(attr, 0);
4920                    break;
4921                case R.styleable.View_onClick:
4922                    if (context.isRestricted()) {
4923                        throw new IllegalStateException("The android:onClick attribute cannot "
4924                                + "be used within a restricted context");
4925                    }
4926
4927                    final String handlerName = a.getString(attr);
4928                    if (handlerName != null) {
4929                        setOnClickListener(new DeclaredOnClickListener(this, handlerName));
4930                    }
4931                    break;
4932                case R.styleable.View_overScrollMode:
4933                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
4934                    break;
4935                case R.styleable.View_verticalScrollbarPosition:
4936                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
4937                    break;
4938                case R.styleable.View_layerType:
4939                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
4940                    break;
4941                case R.styleable.View_textDirection:
4942                    // Clear any text direction flag already set
4943                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
4944                    // Set the text direction flags depending on the value of the attribute
4945                    final int textDirection = a.getInt(attr, -1);
4946                    if (textDirection != -1) {
4947                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
4948                    }
4949                    break;
4950                case R.styleable.View_textAlignment:
4951                    // Clear any text alignment flag already set
4952                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
4953                    // Set the text alignment flag depending on the value of the attribute
4954                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
4955                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
4956                    break;
4957                case R.styleable.View_importantForAccessibility:
4958                    setImportantForAccessibility(a.getInt(attr,
4959                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
4960                    break;
4961                case R.styleable.View_accessibilityLiveRegion:
4962                    setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT));
4963                    break;
4964                case R.styleable.View_transitionName:
4965                    setTransitionName(a.getString(attr));
4966                    break;
4967                case R.styleable.View_nestedScrollingEnabled:
4968                    setNestedScrollingEnabled(a.getBoolean(attr, false));
4969                    break;
4970                case R.styleable.View_stateListAnimator:
4971                    setStateListAnimator(AnimatorInflater.loadStateListAnimator(context,
4972                            a.getResourceId(attr, 0)));
4973                    break;
4974                case R.styleable.View_backgroundTint:
4975                    // This will get applied later during setBackground().
4976                    if (mBackgroundTint == null) {
4977                        mBackgroundTint = new TintInfo();
4978                    }
4979                    mBackgroundTint.mTintList = a.getColorStateList(
4980                            R.styleable.View_backgroundTint);
4981                    mBackgroundTint.mHasTintList = true;
4982                    break;
4983                case R.styleable.View_backgroundTintMode:
4984                    // This will get applied later during setBackground().
4985                    if (mBackgroundTint == null) {
4986                        mBackgroundTint = new TintInfo();
4987                    }
4988                    mBackgroundTint.mTintMode = Drawable.parseTintMode(a.getInt(
4989                            R.styleable.View_backgroundTintMode, -1), null);
4990                    mBackgroundTint.mHasTintMode = true;
4991                    break;
4992                case R.styleable.View_outlineProvider:
4993                    setOutlineProviderFromAttribute(a.getInt(R.styleable.View_outlineProvider,
4994                            PROVIDER_BACKGROUND));
4995                    break;
4996                case R.styleable.View_foreground:
4997                    if (targetSdkVersion >= Build.VERSION_CODES.M || this instanceof FrameLayout) {
4998                        setForeground(a.getDrawable(attr));
4999                    }
5000                    break;
5001                case R.styleable.View_foregroundGravity:
5002                    if (targetSdkVersion >= Build.VERSION_CODES.M || this instanceof FrameLayout) {
5003                        setForegroundGravity(a.getInt(attr, Gravity.NO_GRAVITY));
5004                    }
5005                    break;
5006                case R.styleable.View_foregroundTintMode:
5007                    if (targetSdkVersion >= Build.VERSION_CODES.M || this instanceof FrameLayout) {
5008                        setForegroundTintMode(Drawable.parseTintMode(a.getInt(attr, -1), null));
5009                    }
5010                    break;
5011                case R.styleable.View_foregroundTint:
5012                    if (targetSdkVersion >= Build.VERSION_CODES.M || this instanceof FrameLayout) {
5013                        setForegroundTintList(a.getColorStateList(attr));
5014                    }
5015                    break;
5016                case R.styleable.View_foregroundInsidePadding:
5017                    if (targetSdkVersion >= Build.VERSION_CODES.M || this instanceof FrameLayout) {
5018                        if (mForegroundInfo == null) {
5019                            mForegroundInfo = new ForegroundInfo();
5020                        }
5021                        mForegroundInfo.mInsidePadding = a.getBoolean(attr,
5022                                mForegroundInfo.mInsidePadding);
5023                    }
5024                    break;
5025                case R.styleable.View_scrollIndicators:
5026                    final int scrollIndicators =
5027                            (a.getInt(attr, 0) << SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT)
5028                                    & SCROLL_INDICATORS_PFLAG3_MASK;
5029                    if (scrollIndicators != 0) {
5030                        mPrivateFlags3 |= scrollIndicators;
5031                        initializeScrollIndicators = true;
5032                    }
5033                    break;
5034                case R.styleable.View_pointerIcon:
5035                    final int resourceId = a.getResourceId(attr, 0);
5036                    if (resourceId != 0) {
5037                        setPointerIcon(PointerIcon.load(
5038                                context.getResources(), resourceId));
5039                    } else {
5040                        final int pointerType = a.getInt(attr, PointerIcon.TYPE_NOT_SPECIFIED);
5041                        if (pointerType != PointerIcon.TYPE_NOT_SPECIFIED) {
5042                            setPointerIcon(PointerIcon.getSystemIcon(context, pointerType));
5043                        }
5044                    }
5045                    break;
5046                case R.styleable.View_forceHasOverlappingRendering:
5047                    if (a.peekValue(attr) != null) {
5048                        forceHasOverlappingRendering(a.getBoolean(attr, true));
5049                    }
5050                    break;
5051                case R.styleable.View_tooltipText:
5052                    setTooltipText(a.getText(attr));
5053                    break;
5054                case R.styleable.View_keyboardNavigationCluster:
5055                    if (a.peekValue(attr) != null) {
5056                        setKeyboardNavigationCluster(a.getBoolean(attr, true));
5057                    }
5058                    break;
5059                case R.styleable.View_focusedByDefault:
5060                    if (a.peekValue(attr) != null) {
5061                        setFocusedByDefault(a.getBoolean(attr, true));
5062                    }
5063                    break;
5064                case R.styleable.View_autofillHints:
5065                    if (a.peekValue(attr) != null) {
5066                        CharSequence[] rawHints = null;
5067                        String rawString = null;
5068
5069                        if (a.getType(attr) == TypedValue.TYPE_REFERENCE) {
5070                            int resId = a.getResourceId(attr, 0);
5071
5072                            try {
5073                                rawHints = a.getTextArray(attr);
5074                            } catch (Resources.NotFoundException e) {
5075                                rawString = getResources().getString(resId);
5076                            }
5077                        } else {
5078                            rawString = a.getString(attr);
5079                        }
5080
5081                        if (rawHints == null) {
5082                            if (rawString == null) {
5083                                throw new IllegalArgumentException(
5084                                        "Could not resolve autofillHints");
5085                            } else {
5086                                rawHints = rawString.split(",");
5087                            }
5088                        }
5089
5090                        String[] hints = new String[rawHints.length];
5091
5092                        int numHints = rawHints.length;
5093                        for (int rawHintNum = 0; rawHintNum < numHints; rawHintNum++) {
5094                            hints[rawHintNum] = rawHints[rawHintNum].toString().trim();
5095                        }
5096                        setAutofillHints(hints);
5097                    }
5098                    break;
5099                case R.styleable.View_importantForAutofill:
5100                    if (a.peekValue(attr) != null) {
5101                        setImportantForAutofill(a.getInt(attr, IMPORTANT_FOR_AUTOFILL_AUTO));
5102                    }
5103                    break;
5104                case R.styleable.View_defaultFocusHighlightEnabled:
5105                    if (a.peekValue(attr) != null) {
5106                        setDefaultFocusHighlightEnabled(a.getBoolean(attr, true));
5107                    }
5108                    break;
5109            }
5110        }
5111
5112        setOverScrollMode(overScrollMode);
5113
5114        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
5115        // the resolved layout direction). Those cached values will be used later during padding
5116        // resolution.
5117        mUserPaddingStart = startPadding;
5118        mUserPaddingEnd = endPadding;
5119
5120        if (background != null) {
5121            setBackground(background);
5122        }
5123
5124        // setBackground above will record that padding is currently provided by the background.
5125        // If we have padding specified via xml, record that here instead and use it.
5126        mLeftPaddingDefined = leftPaddingDefined;
5127        mRightPaddingDefined = rightPaddingDefined;
5128
5129        if (padding >= 0) {
5130            leftPadding = padding;
5131            topPadding = padding;
5132            rightPadding = padding;
5133            bottomPadding = padding;
5134            mUserPaddingLeftInitial = padding;
5135            mUserPaddingRightInitial = padding;
5136        } else {
5137            if (paddingHorizontal >= 0) {
5138                leftPadding = paddingHorizontal;
5139                rightPadding = paddingHorizontal;
5140                mUserPaddingLeftInitial = paddingHorizontal;
5141                mUserPaddingRightInitial = paddingHorizontal;
5142            }
5143            if (paddingVertical >= 0) {
5144                topPadding = paddingVertical;
5145                bottomPadding = paddingVertical;
5146            }
5147        }
5148
5149        if (isRtlCompatibilityMode()) {
5150            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
5151            // left / right padding are used if defined (meaning here nothing to do). If they are not
5152            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
5153            // start / end and resolve them as left / right (layout direction is not taken into account).
5154            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
5155            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
5156            // defined.
5157            if (!mLeftPaddingDefined && startPaddingDefined) {
5158                leftPadding = startPadding;
5159            }
5160            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
5161            if (!mRightPaddingDefined && endPaddingDefined) {
5162                rightPadding = endPadding;
5163            }
5164            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
5165        } else {
5166            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
5167            // values defined. Otherwise, left /right values are used.
5168            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
5169            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
5170            // defined.
5171            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
5172
5173            if (mLeftPaddingDefined && !hasRelativePadding) {
5174                mUserPaddingLeftInitial = leftPadding;
5175            }
5176            if (mRightPaddingDefined && !hasRelativePadding) {
5177                mUserPaddingRightInitial = rightPadding;
5178            }
5179        }
5180
5181        internalSetPadding(
5182                mUserPaddingLeftInitial,
5183                topPadding >= 0 ? topPadding : mPaddingTop,
5184                mUserPaddingRightInitial,
5185                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
5186
5187        if (viewFlagMasks != 0) {
5188            setFlags(viewFlagValues, viewFlagMasks);
5189        }
5190
5191        if (initializeScrollbars) {
5192            initializeScrollbarsInternal(a);
5193        }
5194
5195        if (initializeScrollIndicators) {
5196            initializeScrollIndicatorsInternal();
5197        }
5198
5199        a.recycle();
5200
5201        // Needs to be called after mViewFlags is set
5202        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
5203            recomputePadding();
5204        }
5205
5206        if (x != 0 || y != 0) {
5207            scrollTo(x, y);
5208        }
5209
5210        if (transformSet) {
5211            setTranslationX(tx);
5212            setTranslationY(ty);
5213            setTranslationZ(tz);
5214            setElevation(elevation);
5215            setRotation(rotation);
5216            setRotationX(rotationX);
5217            setRotationY(rotationY);
5218            setScaleX(sx);
5219            setScaleY(sy);
5220        }
5221
5222        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
5223            setScrollContainer(true);
5224        }
5225
5226        computeOpaqueFlags();
5227    }
5228
5229    /**
5230     * An implementation of OnClickListener that attempts to lazily load a
5231     * named click handling method from a parent or ancestor context.
5232     */
5233    private static class DeclaredOnClickListener implements OnClickListener {
5234        private final View mHostView;
5235        private final String mMethodName;
5236
5237        private Method mResolvedMethod;
5238        private Context mResolvedContext;
5239
5240        public DeclaredOnClickListener(@NonNull View hostView, @NonNull String methodName) {
5241            mHostView = hostView;
5242            mMethodName = methodName;
5243        }
5244
5245        @Override
5246        public void onClick(@NonNull View v) {
5247            if (mResolvedMethod == null) {
5248                resolveMethod(mHostView.getContext(), mMethodName);
5249            }
5250
5251            try {
5252                mResolvedMethod.invoke(mResolvedContext, v);
5253            } catch (IllegalAccessException e) {
5254                throw new IllegalStateException(
5255                        "Could not execute non-public method for android:onClick", e);
5256            } catch (InvocationTargetException e) {
5257                throw new IllegalStateException(
5258                        "Could not execute method for android:onClick", e);
5259            }
5260        }
5261
5262        @NonNull
5263        private void resolveMethod(@Nullable Context context, @NonNull String name) {
5264            while (context != null) {
5265                try {
5266                    if (!context.isRestricted()) {
5267                        final Method method = context.getClass().getMethod(mMethodName, View.class);
5268                        if (method != null) {
5269                            mResolvedMethod = method;
5270                            mResolvedContext = context;
5271                            return;
5272                        }
5273                    }
5274                } catch (NoSuchMethodException e) {
5275                    // Failed to find method, keep searching up the hierarchy.
5276                }
5277
5278                if (context instanceof ContextWrapper) {
5279                    context = ((ContextWrapper) context).getBaseContext();
5280                } else {
5281                    // Can't search up the hierarchy, null out and fail.
5282                    context = null;
5283                }
5284            }
5285
5286            final int id = mHostView.getId();
5287            final String idText = id == NO_ID ? "" : " with id '"
5288                    + mHostView.getContext().getResources().getResourceEntryName(id) + "'";
5289            throw new IllegalStateException("Could not find method " + mMethodName
5290                    + "(View) in a parent or ancestor Context for android:onClick "
5291                    + "attribute defined on view " + mHostView.getClass() + idText);
5292        }
5293    }
5294
5295    /**
5296     * Non-public constructor for use in testing
5297     */
5298    View() {
5299        mResources = null;
5300        mRenderNode = RenderNode.create(getClass().getName(), this);
5301    }
5302
5303    final boolean debugDraw() {
5304        return DEBUG_DRAW || mAttachInfo != null && mAttachInfo.mDebugLayout;
5305    }
5306
5307    private static SparseArray<String> getAttributeMap() {
5308        if (mAttributeMap == null) {
5309            mAttributeMap = new SparseArray<>();
5310        }
5311        return mAttributeMap;
5312    }
5313
5314    private void saveAttributeData(@Nullable AttributeSet attrs, @NonNull TypedArray t) {
5315        final int attrsCount = attrs == null ? 0 : attrs.getAttributeCount();
5316        final int indexCount = t.getIndexCount();
5317        final String[] attributes = new String[(attrsCount + indexCount) * 2];
5318
5319        int i = 0;
5320
5321        // Store raw XML attributes.
5322        for (int j = 0; j < attrsCount; ++j) {
5323            attributes[i] = attrs.getAttributeName(j);
5324            attributes[i + 1] = attrs.getAttributeValue(j);
5325            i += 2;
5326        }
5327
5328        // Store resolved styleable attributes.
5329        final Resources res = t.getResources();
5330        final SparseArray<String> attributeMap = getAttributeMap();
5331        for (int j = 0; j < indexCount; ++j) {
5332            final int index = t.getIndex(j);
5333            if (!t.hasValueOrEmpty(index)) {
5334                // Value is undefined. Skip it.
5335                continue;
5336            }
5337
5338            final int resourceId = t.getResourceId(index, 0);
5339            if (resourceId == 0) {
5340                // Value is not a reference. Skip it.
5341                continue;
5342            }
5343
5344            String resourceName = attributeMap.get(resourceId);
5345            if (resourceName == null) {
5346                try {
5347                    resourceName = res.getResourceName(resourceId);
5348                } catch (Resources.NotFoundException e) {
5349                    resourceName = "0x" + Integer.toHexString(resourceId);
5350                }
5351                attributeMap.put(resourceId, resourceName);
5352            }
5353
5354            attributes[i] = resourceName;
5355            attributes[i + 1] = t.getString(index);
5356            i += 2;
5357        }
5358
5359        // Trim to fit contents.
5360        final String[] trimmed = new String[i];
5361        System.arraycopy(attributes, 0, trimmed, 0, i);
5362        mAttributes = trimmed;
5363    }
5364
5365    public String toString() {
5366        StringBuilder out = new StringBuilder(128);
5367        out.append(getClass().getName());
5368        out.append('{');
5369        out.append(Integer.toHexString(System.identityHashCode(this)));
5370        out.append(' ');
5371        switch (mViewFlags&VISIBILITY_MASK) {
5372            case VISIBLE: out.append('V'); break;
5373            case INVISIBLE: out.append('I'); break;
5374            case GONE: out.append('G'); break;
5375            default: out.append('.'); break;
5376        }
5377        out.append((mViewFlags & FOCUSABLE) == FOCUSABLE ? 'F' : '.');
5378        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
5379        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
5380        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
5381        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
5382        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
5383        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
5384        out.append((mViewFlags&CONTEXT_CLICKABLE) != 0 ? 'X' : '.');
5385        out.append(' ');
5386        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
5387        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
5388        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
5389        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
5390            out.append('p');
5391        } else {
5392            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
5393        }
5394        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
5395        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
5396        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
5397        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
5398        out.append(' ');
5399        out.append(mLeft);
5400        out.append(',');
5401        out.append(mTop);
5402        out.append('-');
5403        out.append(mRight);
5404        out.append(',');
5405        out.append(mBottom);
5406        final int id = getId();
5407        if (id != NO_ID) {
5408            out.append(" #");
5409            out.append(Integer.toHexString(id));
5410            final Resources r = mResources;
5411            if (id > 0 && Resources.resourceHasPackage(id) && r != null) {
5412                try {
5413                    String pkgname;
5414                    switch (id&0xff000000) {
5415                        case 0x7f000000:
5416                            pkgname="app";
5417                            break;
5418                        case 0x01000000:
5419                            pkgname="android";
5420                            break;
5421                        default:
5422                            pkgname = r.getResourcePackageName(id);
5423                            break;
5424                    }
5425                    String typename = r.getResourceTypeName(id);
5426                    String entryname = r.getResourceEntryName(id);
5427                    out.append(" ");
5428                    out.append(pkgname);
5429                    out.append(":");
5430                    out.append(typename);
5431                    out.append("/");
5432                    out.append(entryname);
5433                } catch (Resources.NotFoundException e) {
5434                }
5435            }
5436        }
5437        out.append("}");
5438        return out.toString();
5439    }
5440
5441    /**
5442     * <p>
5443     * Initializes the fading edges from a given set of styled attributes. This
5444     * method should be called by subclasses that need fading edges and when an
5445     * instance of these subclasses is created programmatically rather than
5446     * being inflated from XML. This method is automatically called when the XML
5447     * is inflated.
5448     * </p>
5449     *
5450     * @param a the styled attributes set to initialize the fading edges from
5451     *
5452     * @removed
5453     */
5454    protected void initializeFadingEdge(TypedArray a) {
5455        // This method probably shouldn't have been included in the SDK to begin with.
5456        // It relies on 'a' having been initialized using an attribute filter array that is
5457        // not publicly available to the SDK. The old method has been renamed
5458        // to initializeFadingEdgeInternal and hidden for framework use only;
5459        // this one initializes using defaults to make it safe to call for apps.
5460
5461        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
5462
5463        initializeFadingEdgeInternal(arr);
5464
5465        arr.recycle();
5466    }
5467
5468    /**
5469     * <p>
5470     * Initializes the fading edges from a given set of styled attributes. This
5471     * method should be called by subclasses that need fading edges and when an
5472     * instance of these subclasses is created programmatically rather than
5473     * being inflated from XML. This method is automatically called when the XML
5474     * is inflated.
5475     * </p>
5476     *
5477     * @param a the styled attributes set to initialize the fading edges from
5478     * @hide This is the real method; the public one is shimmed to be safe to call from apps.
5479     */
5480    protected void initializeFadingEdgeInternal(TypedArray a) {
5481        initScrollCache();
5482
5483        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
5484                R.styleable.View_fadingEdgeLength,
5485                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
5486    }
5487
5488    /**
5489     * Returns the size of the vertical faded edges used to indicate that more
5490     * content in this view is visible.
5491     *
5492     * @return The size in pixels of the vertical faded edge or 0 if vertical
5493     *         faded edges are not enabled for this view.
5494     * @attr ref android.R.styleable#View_fadingEdgeLength
5495     */
5496    public int getVerticalFadingEdgeLength() {
5497        if (isVerticalFadingEdgeEnabled()) {
5498            ScrollabilityCache cache = mScrollCache;
5499            if (cache != null) {
5500                return cache.fadingEdgeLength;
5501            }
5502        }
5503        return 0;
5504    }
5505
5506    /**
5507     * Set the size of the faded edge used to indicate that more content in this
5508     * view is available.  Will not change whether the fading edge is enabled; use
5509     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
5510     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
5511     * for the vertical or horizontal fading edges.
5512     *
5513     * @param length The size in pixels of the faded edge used to indicate that more
5514     *        content in this view is visible.
5515     */
5516    public void setFadingEdgeLength(int length) {
5517        initScrollCache();
5518        mScrollCache.fadingEdgeLength = length;
5519    }
5520
5521    /**
5522     * Returns the size of the horizontal faded edges used to indicate that more
5523     * content in this view is visible.
5524     *
5525     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
5526     *         faded edges are not enabled for this view.
5527     * @attr ref android.R.styleable#View_fadingEdgeLength
5528     */
5529    public int getHorizontalFadingEdgeLength() {
5530        if (isHorizontalFadingEdgeEnabled()) {
5531            ScrollabilityCache cache = mScrollCache;
5532            if (cache != null) {
5533                return cache.fadingEdgeLength;
5534            }
5535        }
5536        return 0;
5537    }
5538
5539    /**
5540     * Returns the width of the vertical scrollbar.
5541     *
5542     * @return The width in pixels of the vertical scrollbar or 0 if there
5543     *         is no vertical scrollbar.
5544     */
5545    public int getVerticalScrollbarWidth() {
5546        ScrollabilityCache cache = mScrollCache;
5547        if (cache != null) {
5548            ScrollBarDrawable scrollBar = cache.scrollBar;
5549            if (scrollBar != null) {
5550                int size = scrollBar.getSize(true);
5551                if (size <= 0) {
5552                    size = cache.scrollBarSize;
5553                }
5554                return size;
5555            }
5556            return 0;
5557        }
5558        return 0;
5559    }
5560
5561    /**
5562     * Returns the height of the horizontal scrollbar.
5563     *
5564     * @return The height in pixels of the horizontal scrollbar or 0 if
5565     *         there is no horizontal scrollbar.
5566     */
5567    protected int getHorizontalScrollbarHeight() {
5568        ScrollabilityCache cache = mScrollCache;
5569        if (cache != null) {
5570            ScrollBarDrawable scrollBar = cache.scrollBar;
5571            if (scrollBar != null) {
5572                int size = scrollBar.getSize(false);
5573                if (size <= 0) {
5574                    size = cache.scrollBarSize;
5575                }
5576                return size;
5577            }
5578            return 0;
5579        }
5580        return 0;
5581    }
5582
5583    /**
5584     * <p>
5585     * Initializes the scrollbars from a given set of styled attributes. This
5586     * method should be called by subclasses that need scrollbars and when an
5587     * instance of these subclasses is created programmatically rather than
5588     * being inflated from XML. This method is automatically called when the XML
5589     * is inflated.
5590     * </p>
5591     *
5592     * @param a the styled attributes set to initialize the scrollbars from
5593     *
5594     * @removed
5595     */
5596    protected void initializeScrollbars(TypedArray a) {
5597        // It's not safe to use this method from apps. The parameter 'a' must have been obtained
5598        // using the View filter array which is not available to the SDK. As such, internal
5599        // framework usage now uses initializeScrollbarsInternal and we grab a default
5600        // TypedArray with the right filter instead here.
5601        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
5602
5603        initializeScrollbarsInternal(arr);
5604
5605        // We ignored the method parameter. Recycle the one we actually did use.
5606        arr.recycle();
5607    }
5608
5609    /**
5610     * <p>
5611     * Initializes the scrollbars from a given set of styled attributes. This
5612     * method should be called by subclasses that need scrollbars and when an
5613     * instance of these subclasses is created programmatically rather than
5614     * being inflated from XML. This method is automatically called when the XML
5615     * is inflated.
5616     * </p>
5617     *
5618     * @param a the styled attributes set to initialize the scrollbars from
5619     * @hide
5620     */
5621    protected void initializeScrollbarsInternal(TypedArray a) {
5622        initScrollCache();
5623
5624        final ScrollabilityCache scrollabilityCache = mScrollCache;
5625
5626        if (scrollabilityCache.scrollBar == null) {
5627            scrollabilityCache.scrollBar = new ScrollBarDrawable();
5628            scrollabilityCache.scrollBar.setState(getDrawableState());
5629            scrollabilityCache.scrollBar.setCallback(this);
5630        }
5631
5632        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
5633
5634        if (!fadeScrollbars) {
5635            scrollabilityCache.state = ScrollabilityCache.ON;
5636        }
5637        scrollabilityCache.fadeScrollBars = fadeScrollbars;
5638
5639
5640        scrollabilityCache.scrollBarFadeDuration = a.getInt(
5641                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
5642                        .getScrollBarFadeDuration());
5643        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
5644                R.styleable.View_scrollbarDefaultDelayBeforeFade,
5645                ViewConfiguration.getScrollDefaultDelay());
5646
5647
5648        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
5649                com.android.internal.R.styleable.View_scrollbarSize,
5650                ViewConfiguration.get(mContext).getScaledScrollBarSize());
5651
5652        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
5653        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
5654
5655        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
5656        if (thumb != null) {
5657            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
5658        }
5659
5660        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
5661                false);
5662        if (alwaysDraw) {
5663            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
5664        }
5665
5666        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
5667        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
5668
5669        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
5670        if (thumb != null) {
5671            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
5672        }
5673
5674        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
5675                false);
5676        if (alwaysDraw) {
5677            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
5678        }
5679
5680        // Apply layout direction to the new Drawables if needed
5681        final int layoutDirection = getLayoutDirection();
5682        if (track != null) {
5683            track.setLayoutDirection(layoutDirection);
5684        }
5685        if (thumb != null) {
5686            thumb.setLayoutDirection(layoutDirection);
5687        }
5688
5689        // Re-apply user/background padding so that scrollbar(s) get added
5690        resolvePadding();
5691    }
5692
5693    private void initializeScrollIndicatorsInternal() {
5694        // Some day maybe we'll break this into top/left/start/etc. and let the
5695        // client control it. Until then, you can have any scroll indicator you
5696        // want as long as it's a 1dp foreground-colored rectangle.
5697        if (mScrollIndicatorDrawable == null) {
5698            mScrollIndicatorDrawable = mContext.getDrawable(R.drawable.scroll_indicator_material);
5699        }
5700    }
5701
5702    /**
5703     * <p>
5704     * Initalizes the scrollability cache if necessary.
5705     * </p>
5706     */
5707    private void initScrollCache() {
5708        if (mScrollCache == null) {
5709            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
5710        }
5711    }
5712
5713    private ScrollabilityCache getScrollCache() {
5714        initScrollCache();
5715        return mScrollCache;
5716    }
5717
5718    /**
5719     * Set the position of the vertical scroll bar. Should be one of
5720     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
5721     * {@link #SCROLLBAR_POSITION_RIGHT}.
5722     *
5723     * @param position Where the vertical scroll bar should be positioned.
5724     */
5725    public void setVerticalScrollbarPosition(int position) {
5726        if (mVerticalScrollbarPosition != position) {
5727            mVerticalScrollbarPosition = position;
5728            computeOpaqueFlags();
5729            resolvePadding();
5730        }
5731    }
5732
5733    /**
5734     * @return The position where the vertical scroll bar will show, if applicable.
5735     * @see #setVerticalScrollbarPosition(int)
5736     */
5737    public int getVerticalScrollbarPosition() {
5738        return mVerticalScrollbarPosition;
5739    }
5740
5741    boolean isOnScrollbar(float x, float y) {
5742        if (mScrollCache == null) {
5743            return false;
5744        }
5745        x += getScrollX();
5746        y += getScrollY();
5747        if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) {
5748            final Rect touchBounds = mScrollCache.mScrollBarTouchBounds;
5749            getVerticalScrollBarBounds(null, touchBounds);
5750            if (touchBounds.contains((int) x, (int) y)) {
5751                return true;
5752            }
5753        }
5754        if (isHorizontalScrollBarEnabled()) {
5755            final Rect touchBounds = mScrollCache.mScrollBarTouchBounds;
5756            getHorizontalScrollBarBounds(null, touchBounds);
5757            if (touchBounds.contains((int) x, (int) y)) {
5758                return true;
5759            }
5760        }
5761        return false;
5762    }
5763
5764    boolean isOnScrollbarThumb(float x, float y) {
5765        return isOnVerticalScrollbarThumb(x, y) || isOnHorizontalScrollbarThumb(x, y);
5766    }
5767
5768    private boolean isOnVerticalScrollbarThumb(float x, float y) {
5769        if (mScrollCache == null) {
5770            return false;
5771        }
5772        if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) {
5773            x += getScrollX();
5774            y += getScrollY();
5775            final Rect bounds = mScrollCache.mScrollBarBounds;
5776            final Rect touchBounds = mScrollCache.mScrollBarTouchBounds;
5777            getVerticalScrollBarBounds(bounds, touchBounds);
5778            final int range = computeVerticalScrollRange();
5779            final int offset = computeVerticalScrollOffset();
5780            final int extent = computeVerticalScrollExtent();
5781            final int thumbLength = ScrollBarUtils.getThumbLength(bounds.height(), bounds.width(),
5782                    extent, range);
5783            final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.height(), thumbLength,
5784                    extent, range, offset);
5785            final int thumbTop = bounds.top + thumbOffset;
5786            final int adjust = Math.max(mScrollCache.scrollBarMinTouchTarget - thumbLength, 0) / 2;
5787            if (x >= touchBounds.left && x <= touchBounds.right
5788                    && y >= thumbTop - adjust && y <= thumbTop + thumbLength + adjust) {
5789                return true;
5790            }
5791        }
5792        return false;
5793    }
5794
5795    private boolean isOnHorizontalScrollbarThumb(float x, float y) {
5796        if (mScrollCache == null) {
5797            return false;
5798        }
5799        if (isHorizontalScrollBarEnabled()) {
5800            x += getScrollX();
5801            y += getScrollY();
5802            final Rect bounds = mScrollCache.mScrollBarBounds;
5803            final Rect touchBounds = mScrollCache.mScrollBarTouchBounds;
5804            getHorizontalScrollBarBounds(bounds, touchBounds);
5805            final int range = computeHorizontalScrollRange();
5806            final int offset = computeHorizontalScrollOffset();
5807            final int extent = computeHorizontalScrollExtent();
5808            final int thumbLength = ScrollBarUtils.getThumbLength(bounds.width(), bounds.height(),
5809                    extent, range);
5810            final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.width(), thumbLength,
5811                    extent, range, offset);
5812            final int thumbLeft = bounds.left + thumbOffset;
5813            final int adjust = Math.max(mScrollCache.scrollBarMinTouchTarget - thumbLength, 0) / 2;
5814            if (x >= thumbLeft - adjust && x <= thumbLeft + thumbLength + adjust
5815                    && y >= touchBounds.top && y <= touchBounds.bottom) {
5816                return true;
5817            }
5818        }
5819        return false;
5820    }
5821
5822    boolean isDraggingScrollBar() {
5823        return mScrollCache != null
5824                && mScrollCache.mScrollBarDraggingState != ScrollabilityCache.NOT_DRAGGING;
5825    }
5826
5827    /**
5828     * Sets the state of all scroll indicators.
5829     * <p>
5830     * See {@link #setScrollIndicators(int, int)} for usage information.
5831     *
5832     * @param indicators a bitmask of indicators that should be enabled, or
5833     *                   {@code 0} to disable all indicators
5834     * @see #setScrollIndicators(int, int)
5835     * @see #getScrollIndicators()
5836     * @attr ref android.R.styleable#View_scrollIndicators
5837     */
5838    public void setScrollIndicators(@ScrollIndicators int indicators) {
5839        setScrollIndicators(indicators,
5840                SCROLL_INDICATORS_PFLAG3_MASK >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT);
5841    }
5842
5843    /**
5844     * Sets the state of the scroll indicators specified by the mask. To change
5845     * all scroll indicators at once, see {@link #setScrollIndicators(int)}.
5846     * <p>
5847     * When a scroll indicator is enabled, it will be displayed if the view
5848     * can scroll in the direction of the indicator.
5849     * <p>
5850     * Multiple indicator types may be enabled or disabled by passing the
5851     * logical OR of the desired types. If multiple types are specified, they
5852     * will all be set to the same enabled state.
5853     * <p>
5854     * For example, to enable the top scroll indicatorExample: {@code setScrollIndicators
5855     *
5856     * @param indicators the indicator direction, or the logical OR of multiple
5857     *             indicator directions. One or more of:
5858     *             <ul>
5859     *               <li>{@link #SCROLL_INDICATOR_TOP}</li>
5860     *               <li>{@link #SCROLL_INDICATOR_BOTTOM}</li>
5861     *               <li>{@link #SCROLL_INDICATOR_LEFT}</li>
5862     *               <li>{@link #SCROLL_INDICATOR_RIGHT}</li>
5863     *               <li>{@link #SCROLL_INDICATOR_START}</li>
5864     *               <li>{@link #SCROLL_INDICATOR_END}</li>
5865     *             </ul>
5866     * @see #setScrollIndicators(int)
5867     * @see #getScrollIndicators()
5868     * @attr ref android.R.styleable#View_scrollIndicators
5869     */
5870    public void setScrollIndicators(@ScrollIndicators int indicators, @ScrollIndicators int mask) {
5871        // Shift and sanitize mask.
5872        mask <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5873        mask &= SCROLL_INDICATORS_PFLAG3_MASK;
5874
5875        // Shift and mask indicators.
5876        indicators <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5877        indicators &= mask;
5878
5879        // Merge with non-masked flags.
5880        final int updatedFlags = indicators | (mPrivateFlags3 & ~mask);
5881
5882        if (mPrivateFlags3 != updatedFlags) {
5883            mPrivateFlags3 = updatedFlags;
5884
5885            if (indicators != 0) {
5886                initializeScrollIndicatorsInternal();
5887            }
5888            invalidate();
5889        }
5890    }
5891
5892    /**
5893     * Returns a bitmask representing the enabled scroll indicators.
5894     * <p>
5895     * For example, if the top and left scroll indicators are enabled and all
5896     * other indicators are disabled, the return value will be
5897     * {@code View.SCROLL_INDICATOR_TOP | View.SCROLL_INDICATOR_LEFT}.
5898     * <p>
5899     * To check whether the bottom scroll indicator is enabled, use the value
5900     * of {@code (getScrollIndicators() & View.SCROLL_INDICATOR_BOTTOM) != 0}.
5901     *
5902     * @return a bitmask representing the enabled scroll indicators
5903     */
5904    @ScrollIndicators
5905    public int getScrollIndicators() {
5906        return (mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK)
5907                >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5908    }
5909
5910    ListenerInfo getListenerInfo() {
5911        if (mListenerInfo != null) {
5912            return mListenerInfo;
5913        }
5914        mListenerInfo = new ListenerInfo();
5915        return mListenerInfo;
5916    }
5917
5918    /**
5919     * Register a callback to be invoked when the scroll X or Y positions of
5920     * this view change.
5921     * <p>
5922     * <b>Note:</b> Some views handle scrolling independently from View and may
5923     * have their own separate listeners for scroll-type events. For example,
5924     * {@link android.widget.ListView ListView} allows clients to register an
5925     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
5926     * to listen for changes in list scroll position.
5927     *
5928     * @param l The listener to notify when the scroll X or Y position changes.
5929     * @see android.view.View#getScrollX()
5930     * @see android.view.View#getScrollY()
5931     */
5932    public void setOnScrollChangeListener(OnScrollChangeListener l) {
5933        getListenerInfo().mOnScrollChangeListener = l;
5934    }
5935
5936    /**
5937     * Register a callback to be invoked when focus of this view changed.
5938     *
5939     * @param l The callback that will run.
5940     */
5941    public void setOnFocusChangeListener(OnFocusChangeListener l) {
5942        getListenerInfo().mOnFocusChangeListener = l;
5943    }
5944
5945    /**
5946     * Add a listener that will be called when the bounds of the view change due to
5947     * layout processing.
5948     *
5949     * @param listener The listener that will be called when layout bounds change.
5950     */
5951    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
5952        ListenerInfo li = getListenerInfo();
5953        if (li.mOnLayoutChangeListeners == null) {
5954            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
5955        }
5956        if (!li.mOnLayoutChangeListeners.contains(listener)) {
5957            li.mOnLayoutChangeListeners.add(listener);
5958        }
5959    }
5960
5961    /**
5962     * Remove a listener for layout changes.
5963     *
5964     * @param listener The listener for layout bounds change.
5965     */
5966    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
5967        ListenerInfo li = mListenerInfo;
5968        if (li == null || li.mOnLayoutChangeListeners == null) {
5969            return;
5970        }
5971        li.mOnLayoutChangeListeners.remove(listener);
5972    }
5973
5974    /**
5975     * Add a listener for attach state changes.
5976     *
5977     * This listener will be called whenever this view is attached or detached
5978     * from a window. Remove the listener using
5979     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
5980     *
5981     * @param listener Listener to attach
5982     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
5983     */
5984    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
5985        ListenerInfo li = getListenerInfo();
5986        if (li.mOnAttachStateChangeListeners == null) {
5987            li.mOnAttachStateChangeListeners
5988                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
5989        }
5990        li.mOnAttachStateChangeListeners.add(listener);
5991    }
5992
5993    /**
5994     * Remove a listener for attach state changes. The listener will receive no further
5995     * notification of window attach/detach events.
5996     *
5997     * @param listener Listener to remove
5998     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
5999     */
6000    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
6001        ListenerInfo li = mListenerInfo;
6002        if (li == null || li.mOnAttachStateChangeListeners == null) {
6003            return;
6004        }
6005        li.mOnAttachStateChangeListeners.remove(listener);
6006    }
6007
6008    /**
6009     * Returns the focus-change callback registered for this view.
6010     *
6011     * @return The callback, or null if one is not registered.
6012     */
6013    public OnFocusChangeListener getOnFocusChangeListener() {
6014        ListenerInfo li = mListenerInfo;
6015        return li != null ? li.mOnFocusChangeListener : null;
6016    }
6017
6018    /**
6019     * Register a callback to be invoked when this view is clicked. If this view is not
6020     * clickable, it becomes clickable.
6021     *
6022     * @param l The callback that will run
6023     *
6024     * @see #setClickable(boolean)
6025     */
6026    public void setOnClickListener(@Nullable OnClickListener l) {
6027        if (!isClickable()) {
6028            setClickable(true);
6029        }
6030        getListenerInfo().mOnClickListener = l;
6031    }
6032
6033    /**
6034     * Return whether this view has an attached OnClickListener.  Returns
6035     * true if there is a listener, false if there is none.
6036     */
6037    public boolean hasOnClickListeners() {
6038        ListenerInfo li = mListenerInfo;
6039        return (li != null && li.mOnClickListener != null);
6040    }
6041
6042    /**
6043     * Register a callback to be invoked when this view is clicked and held. If this view is not
6044     * long clickable, it becomes long clickable.
6045     *
6046     * @param l The callback that will run
6047     *
6048     * @see #setLongClickable(boolean)
6049     */
6050    public void setOnLongClickListener(@Nullable OnLongClickListener l) {
6051        if (!isLongClickable()) {
6052            setLongClickable(true);
6053        }
6054        getListenerInfo().mOnLongClickListener = l;
6055    }
6056
6057    /**
6058     * Register a callback to be invoked when this view is context clicked. If the view is not
6059     * context clickable, it becomes context clickable.
6060     *
6061     * @param l The callback that will run
6062     * @see #setContextClickable(boolean)
6063     */
6064    public void setOnContextClickListener(@Nullable OnContextClickListener l) {
6065        if (!isContextClickable()) {
6066            setContextClickable(true);
6067        }
6068        getListenerInfo().mOnContextClickListener = l;
6069    }
6070
6071    /**
6072     * Register a callback to be invoked when the context menu for this view is
6073     * being built. If this view is not long clickable, it becomes long clickable.
6074     *
6075     * @param l The callback that will run
6076     *
6077     */
6078    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
6079        if (!isLongClickable()) {
6080            setLongClickable(true);
6081        }
6082        getListenerInfo().mOnCreateContextMenuListener = l;
6083    }
6084
6085    /**
6086     * Set an observer to collect stats for each frame rendered for this view.
6087     *
6088     * @hide
6089     */
6090    public void addFrameMetricsListener(Window window,
6091            Window.OnFrameMetricsAvailableListener listener,
6092            Handler handler) {
6093        if (mAttachInfo != null) {
6094            if (mAttachInfo.mThreadedRenderer != null) {
6095                if (mFrameMetricsObservers == null) {
6096                    mFrameMetricsObservers = new ArrayList<>();
6097                }
6098
6099                FrameMetricsObserver fmo = new FrameMetricsObserver(window,
6100                        handler.getLooper(), listener);
6101                mFrameMetricsObservers.add(fmo);
6102                mAttachInfo.mThreadedRenderer.addFrameMetricsObserver(fmo);
6103            } else {
6104                Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats");
6105            }
6106        } else {
6107            if (mFrameMetricsObservers == null) {
6108                mFrameMetricsObservers = new ArrayList<>();
6109            }
6110
6111            FrameMetricsObserver fmo = new FrameMetricsObserver(window,
6112                    handler.getLooper(), listener);
6113            mFrameMetricsObservers.add(fmo);
6114        }
6115    }
6116
6117    /**
6118     * Remove observer configured to collect frame stats for this view.
6119     *
6120     * @hide
6121     */
6122    public void removeFrameMetricsListener(
6123            Window.OnFrameMetricsAvailableListener listener) {
6124        ThreadedRenderer renderer = getThreadedRenderer();
6125        FrameMetricsObserver fmo = findFrameMetricsObserver(listener);
6126        if (fmo == null) {
6127            throw new IllegalArgumentException(
6128                    "attempt to remove OnFrameMetricsAvailableListener that was never added");
6129        }
6130
6131        if (mFrameMetricsObservers != null) {
6132            mFrameMetricsObservers.remove(fmo);
6133            if (renderer != null) {
6134                renderer.removeFrameMetricsObserver(fmo);
6135            }
6136        }
6137    }
6138
6139    private void registerPendingFrameMetricsObservers() {
6140        if (mFrameMetricsObservers != null) {
6141            ThreadedRenderer renderer = getThreadedRenderer();
6142            if (renderer != null) {
6143                for (FrameMetricsObserver fmo : mFrameMetricsObservers) {
6144                    renderer.addFrameMetricsObserver(fmo);
6145                }
6146            } else {
6147                Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats");
6148            }
6149        }
6150    }
6151
6152    private FrameMetricsObserver findFrameMetricsObserver(
6153            Window.OnFrameMetricsAvailableListener listener) {
6154        for (int i = 0; i < mFrameMetricsObservers.size(); i++) {
6155            FrameMetricsObserver observer = mFrameMetricsObservers.get(i);
6156            if (observer.mListener == listener) {
6157                return observer;
6158            }
6159        }
6160
6161        return null;
6162    }
6163
6164    /**
6165     * Call this view's OnClickListener, if it is defined.  Performs all normal
6166     * actions associated with clicking: reporting accessibility event, playing
6167     * a sound, etc.
6168     *
6169     * @return True there was an assigned OnClickListener that was called, false
6170     *         otherwise is returned.
6171     */
6172    public boolean performClick() {
6173        final boolean result;
6174        final ListenerInfo li = mListenerInfo;
6175        if (li != null && li.mOnClickListener != null) {
6176            playSoundEffect(SoundEffectConstants.CLICK);
6177            li.mOnClickListener.onClick(this);
6178            result = true;
6179        } else {
6180            result = false;
6181        }
6182
6183        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
6184
6185        notifyEnterOrExitForAutoFillIfNeeded(true);
6186
6187        return result;
6188    }
6189
6190    /**
6191     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
6192     * this only calls the listener, and does not do any associated clicking
6193     * actions like reporting an accessibility event.
6194     *
6195     * @return True there was an assigned OnClickListener that was called, false
6196     *         otherwise is returned.
6197     */
6198    public boolean callOnClick() {
6199        ListenerInfo li = mListenerInfo;
6200        if (li != null && li.mOnClickListener != null) {
6201            li.mOnClickListener.onClick(this);
6202            return true;
6203        }
6204        return false;
6205    }
6206
6207    /**
6208     * Calls this view's OnLongClickListener, if it is defined. Invokes the
6209     * context menu if the OnLongClickListener did not consume the event.
6210     *
6211     * @return {@code true} if one of the above receivers consumed the event,
6212     *         {@code false} otherwise
6213     */
6214    public boolean performLongClick() {
6215        return performLongClickInternal(mLongClickX, mLongClickY);
6216    }
6217
6218    /**
6219     * Calls this view's OnLongClickListener, if it is defined. Invokes the
6220     * context menu if the OnLongClickListener did not consume the event,
6221     * anchoring it to an (x,y) coordinate.
6222     *
6223     * @param x x coordinate of the anchoring touch event, or {@link Float#NaN}
6224     *          to disable anchoring
6225     * @param y y coordinate of the anchoring touch event, or {@link Float#NaN}
6226     *          to disable anchoring
6227     * @return {@code true} if one of the above receivers consumed the event,
6228     *         {@code false} otherwise
6229     */
6230    public boolean performLongClick(float x, float y) {
6231        mLongClickX = x;
6232        mLongClickY = y;
6233        final boolean handled = performLongClick();
6234        mLongClickX = Float.NaN;
6235        mLongClickY = Float.NaN;
6236        return handled;
6237    }
6238
6239    /**
6240     * Calls this view's OnLongClickListener, if it is defined. Invokes the
6241     * context menu if the OnLongClickListener did not consume the event,
6242     * optionally anchoring it to an (x,y) coordinate.
6243     *
6244     * @param x x coordinate of the anchoring touch event, or {@link Float#NaN}
6245     *          to disable anchoring
6246     * @param y y coordinate of the anchoring touch event, or {@link Float#NaN}
6247     *          to disable anchoring
6248     * @return {@code true} if one of the above receivers consumed the event,
6249     *         {@code false} otherwise
6250     */
6251    private boolean performLongClickInternal(float x, float y) {
6252        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
6253
6254        boolean handled = false;
6255        final ListenerInfo li = mListenerInfo;
6256        if (li != null && li.mOnLongClickListener != null) {
6257            handled = li.mOnLongClickListener.onLongClick(View.this);
6258        }
6259        if (!handled) {
6260            final boolean isAnchored = !Float.isNaN(x) && !Float.isNaN(y);
6261            handled = isAnchored ? showContextMenu(x, y) : showContextMenu();
6262        }
6263        if ((mViewFlags & TOOLTIP) == TOOLTIP) {
6264            if (!handled) {
6265                handled = showLongClickTooltip((int) x, (int) y);
6266            }
6267        }
6268        if (handled) {
6269            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
6270        }
6271        return handled;
6272    }
6273
6274    /**
6275     * Call this view's OnContextClickListener, if it is defined.
6276     *
6277     * @param x the x coordinate of the context click
6278     * @param y the y coordinate of the context click
6279     * @return True if there was an assigned OnContextClickListener that consumed the event, false
6280     *         otherwise.
6281     */
6282    public boolean performContextClick(float x, float y) {
6283        return performContextClick();
6284    }
6285
6286    /**
6287     * Call this view's OnContextClickListener, if it is defined.
6288     *
6289     * @return True if there was an assigned OnContextClickListener that consumed the event, false
6290     *         otherwise.
6291     */
6292    public boolean performContextClick() {
6293        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CONTEXT_CLICKED);
6294
6295        boolean handled = false;
6296        ListenerInfo li = mListenerInfo;
6297        if (li != null && li.mOnContextClickListener != null) {
6298            handled = li.mOnContextClickListener.onContextClick(View.this);
6299        }
6300        if (handled) {
6301            performHapticFeedback(HapticFeedbackConstants.CONTEXT_CLICK);
6302        }
6303        return handled;
6304    }
6305
6306    /**
6307     * Performs button-related actions during a touch down event.
6308     *
6309     * @param event The event.
6310     * @return True if the down was consumed.
6311     *
6312     * @hide
6313     */
6314    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
6315        if (event.isFromSource(InputDevice.SOURCE_MOUSE) &&
6316            (event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
6317            showContextMenu(event.getX(), event.getY());
6318            mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
6319            return true;
6320        }
6321        return false;
6322    }
6323
6324    /**
6325     * Shows the context menu for this view.
6326     *
6327     * @return {@code true} if the context menu was shown, {@code false}
6328     *         otherwise
6329     * @see #showContextMenu(float, float)
6330     */
6331    public boolean showContextMenu() {
6332        return getParent().showContextMenuForChild(this);
6333    }
6334
6335    /**
6336     * Shows the context menu for this view anchored to the specified
6337     * view-relative coordinate.
6338     *
6339     * @param x the X coordinate in pixels relative to the view to which the
6340     *          menu should be anchored, or {@link Float#NaN} to disable anchoring
6341     * @param y the Y coordinate in pixels relative to the view to which the
6342     *          menu should be anchored, or {@link Float#NaN} to disable anchoring
6343     * @return {@code true} if the context menu was shown, {@code false}
6344     *         otherwise
6345     */
6346    public boolean showContextMenu(float x, float y) {
6347        return getParent().showContextMenuForChild(this, x, y);
6348    }
6349
6350    /**
6351     * Start an action mode with the default type {@link ActionMode#TYPE_PRIMARY}.
6352     *
6353     * @param callback Callback that will control the lifecycle of the action mode
6354     * @return The new action mode if it is started, null otherwise
6355     *
6356     * @see ActionMode
6357     * @see #startActionMode(android.view.ActionMode.Callback, int)
6358     */
6359    public ActionMode startActionMode(ActionMode.Callback callback) {
6360        return startActionMode(callback, ActionMode.TYPE_PRIMARY);
6361    }
6362
6363    /**
6364     * Start an action mode with the given type.
6365     *
6366     * @param callback Callback that will control the lifecycle of the action mode
6367     * @param type One of {@link ActionMode#TYPE_PRIMARY} or {@link ActionMode#TYPE_FLOATING}.
6368     * @return The new action mode if it is started, null otherwise
6369     *
6370     * @see ActionMode
6371     */
6372    public ActionMode startActionMode(ActionMode.Callback callback, int type) {
6373        ViewParent parent = getParent();
6374        if (parent == null) return null;
6375        try {
6376            return parent.startActionModeForChild(this, callback, type);
6377        } catch (AbstractMethodError ame) {
6378            // Older implementations of custom views might not implement this.
6379            return parent.startActionModeForChild(this, callback);
6380        }
6381    }
6382
6383    /**
6384     * Call {@link Context#startActivityForResult(String, Intent, int, Bundle)} for the View's
6385     * Context, creating a unique View identifier to retrieve the result.
6386     *
6387     * @param intent The Intent to be started.
6388     * @param requestCode The request code to use.
6389     * @hide
6390     */
6391    public void startActivityForResult(Intent intent, int requestCode) {
6392        mStartActivityRequestWho = "@android:view:" + System.identityHashCode(this);
6393        getContext().startActivityForResult(mStartActivityRequestWho, intent, requestCode, null);
6394    }
6395
6396    /**
6397     * If this View corresponds to the calling who, dispatches the activity result.
6398     * @param who The identifier for the targeted View to receive the result.
6399     * @param requestCode The integer request code originally supplied to
6400     *                    startActivityForResult(), allowing you to identify who this
6401     *                    result came from.
6402     * @param resultCode The integer result code returned by the child activity
6403     *                   through its setResult().
6404     * @param data An Intent, which can return result data to the caller
6405     *               (various data can be attached to Intent "extras").
6406     * @return {@code true} if the activity result was dispatched.
6407     * @hide
6408     */
6409    public boolean dispatchActivityResult(
6410            String who, int requestCode, int resultCode, Intent data) {
6411        if (mStartActivityRequestWho != null && mStartActivityRequestWho.equals(who)) {
6412            onActivityResult(requestCode, resultCode, data);
6413            mStartActivityRequestWho = null;
6414            return true;
6415        }
6416        return false;
6417    }
6418
6419    /**
6420     * Receive the result from a previous call to {@link #startActivityForResult(Intent, int)}.
6421     *
6422     * @param requestCode The integer request code originally supplied to
6423     *                    startActivityForResult(), allowing you to identify who this
6424     *                    result came from.
6425     * @param resultCode The integer result code returned by the child activity
6426     *                   through its setResult().
6427     * @param data An Intent, which can return result data to the caller
6428     *               (various data can be attached to Intent "extras").
6429     * @hide
6430     */
6431    public void onActivityResult(int requestCode, int resultCode, Intent data) {
6432        // Do nothing.
6433    }
6434
6435    /**
6436     * Register a callback to be invoked when a hardware key is pressed in this view.
6437     * Key presses in software input methods will generally not trigger the methods of
6438     * this listener.
6439     * @param l the key listener to attach to this view
6440     */
6441    public void setOnKeyListener(OnKeyListener l) {
6442        getListenerInfo().mOnKeyListener = l;
6443    }
6444
6445    /**
6446     * Register a callback to be invoked when a touch event is sent to this view.
6447     * @param l the touch listener to attach to this view
6448     */
6449    public void setOnTouchListener(OnTouchListener l) {
6450        getListenerInfo().mOnTouchListener = l;
6451    }
6452
6453    /**
6454     * Register a callback to be invoked when a generic motion event is sent to this view.
6455     * @param l the generic motion listener to attach to this view
6456     */
6457    public void setOnGenericMotionListener(OnGenericMotionListener l) {
6458        getListenerInfo().mOnGenericMotionListener = l;
6459    }
6460
6461    /**
6462     * Register a callback to be invoked when a hover event is sent to this view.
6463     * @param l the hover listener to attach to this view
6464     */
6465    public void setOnHoverListener(OnHoverListener l) {
6466        getListenerInfo().mOnHoverListener = l;
6467    }
6468
6469    /**
6470     * Register a drag event listener callback object for this View. The parameter is
6471     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
6472     * View, the system calls the
6473     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
6474     * @param l An implementation of {@link android.view.View.OnDragListener}.
6475     */
6476    public void setOnDragListener(OnDragListener l) {
6477        getListenerInfo().mOnDragListener = l;
6478    }
6479
6480    /**
6481     * Give this view focus. This will cause
6482     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
6483     *
6484     * Note: this does not check whether this {@link View} should get focus, it just
6485     * gives it focus no matter what.  It should only be called internally by framework
6486     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
6487     *
6488     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
6489     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
6490     *        focus moved when requestFocus() is called. It may not always
6491     *        apply, in which case use the default View.FOCUS_DOWN.
6492     * @param previouslyFocusedRect The rectangle of the view that had focus
6493     *        prior in this View's coordinate system.
6494     */
6495    void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) {
6496        if (DBG) {
6497            System.out.println(this + " requestFocus()");
6498        }
6499
6500        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
6501            mPrivateFlags |= PFLAG_FOCUSED;
6502
6503            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
6504
6505            if (mParent != null) {
6506                mParent.requestChildFocus(this, this);
6507                updateFocusedInCluster(oldFocus, direction);
6508            }
6509
6510            if (mAttachInfo != null) {
6511                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
6512            }
6513
6514            onFocusChanged(true, direction, previouslyFocusedRect);
6515            refreshDrawableState();
6516        }
6517    }
6518
6519    /**
6520     * Sets this view's preference for reveal behavior when it gains focus.
6521     *
6522     * <p>When set to true, this is a signal to ancestor views in the hierarchy that
6523     * this view would prefer to be brought fully into view when it gains focus.
6524     * For example, a text field that a user is meant to type into. Other views such
6525     * as scrolling containers may prefer to opt-out of this behavior.</p>
6526     *
6527     * <p>The default value for views is true, though subclasses may change this
6528     * based on their preferred behavior.</p>
6529     *
6530     * @param revealOnFocus true to request reveal on focus in ancestors, false otherwise
6531     *
6532     * @see #getRevealOnFocusHint()
6533     */
6534    public final void setRevealOnFocusHint(boolean revealOnFocus) {
6535        if (revealOnFocus) {
6536            mPrivateFlags3 &= ~PFLAG3_NO_REVEAL_ON_FOCUS;
6537        } else {
6538            mPrivateFlags3 |= PFLAG3_NO_REVEAL_ON_FOCUS;
6539        }
6540    }
6541
6542    /**
6543     * Returns this view's preference for reveal behavior when it gains focus.
6544     *
6545     * <p>When this method returns true for a child view requesting focus, ancestor
6546     * views responding to a focus change in {@link ViewParent#requestChildFocus(View, View)}
6547     * should make a best effort to make the newly focused child fully visible to the user.
6548     * When it returns false, ancestor views should preferably not disrupt scroll positioning or
6549     * other properties affecting visibility to the user as part of the focus change.</p>
6550     *
6551     * @return true if this view would prefer to become fully visible when it gains focus,
6552     *         false if it would prefer not to disrupt scroll positioning
6553     *
6554     * @see #setRevealOnFocusHint(boolean)
6555     */
6556    public final boolean getRevealOnFocusHint() {
6557        return (mPrivateFlags3 & PFLAG3_NO_REVEAL_ON_FOCUS) == 0;
6558    }
6559
6560    /**
6561     * Populates <code>outRect</code> with the hotspot bounds. By default,
6562     * the hotspot bounds are identical to the screen bounds.
6563     *
6564     * @param outRect rect to populate with hotspot bounds
6565     * @hide Only for internal use by views and widgets.
6566     */
6567    public void getHotspotBounds(Rect outRect) {
6568        final Drawable background = getBackground();
6569        if (background != null) {
6570            background.getHotspotBounds(outRect);
6571        } else {
6572            getBoundsOnScreen(outRect);
6573        }
6574    }
6575
6576    /**
6577     * Request that a rectangle of this view be visible on the screen,
6578     * scrolling if necessary just enough.
6579     *
6580     * <p>A View should call this if it maintains some notion of which part
6581     * of its content is interesting.  For example, a text editing view
6582     * should call this when its cursor moves.
6583     * <p>The Rectangle passed into this method should be in the View's content coordinate space.
6584     * It should not be affected by which part of the View is currently visible or its scroll
6585     * position.
6586     *
6587     * @param rectangle The rectangle in the View's content coordinate space
6588     * @return Whether any parent scrolled.
6589     */
6590    public boolean requestRectangleOnScreen(Rect rectangle) {
6591        return requestRectangleOnScreen(rectangle, false);
6592    }
6593
6594    /**
6595     * Request that a rectangle of this view be visible on the screen,
6596     * scrolling if necessary just enough.
6597     *
6598     * <p>A View should call this if it maintains some notion of which part
6599     * of its content is interesting.  For example, a text editing view
6600     * should call this when its cursor moves.
6601     * <p>The Rectangle passed into this method should be in the View's content coordinate space.
6602     * It should not be affected by which part of the View is currently visible or its scroll
6603     * position.
6604     * <p>When <code>immediate</code> is set to true, scrolling will not be
6605     * animated.
6606     *
6607     * @param rectangle The rectangle in the View's content coordinate space
6608     * @param immediate True to forbid animated scrolling, false otherwise
6609     * @return Whether any parent scrolled.
6610     */
6611    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
6612        if (mParent == null) {
6613            return false;
6614        }
6615
6616        View child = this;
6617
6618        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
6619        position.set(rectangle);
6620
6621        ViewParent parent = mParent;
6622        boolean scrolled = false;
6623        while (parent != null) {
6624            rectangle.set((int) position.left, (int) position.top,
6625                    (int) position.right, (int) position.bottom);
6626
6627            scrolled |= parent.requestChildRectangleOnScreen(child, rectangle, immediate);
6628
6629            if (!(parent instanceof View)) {
6630                break;
6631            }
6632
6633            // move it from child's content coordinate space to parent's content coordinate space
6634            position.offset(child.mLeft - child.getScrollX(), child.mTop -child.getScrollY());
6635
6636            child = (View) parent;
6637            parent = child.getParent();
6638        }
6639
6640        return scrolled;
6641    }
6642
6643    /**
6644     * Called when this view wants to give up focus. If focus is cleared
6645     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
6646     * <p>
6647     * <strong>Note:</strong> When a View clears focus the framework is trying
6648     * to give focus to the first focusable View from the top. Hence, if this
6649     * View is the first from the top that can take focus, then all callbacks
6650     * related to clearing focus will be invoked after which the framework will
6651     * give focus to this view.
6652     * </p>
6653     */
6654    public void clearFocus() {
6655        if (DBG) {
6656            System.out.println(this + " clearFocus()");
6657        }
6658
6659        clearFocusInternal(null, true, true);
6660    }
6661
6662    /**
6663     * Clears focus from the view, optionally propagating the change up through
6664     * the parent hierarchy and requesting that the root view place new focus.
6665     *
6666     * @param propagate whether to propagate the change up through the parent
6667     *            hierarchy
6668     * @param refocus when propagate is true, specifies whether to request the
6669     *            root view place new focus
6670     */
6671    void clearFocusInternal(View focused, boolean propagate, boolean refocus) {
6672        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
6673            mPrivateFlags &= ~PFLAG_FOCUSED;
6674
6675            if (propagate && mParent != null) {
6676                mParent.clearChildFocus(this);
6677            }
6678
6679            onFocusChanged(false, 0, null);
6680            refreshDrawableState();
6681
6682            if (propagate && (!refocus || !rootViewRequestFocus())) {
6683                notifyGlobalFocusCleared(this);
6684            }
6685        }
6686    }
6687
6688    void notifyGlobalFocusCleared(View oldFocus) {
6689        if (oldFocus != null && mAttachInfo != null) {
6690            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
6691        }
6692    }
6693
6694    boolean rootViewRequestFocus() {
6695        final View root = getRootView();
6696        return root != null && root.requestFocus();
6697    }
6698
6699    /**
6700     * Called internally by the view system when a new view is getting focus.
6701     * This is what clears the old focus.
6702     * <p>
6703     * <b>NOTE:</b> The parent view's focused child must be updated manually
6704     * after calling this method. Otherwise, the view hierarchy may be left in
6705     * an inconstent state.
6706     */
6707    void unFocus(View focused) {
6708        if (DBG) {
6709            System.out.println(this + " unFocus()");
6710        }
6711
6712        clearFocusInternal(focused, false, false);
6713    }
6714
6715    /**
6716     * Returns true if this view has focus itself, or is the ancestor of the
6717     * view that has focus.
6718     *
6719     * @return True if this view has or contains focus, false otherwise.
6720     */
6721    @ViewDebug.ExportedProperty(category = "focus")
6722    public boolean hasFocus() {
6723        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
6724    }
6725
6726    /**
6727     * Returns true if this view is focusable or if it contains a reachable View
6728     * for which {@link #hasFocusable()} returns {@code true}. A "reachable hasFocusable()"
6729     * is a view whose parents do not block descendants focus.
6730     * Only {@link #VISIBLE} views are considered focusable.
6731     *
6732     * <p>As of {@link Build.VERSION_CODES#O} views that are determined to be focusable
6733     * through {@link #FOCUSABLE_AUTO} will also cause this method to return {@code true}.
6734     * Apps that declare a {@link android.content.pm.ApplicationInfo#targetSdkVersion} of
6735     * earlier than {@link Build.VERSION_CODES#O} will continue to see this method return
6736     * {@code false} for views not explicitly marked as focusable.
6737     * Use {@link #hasExplicitFocusable()} if you require the pre-{@link Build.VERSION_CODES#O}
6738     * behavior.</p>
6739     *
6740     * @return {@code true} if the view is focusable or if the view contains a focusable
6741     *         view, {@code false} otherwise
6742     *
6743     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
6744     * @see ViewGroup#getTouchscreenBlocksFocus()
6745     * @see #hasExplicitFocusable()
6746     */
6747    public boolean hasFocusable() {
6748        return hasFocusable(!sHasFocusableExcludeAutoFocusable, false);
6749    }
6750
6751    /**
6752     * Returns true if this view is focusable or if it contains a reachable View
6753     * for which {@link #hasExplicitFocusable()} returns {@code true}.
6754     * A "reachable hasExplicitFocusable()" is a view whose parents do not block descendants focus.
6755     * Only {@link #VISIBLE} views for which {@link #getFocusable()} would return
6756     * {@link #FOCUSABLE} are considered focusable.
6757     *
6758     * <p>This method preserves the pre-{@link Build.VERSION_CODES#O} behavior of
6759     * {@link #hasFocusable()} in that only views explicitly set focusable will cause
6760     * this method to return true. A view set to {@link #FOCUSABLE_AUTO} that resolves
6761     * to focusable will not.</p>
6762     *
6763     * @return {@code true} if the view is focusable or if the view contains a focusable
6764     *         view, {@code false} otherwise
6765     *
6766     * @see #hasFocusable()
6767     */
6768    public boolean hasExplicitFocusable() {
6769        return hasFocusable(false, true);
6770    }
6771
6772    boolean hasFocusable(boolean allowAutoFocus, boolean dispatchExplicit) {
6773        if (!isFocusableInTouchMode()) {
6774            for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) {
6775                final ViewGroup g = (ViewGroup) p;
6776                if (g.shouldBlockFocusForTouchscreen()) {
6777                    return false;
6778                }
6779            }
6780        }
6781
6782        // Invisible and gone views are never focusable.
6783        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6784            return false;
6785        }
6786
6787        // Only use effective focusable value when allowed.
6788        if ((allowAutoFocus || getFocusable() != FOCUSABLE_AUTO) && isFocusable()) {
6789            return true;
6790        }
6791
6792        return false;
6793    }
6794
6795    /**
6796     * Called by the view system when the focus state of this view changes.
6797     * When the focus change event is caused by directional navigation, direction
6798     * and previouslyFocusedRect provide insight into where the focus is coming from.
6799     * When overriding, be sure to call up through to the super class so that
6800     * the standard focus handling will occur.
6801     *
6802     * @param gainFocus True if the View has focus; false otherwise.
6803     * @param direction The direction focus has moved when requestFocus()
6804     *                  is called to give this view focus. Values are
6805     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
6806     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
6807     *                  It may not always apply, in which case use the default.
6808     * @param previouslyFocusedRect The rectangle, in this view's coordinate
6809     *        system, of the previously focused view.  If applicable, this will be
6810     *        passed in as finer grained information about where the focus is coming
6811     *        from (in addition to direction).  Will be <code>null</code> otherwise.
6812     */
6813    @CallSuper
6814    protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction,
6815            @Nullable Rect previouslyFocusedRect) {
6816        if (gainFocus) {
6817            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
6818        } else {
6819            notifyViewAccessibilityStateChangedIfNeeded(
6820                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
6821        }
6822
6823        // Here we check whether we still need the default focus highlight, and switch it on/off.
6824        switchDefaultFocusHighlight();
6825
6826        InputMethodManager imm = InputMethodManager.peekInstance();
6827        if (!gainFocus) {
6828            if (isPressed()) {
6829                setPressed(false);
6830            }
6831            if (imm != null && mAttachInfo != null && mAttachInfo.mHasWindowFocus) {
6832                imm.focusOut(this);
6833            }
6834            onFocusLost();
6835        } else if (imm != null && mAttachInfo != null && mAttachInfo.mHasWindowFocus) {
6836            imm.focusIn(this);
6837        }
6838
6839        invalidate(true);
6840        ListenerInfo li = mListenerInfo;
6841        if (li != null && li.mOnFocusChangeListener != null) {
6842            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
6843        }
6844
6845        if (mAttachInfo != null) {
6846            mAttachInfo.mKeyDispatchState.reset(this);
6847        }
6848
6849        notifyEnterOrExitForAutoFillIfNeeded(gainFocus);
6850    }
6851
6852    private void notifyEnterOrExitForAutoFillIfNeeded(boolean enter) {
6853        if (isAutofillable() && isAttachedToWindow()) {
6854            AutofillManager afm = getAutofillManager();
6855            if (afm != null) {
6856                if (enter && hasWindowFocus() && isFocused()) {
6857                    // We have not been laid out yet, hence cannot evaluate
6858                    // whether this view is visible to the user, we will do
6859                    // the evaluation once layout is complete.
6860                    if (!isLaidOut()) {
6861                        mPrivateFlags3 |= PFLAG3_NOTIFY_AUTOFILL_ENTER_ON_LAYOUT;
6862                    } else if (isVisibleToUser()) {
6863                        afm.notifyViewEntered(this);
6864                    }
6865                } else if (!hasWindowFocus() || !isFocused()) {
6866                    afm.notifyViewExited(this);
6867                }
6868            }
6869        }
6870    }
6871
6872    /**
6873     * Sends an accessibility event of the given type. If accessibility is
6874     * not enabled this method has no effect. The default implementation calls
6875     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
6876     * to populate information about the event source (this View), then calls
6877     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
6878     * populate the text content of the event source including its descendants,
6879     * and last calls
6880     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
6881     * on its parent to request sending of the event to interested parties.
6882     * <p>
6883     * If an {@link AccessibilityDelegate} has been specified via calling
6884     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6885     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
6886     * responsible for handling this call.
6887     * </p>
6888     *
6889     * @param eventType The type of the event to send, as defined by several types from
6890     * {@link android.view.accessibility.AccessibilityEvent}, such as
6891     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
6892     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
6893     *
6894     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
6895     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6896     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
6897     * @see AccessibilityDelegate
6898     */
6899    public void sendAccessibilityEvent(int eventType) {
6900        if (mAccessibilityDelegate != null) {
6901            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
6902        } else {
6903            sendAccessibilityEventInternal(eventType);
6904        }
6905    }
6906
6907    /**
6908     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
6909     * {@link AccessibilityEvent} to make an announcement which is related to some
6910     * sort of a context change for which none of the events representing UI transitions
6911     * is a good fit. For example, announcing a new page in a book. If accessibility
6912     * is not enabled this method does nothing.
6913     *
6914     * @param text The announcement text.
6915     */
6916    public void announceForAccessibility(CharSequence text) {
6917        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
6918            AccessibilityEvent event = AccessibilityEvent.obtain(
6919                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
6920            onInitializeAccessibilityEvent(event);
6921            event.getText().add(text);
6922            event.setContentDescription(null);
6923            mParent.requestSendAccessibilityEvent(this, event);
6924        }
6925    }
6926
6927    /**
6928     * @see #sendAccessibilityEvent(int)
6929     *
6930     * Note: Called from the default {@link AccessibilityDelegate}.
6931     *
6932     * @hide
6933     */
6934    public void sendAccessibilityEventInternal(int eventType) {
6935        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
6936            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
6937        }
6938    }
6939
6940    /**
6941     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
6942     * takes as an argument an empty {@link AccessibilityEvent} and does not
6943     * perform a check whether accessibility is enabled.
6944     * <p>
6945     * If an {@link AccessibilityDelegate} has been specified via calling
6946     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6947     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
6948     * is responsible for handling this call.
6949     * </p>
6950     *
6951     * @param event The event to send.
6952     *
6953     * @see #sendAccessibilityEvent(int)
6954     */
6955    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
6956        if (mAccessibilityDelegate != null) {
6957            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
6958        } else {
6959            sendAccessibilityEventUncheckedInternal(event);
6960        }
6961    }
6962
6963    /**
6964     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
6965     *
6966     * Note: Called from the default {@link AccessibilityDelegate}.
6967     *
6968     * @hide
6969     */
6970    public void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
6971        if (!isShown()) {
6972            return;
6973        }
6974        onInitializeAccessibilityEvent(event);
6975        // Only a subset of accessibility events populates text content.
6976        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
6977            dispatchPopulateAccessibilityEvent(event);
6978        }
6979        // In the beginning we called #isShown(), so we know that getParent() is not null.
6980        ViewParent parent = getParent();
6981        if (parent != null) {
6982            getParent().requestSendAccessibilityEvent(this, event);
6983        }
6984    }
6985
6986    /**
6987     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
6988     * to its children for adding their text content to the event. Note that the
6989     * event text is populated in a separate dispatch path since we add to the
6990     * event not only the text of the source but also the text of all its descendants.
6991     * A typical implementation will call
6992     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
6993     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
6994     * on each child. Override this method if custom population of the event text
6995     * content is required.
6996     * <p>
6997     * If an {@link AccessibilityDelegate} has been specified via calling
6998     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6999     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
7000     * is responsible for handling this call.
7001     * </p>
7002     * <p>
7003     * <em>Note:</em> Accessibility events of certain types are not dispatched for
7004     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
7005     * </p>
7006     *
7007     * @param event The event.
7008     *
7009     * @return True if the event population was completed.
7010     */
7011    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
7012        if (mAccessibilityDelegate != null) {
7013            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
7014        } else {
7015            return dispatchPopulateAccessibilityEventInternal(event);
7016        }
7017    }
7018
7019    /**
7020     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
7021     *
7022     * Note: Called from the default {@link AccessibilityDelegate}.
7023     *
7024     * @hide
7025     */
7026    public boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
7027        onPopulateAccessibilityEvent(event);
7028        return false;
7029    }
7030
7031    /**
7032     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
7033     * giving a chance to this View to populate the accessibility event with its
7034     * text content. While this method is free to modify event
7035     * attributes other than text content, doing so should normally be performed in
7036     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
7037     * <p>
7038     * Example: Adding formatted date string to an accessibility event in addition
7039     *          to the text added by the super implementation:
7040     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
7041     *     super.onPopulateAccessibilityEvent(event);
7042     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
7043     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
7044     *         mCurrentDate.getTimeInMillis(), flags);
7045     *     event.getText().add(selectedDateUtterance);
7046     * }</pre>
7047     * <p>
7048     * If an {@link AccessibilityDelegate} has been specified via calling
7049     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7050     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
7051     * is responsible for handling this call.
7052     * </p>
7053     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
7054     * information to the event, in case the default implementation has basic information to add.
7055     * </p>
7056     *
7057     * @param event The accessibility event which to populate.
7058     *
7059     * @see #sendAccessibilityEvent(int)
7060     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
7061     */
7062    @CallSuper
7063    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
7064        if (mAccessibilityDelegate != null) {
7065            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
7066        } else {
7067            onPopulateAccessibilityEventInternal(event);
7068        }
7069    }
7070
7071    /**
7072     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
7073     *
7074     * Note: Called from the default {@link AccessibilityDelegate}.
7075     *
7076     * @hide
7077     */
7078    public void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
7079    }
7080
7081    /**
7082     * Initializes an {@link AccessibilityEvent} with information about
7083     * this View which is the event source. In other words, the source of
7084     * an accessibility event is the view whose state change triggered firing
7085     * the event.
7086     * <p>
7087     * Example: Setting the password property of an event in addition
7088     *          to properties set by the super implementation:
7089     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
7090     *     super.onInitializeAccessibilityEvent(event);
7091     *     event.setPassword(true);
7092     * }</pre>
7093     * <p>
7094     * If an {@link AccessibilityDelegate} has been specified via calling
7095     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7096     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
7097     * is responsible for handling this call.
7098     * </p>
7099     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
7100     * information to the event, in case the default implementation has basic information to add.
7101     * </p>
7102     * @param event The event to initialize.
7103     *
7104     * @see #sendAccessibilityEvent(int)
7105     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
7106     */
7107    @CallSuper
7108    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
7109        if (mAccessibilityDelegate != null) {
7110            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
7111        } else {
7112            onInitializeAccessibilityEventInternal(event);
7113        }
7114    }
7115
7116    /**
7117     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
7118     *
7119     * Note: Called from the default {@link AccessibilityDelegate}.
7120     *
7121     * @hide
7122     */
7123    public void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
7124        event.setSource(this);
7125        event.setClassName(getAccessibilityClassName());
7126        event.setPackageName(getContext().getPackageName());
7127        event.setEnabled(isEnabled());
7128        event.setContentDescription(mContentDescription);
7129
7130        switch (event.getEventType()) {
7131            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
7132                ArrayList<View> focusablesTempList = (mAttachInfo != null)
7133                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
7134                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
7135                event.setItemCount(focusablesTempList.size());
7136                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
7137                if (mAttachInfo != null) {
7138                    focusablesTempList.clear();
7139                }
7140            } break;
7141            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
7142                CharSequence text = getIterableTextForAccessibility();
7143                if (text != null && text.length() > 0) {
7144                    event.setFromIndex(getAccessibilitySelectionStart());
7145                    event.setToIndex(getAccessibilitySelectionEnd());
7146                    event.setItemCount(text.length());
7147                }
7148            } break;
7149        }
7150    }
7151
7152    /**
7153     * Returns an {@link AccessibilityNodeInfo} representing this view from the
7154     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
7155     * This method is responsible for obtaining an accessibility node info from a
7156     * pool of reusable instances and calling
7157     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
7158     * initialize the former.
7159     * <p>
7160     * Note: The client is responsible for recycling the obtained instance by calling
7161     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
7162     * </p>
7163     *
7164     * @return A populated {@link AccessibilityNodeInfo}.
7165     *
7166     * @see AccessibilityNodeInfo
7167     */
7168    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
7169        if (mAccessibilityDelegate != null) {
7170            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
7171        } else {
7172            return createAccessibilityNodeInfoInternal();
7173        }
7174    }
7175
7176    /**
7177     * @see #createAccessibilityNodeInfo()
7178     *
7179     * @hide
7180     */
7181    public AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
7182        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
7183        if (provider != null) {
7184            return provider.createAccessibilityNodeInfo(AccessibilityNodeProvider.HOST_VIEW_ID);
7185        } else {
7186            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
7187            onInitializeAccessibilityNodeInfo(info);
7188            return info;
7189        }
7190    }
7191
7192    /**
7193     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
7194     * The base implementation sets:
7195     * <ul>
7196     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
7197     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
7198     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
7199     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
7200     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
7201     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
7202     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
7203     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
7204     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
7205     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
7206     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
7207     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
7208     *   <li>{@link AccessibilityNodeInfo#setContextClickable(boolean)}</li>
7209     * </ul>
7210     * <p>
7211     * Subclasses should override this method, call the super implementation,
7212     * and set additional attributes.
7213     * </p>
7214     * <p>
7215     * If an {@link AccessibilityDelegate} has been specified via calling
7216     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7217     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
7218     * is responsible for handling this call.
7219     * </p>
7220     *
7221     * @param info The instance to initialize.
7222     */
7223    @CallSuper
7224    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
7225        if (mAccessibilityDelegate != null) {
7226            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
7227        } else {
7228            onInitializeAccessibilityNodeInfoInternal(info);
7229        }
7230    }
7231
7232    /**
7233     * Gets the location of this view in screen coordinates.
7234     *
7235     * @param outRect The output location
7236     * @hide
7237     */
7238    public void getBoundsOnScreen(Rect outRect) {
7239        getBoundsOnScreen(outRect, false);
7240    }
7241
7242    /**
7243     * Gets the location of this view in screen coordinates.
7244     *
7245     * @param outRect The output location
7246     * @param clipToParent Whether to clip child bounds to the parent ones.
7247     * @hide
7248     */
7249    public void getBoundsOnScreen(Rect outRect, boolean clipToParent) {
7250        if (mAttachInfo == null) {
7251            return;
7252        }
7253
7254        RectF position = mAttachInfo.mTmpTransformRect;
7255        position.set(0, 0, mRight - mLeft, mBottom - mTop);
7256        mapRectFromViewToScreenCoords(position, clipToParent);
7257        outRect.set(Math.round(position.left), Math.round(position.top),
7258                Math.round(position.right), Math.round(position.bottom));
7259    }
7260
7261    /**
7262     * Map a rectangle from view-relative coordinates to screen-relative coordinates
7263     *
7264     * @param rect The rectangle to be mapped
7265     * @param clipToParent Whether to clip child bounds to the parent ones.
7266     * @hide
7267     */
7268    public void mapRectFromViewToScreenCoords(RectF rect, boolean clipToParent) {
7269        if (!hasIdentityMatrix()) {
7270            getMatrix().mapRect(rect);
7271        }
7272
7273        rect.offset(mLeft, mTop);
7274
7275        ViewParent parent = mParent;
7276        while (parent instanceof View) {
7277            View parentView = (View) parent;
7278
7279            rect.offset(-parentView.mScrollX, -parentView.mScrollY);
7280
7281            if (clipToParent) {
7282                rect.left = Math.max(rect.left, 0);
7283                rect.top = Math.max(rect.top, 0);
7284                rect.right = Math.min(rect.right, parentView.getWidth());
7285                rect.bottom = Math.min(rect.bottom, parentView.getHeight());
7286            }
7287
7288            if (!parentView.hasIdentityMatrix()) {
7289                parentView.getMatrix().mapRect(rect);
7290            }
7291
7292            rect.offset(parentView.mLeft, parentView.mTop);
7293
7294            parent = parentView.mParent;
7295        }
7296
7297        if (parent instanceof ViewRootImpl) {
7298            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
7299            rect.offset(0, -viewRootImpl.mCurScrollY);
7300        }
7301
7302        rect.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
7303    }
7304
7305    /**
7306     * Return the class name of this object to be used for accessibility purposes.
7307     * Subclasses should only override this if they are implementing something that
7308     * should be seen as a completely new class of view when used by accessibility,
7309     * unrelated to the class it is deriving from.  This is used to fill in
7310     * {@link AccessibilityNodeInfo#setClassName AccessibilityNodeInfo.setClassName}.
7311     */
7312    public CharSequence getAccessibilityClassName() {
7313        return View.class.getName();
7314    }
7315
7316    /**
7317     * Called when assist structure is being retrieved from a view as part of
7318     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData}.
7319     * @param structure Fill in with structured view data.  The default implementation
7320     * fills in all data that can be inferred from the view itself.
7321     */
7322    public void onProvideStructure(ViewStructure structure) {
7323        onProvideStructureForAssistOrAutofill(structure, false, 0);
7324    }
7325
7326    /**
7327     * Called when assist structure is being retrieved from a view as part of an autofill request.
7328     *
7329     * <p>This method already provides most of what's needed for autofill, but should be overridden
7330     * when:
7331     * <ul>
7332     *   <li>The view contents does not include PII (Personally Identifiable Information), so it
7333     * can call {@link ViewStructure#setDataIsSensitive(boolean)} passing {@code false}.
7334     *   <li>It must set fields such {@link ViewStructure#setText(CharSequence)},
7335     * {@link ViewStructure#setAutofillOptions(CharSequence[])},
7336     * or {@link ViewStructure#setWebDomain(String)}.
7337     *   <li> The {@code left} and {@code top} values set in
7338     * {@link ViewStructure#setDimens(int, int, int, int, int, int)} need to be relative to the next
7339     * {@link ViewGroup#isImportantForAutofill() included} parent in the structure.
7340     * </ul>
7341     *
7342     * @param structure Fill in with structured view data. The default implementation
7343     * fills in all data that can be inferred from the view itself.
7344     * @param flags optional flags.
7345     *
7346     * @see #AUTOFILL_FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
7347     */
7348    public void onProvideAutofillStructure(ViewStructure structure, @AutofillFlags int flags) {
7349        onProvideStructureForAssistOrAutofill(structure, true, flags);
7350    }
7351
7352    private void onProvideStructureForAssistOrAutofill(ViewStructure structure,
7353            boolean forAutofill, @AutofillFlags int flags) {
7354        final int id = mID;
7355        if (id != NO_ID && !isViewIdGenerated(id)) {
7356            String pkg, type, entry;
7357            try {
7358                final Resources res = getResources();
7359                entry = res.getResourceEntryName(id);
7360                type = res.getResourceTypeName(id);
7361                pkg = res.getResourcePackageName(id);
7362            } catch (Resources.NotFoundException e) {
7363                entry = type = pkg = null;
7364            }
7365            structure.setId(id, pkg, type, entry);
7366        } else {
7367            structure.setId(id, null, null, null);
7368        }
7369
7370        if (forAutofill) {
7371            final @AutofillType int autofillType = getAutofillType();
7372            // Don't need to fill autofill info if view does not support it.
7373            // For example, only TextViews that are editable support autofill
7374            if (autofillType != AUTOFILL_TYPE_NONE) {
7375                structure.setAutofillType(autofillType);
7376                structure.setAutofillHints(getAutofillHints());
7377                structure.setAutofillValue(getAutofillValue());
7378            }
7379        }
7380
7381        int ignoredParentLeft = 0;
7382        int ignoredParentTop = 0;
7383        if (forAutofill && (flags & AUTOFILL_FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) == 0) {
7384            View parentGroup = null;
7385
7386            ViewParent viewParent = getParent();
7387            if (viewParent instanceof View) {
7388                parentGroup = (View) viewParent;
7389            }
7390
7391            while (parentGroup != null && !parentGroup.isImportantForAutofill()) {
7392                ignoredParentLeft += parentGroup.mLeft;
7393                ignoredParentTop += parentGroup.mTop;
7394
7395                viewParent = parentGroup.getParent();
7396                if (viewParent instanceof View) {
7397                    parentGroup = (View) viewParent;
7398                } else {
7399                    break;
7400                }
7401            }
7402        }
7403
7404        structure.setDimens(ignoredParentLeft + mLeft, ignoredParentTop + mTop, mScrollX, mScrollY,
7405                mRight - mLeft, mBottom - mTop);
7406        if (!forAutofill) {
7407            if (!hasIdentityMatrix()) {
7408                structure.setTransformation(getMatrix());
7409            }
7410            structure.setElevation(getZ());
7411        }
7412        structure.setVisibility(getVisibility());
7413        structure.setEnabled(isEnabled());
7414        if (isClickable()) {
7415            structure.setClickable(true);
7416        }
7417        if (isFocusable()) {
7418            structure.setFocusable(true);
7419        }
7420        if (isFocused()) {
7421            structure.setFocused(true);
7422        }
7423        if (isAccessibilityFocused()) {
7424            structure.setAccessibilityFocused(true);
7425        }
7426        if (isSelected()) {
7427            structure.setSelected(true);
7428        }
7429        if (isActivated()) {
7430            structure.setActivated(true);
7431        }
7432        if (isLongClickable()) {
7433            structure.setLongClickable(true);
7434        }
7435        if (this instanceof Checkable) {
7436            structure.setCheckable(true);
7437            if (((Checkable)this).isChecked()) {
7438                structure.setChecked(true);
7439            }
7440        }
7441        if (isOpaque()) {
7442            structure.setOpaque(true);
7443        }
7444        if (isContextClickable()) {
7445            structure.setContextClickable(true);
7446        }
7447        structure.setClassName(getAccessibilityClassName().toString());
7448        structure.setContentDescription(getContentDescription());
7449    }
7450
7451    /**
7452     * Called when assist structure is being retrieved from a view as part of
7453     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData} to
7454     * generate additional virtual structure under this view.  The defaullt implementation
7455     * uses {@link #getAccessibilityNodeProvider()} to try to generate this from the
7456     * view's virtual accessibility nodes, if any.  You can override this for a more
7457     * optimal implementation providing this data.
7458     */
7459    public void onProvideVirtualStructure(ViewStructure structure) {
7460        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
7461        if (provider != null) {
7462            AccessibilityNodeInfo info = createAccessibilityNodeInfo();
7463            structure.setChildCount(1);
7464            ViewStructure root = structure.newChild(0);
7465            populateVirtualStructure(root, provider, info);
7466            info.recycle();
7467        }
7468    }
7469
7470    /**
7471     * Called when assist structure is being retrieved from a view as part of an autofill request
7472     * to generate additional virtual structure under this view.
7473     *
7474     * <p>When implementing this method, subclasses must follow the rules below:
7475     *
7476     * <ol>
7477     * <li>Also implement {@link #autofill(SparseArray)} to autofill the virtual
7478     * children.
7479     * <li>Call
7480     * {@link android.view.autofill.AutofillManager#notifyViewEntered} and
7481     * {@link android.view.autofill.AutofillManager#notifyViewExited(View, int)}
7482     * when the focus inside the view changed.
7483     * <li>Call {@link android.view.autofill.AutofillManager#notifyValueChanged(View, int,
7484     * AutofillValue)} when the value of a child changed.
7485     * <li>Call {@link AutofillManager#commit()} when the autofill context
7486     * of the view structure changed and you want the current autofill interaction if such
7487     * to be commited.
7488     * <li>Call {@link AutofillManager#cancel()} ()} when the autofill context
7489     * of the view structure changed and you want the current autofill interaction if such
7490     * to be cancelled.
7491     * <li> The {@code left} and {@code top} values set in
7492     * {@link ViewStructure#setDimens(int, int, int, int, int, int)} need to be relative to the next
7493     * {@link ViewGroup#isImportantForAutofill() included} parent in the structure.
7494     * </ol>
7495     *
7496     * @param structure Fill in with structured view data.
7497     * @param flags optional flags.
7498     *
7499     * @see #AUTOFILL_FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
7500     */
7501    public void onProvideAutofillVirtualStructure(ViewStructure structure, int flags) {
7502    }
7503
7504    /**
7505     * Automatically fills the content of this view with the {@code value}.
7506     *
7507     * <p>By default does nothing, but views should override it (and {@link #getAutofillType()},
7508     * {@link #getAutofillValue()}, and {@link #onProvideAutofillStructure(ViewStructure, int)}
7509     * to support the Autofill Framework.
7510     *
7511     * <p>Typically, it is implemented by:
7512     *
7513     * <ol>
7514     * <li>Calling the proper getter method on {@link AutofillValue} to fetch the actual value.
7515     * <li>Passing the actual value to the equivalent setter in the view.
7516     * </ol>
7517     *
7518     * <p>For example, a text-field view would call:
7519     * <pre class="prettyprint">
7520     * CharSequence text = value.getTextValue();
7521     * if (text != null) {
7522     *     setText(text);
7523     * }
7524     * </pre>
7525     *
7526     * <p>If the value is updated asyncronously the next call to
7527     * {@link AutofillManager#notifyValueChanged(View)} must happen <u>after</u> the value was
7528     * changed to the autofilled value. If not, the view will not be considered autofilled.
7529     *
7530     * @param value value to be autofilled.
7531     */
7532    public void autofill(@SuppressWarnings("unused") AutofillValue value) {
7533    }
7534
7535    /**
7536     * Automatically fills the content of a virtual views.
7537     *
7538     * <p>See {@link #autofill(AutofillValue)} and
7539     * {@link #onProvideAutofillVirtualStructure(ViewStructure, int)} for more info.
7540     * <p>To indicate that a virtual view was autofilled
7541     * <code>?android:attr/autofilledHighlight</code> should be drawn over it until the data
7542     * changes.
7543     *
7544     * @param values map of values to be autofilled, keyed by virtual child id.
7545     *
7546     * @attr ref android.R.styleable#Theme_autofilledHighlight
7547     */
7548    public void autofill(@NonNull @SuppressWarnings("unused") SparseArray<AutofillValue> values) {
7549    }
7550
7551    /**
7552     * Gets the unique identifier of this view on the screen for Autofill purposes.
7553     *
7554     * @return The View's Autofill id.
7555     */
7556    public final AutofillId getAutofillId() {
7557        if (mAutofillId == null) {
7558            // The autofill id needs to be unique, but its value doesn't matter,
7559            // so it's better to reuse the accessibility id to save space.
7560            mAutofillId = new AutofillId(getAccessibilityViewId());
7561        }
7562        return mAutofillId;
7563    }
7564
7565    /**
7566     * Describes the autofill type that should be used on calls to
7567     * {@link #autofill(AutofillValue)} and {@link #autofill(SparseArray)}.
7568     *
7569     * <p>By default returns {@link #AUTOFILL_TYPE_NONE}, but views should override it (and
7570     * {@link #autofill(AutofillValue)} to support the Autofill Framework.
7571     */
7572    public @AutofillType int getAutofillType() {
7573        return AUTOFILL_TYPE_NONE;
7574    }
7575
7576    /**
7577     * Describes the content of a view so that a autofill service can fill in the appropriate data.
7578     *
7579     * @return The hints set via the attribute or {@code null} if no hint it set.
7580     *
7581     * @attr ref android.R.styleable#View_autofillHints
7582     */
7583    @ViewDebug.ExportedProperty()
7584    @Nullable public String[] getAutofillHints() {
7585        return mAutofillHints;
7586    }
7587
7588    /**
7589     * @hide
7590     */
7591    public boolean isAutofilled() {
7592        return (mPrivateFlags3 & PFLAG3_IS_AUTOFILLED) != 0;
7593    }
7594
7595    /**
7596     * Gets the {@link View}'s current autofill value.
7597     *
7598     * <p>By default returns {@code null}, but views should override it (and
7599     * {@link #autofill(AutofillValue)}, and {@link #getAutofillType()} to support the Autofill
7600     * Framework.
7601     */
7602    @Nullable
7603    public AutofillValue getAutofillValue() {
7604        return null;
7605    }
7606
7607    /**
7608     * Gets the mode for determining whether this View is important for autofill.
7609     *
7610     * <p>See {@link #setImportantForAutofill(int)} for more info about this mode.
7611     *
7612     * @return {@link #IMPORTANT_FOR_AUTOFILL_AUTO} by default, or value passed to
7613     * {@link #setImportantForAutofill(int)}.
7614     *
7615     * @attr ref android.R.styleable#View_importantForAutofill
7616     */
7617    @ViewDebug.ExportedProperty(mapping = {
7618            @ViewDebug.IntToString(from = IMPORTANT_FOR_AUTOFILL_AUTO, to = "auto"),
7619            @ViewDebug.IntToString(from = IMPORTANT_FOR_AUTOFILL_YES, to = "yes"),
7620            @ViewDebug.IntToString(from = IMPORTANT_FOR_AUTOFILL_NO, to = "no"),
7621            @ViewDebug.IntToString(from = IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS,
7622                to = "yesExcludeDescendants"),
7623            @ViewDebug.IntToString(from = IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS,
7624                to = "noExcludeDescendants")})
7625    public @AutofillImportance int getImportantForAutofill() {
7626        return (mPrivateFlags3
7627                & PFLAG3_IMPORTANT_FOR_AUTOFILL_MASK) >> PFLAG3_IMPORTANT_FOR_AUTOFILL_SHIFT;
7628    }
7629
7630    /**
7631     * Sets the mode for determining whether this View is important for autofill.
7632     *
7633     * <p>This property controls how this view is presented to the autofill components
7634     * which help users to fill credentials, addresses, etc. For example, views
7635     * that contain labels and input fields are useful for autofill components to
7636     * determine the user context and provide values for the inputs. Note that the
7637     * user can always override this by manually triggering autotill which would
7638     * expose the view to the autofill provider.
7639     *
7640     * <p>The platform determines the importance for autofill automatically but you
7641     * can use this method to customize the behavior. See the autofill modes below
7642     * for more details.
7643     *
7644     * <p>See {@link #setImportantForAutofill(int)} for more info about this mode.
7645     *
7646     * @param mode {@link #IMPORTANT_FOR_AUTOFILL_AUTO}, {@link #IMPORTANT_FOR_AUTOFILL_YES},
7647     * {@link #IMPORTANT_FOR_AUTOFILL_NO}, {@link #IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS},
7648     * or {@link #IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS}.
7649     *
7650     * @attr ref android.R.styleable#View_importantForAutofill
7651     */
7652    public void setImportantForAutofill(@AutofillImportance int mode) {
7653        mPrivateFlags3 &= ~PFLAG3_IMPORTANT_FOR_AUTOFILL_MASK;
7654        mPrivateFlags3 |= (mode << PFLAG3_IMPORTANT_FOR_AUTOFILL_SHIFT)
7655                & PFLAG3_IMPORTANT_FOR_AUTOFILL_MASK;
7656    }
7657
7658    /**
7659     * Hints the Android System whether the {@link android.app.assist.AssistStructure.ViewNode}
7660     * associated with this View should be included in a {@link ViewStructure} used for
7661     * autofill purposes.
7662     *
7663     * <p>Generally speaking, a view is important for autofill if:
7664     * <ol>
7665     * <li>The view can-be autofilled by an {@link android.service.autofill.AutofillService}.
7666     * <li>The view contents can help an {@link android.service.autofill.AutofillService} to
7667     * autofill other views.
7668     * <ol>
7669     *
7670     * <p>For example, view containers should typically return {@code false} for performance reasons
7671     * (since the important info is provided by their children), but if the container is actually
7672     * whose children are part of a compound view, it should return {@code true} (and then override
7673     * {@link #dispatchProvideAutofillStructure(ViewStructure, int)} to simply call
7674     * {@link #onProvideAutofillStructure(ViewStructure, int)} so its children are not included in
7675     * the structure). On the other hand, views representing labels or editable fields should
7676     * typically return {@code true}, but in some cases they could return {@code false} (for
7677     * example, if they're part of a "Captcha" mechanism).
7678     *
7679     * <p>By default, this method returns {@code true} if {@link #getImportantForAutofill()} returns
7680     * {@link #IMPORTANT_FOR_AUTOFILL_YES}, {@code false } if it returns
7681     * {@link #IMPORTANT_FOR_AUTOFILL_NO}, and use some heuristics to define the importance when it
7682     * returns {@link #IMPORTANT_FOR_AUTOFILL_AUTO}. Hence, it should rarely be overridden - Views
7683     * should use {@link #setImportantForAutofill(int)} instead.
7684     *
7685     * <p><strong>Note:</strong> returning {@code false} does not guarantee the view will be
7686     * excluded from the structure; for example, if the user explicitly requested autofill, the
7687     * View might be always included.
7688     *
7689     * <p>This decision applies just for the view, not its children - if the view children are not
7690     * important for autofill, the view should override
7691     * {@link #dispatchProvideAutofillStructure(ViewStructure, int)} to simply call
7692     * {@link #onProvideAutofillStructure(ViewStructure, int)} (instead of calling
7693     * {@link #dispatchProvideAutofillStructure(ViewStructure, int)} for each child).
7694     *
7695     * @return whether the view is considered important for autofill.
7696     *
7697     * @see #setImportantForAutofill(int)
7698     * @see #IMPORTANT_FOR_AUTOFILL_AUTO
7699     * @see #IMPORTANT_FOR_AUTOFILL_YES
7700     * @see #IMPORTANT_FOR_AUTOFILL_NO
7701     * @see #IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS
7702     * @see #IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS
7703     */
7704    public final boolean isImportantForAutofill() {
7705        // Check parent mode to ensure we're not hidden.
7706        ViewParent parent = mParent;
7707        while (parent instanceof View) {
7708            final int parentImportance = ((View) parent).getImportantForAutofill();
7709            if (parentImportance == IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS
7710                    || parentImportance == IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS) {
7711                return false;
7712            }
7713            parent = parent.getParent();
7714        }
7715
7716        final int importance = getImportantForAutofill();
7717
7718        // First, check the explicit states.
7719        if (importance == IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS
7720                || importance == IMPORTANT_FOR_AUTOFILL_YES) {
7721            return true;
7722        }
7723        if (importance == IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS
7724                || importance == IMPORTANT_FOR_AUTOFILL_NO) {
7725            return false;
7726        }
7727
7728        // Then use some heuristics to handle AUTO.
7729
7730        // Always include views that have an explicit resource id.
7731        final int id = mID;
7732        if (id != NO_ID && !isViewIdGenerated(id)) {
7733            final Resources res = getResources();
7734            String entry = null;
7735            String pkg = null;
7736            try {
7737                entry = res.getResourceEntryName(id);
7738                pkg = res.getResourcePackageName(id);
7739            } catch (Resources.NotFoundException e) {
7740                // ignore
7741            }
7742            if (entry != null && pkg != null && pkg.equals(mContext.getPackageName())) {
7743                return true;
7744            }
7745        }
7746
7747        // Otherwise, assume it's not important...
7748        return false;
7749    }
7750
7751    @Nullable
7752    private AutofillManager getAutofillManager() {
7753        return mContext.getSystemService(AutofillManager.class);
7754    }
7755
7756    private boolean isAutofillable() {
7757        return getAutofillType() != AUTOFILL_TYPE_NONE && isImportantForAutofill()
7758                && getAccessibilityViewId() > LAST_APP_ACCESSIBILITY_ID;
7759    }
7760
7761    private void populateVirtualStructure(ViewStructure structure,
7762            AccessibilityNodeProvider provider, AccessibilityNodeInfo info) {
7763        structure.setId(AccessibilityNodeInfo.getVirtualDescendantId(info.getSourceNodeId()),
7764                null, null, null);
7765        Rect rect = structure.getTempRect();
7766        info.getBoundsInParent(rect);
7767        structure.setDimens(rect.left, rect.top, 0, 0, rect.width(), rect.height());
7768        structure.setVisibility(VISIBLE);
7769        structure.setEnabled(info.isEnabled());
7770        if (info.isClickable()) {
7771            structure.setClickable(true);
7772        }
7773        if (info.isFocusable()) {
7774            structure.setFocusable(true);
7775        }
7776        if (info.isFocused()) {
7777            structure.setFocused(true);
7778        }
7779        if (info.isAccessibilityFocused()) {
7780            structure.setAccessibilityFocused(true);
7781        }
7782        if (info.isSelected()) {
7783            structure.setSelected(true);
7784        }
7785        if (info.isLongClickable()) {
7786            structure.setLongClickable(true);
7787        }
7788        if (info.isCheckable()) {
7789            structure.setCheckable(true);
7790            if (info.isChecked()) {
7791                structure.setChecked(true);
7792            }
7793        }
7794        if (info.isContextClickable()) {
7795            structure.setContextClickable(true);
7796        }
7797        CharSequence cname = info.getClassName();
7798        structure.setClassName(cname != null ? cname.toString() : null);
7799        structure.setContentDescription(info.getContentDescription());
7800        if ((info.getText() != null || info.getError() != null)) {
7801            structure.setText(info.getText(), info.getTextSelectionStart(),
7802                    info.getTextSelectionEnd());
7803        }
7804        final int NCHILDREN = info.getChildCount();
7805        if (NCHILDREN > 0) {
7806            structure.setChildCount(NCHILDREN);
7807            for (int i=0; i<NCHILDREN; i++) {
7808                AccessibilityNodeInfo cinfo = provider.createAccessibilityNodeInfo(
7809                        AccessibilityNodeInfo.getVirtualDescendantId(info.getChildId(i)));
7810                ViewStructure child = structure.newChild(i);
7811                populateVirtualStructure(child, provider, cinfo);
7812                cinfo.recycle();
7813            }
7814        }
7815    }
7816
7817    /**
7818     * Dispatch creation of {@link ViewStructure} down the hierarchy.  The default
7819     * implementation calls {@link #onProvideStructure} and
7820     * {@link #onProvideVirtualStructure}.
7821     */
7822    public void dispatchProvideStructure(ViewStructure structure) {
7823        dispatchProvideStructureForAssistOrAutofill(structure, false, 0);
7824    }
7825
7826    /**
7827     * Dispatch creation of {@link ViewStructure} down the hierarchy.
7828     *
7829     * <p>The default implementation does the following:
7830     *
7831     * <ul>
7832     *   <li>Sets the {@link AutofillId} in the structure.
7833     *   <li>Calls {@link #onProvideAutofillStructure(ViewStructure, int)}.
7834     *   <li>Calls {@link #onProvideAutofillVirtualStructure(ViewStructure, int)}.
7835     * </ul>
7836     *
7837     * <p>When overridden, it must either call
7838     * {@code super.dispatchProvideAutofillStructure(structure, flags)} or explicitly
7839     * set the {@link AutofillId} in the structure (for example, by calling
7840     * {@code structure.setAutofillId(getAutofillId())}).
7841     *
7842     * <p>When providing your implementation you need to decide how to handle
7843     * the {@link #AUTOFILL_FLAG_INCLUDE_NOT_IMPORTANT_VIEWS} flag which instructs you
7844     * to report all views to the structure regardless if {@link #isImportantForAutofill()}
7845     * returns true. We encourage you respect the importance property for a better
7846     * user experience in your app. If the flag is not set then you should filter out
7847     * not important views to optimize autofill performance in your app.
7848     *
7849     * @param structure Fill in with structured view data.
7850     * @param flags optional flags.
7851     *
7852     * @see #AUTOFILL_FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
7853     */
7854    public void dispatchProvideAutofillStructure(@NonNull ViewStructure structure,
7855            @AutofillFlags int flags) {
7856        dispatchProvideStructureForAssistOrAutofill(structure, true, flags);
7857    }
7858
7859    private void dispatchProvideStructureForAssistOrAutofill(ViewStructure structure,
7860            boolean forAutofill, @AutofillFlags int flags) {
7861        if (forAutofill) {
7862            structure.setAutofillId(getAutofillId());
7863            onProvideAutofillStructure(structure, flags);
7864            onProvideAutofillVirtualStructure(structure, flags);
7865        } else if (!isAssistBlocked()) {
7866            onProvideStructure(structure);
7867            onProvideVirtualStructure(structure);
7868        } else {
7869            structure.setClassName(getAccessibilityClassName().toString());
7870            structure.setAssistBlocked(true);
7871        }
7872    }
7873
7874    /**
7875     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
7876     *
7877     * Note: Called from the default {@link AccessibilityDelegate}.
7878     *
7879     * @hide
7880     */
7881    public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
7882        if (mAttachInfo == null) {
7883            return;
7884        }
7885
7886        Rect bounds = mAttachInfo.mTmpInvalRect;
7887
7888        getDrawingRect(bounds);
7889        info.setBoundsInParent(bounds);
7890
7891        getBoundsOnScreen(bounds, true);
7892        info.setBoundsInScreen(bounds);
7893
7894        ViewParent parent = getParentForAccessibility();
7895        if (parent instanceof View) {
7896            info.setParent((View) parent);
7897        }
7898
7899        if (mID != View.NO_ID) {
7900            View rootView = getRootView();
7901            if (rootView == null) {
7902                rootView = this;
7903            }
7904
7905            View label = rootView.findLabelForView(this, mID);
7906            if (label != null) {
7907                info.setLabeledBy(label);
7908            }
7909
7910            if ((mAttachInfo.mAccessibilityFetchFlags
7911                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
7912                    && Resources.resourceHasPackage(mID)) {
7913                try {
7914                    String viewId = getResources().getResourceName(mID);
7915                    info.setViewIdResourceName(viewId);
7916                } catch (Resources.NotFoundException nfe) {
7917                    /* ignore */
7918                }
7919            }
7920        }
7921
7922        if (mLabelForId != View.NO_ID) {
7923            View rootView = getRootView();
7924            if (rootView == null) {
7925                rootView = this;
7926            }
7927            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
7928            if (labeled != null) {
7929                info.setLabelFor(labeled);
7930            }
7931        }
7932
7933        if (mAccessibilityTraversalBeforeId != View.NO_ID) {
7934            View rootView = getRootView();
7935            if (rootView == null) {
7936                rootView = this;
7937            }
7938            View next = rootView.findViewInsideOutShouldExist(this,
7939                    mAccessibilityTraversalBeforeId);
7940            if (next != null && next.includeForAccessibility()) {
7941                info.setTraversalBefore(next);
7942            }
7943        }
7944
7945        if (mAccessibilityTraversalAfterId != View.NO_ID) {
7946            View rootView = getRootView();
7947            if (rootView == null) {
7948                rootView = this;
7949            }
7950            View next = rootView.findViewInsideOutShouldExist(this,
7951                    mAccessibilityTraversalAfterId);
7952            if (next != null && next.includeForAccessibility()) {
7953                info.setTraversalAfter(next);
7954            }
7955        }
7956
7957        info.setVisibleToUser(isVisibleToUser());
7958
7959        info.setImportantForAccessibility(isImportantForAccessibility());
7960        info.setPackageName(mContext.getPackageName());
7961        info.setClassName(getAccessibilityClassName());
7962        info.setContentDescription(getContentDescription());
7963
7964        info.setEnabled(isEnabled());
7965        info.setClickable(isClickable());
7966        info.setFocusable(isFocusable());
7967        info.setFocused(isFocused());
7968        info.setAccessibilityFocused(isAccessibilityFocused());
7969        info.setSelected(isSelected());
7970        info.setLongClickable(isLongClickable());
7971        info.setContextClickable(isContextClickable());
7972        info.setLiveRegion(getAccessibilityLiveRegion());
7973
7974        // TODO: These make sense only if we are in an AdapterView but all
7975        // views can be selected. Maybe from accessibility perspective
7976        // we should report as selectable view in an AdapterView.
7977        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
7978        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
7979
7980        if (isFocusable()) {
7981            if (isFocused()) {
7982                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
7983            } else {
7984                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
7985            }
7986        }
7987
7988        if (!isAccessibilityFocused()) {
7989            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
7990        } else {
7991            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
7992        }
7993
7994        if (isClickable() && isEnabled()) {
7995            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
7996        }
7997
7998        if (isLongClickable() && isEnabled()) {
7999            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
8000        }
8001
8002        if (isContextClickable() && isEnabled()) {
8003            info.addAction(AccessibilityAction.ACTION_CONTEXT_CLICK);
8004        }
8005
8006        CharSequence text = getIterableTextForAccessibility();
8007        if (text != null && text.length() > 0) {
8008            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
8009
8010            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
8011            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
8012            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
8013            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
8014                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
8015                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
8016        }
8017
8018        info.addAction(AccessibilityAction.ACTION_SHOW_ON_SCREEN);
8019        populateAccessibilityNodeInfoDrawingOrderInParent(info);
8020    }
8021
8022    /**
8023     * Adds extra data to an {@link AccessibilityNodeInfo} based on an explicit request for the
8024     * additional data.
8025     * <p>
8026     * This method only needs overloading if the node is marked as having extra data available.
8027     * </p>
8028     *
8029     * @param info The info to which to add the extra data. Never {@code null}.
8030     * @param extraDataKey A key specifying the type of extra data to add to the info. The
8031     *                     extra data should be added to the {@link Bundle} returned by
8032     *                     the info's {@link AccessibilityNodeInfo#getExtras} method. Never
8033     *                     {@code null}.
8034     * @param arguments A {@link Bundle} holding any arguments relevant for this request. May be
8035     *                  {@code null} if the service provided no arguments.
8036     *
8037     * @see AccessibilityNodeInfo#setAvailableExtraData(List)
8038     */
8039    public void addExtraDataToAccessibilityNodeInfo(
8040            @NonNull AccessibilityNodeInfo info, @NonNull String extraDataKey,
8041            @Nullable Bundle arguments) {
8042    }
8043
8044    /**
8045     * Determine the order in which this view will be drawn relative to its siblings for a11y
8046     *
8047     * @param info The info whose drawing order should be populated
8048     */
8049    private void populateAccessibilityNodeInfoDrawingOrderInParent(AccessibilityNodeInfo info) {
8050        /*
8051         * If the view's bounds haven't been set yet, layout has not completed. In that situation,
8052         * drawing order may not be well-defined, and some Views with custom drawing order may
8053         * not be initialized sufficiently to respond properly getChildDrawingOrder.
8054         */
8055        if ((mPrivateFlags & PFLAG_HAS_BOUNDS) == 0) {
8056            info.setDrawingOrder(0);
8057            return;
8058        }
8059        int drawingOrderInParent = 1;
8060        // Iterate up the hierarchy if parents are not important for a11y
8061        View viewAtDrawingLevel = this;
8062        final ViewParent parent = getParentForAccessibility();
8063        while (viewAtDrawingLevel != parent) {
8064            final ViewParent currentParent = viewAtDrawingLevel.getParent();
8065            if (!(currentParent instanceof ViewGroup)) {
8066                // Should only happen for the Decor
8067                drawingOrderInParent = 0;
8068                break;
8069            } else {
8070                final ViewGroup parentGroup = (ViewGroup) currentParent;
8071                final int childCount = parentGroup.getChildCount();
8072                if (childCount > 1) {
8073                    List<View> preorderedList = parentGroup.buildOrderedChildList();
8074                    if (preorderedList != null) {
8075                        final int childDrawIndex = preorderedList.indexOf(viewAtDrawingLevel);
8076                        for (int i = 0; i < childDrawIndex; i++) {
8077                            drawingOrderInParent += numViewsForAccessibility(preorderedList.get(i));
8078                        }
8079                    } else {
8080                        final int childIndex = parentGroup.indexOfChild(viewAtDrawingLevel);
8081                        final boolean customOrder = parentGroup.isChildrenDrawingOrderEnabled();
8082                        final int childDrawIndex = ((childIndex >= 0) && customOrder) ? parentGroup
8083                                .getChildDrawingOrder(childCount, childIndex) : childIndex;
8084                        final int numChildrenToIterate = customOrder ? childCount : childDrawIndex;
8085                        if (childDrawIndex != 0) {
8086                            for (int i = 0; i < numChildrenToIterate; i++) {
8087                                final int otherDrawIndex = (customOrder ?
8088                                        parentGroup.getChildDrawingOrder(childCount, i) : i);
8089                                if (otherDrawIndex < childDrawIndex) {
8090                                    drawingOrderInParent +=
8091                                            numViewsForAccessibility(parentGroup.getChildAt(i));
8092                                }
8093                            }
8094                        }
8095                    }
8096                }
8097            }
8098            viewAtDrawingLevel = (View) currentParent;
8099        }
8100        info.setDrawingOrder(drawingOrderInParent);
8101    }
8102
8103    private static int numViewsForAccessibility(View view) {
8104        if (view != null) {
8105            if (view.includeForAccessibility()) {
8106                return 1;
8107            } else if (view instanceof ViewGroup) {
8108                return ((ViewGroup) view).getNumChildrenForAccessibility();
8109            }
8110        }
8111        return 0;
8112    }
8113
8114    private View findLabelForView(View view, int labeledId) {
8115        if (mMatchLabelForPredicate == null) {
8116            mMatchLabelForPredicate = new MatchLabelForPredicate();
8117        }
8118        mMatchLabelForPredicate.mLabeledId = labeledId;
8119        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
8120    }
8121
8122    /**
8123     * Computes whether this view is visible to the user. Such a view is
8124     * attached, visible, all its predecessors are visible, it is not clipped
8125     * entirely by its predecessors, and has an alpha greater than zero.
8126     *
8127     * @return Whether the view is visible on the screen.
8128     *
8129     * @hide
8130     */
8131    protected boolean isVisibleToUser() {
8132        return isVisibleToUser(null);
8133    }
8134
8135    /**
8136     * Computes whether the given portion of this view is visible to the user.
8137     * Such a view is attached, visible, all its predecessors are visible,
8138     * has an alpha greater than zero, and the specified portion is not
8139     * clipped entirely by its predecessors.
8140     *
8141     * @param boundInView the portion of the view to test; coordinates should be relative; may be
8142     *                    <code>null</code>, and the entire view will be tested in this case.
8143     *                    When <code>true</code> is returned by the function, the actual visible
8144     *                    region will be stored in this parameter; that is, if boundInView is fully
8145     *                    contained within the view, no modification will be made, otherwise regions
8146     *                    outside of the visible area of the view will be clipped.
8147     *
8148     * @return Whether the specified portion of the view is visible on the screen.
8149     *
8150     * @hide
8151     */
8152    protected boolean isVisibleToUser(Rect boundInView) {
8153        if (mAttachInfo != null) {
8154            // Attached to invisible window means this view is not visible.
8155            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
8156                return false;
8157            }
8158            // An invisible predecessor or one with alpha zero means
8159            // that this view is not visible to the user.
8160            Object current = this;
8161            while (current instanceof View) {
8162                View view = (View) current;
8163                // We have attach info so this view is attached and there is no
8164                // need to check whether we reach to ViewRootImpl on the way up.
8165                if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
8166                        view.getVisibility() != VISIBLE) {
8167                    return false;
8168                }
8169                current = view.mParent;
8170            }
8171            // Check if the view is entirely covered by its predecessors.
8172            Rect visibleRect = mAttachInfo.mTmpInvalRect;
8173            Point offset = mAttachInfo.mPoint;
8174            if (!getGlobalVisibleRect(visibleRect, offset)) {
8175                return false;
8176            }
8177            // Check if the visible portion intersects the rectangle of interest.
8178            if (boundInView != null) {
8179                visibleRect.offset(-offset.x, -offset.y);
8180                return boundInView.intersect(visibleRect);
8181            }
8182            return true;
8183        }
8184        return false;
8185    }
8186
8187    /**
8188     * Returns the delegate for implementing accessibility support via
8189     * composition. For more details see {@link AccessibilityDelegate}.
8190     *
8191     * @return The delegate, or null if none set.
8192     *
8193     * @hide
8194     */
8195    public AccessibilityDelegate getAccessibilityDelegate() {
8196        return mAccessibilityDelegate;
8197    }
8198
8199    /**
8200     * Sets a delegate for implementing accessibility support via composition
8201     * (as opposed to inheritance). For more details, see
8202     * {@link AccessibilityDelegate}.
8203     * <p>
8204     * <strong>Note:</strong> On platform versions prior to
8205     * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on
8206     * views in the {@code android.widget.*} package are called <i>before</i>
8207     * host methods. This prevents certain properties such as class name from
8208     * being modified by overriding
8209     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)},
8210     * as any changes will be overwritten by the host class.
8211     * <p>
8212     * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate
8213     * methods are called <i>after</i> host methods, which all properties to be
8214     * modified without being overwritten by the host class.
8215     *
8216     * @param delegate the object to which accessibility method calls should be
8217     *                 delegated
8218     * @see AccessibilityDelegate
8219     */
8220    public void setAccessibilityDelegate(@Nullable AccessibilityDelegate delegate) {
8221        mAccessibilityDelegate = delegate;
8222    }
8223
8224    /**
8225     * Gets the provider for managing a virtual view hierarchy rooted at this View
8226     * and reported to {@link android.accessibilityservice.AccessibilityService}s
8227     * that explore the window content.
8228     * <p>
8229     * If this method returns an instance, this instance is responsible for managing
8230     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
8231     * View including the one representing the View itself. Similarly the returned
8232     * instance is responsible for performing accessibility actions on any virtual
8233     * view or the root view itself.
8234     * </p>
8235     * <p>
8236     * If an {@link AccessibilityDelegate} has been specified via calling
8237     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
8238     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
8239     * is responsible for handling this call.
8240     * </p>
8241     *
8242     * @return The provider.
8243     *
8244     * @see AccessibilityNodeProvider
8245     */
8246    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
8247        if (mAccessibilityDelegate != null) {
8248            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
8249        } else {
8250            return null;
8251        }
8252    }
8253
8254    /**
8255     * Gets the unique identifier of this view on the screen for accessibility purposes.
8256     *
8257     * @return The view accessibility id.
8258     *
8259     * @hide
8260     */
8261    public int getAccessibilityViewId() {
8262        if (mAccessibilityViewId == NO_ID) {
8263            mAccessibilityViewId = mContext.getNextAccessibilityId();
8264        }
8265        return mAccessibilityViewId;
8266    }
8267
8268    /**
8269     * Gets the unique identifier of the window in which this View reseides.
8270     *
8271     * @return The window accessibility id.
8272     *
8273     * @hide
8274     */
8275    public int getAccessibilityWindowId() {
8276        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId
8277                : AccessibilityWindowInfo.UNDEFINED_WINDOW_ID;
8278    }
8279
8280    /**
8281     * Returns the {@link View}'s content description.
8282     * <p>
8283     * <strong>Note:</strong> Do not override this method, as it will have no
8284     * effect on the content description presented to accessibility services.
8285     * You must call {@link #setContentDescription(CharSequence)} to modify the
8286     * content description.
8287     *
8288     * @return the content description
8289     * @see #setContentDescription(CharSequence)
8290     * @attr ref android.R.styleable#View_contentDescription
8291     */
8292    @ViewDebug.ExportedProperty(category = "accessibility")
8293    public CharSequence getContentDescription() {
8294        return mContentDescription;
8295    }
8296
8297    /**
8298     * Sets the {@link View}'s content description.
8299     * <p>
8300     * A content description briefly describes the view and is primarily used
8301     * for accessibility support to determine how a view should be presented to
8302     * the user. In the case of a view with no textual representation, such as
8303     * {@link android.widget.ImageButton}, a useful content description
8304     * explains what the view does. For example, an image button with a phone
8305     * icon that is used to place a call may use "Call" as its content
8306     * description. An image of a floppy disk that is used to save a file may
8307     * use "Save".
8308     *
8309     * @param contentDescription The content description.
8310     * @see #getContentDescription()
8311     * @attr ref android.R.styleable#View_contentDescription
8312     */
8313    @RemotableViewMethod
8314    public void setContentDescription(CharSequence contentDescription) {
8315        if (mContentDescription == null) {
8316            if (contentDescription == null) {
8317                return;
8318            }
8319        } else if (mContentDescription.equals(contentDescription)) {
8320            return;
8321        }
8322        mContentDescription = contentDescription;
8323        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
8324        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
8325            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
8326            notifySubtreeAccessibilityStateChangedIfNeeded();
8327        } else {
8328            notifyViewAccessibilityStateChangedIfNeeded(
8329                    AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
8330        }
8331    }
8332
8333    /**
8334     * Sets the id of a view before which this one is visited in accessibility traversal.
8335     * A screen-reader must visit the content of this view before the content of the one
8336     * it precedes. For example, if view B is set to be before view A, then a screen-reader
8337     * will traverse the entire content of B before traversing the entire content of A,
8338     * regardles of what traversal strategy it is using.
8339     * <p>
8340     * Views that do not have specified before/after relationships are traversed in order
8341     * determined by the screen-reader.
8342     * </p>
8343     * <p>
8344     * Setting that this view is before a view that is not important for accessibility
8345     * or if this view is not important for accessibility will have no effect as the
8346     * screen-reader is not aware of unimportant views.
8347     * </p>
8348     *
8349     * @param beforeId The id of a view this one precedes in accessibility traversal.
8350     *
8351     * @attr ref android.R.styleable#View_accessibilityTraversalBefore
8352     *
8353     * @see #setImportantForAccessibility(int)
8354     */
8355    @RemotableViewMethod
8356    public void setAccessibilityTraversalBefore(int beforeId) {
8357        if (mAccessibilityTraversalBeforeId == beforeId) {
8358            return;
8359        }
8360        mAccessibilityTraversalBeforeId = beforeId;
8361        notifyViewAccessibilityStateChangedIfNeeded(
8362                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
8363    }
8364
8365    /**
8366     * Gets the id of a view before which this one is visited in accessibility traversal.
8367     *
8368     * @return The id of a view this one precedes in accessibility traversal if
8369     *         specified, otherwise {@link #NO_ID}.
8370     *
8371     * @see #setAccessibilityTraversalBefore(int)
8372     */
8373    public int getAccessibilityTraversalBefore() {
8374        return mAccessibilityTraversalBeforeId;
8375    }
8376
8377    /**
8378     * Sets the id of a view after which this one is visited in accessibility traversal.
8379     * A screen-reader must visit the content of the other view before the content of this
8380     * one. For example, if view B is set to be after view A, then a screen-reader
8381     * will traverse the entire content of A before traversing the entire content of B,
8382     * regardles of what traversal strategy it is using.
8383     * <p>
8384     * Views that do not have specified before/after relationships are traversed in order
8385     * determined by the screen-reader.
8386     * </p>
8387     * <p>
8388     * Setting that this view is after a view that is not important for accessibility
8389     * or if this view is not important for accessibility will have no effect as the
8390     * screen-reader is not aware of unimportant views.
8391     * </p>
8392     *
8393     * @param afterId The id of a view this one succedees in accessibility traversal.
8394     *
8395     * @attr ref android.R.styleable#View_accessibilityTraversalAfter
8396     *
8397     * @see #setImportantForAccessibility(int)
8398     */
8399    @RemotableViewMethod
8400    public void setAccessibilityTraversalAfter(int afterId) {
8401        if (mAccessibilityTraversalAfterId == afterId) {
8402            return;
8403        }
8404        mAccessibilityTraversalAfterId = afterId;
8405        notifyViewAccessibilityStateChangedIfNeeded(
8406                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
8407    }
8408
8409    /**
8410     * Gets the id of a view after which this one is visited in accessibility traversal.
8411     *
8412     * @return The id of a view this one succeedes in accessibility traversal if
8413     *         specified, otherwise {@link #NO_ID}.
8414     *
8415     * @see #setAccessibilityTraversalAfter(int)
8416     */
8417    public int getAccessibilityTraversalAfter() {
8418        return mAccessibilityTraversalAfterId;
8419    }
8420
8421    /**
8422     * Gets the id of a view for which this view serves as a label for
8423     * accessibility purposes.
8424     *
8425     * @return The labeled view id.
8426     */
8427    @ViewDebug.ExportedProperty(category = "accessibility")
8428    public int getLabelFor() {
8429        return mLabelForId;
8430    }
8431
8432    /**
8433     * Sets the id of a view for which this view serves as a label for
8434     * accessibility purposes.
8435     *
8436     * @param id The labeled view id.
8437     */
8438    @RemotableViewMethod
8439    public void setLabelFor(@IdRes int id) {
8440        if (mLabelForId == id) {
8441            return;
8442        }
8443        mLabelForId = id;
8444        if (mLabelForId != View.NO_ID
8445                && mID == View.NO_ID) {
8446            mID = generateViewId();
8447        }
8448        notifyViewAccessibilityStateChangedIfNeeded(
8449                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
8450    }
8451
8452    /**
8453     * Invoked whenever this view loses focus, either by losing window focus or by losing
8454     * focus within its window. This method can be used to clear any state tied to the
8455     * focus. For instance, if a button is held pressed with the trackball and the window
8456     * loses focus, this method can be used to cancel the press.
8457     *
8458     * Subclasses of View overriding this method should always call super.onFocusLost().
8459     *
8460     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
8461     * @see #onWindowFocusChanged(boolean)
8462     *
8463     * @hide pending API council approval
8464     */
8465    @CallSuper
8466    protected void onFocusLost() {
8467        resetPressedState();
8468    }
8469
8470    private void resetPressedState() {
8471        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8472            return;
8473        }
8474
8475        if (isPressed()) {
8476            setPressed(false);
8477
8478            if (!mHasPerformedLongPress) {
8479                removeLongPressCallback();
8480            }
8481        }
8482    }
8483
8484    /**
8485     * Returns true if this view has focus
8486     *
8487     * @return True if this view has focus, false otherwise.
8488     */
8489    @ViewDebug.ExportedProperty(category = "focus")
8490    public boolean isFocused() {
8491        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
8492    }
8493
8494    /**
8495     * Find the view in the hierarchy rooted at this view that currently has
8496     * focus.
8497     *
8498     * @return The view that currently has focus, or null if no focused view can
8499     *         be found.
8500     */
8501    public View findFocus() {
8502        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
8503    }
8504
8505    /**
8506     * Indicates whether this view is one of the set of scrollable containers in
8507     * its window.
8508     *
8509     * @return whether this view is one of the set of scrollable containers in
8510     * its window
8511     *
8512     * @attr ref android.R.styleable#View_isScrollContainer
8513     */
8514    public boolean isScrollContainer() {
8515        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
8516    }
8517
8518    /**
8519     * Change whether this view is one of the set of scrollable containers in
8520     * its window.  This will be used to determine whether the window can
8521     * resize or must pan when a soft input area is open -- scrollable
8522     * containers allow the window to use resize mode since the container
8523     * will appropriately shrink.
8524     *
8525     * @attr ref android.R.styleable#View_isScrollContainer
8526     */
8527    public void setScrollContainer(boolean isScrollContainer) {
8528        if (isScrollContainer) {
8529            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
8530                mAttachInfo.mScrollContainers.add(this);
8531                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
8532            }
8533            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
8534        } else {
8535            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
8536                mAttachInfo.mScrollContainers.remove(this);
8537            }
8538            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
8539        }
8540    }
8541
8542    /**
8543     * Returns the quality of the drawing cache.
8544     *
8545     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
8546     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
8547     *
8548     * @see #setDrawingCacheQuality(int)
8549     * @see #setDrawingCacheEnabled(boolean)
8550     * @see #isDrawingCacheEnabled()
8551     *
8552     * @attr ref android.R.styleable#View_drawingCacheQuality
8553     */
8554    @DrawingCacheQuality
8555    public int getDrawingCacheQuality() {
8556        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
8557    }
8558
8559    /**
8560     * Set the drawing cache quality of this view. This value is used only when the
8561     * drawing cache is enabled
8562     *
8563     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
8564     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
8565     *
8566     * @see #getDrawingCacheQuality()
8567     * @see #setDrawingCacheEnabled(boolean)
8568     * @see #isDrawingCacheEnabled()
8569     *
8570     * @attr ref android.R.styleable#View_drawingCacheQuality
8571     */
8572    public void setDrawingCacheQuality(@DrawingCacheQuality int quality) {
8573        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
8574    }
8575
8576    /**
8577     * Returns whether the screen should remain on, corresponding to the current
8578     * value of {@link #KEEP_SCREEN_ON}.
8579     *
8580     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
8581     *
8582     * @see #setKeepScreenOn(boolean)
8583     *
8584     * @attr ref android.R.styleable#View_keepScreenOn
8585     */
8586    public boolean getKeepScreenOn() {
8587        return (mViewFlags & KEEP_SCREEN_ON) != 0;
8588    }
8589
8590    /**
8591     * Controls whether the screen should remain on, modifying the
8592     * value of {@link #KEEP_SCREEN_ON}.
8593     *
8594     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
8595     *
8596     * @see #getKeepScreenOn()
8597     *
8598     * @attr ref android.R.styleable#View_keepScreenOn
8599     */
8600    public void setKeepScreenOn(boolean keepScreenOn) {
8601        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
8602    }
8603
8604    /**
8605     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
8606     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
8607     *
8608     * @attr ref android.R.styleable#View_nextFocusLeft
8609     */
8610    public int getNextFocusLeftId() {
8611        return mNextFocusLeftId;
8612    }
8613
8614    /**
8615     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
8616     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
8617     * decide automatically.
8618     *
8619     * @attr ref android.R.styleable#View_nextFocusLeft
8620     */
8621    public void setNextFocusLeftId(int nextFocusLeftId) {
8622        mNextFocusLeftId = nextFocusLeftId;
8623    }
8624
8625    /**
8626     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
8627     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
8628     *
8629     * @attr ref android.R.styleable#View_nextFocusRight
8630     */
8631    public int getNextFocusRightId() {
8632        return mNextFocusRightId;
8633    }
8634
8635    /**
8636     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
8637     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
8638     * decide automatically.
8639     *
8640     * @attr ref android.R.styleable#View_nextFocusRight
8641     */
8642    public void setNextFocusRightId(int nextFocusRightId) {
8643        mNextFocusRightId = nextFocusRightId;
8644    }
8645
8646    /**
8647     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
8648     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
8649     *
8650     * @attr ref android.R.styleable#View_nextFocusUp
8651     */
8652    public int getNextFocusUpId() {
8653        return mNextFocusUpId;
8654    }
8655
8656    /**
8657     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
8658     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
8659     * decide automatically.
8660     *
8661     * @attr ref android.R.styleable#View_nextFocusUp
8662     */
8663    public void setNextFocusUpId(int nextFocusUpId) {
8664        mNextFocusUpId = nextFocusUpId;
8665    }
8666
8667    /**
8668     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
8669     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
8670     *
8671     * @attr ref android.R.styleable#View_nextFocusDown
8672     */
8673    public int getNextFocusDownId() {
8674        return mNextFocusDownId;
8675    }
8676
8677    /**
8678     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
8679     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
8680     * decide automatically.
8681     *
8682     * @attr ref android.R.styleable#View_nextFocusDown
8683     */
8684    public void setNextFocusDownId(int nextFocusDownId) {
8685        mNextFocusDownId = nextFocusDownId;
8686    }
8687
8688    /**
8689     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
8690     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
8691     *
8692     * @attr ref android.R.styleable#View_nextFocusForward
8693     */
8694    public int getNextFocusForwardId() {
8695        return mNextFocusForwardId;
8696    }
8697
8698    /**
8699     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
8700     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
8701     * decide automatically.
8702     *
8703     * @attr ref android.R.styleable#View_nextFocusForward
8704     */
8705    public void setNextFocusForwardId(int nextFocusForwardId) {
8706        mNextFocusForwardId = nextFocusForwardId;
8707    }
8708
8709    /**
8710     * Gets the id of the root of the next keyboard navigation cluster.
8711     * @return The next keyboard navigation cluster ID, or {@link #NO_ID} if the framework should
8712     * decide automatically.
8713     *
8714     * @attr ref android.R.styleable#View_nextClusterForward
8715     */
8716    public int getNextClusterForwardId() {
8717        return mNextClusterForwardId;
8718    }
8719
8720    /**
8721     * Sets the id of the view to use as the root of the next keyboard navigation cluster.
8722     * @param nextClusterForwardId The next cluster ID, or {@link #NO_ID} if the framework should
8723     * decide automatically.
8724     *
8725     * @attr ref android.R.styleable#View_nextClusterForward
8726     */
8727    public void setNextClusterForwardId(int nextClusterForwardId) {
8728        mNextClusterForwardId = nextClusterForwardId;
8729    }
8730
8731    /**
8732     * Returns the visibility of this view and all of its ancestors
8733     *
8734     * @return True if this view and all of its ancestors are {@link #VISIBLE}
8735     */
8736    public boolean isShown() {
8737        View current = this;
8738        //noinspection ConstantConditions
8739        do {
8740            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
8741                return false;
8742            }
8743            ViewParent parent = current.mParent;
8744            if (parent == null) {
8745                return false; // We are not attached to the view root
8746            }
8747            if (!(parent instanceof View)) {
8748                return true;
8749            }
8750            current = (View) parent;
8751        } while (current != null);
8752
8753        return false;
8754    }
8755
8756    /**
8757     * Called by the view hierarchy when the content insets for a window have
8758     * changed, to allow it to adjust its content to fit within those windows.
8759     * The content insets tell you the space that the status bar, input method,
8760     * and other system windows infringe on the application's window.
8761     *
8762     * <p>You do not normally need to deal with this function, since the default
8763     * window decoration given to applications takes care of applying it to the
8764     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
8765     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
8766     * and your content can be placed under those system elements.  You can then
8767     * use this method within your view hierarchy if you have parts of your UI
8768     * which you would like to ensure are not being covered.
8769     *
8770     * <p>The default implementation of this method simply applies the content
8771     * insets to the view's padding, consuming that content (modifying the
8772     * insets to be 0), and returning true.  This behavior is off by default, but can
8773     * be enabled through {@link #setFitsSystemWindows(boolean)}.
8774     *
8775     * <p>This function's traversal down the hierarchy is depth-first.  The same content
8776     * insets object is propagated down the hierarchy, so any changes made to it will
8777     * be seen by all following views (including potentially ones above in
8778     * the hierarchy since this is a depth-first traversal).  The first view
8779     * that returns true will abort the entire traversal.
8780     *
8781     * <p>The default implementation works well for a situation where it is
8782     * used with a container that covers the entire window, allowing it to
8783     * apply the appropriate insets to its content on all edges.  If you need
8784     * a more complicated layout (such as two different views fitting system
8785     * windows, one on the top of the window, and one on the bottom),
8786     * you can override the method and handle the insets however you would like.
8787     * Note that the insets provided by the framework are always relative to the
8788     * far edges of the window, not accounting for the location of the called view
8789     * within that window.  (In fact when this method is called you do not yet know
8790     * where the layout will place the view, as it is done before layout happens.)
8791     *
8792     * <p>Note: unlike many View methods, there is no dispatch phase to this
8793     * call.  If you are overriding it in a ViewGroup and want to allow the
8794     * call to continue to your children, you must be sure to call the super
8795     * implementation.
8796     *
8797     * <p>Here is a sample layout that makes use of fitting system windows
8798     * to have controls for a video view placed inside of the window decorations
8799     * that it hides and shows.  This can be used with code like the second
8800     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
8801     *
8802     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
8803     *
8804     * @param insets Current content insets of the window.  Prior to
8805     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
8806     * the insets or else you and Android will be unhappy.
8807     *
8808     * @return {@code true} if this view applied the insets and it should not
8809     * continue propagating further down the hierarchy, {@code false} otherwise.
8810     * @see #getFitsSystemWindows()
8811     * @see #setFitsSystemWindows(boolean)
8812     * @see #setSystemUiVisibility(int)
8813     *
8814     * @deprecated As of API 20 use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply
8815     * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use
8816     * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)}
8817     * to implement handling their own insets.
8818     */
8819    @Deprecated
8820    protected boolean fitSystemWindows(Rect insets) {
8821        if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) {
8822            if (insets == null) {
8823                // Null insets by definition have already been consumed.
8824                // This call cannot apply insets since there are none to apply,
8825                // so return false.
8826                return false;
8827            }
8828            // If we're not in the process of dispatching the newer apply insets call,
8829            // that means we're not in the compatibility path. Dispatch into the newer
8830            // apply insets path and take things from there.
8831            try {
8832                mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS;
8833                return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed();
8834            } finally {
8835                mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS;
8836            }
8837        } else {
8838            // We're being called from the newer apply insets path.
8839            // Perform the standard fallback behavior.
8840            return fitSystemWindowsInt(insets);
8841        }
8842    }
8843
8844    private boolean fitSystemWindowsInt(Rect insets) {
8845        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
8846            mUserPaddingStart = UNDEFINED_PADDING;
8847            mUserPaddingEnd = UNDEFINED_PADDING;
8848            Rect localInsets = sThreadLocal.get();
8849            if (localInsets == null) {
8850                localInsets = new Rect();
8851                sThreadLocal.set(localInsets);
8852            }
8853            boolean res = computeFitSystemWindows(insets, localInsets);
8854            mUserPaddingLeftInitial = localInsets.left;
8855            mUserPaddingRightInitial = localInsets.right;
8856            internalSetPadding(localInsets.left, localInsets.top,
8857                    localInsets.right, localInsets.bottom);
8858            return res;
8859        }
8860        return false;
8861    }
8862
8863    /**
8864     * Called when the view should apply {@link WindowInsets} according to its internal policy.
8865     *
8866     * <p>This method should be overridden by views that wish to apply a policy different from or
8867     * in addition to the default behavior. Clients that wish to force a view subtree
8868     * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p>
8869     *
8870     * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set
8871     * it will be called during dispatch instead of this method. The listener may optionally
8872     * call this method from its own implementation if it wishes to apply the view's default
8873     * insets policy in addition to its own.</p>
8874     *
8875     * <p>Implementations of this method should either return the insets parameter unchanged
8876     * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed
8877     * that this view applied itself. This allows new inset types added in future platform
8878     * versions to pass through existing implementations unchanged without being erroneously
8879     * consumed.</p>
8880     *
8881     * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows}
8882     * property is set then the view will consume the system window insets and apply them
8883     * as padding for the view.</p>
8884     *
8885     * @param insets Insets to apply
8886     * @return The supplied insets with any applied insets consumed
8887     */
8888    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
8889        if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) {
8890            // We weren't called from within a direct call to fitSystemWindows,
8891            // call into it as a fallback in case we're in a class that overrides it
8892            // and has logic to perform.
8893            if (fitSystemWindows(insets.getSystemWindowInsets())) {
8894                return insets.consumeSystemWindowInsets();
8895            }
8896        } else {
8897            // We were called from within a direct call to fitSystemWindows.
8898            if (fitSystemWindowsInt(insets.getSystemWindowInsets())) {
8899                return insets.consumeSystemWindowInsets();
8900            }
8901        }
8902        return insets;
8903    }
8904
8905    /**
8906     * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying
8907     * window insets to this view. The listener's
8908     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
8909     * method will be called instead of the view's
8910     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
8911     *
8912     * @param listener Listener to set
8913     *
8914     * @see #onApplyWindowInsets(WindowInsets)
8915     */
8916    public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {
8917        getListenerInfo().mOnApplyWindowInsetsListener = listener;
8918    }
8919
8920    /**
8921     * Request to apply the given window insets to this view or another view in its subtree.
8922     *
8923     * <p>This method should be called by clients wishing to apply insets corresponding to areas
8924     * obscured by window decorations or overlays. This can include the status and navigation bars,
8925     * action bars, input methods and more. New inset categories may be added in the future.
8926     * The method returns the insets provided minus any that were applied by this view or its
8927     * children.</p>
8928     *
8929     * <p>Clients wishing to provide custom behavior should override the
8930     * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a
8931     * {@link OnApplyWindowInsetsListener} via the
8932     * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener}
8933     * method.</p>
8934     *
8935     * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method.
8936     * </p>
8937     *
8938     * @param insets Insets to apply
8939     * @return The provided insets minus the insets that were consumed
8940     */
8941    public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
8942        try {
8943            mPrivateFlags3 |= PFLAG3_APPLYING_INSETS;
8944            if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
8945                return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);
8946            } else {
8947                return onApplyWindowInsets(insets);
8948            }
8949        } finally {
8950            mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS;
8951        }
8952    }
8953
8954    /**
8955     * Compute the view's coordinate within the surface.
8956     *
8957     * <p>Computes the coordinates of this view in its surface. The argument
8958     * must be an array of two integers. After the method returns, the array
8959     * contains the x and y location in that order.</p>
8960     * @hide
8961     * @param location an array of two integers in which to hold the coordinates
8962     */
8963    public void getLocationInSurface(@Size(2) int[] location) {
8964        getLocationInWindow(location);
8965        if (mAttachInfo != null && mAttachInfo.mViewRootImpl != null) {
8966            location[0] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.left;
8967            location[1] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.top;
8968        }
8969    }
8970
8971    /**
8972     * Provide original WindowInsets that are dispatched to the view hierarchy. The insets are
8973     * only available if the view is attached.
8974     *
8975     * @return WindowInsets from the top of the view hierarchy or null if View is detached
8976     */
8977    public WindowInsets getRootWindowInsets() {
8978        if (mAttachInfo != null) {
8979            return mAttachInfo.mViewRootImpl.getWindowInsets(false /* forceConstruct */);
8980        }
8981        return null;
8982    }
8983
8984    /**
8985     * @hide Compute the insets that should be consumed by this view and the ones
8986     * that should propagate to those under it.
8987     */
8988    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
8989        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
8990                || mAttachInfo == null
8991                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
8992                        && !mAttachInfo.mOverscanRequested)) {
8993            outLocalInsets.set(inoutInsets);
8994            inoutInsets.set(0, 0, 0, 0);
8995            return true;
8996        } else {
8997            // The application wants to take care of fitting system window for
8998            // the content...  however we still need to take care of any overscan here.
8999            final Rect overscan = mAttachInfo.mOverscanInsets;
9000            outLocalInsets.set(overscan);
9001            inoutInsets.left -= overscan.left;
9002            inoutInsets.top -= overscan.top;
9003            inoutInsets.right -= overscan.right;
9004            inoutInsets.bottom -= overscan.bottom;
9005            return false;
9006        }
9007    }
9008
9009    /**
9010     * Compute insets that should be consumed by this view and the ones that should propagate
9011     * to those under it.
9012     *
9013     * @param in Insets currently being processed by this View, likely received as a parameter
9014     *           to {@link #onApplyWindowInsets(WindowInsets)}.
9015     * @param outLocalInsets A Rect that will receive the insets that should be consumed
9016     *                       by this view
9017     * @return Insets that should be passed along to views under this one
9018     */
9019    public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) {
9020        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
9021                || mAttachInfo == null
9022                || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
9023            outLocalInsets.set(in.getSystemWindowInsets());
9024            return in.consumeSystemWindowInsets();
9025        } else {
9026            outLocalInsets.set(0, 0, 0, 0);
9027            return in;
9028        }
9029    }
9030
9031    /**
9032     * Sets whether or not this view should account for system screen decorations
9033     * such as the status bar and inset its content; that is, controlling whether
9034     * the default implementation of {@link #fitSystemWindows(Rect)} will be
9035     * executed.  See that method for more details.
9036     *
9037     * <p>Note that if you are providing your own implementation of
9038     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
9039     * flag to true -- your implementation will be overriding the default
9040     * implementation that checks this flag.
9041     *
9042     * @param fitSystemWindows If true, then the default implementation of
9043     * {@link #fitSystemWindows(Rect)} will be executed.
9044     *
9045     * @attr ref android.R.styleable#View_fitsSystemWindows
9046     * @see #getFitsSystemWindows()
9047     * @see #fitSystemWindows(Rect)
9048     * @see #setSystemUiVisibility(int)
9049     */
9050    public void setFitsSystemWindows(boolean fitSystemWindows) {
9051        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
9052    }
9053
9054    /**
9055     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
9056     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
9057     * will be executed.
9058     *
9059     * @return {@code true} if the default implementation of
9060     * {@link #fitSystemWindows(Rect)} will be executed.
9061     *
9062     * @attr ref android.R.styleable#View_fitsSystemWindows
9063     * @see #setFitsSystemWindows(boolean)
9064     * @see #fitSystemWindows(Rect)
9065     * @see #setSystemUiVisibility(int)
9066     */
9067    @ViewDebug.ExportedProperty
9068    public boolean getFitsSystemWindows() {
9069        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
9070    }
9071
9072    /** @hide */
9073    public boolean fitsSystemWindows() {
9074        return getFitsSystemWindows();
9075    }
9076
9077    /**
9078     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
9079     * @deprecated Use {@link #requestApplyInsets()} for newer platform versions.
9080     */
9081    @Deprecated
9082    public void requestFitSystemWindows() {
9083        if (mParent != null) {
9084            mParent.requestFitSystemWindows();
9085        }
9086    }
9087
9088    /**
9089     * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed.
9090     */
9091    public void requestApplyInsets() {
9092        requestFitSystemWindows();
9093    }
9094
9095    /**
9096     * For use by PhoneWindow to make its own system window fitting optional.
9097     * @hide
9098     */
9099    public void makeOptionalFitsSystemWindows() {
9100        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
9101    }
9102
9103    /**
9104     * Returns the outsets, which areas of the device that aren't a surface, but we would like to
9105     * treat them as such.
9106     * @hide
9107     */
9108    public void getOutsets(Rect outOutsetRect) {
9109        if (mAttachInfo != null) {
9110            outOutsetRect.set(mAttachInfo.mOutsets);
9111        } else {
9112            outOutsetRect.setEmpty();
9113        }
9114    }
9115
9116    /**
9117     * Returns the visibility status for this view.
9118     *
9119     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
9120     * @attr ref android.R.styleable#View_visibility
9121     */
9122    @ViewDebug.ExportedProperty(mapping = {
9123        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
9124        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
9125        @ViewDebug.IntToString(from = GONE,      to = "GONE")
9126    })
9127    @Visibility
9128    public int getVisibility() {
9129        return mViewFlags & VISIBILITY_MASK;
9130    }
9131
9132    /**
9133     * Set the visibility state of this view.
9134     *
9135     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
9136     * @attr ref android.R.styleable#View_visibility
9137     */
9138    @RemotableViewMethod
9139    public void setVisibility(@Visibility int visibility) {
9140        setFlags(visibility, VISIBILITY_MASK);
9141    }
9142
9143    /**
9144     * Returns the enabled status for this view. The interpretation of the
9145     * enabled state varies by subclass.
9146     *
9147     * @return True if this view is enabled, false otherwise.
9148     */
9149    @ViewDebug.ExportedProperty
9150    public boolean isEnabled() {
9151        return (mViewFlags & ENABLED_MASK) == ENABLED;
9152    }
9153
9154    /**
9155     * Set the enabled state of this view. The interpretation of the enabled
9156     * state varies by subclass.
9157     *
9158     * @param enabled True if this view is enabled, false otherwise.
9159     */
9160    @RemotableViewMethod
9161    public void setEnabled(boolean enabled) {
9162        if (enabled == isEnabled()) return;
9163
9164        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
9165
9166        /*
9167         * The View most likely has to change its appearance, so refresh
9168         * the drawable state.
9169         */
9170        refreshDrawableState();
9171
9172        // Invalidate too, since the default behavior for views is to be
9173        // be drawn at 50% alpha rather than to change the drawable.
9174        invalidate(true);
9175
9176        if (!enabled) {
9177            cancelPendingInputEvents();
9178        }
9179    }
9180
9181    /**
9182     * Set whether this view can receive the focus.
9183     * <p>
9184     * Setting this to false will also ensure that this view is not focusable
9185     * in touch mode.
9186     *
9187     * @param focusable If true, this view can receive the focus.
9188     *
9189     * @see #setFocusableInTouchMode(boolean)
9190     * @see #setFocusable(int)
9191     * @attr ref android.R.styleable#View_focusable
9192     */
9193    public void setFocusable(boolean focusable) {
9194        setFocusable(focusable ? FOCUSABLE : NOT_FOCUSABLE);
9195    }
9196
9197    /**
9198     * Sets whether this view can receive focus.
9199     * <p>
9200     * Setting this to {@link #FOCUSABLE_AUTO} tells the framework to determine focusability
9201     * automatically based on the view's interactivity. This is the default.
9202     * <p>
9203     * Setting this to NOT_FOCUSABLE will ensure that this view is also not focusable
9204     * in touch mode.
9205     *
9206     * @param focusable One of {@link #NOT_FOCUSABLE}, {@link #FOCUSABLE},
9207     *                  or {@link #FOCUSABLE_AUTO}.
9208     * @see #setFocusableInTouchMode(boolean)
9209     * @attr ref android.R.styleable#View_focusable
9210     */
9211    public void setFocusable(@Focusable int focusable) {
9212        if ((focusable & (FOCUSABLE_AUTO | FOCUSABLE)) == 0) {
9213            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
9214        }
9215        setFlags(focusable, FOCUSABLE_MASK);
9216    }
9217
9218    /**
9219     * Set whether this view can receive focus while in touch mode.
9220     *
9221     * Setting this to true will also ensure that this view is focusable.
9222     *
9223     * @param focusableInTouchMode If true, this view can receive the focus while
9224     *   in touch mode.
9225     *
9226     * @see #setFocusable(boolean)
9227     * @attr ref android.R.styleable#View_focusableInTouchMode
9228     */
9229    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
9230        // Focusable in touch mode should always be set before the focusable flag
9231        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
9232        // which, in touch mode, will not successfully request focus on this view
9233        // because the focusable in touch mode flag is not set
9234        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
9235
9236        // Clear FOCUSABLE_AUTO if set.
9237        if (focusableInTouchMode) {
9238            // Clears FOCUSABLE_AUTO if set.
9239            setFlags(FOCUSABLE, FOCUSABLE_MASK);
9240        }
9241    }
9242
9243    /**
9244     * Sets the hints that helps the autofill service to select the appropriate data to fill the
9245     * view.
9246     *
9247     * @param autofillHints The autofill hints to set. If the array is emtpy, {@code null} is set.
9248     * @attr ref android.R.styleable#View_autofillHints
9249     */
9250    public void setAutofillHints(@Nullable String... autofillHints) {
9251        if (autofillHints == null || autofillHints.length == 0) {
9252            mAutofillHints = null;
9253        } else {
9254            mAutofillHints = autofillHints;
9255        }
9256    }
9257
9258    /**
9259     * @hide
9260     */
9261    @TestApi
9262    public void setAutofilled(boolean isAutofilled) {
9263        boolean wasChanged = isAutofilled != isAutofilled();
9264
9265        if (wasChanged) {
9266            if (isAutofilled) {
9267                mPrivateFlags3 |= PFLAG3_IS_AUTOFILLED;
9268            } else {
9269                mPrivateFlags3 &= ~PFLAG3_IS_AUTOFILLED;
9270            }
9271
9272            invalidate();
9273        }
9274    }
9275
9276    /**
9277     * Set whether this view should have sound effects enabled for events such as
9278     * clicking and touching.
9279     *
9280     * <p>You may wish to disable sound effects for a view if you already play sounds,
9281     * for instance, a dial key that plays dtmf tones.
9282     *
9283     * @param soundEffectsEnabled whether sound effects are enabled for this view.
9284     * @see #isSoundEffectsEnabled()
9285     * @see #playSoundEffect(int)
9286     * @attr ref android.R.styleable#View_soundEffectsEnabled
9287     */
9288    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
9289        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
9290    }
9291
9292    /**
9293     * @return whether this view should have sound effects enabled for events such as
9294     *     clicking and touching.
9295     *
9296     * @see #setSoundEffectsEnabled(boolean)
9297     * @see #playSoundEffect(int)
9298     * @attr ref android.R.styleable#View_soundEffectsEnabled
9299     */
9300    @ViewDebug.ExportedProperty
9301    public boolean isSoundEffectsEnabled() {
9302        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
9303    }
9304
9305    /**
9306     * Set whether this view should have haptic feedback for events such as
9307     * long presses.
9308     *
9309     * <p>You may wish to disable haptic feedback if your view already controls
9310     * its own haptic feedback.
9311     *
9312     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
9313     * @see #isHapticFeedbackEnabled()
9314     * @see #performHapticFeedback(int)
9315     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
9316     */
9317    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
9318        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
9319    }
9320
9321    /**
9322     * @return whether this view should have haptic feedback enabled for events
9323     * long presses.
9324     *
9325     * @see #setHapticFeedbackEnabled(boolean)
9326     * @see #performHapticFeedback(int)
9327     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
9328     */
9329    @ViewDebug.ExportedProperty
9330    public boolean isHapticFeedbackEnabled() {
9331        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
9332    }
9333
9334    /**
9335     * Returns the layout direction for this view.
9336     *
9337     * @return One of {@link #LAYOUT_DIRECTION_LTR},
9338     *   {@link #LAYOUT_DIRECTION_RTL},
9339     *   {@link #LAYOUT_DIRECTION_INHERIT} or
9340     *   {@link #LAYOUT_DIRECTION_LOCALE}.
9341     *
9342     * @attr ref android.R.styleable#View_layoutDirection
9343     *
9344     * @hide
9345     */
9346    @ViewDebug.ExportedProperty(category = "layout", mapping = {
9347        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
9348        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
9349        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
9350        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
9351    })
9352    @LayoutDir
9353    public int getRawLayoutDirection() {
9354        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
9355    }
9356
9357    /**
9358     * Set the layout direction for this view. This will propagate a reset of layout direction
9359     * resolution to the view's children and resolve layout direction for this view.
9360     *
9361     * @param layoutDirection the layout direction to set. Should be one of:
9362     *
9363     * {@link #LAYOUT_DIRECTION_LTR},
9364     * {@link #LAYOUT_DIRECTION_RTL},
9365     * {@link #LAYOUT_DIRECTION_INHERIT},
9366     * {@link #LAYOUT_DIRECTION_LOCALE}.
9367     *
9368     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
9369     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
9370     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
9371     *
9372     * @attr ref android.R.styleable#View_layoutDirection
9373     */
9374    @RemotableViewMethod
9375    public void setLayoutDirection(@LayoutDir int layoutDirection) {
9376        if (getRawLayoutDirection() != layoutDirection) {
9377            // Reset the current layout direction and the resolved one
9378            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
9379            resetRtlProperties();
9380            // Set the new layout direction (filtered)
9381            mPrivateFlags2 |=
9382                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
9383            // We need to resolve all RTL properties as they all depend on layout direction
9384            resolveRtlPropertiesIfNeeded();
9385            requestLayout();
9386            invalidate(true);
9387        }
9388    }
9389
9390    /**
9391     * Returns the resolved layout direction for this view.
9392     *
9393     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
9394     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
9395     *
9396     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
9397     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
9398     *
9399     * @attr ref android.R.styleable#View_layoutDirection
9400     */
9401    @ViewDebug.ExportedProperty(category = "layout", mapping = {
9402        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
9403        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
9404    })
9405    @ResolvedLayoutDir
9406    public int getLayoutDirection() {
9407        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
9408        if (targetSdkVersion < Build.VERSION_CODES.JELLY_BEAN_MR1) {
9409            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
9410            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
9411        }
9412        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
9413                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
9414    }
9415
9416    /**
9417     * Indicates whether or not this view's layout is right-to-left. This is resolved from
9418     * layout attribute and/or the inherited value from the parent
9419     *
9420     * @return true if the layout is right-to-left.
9421     *
9422     * @hide
9423     */
9424    @ViewDebug.ExportedProperty(category = "layout")
9425    public boolean isLayoutRtl() {
9426        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
9427    }
9428
9429    /**
9430     * Indicates whether the view is currently tracking transient state that the
9431     * app should not need to concern itself with saving and restoring, but that
9432     * the framework should take special note to preserve when possible.
9433     *
9434     * <p>A view with transient state cannot be trivially rebound from an external
9435     * data source, such as an adapter binding item views in a list. This may be
9436     * because the view is performing an animation, tracking user selection
9437     * of content, or similar.</p>
9438     *
9439     * @return true if the view has transient state
9440     */
9441    @ViewDebug.ExportedProperty(category = "layout")
9442    public boolean hasTransientState() {
9443        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
9444    }
9445
9446    /**
9447     * Set whether this view is currently tracking transient state that the
9448     * framework should attempt to preserve when possible. This flag is reference counted,
9449     * so every call to setHasTransientState(true) should be paired with a later call
9450     * to setHasTransientState(false).
9451     *
9452     * <p>A view with transient state cannot be trivially rebound from an external
9453     * data source, such as an adapter binding item views in a list. This may be
9454     * because the view is performing an animation, tracking user selection
9455     * of content, or similar.</p>
9456     *
9457     * @param hasTransientState true if this view has transient state
9458     */
9459    public void setHasTransientState(boolean hasTransientState) {
9460        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
9461                mTransientStateCount - 1;
9462        if (mTransientStateCount < 0) {
9463            mTransientStateCount = 0;
9464            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
9465                    "unmatched pair of setHasTransientState calls");
9466        } else if ((hasTransientState && mTransientStateCount == 1) ||
9467                (!hasTransientState && mTransientStateCount == 0)) {
9468            // update flag if we've just incremented up from 0 or decremented down to 0
9469            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
9470                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
9471            if (mParent != null) {
9472                try {
9473                    mParent.childHasTransientStateChanged(this, hasTransientState);
9474                } catch (AbstractMethodError e) {
9475                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
9476                            " does not fully implement ViewParent", e);
9477                }
9478            }
9479        }
9480    }
9481
9482    /**
9483     * Returns true if this view is currently attached to a window.
9484     */
9485    public boolean isAttachedToWindow() {
9486        return mAttachInfo != null;
9487    }
9488
9489    /**
9490     * Returns true if this view has been through at least one layout since it
9491     * was last attached to or detached from a window.
9492     */
9493    public boolean isLaidOut() {
9494        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
9495    }
9496
9497    /**
9498     * If this view doesn't do any drawing on its own, set this flag to
9499     * allow further optimizations. By default, this flag is not set on
9500     * View, but could be set on some View subclasses such as ViewGroup.
9501     *
9502     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
9503     * you should clear this flag.
9504     *
9505     * @param willNotDraw whether or not this View draw on its own
9506     */
9507    public void setWillNotDraw(boolean willNotDraw) {
9508        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
9509    }
9510
9511    /**
9512     * Returns whether or not this View draws on its own.
9513     *
9514     * @return true if this view has nothing to draw, false otherwise
9515     */
9516    @ViewDebug.ExportedProperty(category = "drawing")
9517    public boolean willNotDraw() {
9518        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
9519    }
9520
9521    /**
9522     * When a View's drawing cache is enabled, drawing is redirected to an
9523     * offscreen bitmap. Some views, like an ImageView, must be able to
9524     * bypass this mechanism if they already draw a single bitmap, to avoid
9525     * unnecessary usage of the memory.
9526     *
9527     * @param willNotCacheDrawing true if this view does not cache its
9528     *        drawing, false otherwise
9529     */
9530    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
9531        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
9532    }
9533
9534    /**
9535     * Returns whether or not this View can cache its drawing or not.
9536     *
9537     * @return true if this view does not cache its drawing, false otherwise
9538     */
9539    @ViewDebug.ExportedProperty(category = "drawing")
9540    public boolean willNotCacheDrawing() {
9541        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
9542    }
9543
9544    /**
9545     * Indicates whether this view reacts to click events or not.
9546     *
9547     * @return true if the view is clickable, false otherwise
9548     *
9549     * @see #setClickable(boolean)
9550     * @attr ref android.R.styleable#View_clickable
9551     */
9552    @ViewDebug.ExportedProperty
9553    public boolean isClickable() {
9554        return (mViewFlags & CLICKABLE) == CLICKABLE;
9555    }
9556
9557    /**
9558     * Enables or disables click events for this view. When a view
9559     * is clickable it will change its state to "pressed" on every click.
9560     * Subclasses should set the view clickable to visually react to
9561     * user's clicks.
9562     *
9563     * @param clickable true to make the view clickable, false otherwise
9564     *
9565     * @see #isClickable()
9566     * @attr ref android.R.styleable#View_clickable
9567     */
9568    public void setClickable(boolean clickable) {
9569        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
9570    }
9571
9572    /**
9573     * Indicates whether this view reacts to long click events or not.
9574     *
9575     * @return true if the view is long clickable, false otherwise
9576     *
9577     * @see #setLongClickable(boolean)
9578     * @attr ref android.R.styleable#View_longClickable
9579     */
9580    public boolean isLongClickable() {
9581        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
9582    }
9583
9584    /**
9585     * Enables or disables long click events for this view. When a view is long
9586     * clickable it reacts to the user holding down the button for a longer
9587     * duration than a tap. This event can either launch the listener or a
9588     * context menu.
9589     *
9590     * @param longClickable true to make the view long clickable, false otherwise
9591     * @see #isLongClickable()
9592     * @attr ref android.R.styleable#View_longClickable
9593     */
9594    public void setLongClickable(boolean longClickable) {
9595        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
9596    }
9597
9598    /**
9599     * Indicates whether this view reacts to context clicks or not.
9600     *
9601     * @return true if the view is context clickable, false otherwise
9602     * @see #setContextClickable(boolean)
9603     * @attr ref android.R.styleable#View_contextClickable
9604     */
9605    public boolean isContextClickable() {
9606        return (mViewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
9607    }
9608
9609    /**
9610     * Enables or disables context clicking for this view. This event can launch the listener.
9611     *
9612     * @param contextClickable true to make the view react to a context click, false otherwise
9613     * @see #isContextClickable()
9614     * @attr ref android.R.styleable#View_contextClickable
9615     */
9616    public void setContextClickable(boolean contextClickable) {
9617        setFlags(contextClickable ? CONTEXT_CLICKABLE : 0, CONTEXT_CLICKABLE);
9618    }
9619
9620    /**
9621     * Sets the pressed state for this view and provides a touch coordinate for
9622     * animation hinting.
9623     *
9624     * @param pressed Pass true to set the View's internal state to "pressed",
9625     *            or false to reverts the View's internal state from a
9626     *            previously set "pressed" state.
9627     * @param x The x coordinate of the touch that caused the press
9628     * @param y The y coordinate of the touch that caused the press
9629     */
9630    private void setPressed(boolean pressed, float x, float y) {
9631        if (pressed) {
9632            drawableHotspotChanged(x, y);
9633        }
9634
9635        setPressed(pressed);
9636    }
9637
9638    /**
9639     * Sets the pressed state for this view.
9640     *
9641     * @see #isClickable()
9642     * @see #setClickable(boolean)
9643     *
9644     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
9645     *        the View's internal state from a previously set "pressed" state.
9646     */
9647    public void setPressed(boolean pressed) {
9648        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
9649
9650        if (pressed) {
9651            mPrivateFlags |= PFLAG_PRESSED;
9652        } else {
9653            mPrivateFlags &= ~PFLAG_PRESSED;
9654        }
9655
9656        if (needsRefresh) {
9657            refreshDrawableState();
9658        }
9659        dispatchSetPressed(pressed);
9660    }
9661
9662    /**
9663     * Dispatch setPressed to all of this View's children.
9664     *
9665     * @see #setPressed(boolean)
9666     *
9667     * @param pressed The new pressed state
9668     */
9669    protected void dispatchSetPressed(boolean pressed) {
9670    }
9671
9672    /**
9673     * Indicates whether the view is currently in pressed state. Unless
9674     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
9675     * the pressed state.
9676     *
9677     * @see #setPressed(boolean)
9678     * @see #isClickable()
9679     * @see #setClickable(boolean)
9680     *
9681     * @return true if the view is currently pressed, false otherwise
9682     */
9683    @ViewDebug.ExportedProperty
9684    public boolean isPressed() {
9685        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
9686    }
9687
9688    /**
9689     * @hide
9690     * Indicates whether this view will participate in data collection through
9691     * {@link ViewStructure}.  If true, it will not provide any data
9692     * for itself or its children.  If false, the normal data collection will be allowed.
9693     *
9694     * @return Returns false if assist data collection is not blocked, else true.
9695     *
9696     * @see #setAssistBlocked(boolean)
9697     * @attr ref android.R.styleable#View_assistBlocked
9698     */
9699    public boolean isAssistBlocked() {
9700        return (mPrivateFlags3 & PFLAG3_ASSIST_BLOCKED) != 0;
9701    }
9702
9703    /**
9704     * @hide
9705     * Controls whether assist data collection from this view and its children is enabled
9706     * (that is, whether {@link #onProvideStructure} and
9707     * {@link #onProvideVirtualStructure} will be called).  The default value is false,
9708     * allowing normal assist collection.  Setting this to false will disable assist collection.
9709     *
9710     * @param enabled Set to true to <em>disable</em> assist data collection, or false
9711     * (the default) to allow it.
9712     *
9713     * @see #isAssistBlocked()
9714     * @see #onProvideStructure
9715     * @see #onProvideVirtualStructure
9716     * @attr ref android.R.styleable#View_assistBlocked
9717     */
9718    public void setAssistBlocked(boolean enabled) {
9719        if (enabled) {
9720            mPrivateFlags3 |= PFLAG3_ASSIST_BLOCKED;
9721        } else {
9722            mPrivateFlags3 &= ~PFLAG3_ASSIST_BLOCKED;
9723        }
9724    }
9725
9726    /**
9727     * Indicates whether this view will save its state (that is,
9728     * whether its {@link #onSaveInstanceState} method will be called).
9729     *
9730     * @return Returns true if the view state saving is enabled, else false.
9731     *
9732     * @see #setSaveEnabled(boolean)
9733     * @attr ref android.R.styleable#View_saveEnabled
9734     */
9735    public boolean isSaveEnabled() {
9736        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
9737    }
9738
9739    /**
9740     * Controls whether the saving of this view's state is
9741     * enabled (that is, whether its {@link #onSaveInstanceState} method
9742     * will be called).  Note that even if freezing is enabled, the
9743     * view still must have an id assigned to it (via {@link #setId(int)})
9744     * for its state to be saved.  This flag can only disable the
9745     * saving of this view; any child views may still have their state saved.
9746     *
9747     * @param enabled Set to false to <em>disable</em> state saving, or true
9748     * (the default) to allow it.
9749     *
9750     * @see #isSaveEnabled()
9751     * @see #setId(int)
9752     * @see #onSaveInstanceState()
9753     * @attr ref android.R.styleable#View_saveEnabled
9754     */
9755    public void setSaveEnabled(boolean enabled) {
9756        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
9757    }
9758
9759    /**
9760     * Gets whether the framework should discard touches when the view's
9761     * window is obscured by another visible window.
9762     * Refer to the {@link View} security documentation for more details.
9763     *
9764     * @return True if touch filtering is enabled.
9765     *
9766     * @see #setFilterTouchesWhenObscured(boolean)
9767     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
9768     */
9769    @ViewDebug.ExportedProperty
9770    public boolean getFilterTouchesWhenObscured() {
9771        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
9772    }
9773
9774    /**
9775     * Sets whether the framework should discard touches when the view's
9776     * window is obscured by another visible window.
9777     * Refer to the {@link View} security documentation for more details.
9778     *
9779     * @param enabled True if touch filtering should be enabled.
9780     *
9781     * @see #getFilterTouchesWhenObscured
9782     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
9783     */
9784    public void setFilterTouchesWhenObscured(boolean enabled) {
9785        setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0,
9786                FILTER_TOUCHES_WHEN_OBSCURED);
9787    }
9788
9789    /**
9790     * Indicates whether the entire hierarchy under this view will save its
9791     * state when a state saving traversal occurs from its parent.  The default
9792     * is true; if false, these views will not be saved unless
9793     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
9794     *
9795     * @return Returns true if the view state saving from parent is enabled, else false.
9796     *
9797     * @see #setSaveFromParentEnabled(boolean)
9798     */
9799    public boolean isSaveFromParentEnabled() {
9800        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
9801    }
9802
9803    /**
9804     * Controls whether the entire hierarchy under this view will save its
9805     * state when a state saving traversal occurs from its parent.  The default
9806     * is true; if false, these views will not be saved unless
9807     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
9808     *
9809     * @param enabled Set to false to <em>disable</em> state saving, or true
9810     * (the default) to allow it.
9811     *
9812     * @see #isSaveFromParentEnabled()
9813     * @see #setId(int)
9814     * @see #onSaveInstanceState()
9815     */
9816    public void setSaveFromParentEnabled(boolean enabled) {
9817        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
9818    }
9819
9820
9821    /**
9822     * Returns whether this View is currently able to take focus.
9823     *
9824     * @return True if this view can take focus, or false otherwise.
9825     */
9826    @ViewDebug.ExportedProperty(category = "focus")
9827    public final boolean isFocusable() {
9828        return FOCUSABLE == (mViewFlags & FOCUSABLE);
9829    }
9830
9831    /**
9832     * Returns the focusable setting for this view.
9833     *
9834     * @return One of {@link #NOT_FOCUSABLE}, {@link #FOCUSABLE}, or {@link #FOCUSABLE_AUTO}.
9835     * @attr ref android.R.styleable#View_focusable
9836     */
9837    @ViewDebug.ExportedProperty(mapping = {
9838            @ViewDebug.IntToString(from = NOT_FOCUSABLE, to = "NOT_FOCUSABLE"),
9839            @ViewDebug.IntToString(from = FOCUSABLE, to = "FOCUSABLE"),
9840            @ViewDebug.IntToString(from = FOCUSABLE_AUTO, to = "FOCUSABLE_AUTO")
9841            }, category = "focus")
9842    @Focusable
9843    public int getFocusable() {
9844        return (mViewFlags & FOCUSABLE_AUTO) > 0 ? FOCUSABLE_AUTO : mViewFlags & FOCUSABLE;
9845    }
9846
9847    /**
9848     * When a view is focusable, it may not want to take focus when in touch mode.
9849     * For example, a button would like focus when the user is navigating via a D-pad
9850     * so that the user can click on it, but once the user starts touching the screen,
9851     * the button shouldn't take focus
9852     * @return Whether the view is focusable in touch mode.
9853     * @attr ref android.R.styleable#View_focusableInTouchMode
9854     */
9855    @ViewDebug.ExportedProperty(category = "focus")
9856    public final boolean isFocusableInTouchMode() {
9857        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
9858    }
9859
9860    /**
9861     * Find the nearest view in the specified direction that can take focus.
9862     * This does not actually give focus to that view.
9863     *
9864     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
9865     *
9866     * @return The nearest focusable in the specified direction, or null if none
9867     *         can be found.
9868     */
9869    public View focusSearch(@FocusRealDirection int direction) {
9870        if (mParent != null) {
9871            return mParent.focusSearch(this, direction);
9872        } else {
9873            return null;
9874        }
9875    }
9876
9877    /**
9878     * Returns whether this View is a root of a keyboard navigation cluster.
9879     *
9880     * @return True if this view is a root of a cluster, or false otherwise.
9881     * @attr ref android.R.styleable#View_keyboardNavigationCluster
9882     */
9883    @ViewDebug.ExportedProperty(category = "focus")
9884    public final boolean isKeyboardNavigationCluster() {
9885        return (mPrivateFlags3 & PFLAG3_CLUSTER) != 0;
9886    }
9887
9888    /**
9889     * Searches up the view hierarchy to find the top-most cluster. All deeper/nested clusters
9890     * will be ignored.
9891     *
9892     * @return the keyboard navigation cluster that this view is in (can be this view)
9893     *         or {@code null} if not in one
9894     */
9895    View findKeyboardNavigationCluster() {
9896        if (mParent instanceof View) {
9897            View cluster = ((View) mParent).findKeyboardNavigationCluster();
9898            if (cluster != null) {
9899                return cluster;
9900            } else if (isKeyboardNavigationCluster()) {
9901                return this;
9902            }
9903        }
9904        return null;
9905    }
9906
9907    /**
9908     * Set whether this view is a root of a keyboard navigation cluster.
9909     *
9910     * @param isCluster If true, this view is a root of a cluster.
9911     *
9912     * @attr ref android.R.styleable#View_keyboardNavigationCluster
9913     */
9914    public void setKeyboardNavigationCluster(boolean isCluster) {
9915        if (isCluster) {
9916            mPrivateFlags3 |= PFLAG3_CLUSTER;
9917        } else {
9918            mPrivateFlags3 &= ~PFLAG3_CLUSTER;
9919        }
9920    }
9921
9922    /**
9923     * Sets this View as the one which receives focus the next time cluster navigation jumps
9924     * to the cluster containing this View. This does NOT change focus even if the cluster
9925     * containing this view is current.
9926     *
9927     * @hide
9928     */
9929    public final void setFocusedInCluster() {
9930        setFocusedInCluster(findKeyboardNavigationCluster());
9931    }
9932
9933    private void setFocusedInCluster(View cluster) {
9934        if (this instanceof ViewGroup) {
9935            ((ViewGroup) this).mFocusedInCluster = null;
9936        }
9937        if (cluster == this) {
9938            return;
9939        }
9940        ViewParent parent = mParent;
9941        View child = this;
9942        while (parent instanceof ViewGroup) {
9943            ((ViewGroup) parent).mFocusedInCluster = child;
9944            if (parent == cluster) {
9945                break;
9946            }
9947            child = (View) parent;
9948            parent = parent.getParent();
9949        }
9950    }
9951
9952    private void updateFocusedInCluster(View oldFocus, @FocusDirection int direction) {
9953        if (oldFocus != null) {
9954            View oldCluster = oldFocus.findKeyboardNavigationCluster();
9955            View cluster = findKeyboardNavigationCluster();
9956            if (oldCluster != cluster) {
9957                // Going from one cluster to another, so save last-focused.
9958                // This covers cluster jumps because they are always FOCUS_DOWN
9959                oldFocus.setFocusedInCluster(oldCluster);
9960                if (!(oldFocus.mParent instanceof ViewGroup)) {
9961                    return;
9962                }
9963                if (direction == FOCUS_FORWARD || direction == FOCUS_BACKWARD) {
9964                    // This is a result of ordered navigation so consider navigation through
9965                    // the previous cluster "complete" and clear its last-focused memory.
9966                    ((ViewGroup) oldFocus.mParent).clearFocusedInCluster(oldFocus);
9967                } else if (oldFocus instanceof ViewGroup
9968                        && ((ViewGroup) oldFocus).getDescendantFocusability()
9969                                == ViewGroup.FOCUS_AFTER_DESCENDANTS
9970                        && ViewRootImpl.isViewDescendantOf(this, oldFocus)) {
9971                    // This means oldFocus is not focusable since it obviously has a focusable
9972                    // child (this). Don't restore focus to it in the future.
9973                    ((ViewGroup) oldFocus.mParent).clearFocusedInCluster(oldFocus);
9974                }
9975            }
9976        }
9977    }
9978
9979    /**
9980     * Returns whether this View should receive focus when the focus is restored for the view
9981     * hierarchy containing this view.
9982     * <p>
9983     * Focus gets restored for a view hierarchy when the root of the hierarchy gets added to a
9984     * window or serves as a target of cluster navigation.
9985     *
9986     * @see #restoreDefaultFocus()
9987     *
9988     * @return {@code true} if this view is the default-focus view, {@code false} otherwise
9989     * @attr ref android.R.styleable#View_focusedByDefault
9990     */
9991    @ViewDebug.ExportedProperty(category = "focus")
9992    public final boolean isFocusedByDefault() {
9993        return (mPrivateFlags3 & PFLAG3_FOCUSED_BY_DEFAULT) != 0;
9994    }
9995
9996    /**
9997     * Sets whether this View should receive focus when the focus is restored for the view
9998     * hierarchy containing this view.
9999     * <p>
10000     * Focus gets restored for a view hierarchy when the root of the hierarchy gets added to a
10001     * window or serves as a target of cluster navigation.
10002     *
10003     * @param isFocusedByDefault {@code true} to set this view as the default-focus view,
10004     *                           {@code false} otherwise.
10005     *
10006     * @see #restoreDefaultFocus()
10007     *
10008     * @attr ref android.R.styleable#View_focusedByDefault
10009     */
10010    public void setFocusedByDefault(boolean isFocusedByDefault) {
10011        if (isFocusedByDefault == ((mPrivateFlags3 & PFLAG3_FOCUSED_BY_DEFAULT) != 0)) {
10012            return;
10013        }
10014
10015        if (isFocusedByDefault) {
10016            mPrivateFlags3 |= PFLAG3_FOCUSED_BY_DEFAULT;
10017        } else {
10018            mPrivateFlags3 &= ~PFLAG3_FOCUSED_BY_DEFAULT;
10019        }
10020
10021        if (mParent instanceof ViewGroup) {
10022            if (isFocusedByDefault) {
10023                ((ViewGroup) mParent).setDefaultFocus(this);
10024            } else {
10025                ((ViewGroup) mParent).clearDefaultFocus(this);
10026            }
10027        }
10028    }
10029
10030    /**
10031     * Returns whether the view hierarchy with this view as a root contain a default-focus view.
10032     *
10033     * @return {@code true} if this view has default focus, {@code false} otherwise
10034     */
10035    boolean hasDefaultFocus() {
10036        return isFocusedByDefault();
10037    }
10038
10039    /**
10040     * Find the nearest keyboard navigation cluster in the specified direction.
10041     * This does not actually give focus to that cluster.
10042     *
10043     * @param currentCluster The starting point of the search. Null means the current cluster is not
10044     *                       found yet
10045     * @param direction Direction to look
10046     *
10047     * @return The nearest keyboard navigation cluster in the specified direction, or null if none
10048     *         can be found
10049     */
10050    public View keyboardNavigationClusterSearch(View currentCluster,
10051            @FocusDirection int direction) {
10052        if (isKeyboardNavigationCluster()) {
10053            currentCluster = this;
10054        }
10055        if (isRootNamespace()) {
10056            // Root namespace means we should consider ourselves the top of the
10057            // tree for group searching; otherwise we could be group searching
10058            // into other tabs.  see LocalActivityManager and TabHost for more info.
10059            return FocusFinder.getInstance().findNextKeyboardNavigationCluster(
10060                    this, currentCluster, direction);
10061        } else if (mParent != null) {
10062            return mParent.keyboardNavigationClusterSearch(currentCluster, direction);
10063        }
10064        return null;
10065    }
10066
10067    /**
10068     * This method is the last chance for the focused view and its ancestors to
10069     * respond to an arrow key. This is called when the focused view did not
10070     * consume the key internally, nor could the view system find a new view in
10071     * the requested direction to give focus to.
10072     *
10073     * @param focused The currently focused view.
10074     * @param direction The direction focus wants to move. One of FOCUS_UP,
10075     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
10076     * @return True if the this view consumed this unhandled move.
10077     */
10078    public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) {
10079        return false;
10080    }
10081
10082    /**
10083     * Sets whether this View should use a default focus highlight when it gets focused but doesn't
10084     * have {@link android.R.attr#state_focused} defined in its background.
10085     *
10086     * @param defaultFocusHighlightEnabled {@code true} to set this view to use a default focus
10087     *                                      highlight, {@code false} otherwise.
10088     *
10089     * @attr ref android.R.styleable#View_defaultFocusHighlightEnabled
10090     */
10091    public void setDefaultFocusHighlightEnabled(boolean defaultFocusHighlightEnabled) {
10092        mDefaultFocusHighlightEnabled = defaultFocusHighlightEnabled;
10093    }
10094
10095    /**
10096
10097    /**
10098     * Returns whether this View should use a default focus highlight when it gets focused but
10099     * doesn't have {@link android.R.attr#state_focused} defined in its background.
10100     *
10101     * @return True if this View should use a default focus highlight.
10102     * @attr ref android.R.styleable#View_defaultFocusHighlightEnabled
10103     */
10104    @ViewDebug.ExportedProperty(category = "focus")
10105    public final boolean getDefaultFocusHighlightEnabled() {
10106        return mDefaultFocusHighlightEnabled;
10107    }
10108
10109    /**
10110     * If a user manually specified the next view id for a particular direction,
10111     * use the root to look up the view.
10112     * @param root The root view of the hierarchy containing this view.
10113     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
10114     * or FOCUS_BACKWARD.
10115     * @return The user specified next view, or null if there is none.
10116     */
10117    View findUserSetNextFocus(View root, @FocusDirection int direction) {
10118        switch (direction) {
10119            case FOCUS_LEFT:
10120                if (mNextFocusLeftId == View.NO_ID) return null;
10121                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
10122            case FOCUS_RIGHT:
10123                if (mNextFocusRightId == View.NO_ID) return null;
10124                return findViewInsideOutShouldExist(root, mNextFocusRightId);
10125            case FOCUS_UP:
10126                if (mNextFocusUpId == View.NO_ID) return null;
10127                return findViewInsideOutShouldExist(root, mNextFocusUpId);
10128            case FOCUS_DOWN:
10129                if (mNextFocusDownId == View.NO_ID) return null;
10130                return findViewInsideOutShouldExist(root, mNextFocusDownId);
10131            case FOCUS_FORWARD:
10132                if (mNextFocusForwardId == View.NO_ID) return null;
10133                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
10134            case FOCUS_BACKWARD: {
10135                if (mID == View.NO_ID) return null;
10136                final int id = mID;
10137                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
10138                    @Override
10139                    public boolean test(View t) {
10140                        return t.mNextFocusForwardId == id;
10141                    }
10142                });
10143            }
10144        }
10145        return null;
10146    }
10147
10148    /**
10149     * If a user manually specified the next keyboard-navigation cluster for a particular direction,
10150     * use the root to look up the view.
10151     *
10152     * @param root the root view of the hierarchy containing this view
10153     * @param direction {@link #FOCUS_FORWARD} or {@link #FOCUS_BACKWARD}
10154     * @return the user-specified next cluster, or {@code null} if there is none
10155     */
10156    View findUserSetNextKeyboardNavigationCluster(View root, @FocusDirection int direction) {
10157        switch (direction) {
10158            case FOCUS_FORWARD:
10159                if (mNextClusterForwardId == View.NO_ID) return null;
10160                return findViewInsideOutShouldExist(root, mNextClusterForwardId);
10161            case FOCUS_BACKWARD: {
10162                if (mID == View.NO_ID) return null;
10163                final int id = mID;
10164                return root.findViewByPredicateInsideOut(this,
10165                        (Predicate<View>) t -> t.mNextClusterForwardId == id);
10166            }
10167        }
10168        return null;
10169    }
10170
10171    private View findViewInsideOutShouldExist(View root, int id) {
10172        if (mMatchIdPredicate == null) {
10173            mMatchIdPredicate = new MatchIdPredicate();
10174        }
10175        mMatchIdPredicate.mId = id;
10176        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
10177        if (result == null) {
10178            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
10179        }
10180        return result;
10181    }
10182
10183    /**
10184     * Find and return all focusable views that are descendants of this view,
10185     * possibly including this view if it is focusable itself.
10186     *
10187     * @param direction The direction of the focus
10188     * @return A list of focusable views
10189     */
10190    public ArrayList<View> getFocusables(@FocusDirection int direction) {
10191        ArrayList<View> result = new ArrayList<View>(24);
10192        addFocusables(result, direction);
10193        return result;
10194    }
10195
10196    /**
10197     * Add any focusable views that are descendants of this view (possibly
10198     * including this view if it is focusable itself) to views.  If we are in touch mode,
10199     * only add views that are also focusable in touch mode.
10200     *
10201     * @param views Focusable views found so far
10202     * @param direction The direction of the focus
10203     */
10204    public void addFocusables(ArrayList<View> views, @FocusDirection int direction) {
10205        addFocusables(views, direction, isInTouchMode() ? FOCUSABLES_TOUCH_MODE : FOCUSABLES_ALL);
10206    }
10207
10208    /**
10209     * Adds any focusable views that are descendants of this view (possibly
10210     * including this view if it is focusable itself) to views. This method
10211     * adds all focusable views regardless if we are in touch mode or
10212     * only views focusable in touch mode if we are in touch mode or
10213     * only views that can take accessibility focus if accessibility is enabled
10214     * depending on the focusable mode parameter.
10215     *
10216     * @param views Focusable views found so far or null if all we are interested is
10217     *        the number of focusables.
10218     * @param direction The direction of the focus.
10219     * @param focusableMode The type of focusables to be added.
10220     *
10221     * @see #FOCUSABLES_ALL
10222     * @see #FOCUSABLES_TOUCH_MODE
10223     */
10224    public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
10225            @FocusableMode int focusableMode) {
10226        if (views == null) {
10227            return;
10228        }
10229        if (!isFocusable()) {
10230            return;
10231        }
10232        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
10233                && !isFocusableInTouchMode()) {
10234            return;
10235        }
10236        views.add(this);
10237    }
10238
10239    /**
10240     * Adds any keyboard navigation cluster roots that are descendants of this view (possibly
10241     * including this view if it is a cluster root itself) to views.
10242     *
10243     * @param views Keyboard navigation cluster roots found so far
10244     * @param direction Direction to look
10245     */
10246    public void addKeyboardNavigationClusters(
10247            @NonNull Collection<View> views,
10248            int direction) {
10249        if (!isKeyboardNavigationCluster()) {
10250            return;
10251        }
10252        if (!hasFocusable()) {
10253            return;
10254        }
10255        views.add(this);
10256    }
10257
10258    /**
10259     * Finds the Views that contain given text. The containment is case insensitive.
10260     * The search is performed by either the text that the View renders or the content
10261     * description that describes the view for accessibility purposes and the view does
10262     * not render or both. Clients can specify how the search is to be performed via
10263     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
10264     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
10265     *
10266     * @param outViews The output list of matching Views.
10267     * @param searched The text to match against.
10268     *
10269     * @see #FIND_VIEWS_WITH_TEXT
10270     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
10271     * @see #setContentDescription(CharSequence)
10272     */
10273    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched,
10274            @FindViewFlags int flags) {
10275        if (getAccessibilityNodeProvider() != null) {
10276            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
10277                outViews.add(this);
10278            }
10279        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
10280                && (searched != null && searched.length() > 0)
10281                && (mContentDescription != null && mContentDescription.length() > 0)) {
10282            String searchedLowerCase = searched.toString().toLowerCase();
10283            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
10284            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
10285                outViews.add(this);
10286            }
10287        }
10288    }
10289
10290    /**
10291     * Find and return all touchable views that are descendants of this view,
10292     * possibly including this view if it is touchable itself.
10293     *
10294     * @return A list of touchable views
10295     */
10296    public ArrayList<View> getTouchables() {
10297        ArrayList<View> result = new ArrayList<View>();
10298        addTouchables(result);
10299        return result;
10300    }
10301
10302    /**
10303     * Add any touchable views that are descendants of this view (possibly
10304     * including this view if it is touchable itself) to views.
10305     *
10306     * @param views Touchable views found so far
10307     */
10308    public void addTouchables(ArrayList<View> views) {
10309        final int viewFlags = mViewFlags;
10310
10311        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE
10312                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE)
10313                && (viewFlags & ENABLED_MASK) == ENABLED) {
10314            views.add(this);
10315        }
10316    }
10317
10318    /**
10319     * Returns whether this View is accessibility focused.
10320     *
10321     * @return True if this View is accessibility focused.
10322     */
10323    public boolean isAccessibilityFocused() {
10324        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
10325    }
10326
10327    /**
10328     * Call this to try to give accessibility focus to this view.
10329     *
10330     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
10331     * returns false or the view is no visible or the view already has accessibility
10332     * focus.
10333     *
10334     * See also {@link #focusSearch(int)}, which is what you call to say that you
10335     * have focus, and you want your parent to look for the next one.
10336     *
10337     * @return Whether this view actually took accessibility focus.
10338     *
10339     * @hide
10340     */
10341    public boolean requestAccessibilityFocus() {
10342        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
10343        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
10344            return false;
10345        }
10346        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
10347            return false;
10348        }
10349        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
10350            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
10351            ViewRootImpl viewRootImpl = getViewRootImpl();
10352            if (viewRootImpl != null) {
10353                viewRootImpl.setAccessibilityFocus(this, null);
10354            }
10355            invalidate();
10356            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
10357            return true;
10358        }
10359        return false;
10360    }
10361
10362    /**
10363     * Call this to try to clear accessibility focus of this view.
10364     *
10365     * See also {@link #focusSearch(int)}, which is what you call to say that you
10366     * have focus, and you want your parent to look for the next one.
10367     *
10368     * @hide
10369     */
10370    public void clearAccessibilityFocus() {
10371        clearAccessibilityFocusNoCallbacks(0);
10372
10373        // Clear the global reference of accessibility focus if this view or
10374        // any of its descendants had accessibility focus. This will NOT send
10375        // an event or update internal state if focus is cleared from a
10376        // descendant view, which may leave views in inconsistent states.
10377        final ViewRootImpl viewRootImpl = getViewRootImpl();
10378        if (viewRootImpl != null) {
10379            final View focusHost = viewRootImpl.getAccessibilityFocusedHost();
10380            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
10381                viewRootImpl.setAccessibilityFocus(null, null);
10382            }
10383        }
10384    }
10385
10386    private void sendAccessibilityHoverEvent(int eventType) {
10387        // Since we are not delivering to a client accessibility events from not
10388        // important views (unless the clinet request that) we need to fire the
10389        // event from the deepest view exposed to the client. As a consequence if
10390        // the user crosses a not exposed view the client will see enter and exit
10391        // of the exposed predecessor followed by and enter and exit of that same
10392        // predecessor when entering and exiting the not exposed descendant. This
10393        // is fine since the client has a clear idea which view is hovered at the
10394        // price of a couple more events being sent. This is a simple and
10395        // working solution.
10396        View source = this;
10397        while (true) {
10398            if (source.includeForAccessibility()) {
10399                source.sendAccessibilityEvent(eventType);
10400                return;
10401            }
10402            ViewParent parent = source.getParent();
10403            if (parent instanceof View) {
10404                source = (View) parent;
10405            } else {
10406                return;
10407            }
10408        }
10409    }
10410
10411    /**
10412     * Clears accessibility focus without calling any callback methods
10413     * normally invoked in {@link #clearAccessibilityFocus()}. This method
10414     * is used separately from that one for clearing accessibility focus when
10415     * giving this focus to another view.
10416     *
10417     * @param action The action, if any, that led to focus being cleared. Set to
10418     * AccessibilityNodeInfo#ACTION_ACCESSIBILITY_FOCUS to specify that focus is moving within
10419     * the window.
10420     */
10421    void clearAccessibilityFocusNoCallbacks(int action) {
10422        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
10423            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
10424            invalidate();
10425            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
10426                AccessibilityEvent event = AccessibilityEvent.obtain(
10427                        AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
10428                event.setAction(action);
10429                if (mAccessibilityDelegate != null) {
10430                    mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
10431                } else {
10432                    sendAccessibilityEventUnchecked(event);
10433                }
10434            }
10435        }
10436    }
10437
10438    /**
10439     * Call this to try to give focus to a specific view or to one of its
10440     * descendants.
10441     *
10442     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
10443     * false), or if it is focusable and it is not focusable in touch mode
10444     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
10445     *
10446     * See also {@link #focusSearch(int)}, which is what you call to say that you
10447     * have focus, and you want your parent to look for the next one.
10448     *
10449     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
10450     * {@link #FOCUS_DOWN} and <code>null</code>.
10451     *
10452     * @return Whether this view or one of its descendants actually took focus.
10453     */
10454    public final boolean requestFocus() {
10455        return requestFocus(View.FOCUS_DOWN);
10456    }
10457
10458    /**
10459     * This will request focus for whichever View was last focused within this
10460     * cluster before a focus-jump out of it.
10461     *
10462     * @hide
10463     */
10464    @TestApi
10465    public boolean restoreFocusInCluster(@FocusRealDirection int direction) {
10466        // Prioritize focusableByDefault over algorithmic focus selection.
10467        if (restoreDefaultFocus()) {
10468            return true;
10469        }
10470        return requestFocus(direction);
10471    }
10472
10473    /**
10474     * This will request focus for whichever View not in a cluster was last focused before a
10475     * focus-jump to a cluster. If no non-cluster View has previously had focus, this will focus
10476     * the "first" focusable view it finds.
10477     *
10478     * @hide
10479     */
10480    @TestApi
10481    public boolean restoreFocusNotInCluster() {
10482        return requestFocus(View.FOCUS_DOWN);
10483    }
10484
10485    /**
10486     * Gives focus to the default-focus view in the view hierarchy that has this view as a root.
10487     * If the default-focus view cannot be found, falls back to calling {@link #requestFocus(int)}.
10488     *
10489     * @return Whether this view or one of its descendants actually took focus
10490     */
10491    public boolean restoreDefaultFocus() {
10492        return requestFocus(View.FOCUS_DOWN);
10493    }
10494
10495    /**
10496     * Call this to try to give focus to a specific view or to one of its
10497     * descendants and give it a hint about what direction focus is heading.
10498     *
10499     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
10500     * false), or if it is focusable and it is not focusable in touch mode
10501     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
10502     *
10503     * See also {@link #focusSearch(int)}, which is what you call to say that you
10504     * have focus, and you want your parent to look for the next one.
10505     *
10506     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
10507     * <code>null</code> set for the previously focused rectangle.
10508     *
10509     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
10510     * @return Whether this view or one of its descendants actually took focus.
10511     */
10512    public final boolean requestFocus(int direction) {
10513        return requestFocus(direction, null);
10514    }
10515
10516    /**
10517     * Call this to try to give focus to a specific view or to one of its descendants
10518     * and give it hints about the direction and a specific rectangle that the focus
10519     * is coming from.  The rectangle can help give larger views a finer grained hint
10520     * about where focus is coming from, and therefore, where to show selection, or
10521     * forward focus change internally.
10522     *
10523     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
10524     * false), or if it is focusable and it is not focusable in touch mode
10525     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
10526     *
10527     * A View will not take focus if it is not visible.
10528     *
10529     * A View will not take focus if one of its parents has
10530     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
10531     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
10532     *
10533     * See also {@link #focusSearch(int)}, which is what you call to say that you
10534     * have focus, and you want your parent to look for the next one.
10535     *
10536     * You may wish to override this method if your custom {@link View} has an internal
10537     * {@link View} that it wishes to forward the request to.
10538     *
10539     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
10540     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
10541     *        to give a finer grained hint about where focus is coming from.  May be null
10542     *        if there is no hint.
10543     * @return Whether this view or one of its descendants actually took focus.
10544     */
10545    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
10546        return requestFocusNoSearch(direction, previouslyFocusedRect);
10547    }
10548
10549    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
10550        // need to be focusable
10551        if ((mViewFlags & FOCUSABLE) != FOCUSABLE
10552                || (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
10553            return false;
10554        }
10555
10556        // need to be focusable in touch mode if in touch mode
10557        if (isInTouchMode() &&
10558            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
10559               return false;
10560        }
10561
10562        // need to not have any parents blocking us
10563        if (hasAncestorThatBlocksDescendantFocus()) {
10564            return false;
10565        }
10566
10567        handleFocusGainInternal(direction, previouslyFocusedRect);
10568        return true;
10569    }
10570
10571    /**
10572     * Call this to try to give focus to a specific view or to one of its descendants. This is a
10573     * special variant of {@link #requestFocus() } that will allow views that are not focusable in
10574     * touch mode to request focus when they are touched.
10575     *
10576     * @return Whether this view or one of its descendants actually took focus.
10577     *
10578     * @see #isInTouchMode()
10579     *
10580     */
10581    public final boolean requestFocusFromTouch() {
10582        // Leave touch mode if we need to
10583        if (isInTouchMode()) {
10584            ViewRootImpl viewRoot = getViewRootImpl();
10585            if (viewRoot != null) {
10586                viewRoot.ensureTouchMode(false);
10587            }
10588        }
10589        return requestFocus(View.FOCUS_DOWN);
10590    }
10591
10592    /**
10593     * @return Whether any ancestor of this view blocks descendant focus.
10594     */
10595    private boolean hasAncestorThatBlocksDescendantFocus() {
10596        final boolean focusableInTouchMode = isFocusableInTouchMode();
10597        ViewParent ancestor = mParent;
10598        while (ancestor instanceof ViewGroup) {
10599            final ViewGroup vgAncestor = (ViewGroup) ancestor;
10600            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS
10601                    || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) {
10602                return true;
10603            } else {
10604                ancestor = vgAncestor.getParent();
10605            }
10606        }
10607        return false;
10608    }
10609
10610    /**
10611     * Gets the mode for determining whether this View is important for accessibility.
10612     * A view is important for accessibility if it fires accessibility events and if it
10613     * is reported to accessibility services that query the screen.
10614     *
10615     * @return The mode for determining whether a view is important for accessibility, one
10616     * of {@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, {@link #IMPORTANT_FOR_ACCESSIBILITY_YES},
10617     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO}, or
10618     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}.
10619     *
10620     * @attr ref android.R.styleable#View_importantForAccessibility
10621     *
10622     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
10623     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
10624     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
10625     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
10626     */
10627    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
10628            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
10629            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
10630            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"),
10631            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
10632                    to = "noHideDescendants")
10633        })
10634    public int getImportantForAccessibility() {
10635        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
10636                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
10637    }
10638
10639    /**
10640     * Sets the live region mode for this view. This indicates to accessibility
10641     * services whether they should automatically notify the user about changes
10642     * to the view's content description or text, or to the content descriptions
10643     * or text of the view's children (where applicable).
10644     * <p>
10645     * For example, in a login screen with a TextView that displays an "incorrect
10646     * password" notification, that view should be marked as a live region with
10647     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
10648     * <p>
10649     * To disable change notifications for this view, use
10650     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
10651     * mode for most views.
10652     * <p>
10653     * To indicate that the user should be notified of changes, use
10654     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
10655     * <p>
10656     * If the view's changes should interrupt ongoing speech and notify the user
10657     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
10658     *
10659     * @param mode The live region mode for this view, one of:
10660     *        <ul>
10661     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
10662     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
10663     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
10664     *        </ul>
10665     * @attr ref android.R.styleable#View_accessibilityLiveRegion
10666     */
10667    public void setAccessibilityLiveRegion(int mode) {
10668        if (mode != getAccessibilityLiveRegion()) {
10669            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
10670            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
10671                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
10672            notifyViewAccessibilityStateChangedIfNeeded(
10673                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10674        }
10675    }
10676
10677    /**
10678     * Gets the live region mode for this View.
10679     *
10680     * @return The live region mode for the view.
10681     *
10682     * @attr ref android.R.styleable#View_accessibilityLiveRegion
10683     *
10684     * @see #setAccessibilityLiveRegion(int)
10685     */
10686    public int getAccessibilityLiveRegion() {
10687        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
10688                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
10689    }
10690
10691    /**
10692     * Sets how to determine whether this view is important for accessibility
10693     * which is if it fires accessibility events and if it is reported to
10694     * accessibility services that query the screen.
10695     *
10696     * @param mode How to determine whether this view is important for accessibility.
10697     *
10698     * @attr ref android.R.styleable#View_importantForAccessibility
10699     *
10700     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
10701     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
10702     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
10703     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
10704     */
10705    public void setImportantForAccessibility(int mode) {
10706        final int oldMode = getImportantForAccessibility();
10707        if (mode != oldMode) {
10708            final boolean hideDescendants =
10709                    mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS;
10710
10711            // If this node or its descendants are no longer important, try to
10712            // clear accessibility focus.
10713            if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO || hideDescendants) {
10714                final View focusHost = findAccessibilityFocusHost(hideDescendants);
10715                if (focusHost != null) {
10716                    focusHost.clearAccessibilityFocus();
10717                }
10718            }
10719
10720            // If we're moving between AUTO and another state, we might not need
10721            // to send a subtree changed notification. We'll store the computed
10722            // importance, since we'll need to check it later to make sure.
10723            final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO
10724                    || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO;
10725            final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility();
10726            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
10727            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
10728                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
10729            if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) {
10730                notifySubtreeAccessibilityStateChangedIfNeeded();
10731            } else {
10732                notifyViewAccessibilityStateChangedIfNeeded(
10733                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10734            }
10735        }
10736    }
10737
10738    /**
10739     * Returns the view within this view's hierarchy that is hosting
10740     * accessibility focus.
10741     *
10742     * @param searchDescendants whether to search for focus in descendant views
10743     * @return the view hosting accessibility focus, or {@code null}
10744     */
10745    private View findAccessibilityFocusHost(boolean searchDescendants) {
10746        if (isAccessibilityFocusedViewOrHost()) {
10747            return this;
10748        }
10749
10750        if (searchDescendants) {
10751            final ViewRootImpl viewRoot = getViewRootImpl();
10752            if (viewRoot != null) {
10753                final View focusHost = viewRoot.getAccessibilityFocusedHost();
10754                if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
10755                    return focusHost;
10756                }
10757            }
10758        }
10759
10760        return null;
10761    }
10762
10763    /**
10764     * Computes whether this view should be exposed for accessibility. In
10765     * general, views that are interactive or provide information are exposed
10766     * while views that serve only as containers are hidden.
10767     * <p>
10768     * If an ancestor of this view has importance
10769     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method
10770     * returns <code>false</code>.
10771     * <p>
10772     * Otherwise, the value is computed according to the view's
10773     * {@link #getImportantForAccessibility()} value:
10774     * <ol>
10775     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or
10776     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false
10777     * </code>
10778     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code>
10779     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if
10780     * view satisfies any of the following:
10781     * <ul>
10782     * <li>Is actionable, e.g. {@link #isClickable()},
10783     * {@link #isLongClickable()}, or {@link #isFocusable()}
10784     * <li>Has an {@link AccessibilityDelegate}
10785     * <li>Has an interaction listener, e.g. {@link OnTouchListener},
10786     * {@link OnKeyListener}, etc.
10787     * <li>Is an accessibility live region, e.g.
10788     * {@link #getAccessibilityLiveRegion()} is not
10789     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}.
10790     * </ul>
10791     * </ol>
10792     *
10793     * @return Whether the view is exposed for accessibility.
10794     * @see #setImportantForAccessibility(int)
10795     * @see #getImportantForAccessibility()
10796     */
10797    public boolean isImportantForAccessibility() {
10798        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
10799                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
10800        if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO
10801                || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
10802            return false;
10803        }
10804
10805        // Check parent mode to ensure we're not hidden.
10806        ViewParent parent = mParent;
10807        while (parent instanceof View) {
10808            if (((View) parent).getImportantForAccessibility()
10809                    == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
10810                return false;
10811            }
10812            parent = parent.getParent();
10813        }
10814
10815        return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
10816                || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
10817                || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE;
10818    }
10819
10820    /**
10821     * Gets the parent for accessibility purposes. Note that the parent for
10822     * accessibility is not necessary the immediate parent. It is the first
10823     * predecessor that is important for accessibility.
10824     *
10825     * @return The parent for accessibility purposes.
10826     */
10827    public ViewParent getParentForAccessibility() {
10828        if (mParent instanceof View) {
10829            View parentView = (View) mParent;
10830            if (parentView.includeForAccessibility()) {
10831                return mParent;
10832            } else {
10833                return mParent.getParentForAccessibility();
10834            }
10835        }
10836        return null;
10837    }
10838
10839    /**
10840     * Adds the children of this View relevant for accessibility to the given list
10841     * as output. Since some Views are not important for accessibility the added
10842     * child views are not necessarily direct children of this view, rather they are
10843     * the first level of descendants important for accessibility.
10844     *
10845     * @param outChildren The output list that will receive children for accessibility.
10846     */
10847    public void addChildrenForAccessibility(ArrayList<View> outChildren) {
10848
10849    }
10850
10851    /**
10852     * Whether to regard this view for accessibility. A view is regarded for
10853     * accessibility if it is important for accessibility or the querying
10854     * accessibility service has explicitly requested that view not
10855     * important for accessibility are regarded.
10856     *
10857     * @return Whether to regard the view for accessibility.
10858     *
10859     * @hide
10860     */
10861    public boolean includeForAccessibility() {
10862        if (mAttachInfo != null) {
10863            return (mAttachInfo.mAccessibilityFetchFlags
10864                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
10865                    || isImportantForAccessibility();
10866        }
10867        return false;
10868    }
10869
10870    /**
10871     * Returns whether the View is considered actionable from
10872     * accessibility perspective. Such view are important for
10873     * accessibility.
10874     *
10875     * @return True if the view is actionable for accessibility.
10876     *
10877     * @hide
10878     */
10879    public boolean isActionableForAccessibility() {
10880        return (isClickable() || isLongClickable() || isFocusable());
10881    }
10882
10883    /**
10884     * Returns whether the View has registered callbacks which makes it
10885     * important for accessibility.
10886     *
10887     * @return True if the view is actionable for accessibility.
10888     */
10889    private boolean hasListenersForAccessibility() {
10890        ListenerInfo info = getListenerInfo();
10891        return mTouchDelegate != null || info.mOnKeyListener != null
10892                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
10893                || info.mOnHoverListener != null || info.mOnDragListener != null;
10894    }
10895
10896    /**
10897     * Notifies that the accessibility state of this view changed. The change
10898     * is local to this view and does not represent structural changes such
10899     * as children and parent. For example, the view became focusable. The
10900     * notification is at at most once every
10901     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
10902     * to avoid unnecessary load to the system. Also once a view has a pending
10903     * notification this method is a NOP until the notification has been sent.
10904     *
10905     * @hide
10906     */
10907    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
10908        if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) {
10909            return;
10910        }
10911        if (mSendViewStateChangedAccessibilityEvent == null) {
10912            mSendViewStateChangedAccessibilityEvent =
10913                    new SendViewStateChangedAccessibilityEvent();
10914        }
10915        mSendViewStateChangedAccessibilityEvent.runOrPost(changeType);
10916    }
10917
10918    /**
10919     * Notifies that the accessibility state of this view changed. The change
10920     * is *not* local to this view and does represent structural changes such
10921     * as children and parent. For example, the view size changed. The
10922     * notification is at at most once every
10923     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
10924     * to avoid unnecessary load to the system. Also once a view has a pending
10925     * notification this method is a NOP until the notification has been sent.
10926     *
10927     * @hide
10928     */
10929    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
10930        if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) {
10931            return;
10932        }
10933        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
10934            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
10935            if (mParent != null) {
10936                try {
10937                    mParent.notifySubtreeAccessibilityStateChanged(
10938                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
10939                } catch (AbstractMethodError e) {
10940                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
10941                            " does not fully implement ViewParent", e);
10942                }
10943            }
10944        }
10945    }
10946
10947    /**
10948     * Change the visibility of the View without triggering any other changes. This is
10949     * important for transitions, where visibility changes should not adjust focus or
10950     * trigger a new layout. This is only used when the visibility has already been changed
10951     * and we need a transient value during an animation. When the animation completes,
10952     * the original visibility value is always restored.
10953     *
10954     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
10955     * @hide
10956     */
10957    public void setTransitionVisibility(@Visibility int visibility) {
10958        mViewFlags = (mViewFlags & ~View.VISIBILITY_MASK) | visibility;
10959    }
10960
10961    /**
10962     * Reset the flag indicating the accessibility state of the subtree rooted
10963     * at this view changed.
10964     */
10965    void resetSubtreeAccessibilityStateChanged() {
10966        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
10967    }
10968
10969    /**
10970     * Report an accessibility action to this view's parents for delegated processing.
10971     *
10972     * <p>Implementations of {@link #performAccessibilityAction(int, Bundle)} may internally
10973     * call this method to delegate an accessibility action to a supporting parent. If the parent
10974     * returns true from its
10975     * {@link ViewParent#onNestedPrePerformAccessibilityAction(View, int, android.os.Bundle)}
10976     * method this method will return true to signify that the action was consumed.</p>
10977     *
10978     * <p>This method is useful for implementing nested scrolling child views. If
10979     * {@link #isNestedScrollingEnabled()} returns true and the action is a scrolling action
10980     * a custom view implementation may invoke this method to allow a parent to consume the
10981     * scroll first. If this method returns true the custom view should skip its own scrolling
10982     * behavior.</p>
10983     *
10984     * @param action Accessibility action to delegate
10985     * @param arguments Optional action arguments
10986     * @return true if the action was consumed by a parent
10987     */
10988    public boolean dispatchNestedPrePerformAccessibilityAction(int action, Bundle arguments) {
10989        for (ViewParent p = getParent(); p != null; p = p.getParent()) {
10990            if (p.onNestedPrePerformAccessibilityAction(this, action, arguments)) {
10991                return true;
10992            }
10993        }
10994        return false;
10995    }
10996
10997    /**
10998     * Performs the specified accessibility action on the view. For
10999     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
11000     * <p>
11001     * If an {@link AccessibilityDelegate} has been specified via calling
11002     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
11003     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
11004     * is responsible for handling this call.
11005     * </p>
11006     *
11007     * <p>The default implementation will delegate
11008     * {@link AccessibilityNodeInfo#ACTION_SCROLL_BACKWARD} and
11009     * {@link AccessibilityNodeInfo#ACTION_SCROLL_FORWARD} to nested scrolling parents if
11010     * {@link #isNestedScrollingEnabled() nested scrolling is enabled} on this view.</p>
11011     *
11012     * @param action The action to perform.
11013     * @param arguments Optional action arguments.
11014     * @return Whether the action was performed.
11015     */
11016    public boolean performAccessibilityAction(int action, Bundle arguments) {
11017      if (mAccessibilityDelegate != null) {
11018          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
11019      } else {
11020          return performAccessibilityActionInternal(action, arguments);
11021      }
11022    }
11023
11024   /**
11025    * @see #performAccessibilityAction(int, Bundle)
11026    *
11027    * Note: Called from the default {@link AccessibilityDelegate}.
11028    *
11029    * @hide
11030    */
11031    public boolean performAccessibilityActionInternal(int action, Bundle arguments) {
11032        if (isNestedScrollingEnabled()
11033                && (action == AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD
11034                || action == AccessibilityNodeInfo.ACTION_SCROLL_FORWARD
11035                || action == R.id.accessibilityActionScrollUp
11036                || action == R.id.accessibilityActionScrollLeft
11037                || action == R.id.accessibilityActionScrollDown
11038                || action == R.id.accessibilityActionScrollRight)) {
11039            if (dispatchNestedPrePerformAccessibilityAction(action, arguments)) {
11040                return true;
11041            }
11042        }
11043
11044        switch (action) {
11045            case AccessibilityNodeInfo.ACTION_CLICK: {
11046                if (isClickable()) {
11047                    performClick();
11048                    return true;
11049                }
11050            } break;
11051            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
11052                if (isLongClickable()) {
11053                    performLongClick();
11054                    return true;
11055                }
11056            } break;
11057            case AccessibilityNodeInfo.ACTION_FOCUS: {
11058                if (!hasFocus()) {
11059                    // Get out of touch mode since accessibility
11060                    // wants to move focus around.
11061                    getViewRootImpl().ensureTouchMode(false);
11062                    return requestFocus();
11063                }
11064            } break;
11065            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
11066                if (hasFocus()) {
11067                    clearFocus();
11068                    return !isFocused();
11069                }
11070            } break;
11071            case AccessibilityNodeInfo.ACTION_SELECT: {
11072                if (!isSelected()) {
11073                    setSelected(true);
11074                    return isSelected();
11075                }
11076            } break;
11077            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
11078                if (isSelected()) {
11079                    setSelected(false);
11080                    return !isSelected();
11081                }
11082            } break;
11083            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
11084                if (!isAccessibilityFocused()) {
11085                    return requestAccessibilityFocus();
11086                }
11087            } break;
11088            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
11089                if (isAccessibilityFocused()) {
11090                    clearAccessibilityFocus();
11091                    return true;
11092                }
11093            } break;
11094            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
11095                if (arguments != null) {
11096                    final int granularity = arguments.getInt(
11097                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
11098                    final boolean extendSelection = arguments.getBoolean(
11099                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
11100                    return traverseAtGranularity(granularity, true, extendSelection);
11101                }
11102            } break;
11103            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
11104                if (arguments != null) {
11105                    final int granularity = arguments.getInt(
11106                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
11107                    final boolean extendSelection = arguments.getBoolean(
11108                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
11109                    return traverseAtGranularity(granularity, false, extendSelection);
11110                }
11111            } break;
11112            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
11113                CharSequence text = getIterableTextForAccessibility();
11114                if (text == null) {
11115                    return false;
11116                }
11117                final int start = (arguments != null) ? arguments.getInt(
11118                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
11119                final int end = (arguments != null) ? arguments.getInt(
11120                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
11121                // Only cursor position can be specified (selection length == 0)
11122                if ((getAccessibilitySelectionStart() != start
11123                        || getAccessibilitySelectionEnd() != end)
11124                        && (start == end)) {
11125                    setAccessibilitySelection(start, end);
11126                    notifyViewAccessibilityStateChangedIfNeeded(
11127                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
11128                    return true;
11129                }
11130            } break;
11131            case R.id.accessibilityActionShowOnScreen: {
11132                if (mAttachInfo != null) {
11133                    final Rect r = mAttachInfo.mTmpInvalRect;
11134                    getDrawingRect(r);
11135                    return requestRectangleOnScreen(r, true);
11136                }
11137            } break;
11138            case R.id.accessibilityActionContextClick: {
11139                if (isContextClickable()) {
11140                    performContextClick();
11141                    return true;
11142                }
11143            } break;
11144        }
11145        return false;
11146    }
11147
11148    private boolean traverseAtGranularity(int granularity, boolean forward,
11149            boolean extendSelection) {
11150        CharSequence text = getIterableTextForAccessibility();
11151        if (text == null || text.length() == 0) {
11152            return false;
11153        }
11154        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
11155        if (iterator == null) {
11156            return false;
11157        }
11158        int current = getAccessibilitySelectionEnd();
11159        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
11160            current = forward ? 0 : text.length();
11161        }
11162        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
11163        if (range == null) {
11164            return false;
11165        }
11166        final int segmentStart = range[0];
11167        final int segmentEnd = range[1];
11168        int selectionStart;
11169        int selectionEnd;
11170        if (extendSelection && isAccessibilitySelectionExtendable()) {
11171            selectionStart = getAccessibilitySelectionStart();
11172            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
11173                selectionStart = forward ? segmentStart : segmentEnd;
11174            }
11175            selectionEnd = forward ? segmentEnd : segmentStart;
11176        } else {
11177            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
11178        }
11179        setAccessibilitySelection(selectionStart, selectionEnd);
11180        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
11181                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
11182        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
11183        return true;
11184    }
11185
11186    /**
11187     * Gets the text reported for accessibility purposes.
11188     *
11189     * @return The accessibility text.
11190     *
11191     * @hide
11192     */
11193    public CharSequence getIterableTextForAccessibility() {
11194        return getContentDescription();
11195    }
11196
11197    /**
11198     * Gets whether accessibility selection can be extended.
11199     *
11200     * @return If selection is extensible.
11201     *
11202     * @hide
11203     */
11204    public boolean isAccessibilitySelectionExtendable() {
11205        return false;
11206    }
11207
11208    /**
11209     * @hide
11210     */
11211    public int getAccessibilitySelectionStart() {
11212        return mAccessibilityCursorPosition;
11213    }
11214
11215    /**
11216     * @hide
11217     */
11218    public int getAccessibilitySelectionEnd() {
11219        return getAccessibilitySelectionStart();
11220    }
11221
11222    /**
11223     * @hide
11224     */
11225    public void setAccessibilitySelection(int start, int end) {
11226        if (start ==  end && end == mAccessibilityCursorPosition) {
11227            return;
11228        }
11229        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
11230            mAccessibilityCursorPosition = start;
11231        } else {
11232            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
11233        }
11234        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
11235    }
11236
11237    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
11238            int fromIndex, int toIndex) {
11239        if (mParent == null) {
11240            return;
11241        }
11242        AccessibilityEvent event = AccessibilityEvent.obtain(
11243                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
11244        onInitializeAccessibilityEvent(event);
11245        onPopulateAccessibilityEvent(event);
11246        event.setFromIndex(fromIndex);
11247        event.setToIndex(toIndex);
11248        event.setAction(action);
11249        event.setMovementGranularity(granularity);
11250        mParent.requestSendAccessibilityEvent(this, event);
11251    }
11252
11253    /**
11254     * @hide
11255     */
11256    public TextSegmentIterator getIteratorForGranularity(int granularity) {
11257        switch (granularity) {
11258            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
11259                CharSequence text = getIterableTextForAccessibility();
11260                if (text != null && text.length() > 0) {
11261                    CharacterTextSegmentIterator iterator =
11262                        CharacterTextSegmentIterator.getInstance(
11263                                mContext.getResources().getConfiguration().locale);
11264                    iterator.initialize(text.toString());
11265                    return iterator;
11266                }
11267            } break;
11268            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
11269                CharSequence text = getIterableTextForAccessibility();
11270                if (text != null && text.length() > 0) {
11271                    WordTextSegmentIterator iterator =
11272                        WordTextSegmentIterator.getInstance(
11273                                mContext.getResources().getConfiguration().locale);
11274                    iterator.initialize(text.toString());
11275                    return iterator;
11276                }
11277            } break;
11278            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
11279                CharSequence text = getIterableTextForAccessibility();
11280                if (text != null && text.length() > 0) {
11281                    ParagraphTextSegmentIterator iterator =
11282                        ParagraphTextSegmentIterator.getInstance();
11283                    iterator.initialize(text.toString());
11284                    return iterator;
11285                }
11286            } break;
11287        }
11288        return null;
11289    }
11290
11291    /**
11292     * Tells whether the {@link View} is in the state between {@link #onStartTemporaryDetach()}
11293     * and {@link #onFinishTemporaryDetach()}.
11294     *
11295     * <p>This method always returns {@code true} when called directly or indirectly from
11296     * {@link #onStartTemporaryDetach()}. The return value when called directly or indirectly from
11297     * {@link #onFinishTemporaryDetach()}, however, depends on the OS version.
11298     * <ul>
11299     *     <li>{@code true} on {@link android.os.Build.VERSION_CODES#N API 24}</li>
11300     *     <li>{@code false} on {@link android.os.Build.VERSION_CODES#N_MR1 API 25}} and later</li>
11301     * </ul>
11302     * </p>
11303     *
11304     * @return {@code true} when the View is in the state between {@link #onStartTemporaryDetach()}
11305     * and {@link #onFinishTemporaryDetach()}.
11306     */
11307    public final boolean isTemporarilyDetached() {
11308        return (mPrivateFlags3 & PFLAG3_TEMPORARY_DETACH) != 0;
11309    }
11310
11311    /**
11312     * Dispatch {@link #onStartTemporaryDetach()} to this View and its direct children if this is
11313     * a container View.
11314     */
11315    @CallSuper
11316    public void dispatchStartTemporaryDetach() {
11317        mPrivateFlags3 |= PFLAG3_TEMPORARY_DETACH;
11318        notifyEnterOrExitForAutoFillIfNeeded(false);
11319        onStartTemporaryDetach();
11320    }
11321
11322    /**
11323     * This is called when a container is going to temporarily detach a child, with
11324     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
11325     * It will either be followed by {@link #onFinishTemporaryDetach()} or
11326     * {@link #onDetachedFromWindow()} when the container is done.
11327     */
11328    public void onStartTemporaryDetach() {
11329        removeUnsetPressCallback();
11330        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
11331    }
11332
11333    /**
11334     * Dispatch {@link #onFinishTemporaryDetach()} to this View and its direct children if this is
11335     * a container View.
11336     */
11337    @CallSuper
11338    public void dispatchFinishTemporaryDetach() {
11339        mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH;
11340        onFinishTemporaryDetach();
11341        if (hasWindowFocus() && hasFocus()) {
11342            InputMethodManager.getInstance().focusIn(this);
11343        }
11344        notifyEnterOrExitForAutoFillIfNeeded(true);
11345    }
11346
11347    /**
11348     * Called after {@link #onStartTemporaryDetach} when the container is done
11349     * changing the view.
11350     */
11351    public void onFinishTemporaryDetach() {
11352    }
11353
11354    /**
11355     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
11356     * for this view's window.  Returns null if the view is not currently attached
11357     * to the window.  Normally you will not need to use this directly, but
11358     * just use the standard high-level event callbacks like
11359     * {@link #onKeyDown(int, KeyEvent)}.
11360     */
11361    public KeyEvent.DispatcherState getKeyDispatcherState() {
11362        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
11363    }
11364
11365    /**
11366     * Dispatch a key event before it is processed by any input method
11367     * associated with the view hierarchy.  This can be used to intercept
11368     * key events in special situations before the IME consumes them; a
11369     * typical example would be handling the BACK key to update the application's
11370     * UI instead of allowing the IME to see it and close itself.
11371     *
11372     * @param event The key event to be dispatched.
11373     * @return True if the event was handled, false otherwise.
11374     */
11375    public boolean dispatchKeyEventPreIme(KeyEvent event) {
11376        return onKeyPreIme(event.getKeyCode(), event);
11377    }
11378
11379    /**
11380     * Dispatch a key event to the next view on the focus path. This path runs
11381     * from the top of the view tree down to the currently focused view. If this
11382     * view has focus, it will dispatch to itself. Otherwise it will dispatch
11383     * the next node down the focus path. This method also fires any key
11384     * listeners.
11385     *
11386     * @param event The key event to be dispatched.
11387     * @return True if the event was handled, false otherwise.
11388     */
11389    public boolean dispatchKeyEvent(KeyEvent event) {
11390        if (mInputEventConsistencyVerifier != null) {
11391            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
11392        }
11393
11394        // Give any attached key listener a first crack at the event.
11395        //noinspection SimplifiableIfStatement
11396        ListenerInfo li = mListenerInfo;
11397        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
11398                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
11399            return true;
11400        }
11401
11402        if (event.dispatch(this, mAttachInfo != null
11403                ? mAttachInfo.mKeyDispatchState : null, this)) {
11404            return true;
11405        }
11406
11407        if (mInputEventConsistencyVerifier != null) {
11408            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
11409        }
11410        return false;
11411    }
11412
11413    /**
11414     * Dispatches a key shortcut event.
11415     *
11416     * @param event The key event to be dispatched.
11417     * @return True if the event was handled by the view, false otherwise.
11418     */
11419    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
11420        return onKeyShortcut(event.getKeyCode(), event);
11421    }
11422
11423    /**
11424     * Pass the touch screen motion event down to the target view, or this
11425     * view if it is the target.
11426     *
11427     * @param event The motion event to be dispatched.
11428     * @return True if the event was handled by the view, false otherwise.
11429     */
11430    public boolean dispatchTouchEvent(MotionEvent event) {
11431        // If the event should be handled by accessibility focus first.
11432        if (event.isTargetAccessibilityFocus()) {
11433            // We don't have focus or no virtual descendant has it, do not handle the event.
11434            if (!isAccessibilityFocusedViewOrHost()) {
11435                return false;
11436            }
11437            // We have focus and got the event, then use normal event dispatch.
11438            event.setTargetAccessibilityFocus(false);
11439        }
11440
11441        boolean result = false;
11442
11443        if (mInputEventConsistencyVerifier != null) {
11444            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
11445        }
11446
11447        final int actionMasked = event.getActionMasked();
11448        if (actionMasked == MotionEvent.ACTION_DOWN) {
11449            // Defensive cleanup for new gesture
11450            stopNestedScroll();
11451        }
11452
11453        if (onFilterTouchEventForSecurity(event)) {
11454            if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
11455                result = true;
11456            }
11457            //noinspection SimplifiableIfStatement
11458            ListenerInfo li = mListenerInfo;
11459            if (li != null && li.mOnTouchListener != null
11460                    && (mViewFlags & ENABLED_MASK) == ENABLED
11461                    && li.mOnTouchListener.onTouch(this, event)) {
11462                result = true;
11463            }
11464
11465            if (!result && onTouchEvent(event)) {
11466                result = true;
11467            }
11468        }
11469
11470        if (!result && mInputEventConsistencyVerifier != null) {
11471            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
11472        }
11473
11474        // Clean up after nested scrolls if this is the end of a gesture;
11475        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
11476        // of the gesture.
11477        if (actionMasked == MotionEvent.ACTION_UP ||
11478                actionMasked == MotionEvent.ACTION_CANCEL ||
11479                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
11480            stopNestedScroll();
11481        }
11482
11483        return result;
11484    }
11485
11486    boolean isAccessibilityFocusedViewOrHost() {
11487        return isAccessibilityFocused() || (getViewRootImpl() != null && getViewRootImpl()
11488                .getAccessibilityFocusedHost() == this);
11489    }
11490
11491    /**
11492     * Filter the touch event to apply security policies.
11493     *
11494     * @param event The motion event to be filtered.
11495     * @return True if the event should be dispatched, false if the event should be dropped.
11496     *
11497     * @see #getFilterTouchesWhenObscured
11498     */
11499    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
11500        //noinspection RedundantIfStatement
11501        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
11502                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
11503            // Window is obscured, drop this touch.
11504            return false;
11505        }
11506        return true;
11507    }
11508
11509    /**
11510     * Pass a trackball motion event down to the focused view.
11511     *
11512     * @param event The motion event to be dispatched.
11513     * @return True if the event was handled by the view, false otherwise.
11514     */
11515    public boolean dispatchTrackballEvent(MotionEvent event) {
11516        if (mInputEventConsistencyVerifier != null) {
11517            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
11518        }
11519
11520        return onTrackballEvent(event);
11521    }
11522
11523    /**
11524     * Pass a captured pointer event down to the focused view.
11525     *
11526     * @param event The motion event to be dispatched.
11527     * @return True if the event was handled by the view, false otherwise.
11528     */
11529    public boolean dispatchCapturedPointerEvent(MotionEvent event) {
11530        if (!hasPointerCapture()) {
11531            return false;
11532        }
11533        //noinspection SimplifiableIfStatement
11534        ListenerInfo li = mListenerInfo;
11535        if (li != null && li.mOnCapturedPointerListener != null
11536                && li.mOnCapturedPointerListener.onCapturedPointer(this, event)) {
11537            return true;
11538        }
11539        return onCapturedPointerEvent(event);
11540    }
11541
11542    /**
11543     * Dispatch a generic motion event.
11544     * <p>
11545     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
11546     * are delivered to the view under the pointer.  All other generic motion events are
11547     * delivered to the focused view.  Hover events are handled specially and are delivered
11548     * to {@link #onHoverEvent(MotionEvent)}.
11549     * </p>
11550     *
11551     * @param event The motion event to be dispatched.
11552     * @return True if the event was handled by the view, false otherwise.
11553     */
11554    public boolean dispatchGenericMotionEvent(MotionEvent event) {
11555        if (mInputEventConsistencyVerifier != null) {
11556            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
11557        }
11558
11559        final int source = event.getSource();
11560        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
11561            final int action = event.getAction();
11562            if (action == MotionEvent.ACTION_HOVER_ENTER
11563                    || action == MotionEvent.ACTION_HOVER_MOVE
11564                    || action == MotionEvent.ACTION_HOVER_EXIT) {
11565                if (dispatchHoverEvent(event)) {
11566                    return true;
11567                }
11568            } else if (dispatchGenericPointerEvent(event)) {
11569                return true;
11570            }
11571        } else if (dispatchGenericFocusedEvent(event)) {
11572            return true;
11573        }
11574
11575        if (dispatchGenericMotionEventInternal(event)) {
11576            return true;
11577        }
11578
11579        if (mInputEventConsistencyVerifier != null) {
11580            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
11581        }
11582        return false;
11583    }
11584
11585    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
11586        //noinspection SimplifiableIfStatement
11587        ListenerInfo li = mListenerInfo;
11588        if (li != null && li.mOnGenericMotionListener != null
11589                && (mViewFlags & ENABLED_MASK) == ENABLED
11590                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
11591            return true;
11592        }
11593
11594        if (onGenericMotionEvent(event)) {
11595            return true;
11596        }
11597
11598        final int actionButton = event.getActionButton();
11599        switch (event.getActionMasked()) {
11600            case MotionEvent.ACTION_BUTTON_PRESS:
11601                if (isContextClickable() && !mInContextButtonPress && !mHasPerformedLongPress
11602                        && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY
11603                        || actionButton == MotionEvent.BUTTON_SECONDARY)) {
11604                    if (performContextClick(event.getX(), event.getY())) {
11605                        mInContextButtonPress = true;
11606                        setPressed(true, event.getX(), event.getY());
11607                        removeTapCallback();
11608                        removeLongPressCallback();
11609                        return true;
11610                    }
11611                }
11612                break;
11613
11614            case MotionEvent.ACTION_BUTTON_RELEASE:
11615                if (mInContextButtonPress && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY
11616                        || actionButton == MotionEvent.BUTTON_SECONDARY)) {
11617                    mInContextButtonPress = false;
11618                    mIgnoreNextUpEvent = true;
11619                }
11620                break;
11621        }
11622
11623        if (mInputEventConsistencyVerifier != null) {
11624            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
11625        }
11626        return false;
11627    }
11628
11629    /**
11630     * Dispatch a hover event.
11631     * <p>
11632     * Do not call this method directly.
11633     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
11634     * </p>
11635     *
11636     * @param event The motion event to be dispatched.
11637     * @return True if the event was handled by the view, false otherwise.
11638     */
11639    protected boolean dispatchHoverEvent(MotionEvent event) {
11640        ListenerInfo li = mListenerInfo;
11641        //noinspection SimplifiableIfStatement
11642        if (li != null && li.mOnHoverListener != null
11643                && (mViewFlags & ENABLED_MASK) == ENABLED
11644                && li.mOnHoverListener.onHover(this, event)) {
11645            return true;
11646        }
11647
11648        return onHoverEvent(event);
11649    }
11650
11651    /**
11652     * Returns true if the view has a child to which it has recently sent
11653     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
11654     * it does not have a hovered child, then it must be the innermost hovered view.
11655     * @hide
11656     */
11657    protected boolean hasHoveredChild() {
11658        return false;
11659    }
11660
11661    /**
11662     * Dispatch a generic motion event to the view under the first pointer.
11663     * <p>
11664     * Do not call this method directly.
11665     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
11666     * </p>
11667     *
11668     * @param event The motion event to be dispatched.
11669     * @return True if the event was handled by the view, false otherwise.
11670     */
11671    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
11672        return false;
11673    }
11674
11675    /**
11676     * Dispatch a generic motion event to the currently focused view.
11677     * <p>
11678     * Do not call this method directly.
11679     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
11680     * </p>
11681     *
11682     * @param event The motion event to be dispatched.
11683     * @return True if the event was handled by the view, false otherwise.
11684     */
11685    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
11686        return false;
11687    }
11688
11689    /**
11690     * Dispatch a pointer event.
11691     * <p>
11692     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
11693     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
11694     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
11695     * and should not be expected to handle other pointing device features.
11696     * </p>
11697     *
11698     * @param event The motion event to be dispatched.
11699     * @return True if the event was handled by the view, false otherwise.
11700     * @hide
11701     */
11702    public final boolean dispatchPointerEvent(MotionEvent event) {
11703        if (event.isTouchEvent()) {
11704            return dispatchTouchEvent(event);
11705        } else {
11706            return dispatchGenericMotionEvent(event);
11707        }
11708    }
11709
11710    /**
11711     * Called when the window containing this view gains or loses window focus.
11712     * ViewGroups should override to route to their children.
11713     *
11714     * @param hasFocus True if the window containing this view now has focus,
11715     *        false otherwise.
11716     */
11717    public void dispatchWindowFocusChanged(boolean hasFocus) {
11718        onWindowFocusChanged(hasFocus);
11719    }
11720
11721    /**
11722     * Called when the window containing this view gains or loses focus.  Note
11723     * that this is separate from view focus: to receive key events, both
11724     * your view and its window must have focus.  If a window is displayed
11725     * on top of yours that takes input focus, then your own window will lose
11726     * focus but the view focus will remain unchanged.
11727     *
11728     * @param hasWindowFocus True if the window containing this view now has
11729     *        focus, false otherwise.
11730     */
11731    public void onWindowFocusChanged(boolean hasWindowFocus) {
11732        InputMethodManager imm = InputMethodManager.peekInstance();
11733        if (!hasWindowFocus) {
11734            if (isPressed()) {
11735                setPressed(false);
11736            }
11737            mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
11738            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
11739                imm.focusOut(this);
11740            }
11741            removeLongPressCallback();
11742            removeTapCallback();
11743            onFocusLost();
11744        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
11745            imm.focusIn(this);
11746        }
11747
11748        notifyEnterOrExitForAutoFillIfNeeded(hasWindowFocus);
11749
11750        refreshDrawableState();
11751    }
11752
11753    /**
11754     * Returns true if this view is in a window that currently has window focus.
11755     * Note that this is not the same as the view itself having focus.
11756     *
11757     * @return True if this view is in a window that currently has window focus.
11758     */
11759    public boolean hasWindowFocus() {
11760        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
11761    }
11762
11763    /**
11764     * Dispatch a view visibility change down the view hierarchy.
11765     * ViewGroups should override to route to their children.
11766     * @param changedView The view whose visibility changed. Could be 'this' or
11767     * an ancestor view.
11768     * @param visibility The new visibility of changedView: {@link #VISIBLE},
11769     * {@link #INVISIBLE} or {@link #GONE}.
11770     */
11771    protected void dispatchVisibilityChanged(@NonNull View changedView,
11772            @Visibility int visibility) {
11773        onVisibilityChanged(changedView, visibility);
11774    }
11775
11776    /**
11777     * Called when the visibility of the view or an ancestor of the view has
11778     * changed.
11779     *
11780     * @param changedView The view whose visibility changed. May be
11781     *                    {@code this} or an ancestor view.
11782     * @param visibility The new visibility, one of {@link #VISIBLE},
11783     *                   {@link #INVISIBLE} or {@link #GONE}.
11784     */
11785    protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) {
11786    }
11787
11788    /**
11789     * Dispatch a hint about whether this view is displayed. For instance, when
11790     * a View moves out of the screen, it might receives a display hint indicating
11791     * the view is not displayed. Applications should not <em>rely</em> on this hint
11792     * as there is no guarantee that they will receive one.
11793     *
11794     * @param hint A hint about whether or not this view is displayed:
11795     * {@link #VISIBLE} or {@link #INVISIBLE}.
11796     */
11797    public void dispatchDisplayHint(@Visibility int hint) {
11798        onDisplayHint(hint);
11799    }
11800
11801    /**
11802     * Gives this view a hint about whether is displayed or not. For instance, when
11803     * a View moves out of the screen, it might receives a display hint indicating
11804     * the view is not displayed. Applications should not <em>rely</em> on this hint
11805     * as there is no guarantee that they will receive one.
11806     *
11807     * @param hint A hint about whether or not this view is displayed:
11808     * {@link #VISIBLE} or {@link #INVISIBLE}.
11809     */
11810    protected void onDisplayHint(@Visibility int hint) {
11811    }
11812
11813    /**
11814     * Dispatch a window visibility change down the view hierarchy.
11815     * ViewGroups should override to route to their children.
11816     *
11817     * @param visibility The new visibility of the window.
11818     *
11819     * @see #onWindowVisibilityChanged(int)
11820     */
11821    public void dispatchWindowVisibilityChanged(@Visibility int visibility) {
11822        onWindowVisibilityChanged(visibility);
11823    }
11824
11825    /**
11826     * Called when the window containing has change its visibility
11827     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
11828     * that this tells you whether or not your window is being made visible
11829     * to the window manager; this does <em>not</em> tell you whether or not
11830     * your window is obscured by other windows on the screen, even if it
11831     * is itself visible.
11832     *
11833     * @param visibility The new visibility of the window.
11834     */
11835    protected void onWindowVisibilityChanged(@Visibility int visibility) {
11836        if (visibility == VISIBLE) {
11837            initialAwakenScrollBars();
11838        }
11839    }
11840
11841    /**
11842     * Internal dispatching method for {@link #onVisibilityAggregated}. Overridden by
11843     * ViewGroup. Intended to only be called when {@link #isAttachedToWindow()},
11844     * {@link #getWindowVisibility()} is {@link #VISIBLE} and this view's parent {@link #isShown()}.
11845     *
11846     * @param isVisible true if this view's visibility to the user is uninterrupted by its
11847     *                  ancestors or by window visibility
11848     * @return true if this view is visible to the user, not counting clipping or overlapping
11849     */
11850    boolean dispatchVisibilityAggregated(boolean isVisible) {
11851        final boolean thisVisible = getVisibility() == VISIBLE;
11852        // If we're not visible but something is telling us we are, ignore it.
11853        if (thisVisible || !isVisible) {
11854            onVisibilityAggregated(isVisible);
11855        }
11856        return thisVisible && isVisible;
11857    }
11858
11859    /**
11860     * Called when the user-visibility of this View is potentially affected by a change
11861     * to this view itself, an ancestor view or the window this view is attached to.
11862     *
11863     * @param isVisible true if this view and all of its ancestors are {@link #VISIBLE}
11864     *                  and this view's window is also visible
11865     */
11866    @CallSuper
11867    public void onVisibilityAggregated(boolean isVisible) {
11868        if (isVisible && mAttachInfo != null) {
11869            initialAwakenScrollBars();
11870        }
11871
11872        final Drawable dr = mBackground;
11873        if (dr != null && isVisible != dr.isVisible()) {
11874            dr.setVisible(isVisible, false);
11875        }
11876        final Drawable hl = mDefaultFocusHighlight;
11877        if (hl != null && isVisible != hl.isVisible()) {
11878            hl.setVisible(isVisible, false);
11879        }
11880        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
11881        if (fg != null && isVisible != fg.isVisible()) {
11882            fg.setVisible(isVisible, false);
11883        }
11884
11885        if (isAutofillable()) {
11886            AutofillManager afm = getAutofillManager();
11887
11888            if (afm != null && getAccessibilityViewId() > LAST_APP_ACCESSIBILITY_ID) {
11889                if (mVisibilityChangeForAutofillHandler != null) {
11890                    mVisibilityChangeForAutofillHandler.removeMessages(0);
11891                }
11892
11893                // If the view is in the background but still part of the hierarchy this is called
11894                // with isVisible=false. Hence visibility==false requires further checks
11895                if (isVisible) {
11896                    afm.notifyViewVisibilityChange(this, true);
11897                } else {
11898                    if (mVisibilityChangeForAutofillHandler == null) {
11899                        mVisibilityChangeForAutofillHandler =
11900                                new VisibilityChangeForAutofillHandler(afm, this);
11901                    }
11902                    // Let current operation (e.g. removal of the view from the hierarchy)
11903                    // finish before checking state
11904                    mVisibilityChangeForAutofillHandler.obtainMessage(0, this).sendToTarget();
11905                }
11906            }
11907        }
11908    }
11909
11910    /**
11911     * Returns the current visibility of the window this view is attached to
11912     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
11913     *
11914     * @return Returns the current visibility of the view's window.
11915     */
11916    @Visibility
11917    public int getWindowVisibility() {
11918        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
11919    }
11920
11921    /**
11922     * Retrieve the overall visible display size in which the window this view is
11923     * attached to has been positioned in.  This takes into account screen
11924     * decorations above the window, for both cases where the window itself
11925     * is being position inside of them or the window is being placed under
11926     * then and covered insets are used for the window to position its content
11927     * inside.  In effect, this tells you the available area where content can
11928     * be placed and remain visible to users.
11929     *
11930     * <p>This function requires an IPC back to the window manager to retrieve
11931     * the requested information, so should not be used in performance critical
11932     * code like drawing.
11933     *
11934     * @param outRect Filled in with the visible display frame.  If the view
11935     * is not attached to a window, this is simply the raw display size.
11936     */
11937    public void getWindowVisibleDisplayFrame(Rect outRect) {
11938        if (mAttachInfo != null) {
11939            try {
11940                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
11941            } catch (RemoteException e) {
11942                return;
11943            }
11944            // XXX This is really broken, and probably all needs to be done
11945            // in the window manager, and we need to know more about whether
11946            // we want the area behind or in front of the IME.
11947            final Rect insets = mAttachInfo.mVisibleInsets;
11948            outRect.left += insets.left;
11949            outRect.top += insets.top;
11950            outRect.right -= insets.right;
11951            outRect.bottom -= insets.bottom;
11952            return;
11953        }
11954        // The view is not attached to a display so we don't have a context.
11955        // Make a best guess about the display size.
11956        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
11957        d.getRectSize(outRect);
11958    }
11959
11960    /**
11961     * Like {@link #getWindowVisibleDisplayFrame}, but returns the "full" display frame this window
11962     * is currently in without any insets.
11963     *
11964     * @hide
11965     */
11966    public void getWindowDisplayFrame(Rect outRect) {
11967        if (mAttachInfo != null) {
11968            try {
11969                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
11970            } catch (RemoteException e) {
11971                return;
11972            }
11973            return;
11974        }
11975        // The view is not attached to a display so we don't have a context.
11976        // Make a best guess about the display size.
11977        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
11978        d.getRectSize(outRect);
11979    }
11980
11981    /**
11982     * Dispatch a notification about a resource configuration change down
11983     * the view hierarchy.
11984     * ViewGroups should override to route to their children.
11985     *
11986     * @param newConfig The new resource configuration.
11987     *
11988     * @see #onConfigurationChanged(android.content.res.Configuration)
11989     */
11990    public void dispatchConfigurationChanged(Configuration newConfig) {
11991        onConfigurationChanged(newConfig);
11992    }
11993
11994    /**
11995     * Called when the current configuration of the resources being used
11996     * by the application have changed.  You can use this to decide when
11997     * to reload resources that can changed based on orientation and other
11998     * configuration characteristics.  You only need to use this if you are
11999     * not relying on the normal {@link android.app.Activity} mechanism of
12000     * recreating the activity instance upon a configuration change.
12001     *
12002     * @param newConfig The new resource configuration.
12003     */
12004    protected void onConfigurationChanged(Configuration newConfig) {
12005    }
12006
12007    /**
12008     * Private function to aggregate all per-view attributes in to the view
12009     * root.
12010     */
12011    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
12012        performCollectViewAttributes(attachInfo, visibility);
12013    }
12014
12015    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
12016        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
12017            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
12018                attachInfo.mKeepScreenOn = true;
12019            }
12020            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
12021            ListenerInfo li = mListenerInfo;
12022            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
12023                attachInfo.mHasSystemUiListeners = true;
12024            }
12025        }
12026    }
12027
12028    void needGlobalAttributesUpdate(boolean force) {
12029        final AttachInfo ai = mAttachInfo;
12030        if (ai != null && !ai.mRecomputeGlobalAttributes) {
12031            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
12032                    || ai.mHasSystemUiListeners) {
12033                ai.mRecomputeGlobalAttributes = true;
12034            }
12035        }
12036    }
12037
12038    /**
12039     * Returns whether the device is currently in touch mode.  Touch mode is entered
12040     * once the user begins interacting with the device by touch, and affects various
12041     * things like whether focus is always visible to the user.
12042     *
12043     * @return Whether the device is in touch mode.
12044     */
12045    @ViewDebug.ExportedProperty
12046    public boolean isInTouchMode() {
12047        if (mAttachInfo != null) {
12048            return mAttachInfo.mInTouchMode;
12049        } else {
12050            return ViewRootImpl.isInTouchMode();
12051        }
12052    }
12053
12054    /**
12055     * Returns the context the view is running in, through which it can
12056     * access the current theme, resources, etc.
12057     *
12058     * @return The view's Context.
12059     */
12060    @ViewDebug.CapturedViewProperty
12061    public final Context getContext() {
12062        return mContext;
12063    }
12064
12065    /**
12066     * Handle a key event before it is processed by any input method
12067     * associated with the view hierarchy.  This can be used to intercept
12068     * key events in special situations before the IME consumes them; a
12069     * typical example would be handling the BACK key to update the application's
12070     * UI instead of allowing the IME to see it and close itself.
12071     *
12072     * @param keyCode The value in event.getKeyCode().
12073     * @param event Description of the key event.
12074     * @return If you handled the event, return true. If you want to allow the
12075     *         event to be handled by the next receiver, return false.
12076     */
12077    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
12078        return false;
12079    }
12080
12081    /**
12082     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
12083     * KeyEvent.Callback.onKeyDown()}: perform press of the view
12084     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
12085     * is released, if the view is enabled and clickable.
12086     * <p>
12087     * Key presses in software keyboards will generally NOT trigger this
12088     * listener, although some may elect to do so in some situations. Do not
12089     * rely on this to catch software key presses.
12090     *
12091     * @param keyCode a key code that represents the button pressed, from
12092     *                {@link android.view.KeyEvent}
12093     * @param event the KeyEvent object that defines the button action
12094     */
12095    public boolean onKeyDown(int keyCode, KeyEvent event) {
12096        if (KeyEvent.isConfirmKey(keyCode)) {
12097            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
12098                return true;
12099            }
12100
12101            if (event.getRepeatCount() == 0) {
12102                // Long clickable items don't necessarily have to be clickable.
12103                final boolean clickable = (mViewFlags & CLICKABLE) == CLICKABLE
12104                        || (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
12105                if (clickable || (mViewFlags & TOOLTIP) == TOOLTIP) {
12106                    // For the purposes of menu anchoring and drawable hotspots,
12107                    // key events are considered to be at the center of the view.
12108                    final float x = getWidth() / 2f;
12109                    final float y = getHeight() / 2f;
12110                    if (clickable) {
12111                        setPressed(true, x, y);
12112                    }
12113                    checkForLongClick(0, x, y);
12114                    return true;
12115                }
12116            }
12117        }
12118
12119        return false;
12120    }
12121
12122    /**
12123     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
12124     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
12125     * the event).
12126     * <p>Key presses in software keyboards will generally NOT trigger this listener,
12127     * although some may elect to do so in some situations. Do not rely on this to
12128     * catch software key presses.
12129     */
12130    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
12131        return false;
12132    }
12133
12134    /**
12135     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
12136     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
12137     * when {@link KeyEvent#KEYCODE_DPAD_CENTER}, {@link KeyEvent#KEYCODE_ENTER}
12138     * or {@link KeyEvent#KEYCODE_SPACE} is released.
12139     * <p>Key presses in software keyboards will generally NOT trigger this listener,
12140     * although some may elect to do so in some situations. Do not rely on this to
12141     * catch software key presses.
12142     *
12143     * @param keyCode A key code that represents the button pressed, from
12144     *                {@link android.view.KeyEvent}.
12145     * @param event   The KeyEvent object that defines the button action.
12146     */
12147    public boolean onKeyUp(int keyCode, KeyEvent event) {
12148        if (KeyEvent.isConfirmKey(keyCode)) {
12149            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
12150                return true;
12151            }
12152            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
12153                setPressed(false);
12154
12155                if (!mHasPerformedLongPress) {
12156                    // This is a tap, so remove the longpress check
12157                    removeLongPressCallback();
12158                    if (!event.isCanceled()) {
12159                        return performClick();
12160                    }
12161                }
12162            }
12163        }
12164        return false;
12165    }
12166
12167    /**
12168     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
12169     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
12170     * the event).
12171     * <p>Key presses in software keyboards will generally NOT trigger this listener,
12172     * although some may elect to do so in some situations. Do not rely on this to
12173     * catch software key presses.
12174     *
12175     * @param keyCode     A key code that represents the button pressed, from
12176     *                    {@link android.view.KeyEvent}.
12177     * @param repeatCount The number of times the action was made.
12178     * @param event       The KeyEvent object that defines the button action.
12179     */
12180    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
12181        return false;
12182    }
12183
12184    /**
12185     * Called on the focused view when a key shortcut event is not handled.
12186     * Override this method to implement local key shortcuts for the View.
12187     * Key shortcuts can also be implemented by setting the
12188     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
12189     *
12190     * @param keyCode The value in event.getKeyCode().
12191     * @param event Description of the key event.
12192     * @return If you handled the event, return true. If you want to allow the
12193     *         event to be handled by the next receiver, return false.
12194     */
12195    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
12196        return false;
12197    }
12198
12199    /**
12200     * Check whether the called view is a text editor, in which case it
12201     * would make sense to automatically display a soft input window for
12202     * it.  Subclasses should override this if they implement
12203     * {@link #onCreateInputConnection(EditorInfo)} to return true if
12204     * a call on that method would return a non-null InputConnection, and
12205     * they are really a first-class editor that the user would normally
12206     * start typing on when the go into a window containing your view.
12207     *
12208     * <p>The default implementation always returns false.  This does
12209     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
12210     * will not be called or the user can not otherwise perform edits on your
12211     * view; it is just a hint to the system that this is not the primary
12212     * purpose of this view.
12213     *
12214     * @return Returns true if this view is a text editor, else false.
12215     */
12216    public boolean onCheckIsTextEditor() {
12217        return false;
12218    }
12219
12220    /**
12221     * Create a new InputConnection for an InputMethod to interact
12222     * with the view.  The default implementation returns null, since it doesn't
12223     * support input methods.  You can override this to implement such support.
12224     * This is only needed for views that take focus and text input.
12225     *
12226     * <p>When implementing this, you probably also want to implement
12227     * {@link #onCheckIsTextEditor()} to indicate you will return a
12228     * non-null InputConnection.</p>
12229     *
12230     * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo}
12231     * object correctly and in its entirety, so that the connected IME can rely
12232     * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart}
12233     * and  {@link android.view.inputmethod.EditorInfo#initialSelEnd} members
12234     * must be filled in with the correct cursor position for IMEs to work correctly
12235     * with your application.</p>
12236     *
12237     * @param outAttrs Fill in with attribute information about the connection.
12238     */
12239    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
12240        return null;
12241    }
12242
12243    /**
12244     * Called by the {@link android.view.inputmethod.InputMethodManager}
12245     * when a view who is not the current
12246     * input connection target is trying to make a call on the manager.  The
12247     * default implementation returns false; you can override this to return
12248     * true for certain views if you are performing InputConnection proxying
12249     * to them.
12250     * @param view The View that is making the InputMethodManager call.
12251     * @return Return true to allow the call, false to reject.
12252     */
12253    public boolean checkInputConnectionProxy(View view) {
12254        return false;
12255    }
12256
12257    /**
12258     * Show the context menu for this view. It is not safe to hold on to the
12259     * menu after returning from this method.
12260     *
12261     * You should normally not overload this method. Overload
12262     * {@link #onCreateContextMenu(ContextMenu)} or define an
12263     * {@link OnCreateContextMenuListener} to add items to the context menu.
12264     *
12265     * @param menu The context menu to populate
12266     */
12267    public void createContextMenu(ContextMenu menu) {
12268        ContextMenuInfo menuInfo = getContextMenuInfo();
12269
12270        // Sets the current menu info so all items added to menu will have
12271        // my extra info set.
12272        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
12273
12274        onCreateContextMenu(menu);
12275        ListenerInfo li = mListenerInfo;
12276        if (li != null && li.mOnCreateContextMenuListener != null) {
12277            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
12278        }
12279
12280        // Clear the extra information so subsequent items that aren't mine don't
12281        // have my extra info.
12282        ((MenuBuilder)menu).setCurrentMenuInfo(null);
12283
12284        if (mParent != null) {
12285            mParent.createContextMenu(menu);
12286        }
12287    }
12288
12289    /**
12290     * Views should implement this if they have extra information to associate
12291     * with the context menu. The return result is supplied as a parameter to
12292     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
12293     * callback.
12294     *
12295     * @return Extra information about the item for which the context menu
12296     *         should be shown. This information will vary across different
12297     *         subclasses of View.
12298     */
12299    protected ContextMenuInfo getContextMenuInfo() {
12300        return null;
12301    }
12302
12303    /**
12304     * Views should implement this if the view itself is going to add items to
12305     * the context menu.
12306     *
12307     * @param menu the context menu to populate
12308     */
12309    protected void onCreateContextMenu(ContextMenu menu) {
12310    }
12311
12312    /**
12313     * Implement this method to handle trackball motion events.  The
12314     * <em>relative</em> movement of the trackball since the last event
12315     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
12316     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
12317     * that a movement of 1 corresponds to the user pressing one DPAD key (so
12318     * they will often be fractional values, representing the more fine-grained
12319     * movement information available from a trackball).
12320     *
12321     * @param event The motion event.
12322     * @return True if the event was handled, false otherwise.
12323     */
12324    public boolean onTrackballEvent(MotionEvent event) {
12325        return false;
12326    }
12327
12328    /**
12329     * Implement this method to handle generic motion events.
12330     * <p>
12331     * Generic motion events describe joystick movements, mouse hovers, track pad
12332     * touches, scroll wheel movements and other input events.  The
12333     * {@link MotionEvent#getSource() source} of the motion event specifies
12334     * the class of input that was received.  Implementations of this method
12335     * must examine the bits in the source before processing the event.
12336     * The following code example shows how this is done.
12337     * </p><p>
12338     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
12339     * are delivered to the view under the pointer.  All other generic motion events are
12340     * delivered to the focused view.
12341     * </p>
12342     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
12343     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
12344     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
12345     *             // process the joystick movement...
12346     *             return true;
12347     *         }
12348     *     }
12349     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
12350     *         switch (event.getAction()) {
12351     *             case MotionEvent.ACTION_HOVER_MOVE:
12352     *                 // process the mouse hover movement...
12353     *                 return true;
12354     *             case MotionEvent.ACTION_SCROLL:
12355     *                 // process the scroll wheel movement...
12356     *                 return true;
12357     *         }
12358     *     }
12359     *     return super.onGenericMotionEvent(event);
12360     * }</pre>
12361     *
12362     * @param event The generic motion event being processed.
12363     * @return True if the event was handled, false otherwise.
12364     */
12365    public boolean onGenericMotionEvent(MotionEvent event) {
12366        return false;
12367    }
12368
12369    /**
12370     * Implement this method to handle hover events.
12371     * <p>
12372     * This method is called whenever a pointer is hovering into, over, or out of the
12373     * bounds of a view and the view is not currently being touched.
12374     * Hover events are represented as pointer events with action
12375     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
12376     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
12377     * </p>
12378     * <ul>
12379     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
12380     * when the pointer enters the bounds of the view.</li>
12381     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
12382     * when the pointer has already entered the bounds of the view and has moved.</li>
12383     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
12384     * when the pointer has exited the bounds of the view or when the pointer is
12385     * about to go down due to a button click, tap, or similar user action that
12386     * causes the view to be touched.</li>
12387     * </ul>
12388     * <p>
12389     * The view should implement this method to return true to indicate that it is
12390     * handling the hover event, such as by changing its drawable state.
12391     * </p><p>
12392     * The default implementation calls {@link #setHovered} to update the hovered state
12393     * of the view when a hover enter or hover exit event is received, if the view
12394     * is enabled and is clickable.  The default implementation also sends hover
12395     * accessibility events.
12396     * </p>
12397     *
12398     * @param event The motion event that describes the hover.
12399     * @return True if the view handled the hover event.
12400     *
12401     * @see #isHovered
12402     * @see #setHovered
12403     * @see #onHoverChanged
12404     */
12405    public boolean onHoverEvent(MotionEvent event) {
12406        // The root view may receive hover (or touch) events that are outside the bounds of
12407        // the window.  This code ensures that we only send accessibility events for
12408        // hovers that are actually within the bounds of the root view.
12409        final int action = event.getActionMasked();
12410        if (!mSendingHoverAccessibilityEvents) {
12411            if ((action == MotionEvent.ACTION_HOVER_ENTER
12412                    || action == MotionEvent.ACTION_HOVER_MOVE)
12413                    && !hasHoveredChild()
12414                    && pointInView(event.getX(), event.getY())) {
12415                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
12416                mSendingHoverAccessibilityEvents = true;
12417            }
12418        } else {
12419            if (action == MotionEvent.ACTION_HOVER_EXIT
12420                    || (action == MotionEvent.ACTION_MOVE
12421                            && !pointInView(event.getX(), event.getY()))) {
12422                mSendingHoverAccessibilityEvents = false;
12423                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
12424            }
12425        }
12426
12427        if ((action == MotionEvent.ACTION_HOVER_ENTER || action == MotionEvent.ACTION_HOVER_MOVE)
12428                && event.isFromSource(InputDevice.SOURCE_MOUSE)
12429                && isOnScrollbar(event.getX(), event.getY())) {
12430            awakenScrollBars();
12431        }
12432
12433        // If we consider ourself hoverable, or if we we're already hovered,
12434        // handle changing state in response to ENTER and EXIT events.
12435        if (isHoverable() || isHovered()) {
12436            switch (action) {
12437                case MotionEvent.ACTION_HOVER_ENTER:
12438                    setHovered(true);
12439                    break;
12440                case MotionEvent.ACTION_HOVER_EXIT:
12441                    setHovered(false);
12442                    break;
12443            }
12444
12445            // Dispatch the event to onGenericMotionEvent before returning true.
12446            // This is to provide compatibility with existing applications that
12447            // handled HOVER_MOVE events in onGenericMotionEvent and that would
12448            // break because of the new default handling for hoverable views
12449            // in onHoverEvent.
12450            // Note that onGenericMotionEvent will be called by default when
12451            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
12452            dispatchGenericMotionEventInternal(event);
12453            // The event was already handled by calling setHovered(), so always
12454            // return true.
12455            return true;
12456        }
12457
12458        return false;
12459    }
12460
12461    /**
12462     * Returns true if the view should handle {@link #onHoverEvent}
12463     * by calling {@link #setHovered} to change its hovered state.
12464     *
12465     * @return True if the view is hoverable.
12466     */
12467    private boolean isHoverable() {
12468        final int viewFlags = mViewFlags;
12469        if ((viewFlags & ENABLED_MASK) == DISABLED) {
12470            return false;
12471        }
12472
12473        return (viewFlags & CLICKABLE) == CLICKABLE
12474                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE
12475                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
12476    }
12477
12478    /**
12479     * Returns true if the view is currently hovered.
12480     *
12481     * @return True if the view is currently hovered.
12482     *
12483     * @see #setHovered
12484     * @see #onHoverChanged
12485     */
12486    @ViewDebug.ExportedProperty
12487    public boolean isHovered() {
12488        return (mPrivateFlags & PFLAG_HOVERED) != 0;
12489    }
12490
12491    /**
12492     * Sets whether the view is currently hovered.
12493     * <p>
12494     * Calling this method also changes the drawable state of the view.  This
12495     * enables the view to react to hover by using different drawable resources
12496     * to change its appearance.
12497     * </p><p>
12498     * The {@link #onHoverChanged} method is called when the hovered state changes.
12499     * </p>
12500     *
12501     * @param hovered True if the view is hovered.
12502     *
12503     * @see #isHovered
12504     * @see #onHoverChanged
12505     */
12506    public void setHovered(boolean hovered) {
12507        if (hovered) {
12508            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
12509                mPrivateFlags |= PFLAG_HOVERED;
12510                refreshDrawableState();
12511                onHoverChanged(true);
12512            }
12513        } else {
12514            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
12515                mPrivateFlags &= ~PFLAG_HOVERED;
12516                refreshDrawableState();
12517                onHoverChanged(false);
12518            }
12519        }
12520    }
12521
12522    /**
12523     * Implement this method to handle hover state changes.
12524     * <p>
12525     * This method is called whenever the hover state changes as a result of a
12526     * call to {@link #setHovered}.
12527     * </p>
12528     *
12529     * @param hovered The current hover state, as returned by {@link #isHovered}.
12530     *
12531     * @see #isHovered
12532     * @see #setHovered
12533     */
12534    public void onHoverChanged(boolean hovered) {
12535    }
12536
12537    /**
12538     * Handles scroll bar dragging by mouse input.
12539     *
12540     * @hide
12541     * @param event The motion event.
12542     *
12543     * @return true if the event was handled as a scroll bar dragging, false otherwise.
12544     */
12545    protected boolean handleScrollBarDragging(MotionEvent event) {
12546        if (mScrollCache == null) {
12547            return false;
12548        }
12549        final float x = event.getX();
12550        final float y = event.getY();
12551        final int action = event.getAction();
12552        if ((mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING
12553                && action != MotionEvent.ACTION_DOWN)
12554                    || !event.isFromSource(InputDevice.SOURCE_MOUSE)
12555                    || !event.isButtonPressed(MotionEvent.BUTTON_PRIMARY)) {
12556            mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING;
12557            return false;
12558        }
12559
12560        switch (action) {
12561            case MotionEvent.ACTION_MOVE:
12562                if (mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING) {
12563                    return false;
12564                }
12565                if (mScrollCache.mScrollBarDraggingState
12566                        == ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR) {
12567                    final Rect bounds = mScrollCache.mScrollBarBounds;
12568                    getVerticalScrollBarBounds(bounds, null);
12569                    final int range = computeVerticalScrollRange();
12570                    final int offset = computeVerticalScrollOffset();
12571                    final int extent = computeVerticalScrollExtent();
12572
12573                    final int thumbLength = ScrollBarUtils.getThumbLength(
12574                            bounds.height(), bounds.width(), extent, range);
12575                    final int thumbOffset = ScrollBarUtils.getThumbOffset(
12576                            bounds.height(), thumbLength, extent, range, offset);
12577
12578                    final float diff = y - mScrollCache.mScrollBarDraggingPos;
12579                    final float maxThumbOffset = bounds.height() - thumbLength;
12580                    final float newThumbOffset =
12581                            Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset);
12582                    final int height = getHeight();
12583                    if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0
12584                            && height > 0 && extent > 0) {
12585                        final int newY = Math.round((range - extent)
12586                                / ((float)extent / height) * (newThumbOffset / maxThumbOffset));
12587                        if (newY != getScrollY()) {
12588                            mScrollCache.mScrollBarDraggingPos = y;
12589                            setScrollY(newY);
12590                        }
12591                    }
12592                    return true;
12593                }
12594                if (mScrollCache.mScrollBarDraggingState
12595                        == ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR) {
12596                    final Rect bounds = mScrollCache.mScrollBarBounds;
12597                    getHorizontalScrollBarBounds(bounds, null);
12598                    final int range = computeHorizontalScrollRange();
12599                    final int offset = computeHorizontalScrollOffset();
12600                    final int extent = computeHorizontalScrollExtent();
12601
12602                    final int thumbLength = ScrollBarUtils.getThumbLength(
12603                            bounds.width(), bounds.height(), extent, range);
12604                    final int thumbOffset = ScrollBarUtils.getThumbOffset(
12605                            bounds.width(), thumbLength, extent, range, offset);
12606
12607                    final float diff = x - mScrollCache.mScrollBarDraggingPos;
12608                    final float maxThumbOffset = bounds.width() - thumbLength;
12609                    final float newThumbOffset =
12610                            Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset);
12611                    final int width = getWidth();
12612                    if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0
12613                            && width > 0 && extent > 0) {
12614                        final int newX = Math.round((range - extent)
12615                                / ((float)extent / width) * (newThumbOffset / maxThumbOffset));
12616                        if (newX != getScrollX()) {
12617                            mScrollCache.mScrollBarDraggingPos = x;
12618                            setScrollX(newX);
12619                        }
12620                    }
12621                    return true;
12622                }
12623            case MotionEvent.ACTION_DOWN:
12624                if (mScrollCache.state == ScrollabilityCache.OFF) {
12625                    return false;
12626                }
12627                if (isOnVerticalScrollbarThumb(x, y)) {
12628                    mScrollCache.mScrollBarDraggingState =
12629                            ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR;
12630                    mScrollCache.mScrollBarDraggingPos = y;
12631                    return true;
12632                }
12633                if (isOnHorizontalScrollbarThumb(x, y)) {
12634                    mScrollCache.mScrollBarDraggingState =
12635                            ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR;
12636                    mScrollCache.mScrollBarDraggingPos = x;
12637                    return true;
12638                }
12639        }
12640        mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING;
12641        return false;
12642    }
12643
12644    /**
12645     * Implement this method to handle touch screen motion events.
12646     * <p>
12647     * If this method is used to detect click actions, it is recommended that
12648     * the actions be performed by implementing and calling
12649     * {@link #performClick()}. This will ensure consistent system behavior,
12650     * including:
12651     * <ul>
12652     * <li>obeying click sound preferences
12653     * <li>dispatching OnClickListener calls
12654     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
12655     * accessibility features are enabled
12656     * </ul>
12657     *
12658     * @param event The motion event.
12659     * @return True if the event was handled, false otherwise.
12660     */
12661    public boolean onTouchEvent(MotionEvent event) {
12662        final float x = event.getX();
12663        final float y = event.getY();
12664        final int viewFlags = mViewFlags;
12665        final int action = event.getAction();
12666
12667        final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE
12668                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
12669                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
12670
12671        if ((viewFlags & ENABLED_MASK) == DISABLED) {
12672            if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
12673                setPressed(false);
12674            }
12675            mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
12676            // A disabled view that is clickable still consumes the touch
12677            // events, it just doesn't respond to them.
12678            return clickable;
12679        }
12680        if (mTouchDelegate != null) {
12681            if (mTouchDelegate.onTouchEvent(event)) {
12682                return true;
12683            }
12684        }
12685
12686        if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
12687            switch (action) {
12688                case MotionEvent.ACTION_UP:
12689                    mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
12690                    if ((viewFlags & TOOLTIP) == TOOLTIP) {
12691                        handleTooltipUp();
12692                    }
12693                    if (!clickable) {
12694                        removeTapCallback();
12695                        removeLongPressCallback();
12696                        mInContextButtonPress = false;
12697                        mHasPerformedLongPress = false;
12698                        mIgnoreNextUpEvent = false;
12699                        break;
12700                    }
12701                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
12702                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
12703                        // take focus if we don't have it already and we should in
12704                        // touch mode.
12705                        boolean focusTaken = false;
12706                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
12707                            focusTaken = requestFocus();
12708                        }
12709
12710                        if (prepressed) {
12711                            // The button is being released before we actually
12712                            // showed it as pressed.  Make it show the pressed
12713                            // state now (before scheduling the click) to ensure
12714                            // the user sees it.
12715                            setPressed(true, x, y);
12716                        }
12717
12718                        if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
12719                            // This is a tap, so remove the longpress check
12720                            removeLongPressCallback();
12721
12722                            // Only perform take click actions if we were in the pressed state
12723                            if (!focusTaken) {
12724                                // Use a Runnable and post this rather than calling
12725                                // performClick directly. This lets other visual state
12726                                // of the view update before click actions start.
12727                                if (mPerformClick == null) {
12728                                    mPerformClick = new PerformClick();
12729                                }
12730                                if (!post(mPerformClick)) {
12731                                    performClick();
12732                                }
12733                            }
12734                        }
12735
12736                        if (mUnsetPressedState == null) {
12737                            mUnsetPressedState = new UnsetPressedState();
12738                        }
12739
12740                        if (prepressed) {
12741                            postDelayed(mUnsetPressedState,
12742                                    ViewConfiguration.getPressedStateDuration());
12743                        } else if (!post(mUnsetPressedState)) {
12744                            // If the post failed, unpress right now
12745                            mUnsetPressedState.run();
12746                        }
12747
12748                        removeTapCallback();
12749                    }
12750                    mIgnoreNextUpEvent = false;
12751                    break;
12752
12753                case MotionEvent.ACTION_DOWN:
12754                    if (event.getSource() == InputDevice.SOURCE_TOUCHSCREEN) {
12755                        mPrivateFlags3 |= PFLAG3_FINGER_DOWN;
12756                    }
12757                    mHasPerformedLongPress = false;
12758
12759                    if (!clickable) {
12760                        checkForLongClick(0, x, y);
12761                        break;
12762                    }
12763
12764                    if (performButtonActionOnTouchDown(event)) {
12765                        break;
12766                    }
12767
12768                    // Walk up the hierarchy to determine if we're inside a scrolling container.
12769                    boolean isInScrollingContainer = isInScrollingContainer();
12770
12771                    // For views inside a scrolling container, delay the pressed feedback for
12772                    // a short period in case this is a scroll.
12773                    if (isInScrollingContainer) {
12774                        mPrivateFlags |= PFLAG_PREPRESSED;
12775                        if (mPendingCheckForTap == null) {
12776                            mPendingCheckForTap = new CheckForTap();
12777                        }
12778                        mPendingCheckForTap.x = event.getX();
12779                        mPendingCheckForTap.y = event.getY();
12780                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
12781                    } else {
12782                        // Not inside a scrolling container, so show the feedback right away
12783                        setPressed(true, x, y);
12784                        checkForLongClick(0, x, y);
12785                    }
12786                    break;
12787
12788                case MotionEvent.ACTION_CANCEL:
12789                    if (clickable) {
12790                        setPressed(false);
12791                    }
12792                    removeTapCallback();
12793                    removeLongPressCallback();
12794                    mInContextButtonPress = false;
12795                    mHasPerformedLongPress = false;
12796                    mIgnoreNextUpEvent = false;
12797                    mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
12798                    break;
12799
12800                case MotionEvent.ACTION_MOVE:
12801                    if (clickable) {
12802                        drawableHotspotChanged(x, y);
12803                    }
12804
12805                    // Be lenient about moving outside of buttons
12806                    if (!pointInView(x, y, mTouchSlop)) {
12807                        // Outside button
12808                        // Remove any future long press/tap checks
12809                        removeTapCallback();
12810                        removeLongPressCallback();
12811                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
12812                            setPressed(false);
12813                        }
12814                        mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
12815                    }
12816                    break;
12817            }
12818
12819            return true;
12820        }
12821
12822        return false;
12823    }
12824
12825    /**
12826     * @hide
12827     */
12828    public boolean isInScrollingContainer() {
12829        ViewParent p = getParent();
12830        while (p != null && p instanceof ViewGroup) {
12831            if (((ViewGroup) p).shouldDelayChildPressedState()) {
12832                return true;
12833            }
12834            p = p.getParent();
12835        }
12836        return false;
12837    }
12838
12839    /**
12840     * Remove the longpress detection timer.
12841     */
12842    private void removeLongPressCallback() {
12843        if (mPendingCheckForLongPress != null) {
12844            removeCallbacks(mPendingCheckForLongPress);
12845        }
12846    }
12847
12848    /**
12849     * Remove the pending click action
12850     */
12851    private void removePerformClickCallback() {
12852        if (mPerformClick != null) {
12853            removeCallbacks(mPerformClick);
12854        }
12855    }
12856
12857    /**
12858     * Remove the prepress detection timer.
12859     */
12860    private void removeUnsetPressCallback() {
12861        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
12862            setPressed(false);
12863            removeCallbacks(mUnsetPressedState);
12864        }
12865    }
12866
12867    /**
12868     * Remove the tap detection timer.
12869     */
12870    private void removeTapCallback() {
12871        if (mPendingCheckForTap != null) {
12872            mPrivateFlags &= ~PFLAG_PREPRESSED;
12873            removeCallbacks(mPendingCheckForTap);
12874        }
12875    }
12876
12877    /**
12878     * Cancels a pending long press.  Your subclass can use this if you
12879     * want the context menu to come up if the user presses and holds
12880     * at the same place, but you don't want it to come up if they press
12881     * and then move around enough to cause scrolling.
12882     */
12883    public void cancelLongPress() {
12884        removeLongPressCallback();
12885
12886        /*
12887         * The prepressed state handled by the tap callback is a display
12888         * construct, but the tap callback will post a long press callback
12889         * less its own timeout. Remove it here.
12890         */
12891        removeTapCallback();
12892    }
12893
12894    /**
12895     * Remove the pending callback for sending a
12896     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
12897     */
12898    private void removeSendViewScrolledAccessibilityEventCallback() {
12899        if (mSendViewScrolledAccessibilityEvent != null) {
12900            removeCallbacks(mSendViewScrolledAccessibilityEvent);
12901            mSendViewScrolledAccessibilityEvent.mIsPending = false;
12902        }
12903    }
12904
12905    /**
12906     * Sets the TouchDelegate for this View.
12907     */
12908    public void setTouchDelegate(TouchDelegate delegate) {
12909        mTouchDelegate = delegate;
12910    }
12911
12912    /**
12913     * Gets the TouchDelegate for this View.
12914     */
12915    public TouchDelegate getTouchDelegate() {
12916        return mTouchDelegate;
12917    }
12918
12919    /**
12920     * Request unbuffered dispatch of the given stream of MotionEvents to this View.
12921     *
12922     * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input
12923     * system not batch {@link MotionEvent}s but instead deliver them as soon as they're
12924     * available. This method should only be called for touch events.
12925     *
12926     * <p class="note">This api is not intended for most applications. Buffered dispatch
12927     * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent
12928     * streams will not improve your input latency. Side effects include: increased latency,
12929     * jittery scrolls and inability to take advantage of system resampling. Talk to your input
12930     * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for
12931     * you.</p>
12932     */
12933    public final void requestUnbufferedDispatch(MotionEvent event) {
12934        final int action = event.getAction();
12935        if (mAttachInfo == null
12936                || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE
12937                || !event.isTouchEvent()) {
12938            return;
12939        }
12940        mAttachInfo.mUnbufferedDispatchRequested = true;
12941    }
12942
12943    /**
12944     * Set flags controlling behavior of this view.
12945     *
12946     * @param flags Constant indicating the value which should be set
12947     * @param mask Constant indicating the bit range that should be changed
12948     */
12949    void setFlags(int flags, int mask) {
12950        final boolean accessibilityEnabled =
12951                AccessibilityManager.getInstance(mContext).isEnabled();
12952        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
12953
12954        int old = mViewFlags;
12955        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
12956
12957        int changed = mViewFlags ^ old;
12958        if (changed == 0) {
12959            return;
12960        }
12961        int privateFlags = mPrivateFlags;
12962
12963        // If focusable is auto, update the FOCUSABLE bit.
12964        int focusableChangedByAuto = 0;
12965        if (((mViewFlags & FOCUSABLE_AUTO) != 0)
12966                && (changed & (FOCUSABLE_MASK | CLICKABLE)) != 0) {
12967            // Heuristic only takes into account whether view is clickable.
12968            final int newFocus;
12969            if ((mViewFlags & CLICKABLE) != 0) {
12970                newFocus = FOCUSABLE;
12971            } else {
12972                newFocus = NOT_FOCUSABLE;
12973            }
12974            mViewFlags = (mViewFlags & ~FOCUSABLE) | newFocus;
12975            focusableChangedByAuto = (old & FOCUSABLE) ^ (newFocus & FOCUSABLE);
12976            changed = (changed & ~FOCUSABLE) | focusableChangedByAuto;
12977        }
12978
12979        /* Check if the FOCUSABLE bit has changed */
12980        if (((changed & FOCUSABLE) != 0) && ((privateFlags & PFLAG_HAS_BOUNDS) != 0)) {
12981            if (((old & FOCUSABLE) == FOCUSABLE)
12982                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
12983                /* Give up focus if we are no longer focusable */
12984                clearFocus();
12985            } else if (((old & FOCUSABLE) == NOT_FOCUSABLE)
12986                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
12987                /*
12988                 * Tell the view system that we are now available to take focus
12989                 * if no one else already has it.
12990                 */
12991                if (mParent != null) {
12992                    ViewRootImpl viewRootImpl = getViewRootImpl();
12993                    if (!sAutoFocusableOffUIThreadWontNotifyParents
12994                            || focusableChangedByAuto == 0
12995                            || viewRootImpl == null
12996                            || viewRootImpl.mThread == Thread.currentThread()) {
12997                        mParent.focusableViewAvailable(this);
12998                    }
12999                }
13000            }
13001        }
13002
13003        final int newVisibility = flags & VISIBILITY_MASK;
13004        if (newVisibility == VISIBLE) {
13005            if ((changed & VISIBILITY_MASK) != 0) {
13006                /*
13007                 * If this view is becoming visible, invalidate it in case it changed while
13008                 * it was not visible. Marking it drawn ensures that the invalidation will
13009                 * go through.
13010                 */
13011                mPrivateFlags |= PFLAG_DRAWN;
13012                invalidate(true);
13013
13014                needGlobalAttributesUpdate(true);
13015
13016                // a view becoming visible is worth notifying the parent
13017                // about in case nothing has focus.  even if this specific view
13018                // isn't focusable, it may contain something that is, so let
13019                // the root view try to give this focus if nothing else does.
13020                if ((mParent != null)) {
13021                    mParent.focusableViewAvailable(this);
13022                }
13023            }
13024        }
13025
13026        /* Check if the GONE bit has changed */
13027        if ((changed & GONE) != 0) {
13028            needGlobalAttributesUpdate(false);
13029            requestLayout();
13030
13031            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
13032                if (hasFocus()) clearFocus();
13033                clearAccessibilityFocus();
13034                destroyDrawingCache();
13035                if (mParent instanceof View) {
13036                    // GONE views noop invalidation, so invalidate the parent
13037                    ((View) mParent).invalidate(true);
13038                }
13039                // Mark the view drawn to ensure that it gets invalidated properly the next
13040                // time it is visible and gets invalidated
13041                mPrivateFlags |= PFLAG_DRAWN;
13042            }
13043            if (mAttachInfo != null) {
13044                mAttachInfo.mViewVisibilityChanged = true;
13045            }
13046        }
13047
13048        /* Check if the VISIBLE bit has changed */
13049        if ((changed & INVISIBLE) != 0) {
13050            needGlobalAttributesUpdate(false);
13051            /*
13052             * If this view is becoming invisible, set the DRAWN flag so that
13053             * the next invalidate() will not be skipped.
13054             */
13055            mPrivateFlags |= PFLAG_DRAWN;
13056
13057            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
13058                // root view becoming invisible shouldn't clear focus and accessibility focus
13059                if (getRootView() != this) {
13060                    if (hasFocus()) clearFocus();
13061                    clearAccessibilityFocus();
13062                }
13063            }
13064            if (mAttachInfo != null) {
13065                mAttachInfo.mViewVisibilityChanged = true;
13066            }
13067        }
13068
13069        if ((changed & VISIBILITY_MASK) != 0) {
13070            // If the view is invisible, cleanup its display list to free up resources
13071            if (newVisibility != VISIBLE && mAttachInfo != null) {
13072                cleanupDraw();
13073            }
13074
13075            if (mParent instanceof ViewGroup) {
13076                ((ViewGroup) mParent).onChildVisibilityChanged(this,
13077                        (changed & VISIBILITY_MASK), newVisibility);
13078                ((View) mParent).invalidate(true);
13079            } else if (mParent != null) {
13080                mParent.invalidateChild(this, null);
13081            }
13082
13083            if (mAttachInfo != null) {
13084                dispatchVisibilityChanged(this, newVisibility);
13085
13086                // Aggregated visibility changes are dispatched to attached views
13087                // in visible windows where the parent is currently shown/drawn
13088                // or the parent is not a ViewGroup (and therefore assumed to be a ViewRoot),
13089                // discounting clipping or overlapping. This makes it a good place
13090                // to change animation states.
13091                if (mParent != null && getWindowVisibility() == VISIBLE &&
13092                        ((!(mParent instanceof ViewGroup)) || ((ViewGroup) mParent).isShown())) {
13093                    dispatchVisibilityAggregated(newVisibility == VISIBLE);
13094                }
13095                notifySubtreeAccessibilityStateChangedIfNeeded();
13096            }
13097        }
13098
13099        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
13100            destroyDrawingCache();
13101        }
13102
13103        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
13104            destroyDrawingCache();
13105            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
13106            invalidateParentCaches();
13107        }
13108
13109        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
13110            destroyDrawingCache();
13111            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
13112        }
13113
13114        if ((changed & DRAW_MASK) != 0) {
13115            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
13116                if (mBackground != null
13117                        || mDefaultFocusHighlight != null
13118                        || (mForegroundInfo != null && mForegroundInfo.mDrawable != null)) {
13119                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
13120                } else {
13121                    mPrivateFlags |= PFLAG_SKIP_DRAW;
13122                }
13123            } else {
13124                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
13125            }
13126            requestLayout();
13127            invalidate(true);
13128        }
13129
13130        if ((changed & KEEP_SCREEN_ON) != 0) {
13131            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
13132                mParent.recomputeViewAttributes(this);
13133            }
13134        }
13135
13136        if (accessibilityEnabled) {
13137            if ((changed & FOCUSABLE) != 0 || (changed & VISIBILITY_MASK) != 0
13138                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0
13139                    || (changed & CONTEXT_CLICKABLE) != 0) {
13140                if (oldIncludeForAccessibility != includeForAccessibility()) {
13141                    notifySubtreeAccessibilityStateChangedIfNeeded();
13142                } else {
13143                    notifyViewAccessibilityStateChangedIfNeeded(
13144                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
13145                }
13146            } else if ((changed & ENABLED_MASK) != 0) {
13147                notifyViewAccessibilityStateChangedIfNeeded(
13148                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
13149            }
13150        }
13151    }
13152
13153    /**
13154     * Change the view's z order in the tree, so it's on top of other sibling
13155     * views. This ordering change may affect layout, if the parent container
13156     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
13157     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
13158     * method should be followed by calls to {@link #requestLayout()} and
13159     * {@link View#invalidate()} on the view's parent to force the parent to redraw
13160     * with the new child ordering.
13161     *
13162     * @see ViewGroup#bringChildToFront(View)
13163     */
13164    public void bringToFront() {
13165        if (mParent != null) {
13166            mParent.bringChildToFront(this);
13167        }
13168    }
13169
13170    /**
13171     * This is called in response to an internal scroll in this view (i.e., the
13172     * view scrolled its own contents). This is typically as a result of
13173     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
13174     * called.
13175     *
13176     * @param l Current horizontal scroll origin.
13177     * @param t Current vertical scroll origin.
13178     * @param oldl Previous horizontal scroll origin.
13179     * @param oldt Previous vertical scroll origin.
13180     */
13181    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
13182        notifySubtreeAccessibilityStateChangedIfNeeded();
13183
13184        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
13185            postSendViewScrolledAccessibilityEventCallback();
13186        }
13187
13188        mBackgroundSizeChanged = true;
13189        mDefaultFocusHighlightSizeChanged = true;
13190        if (mForegroundInfo != null) {
13191            mForegroundInfo.mBoundsChanged = true;
13192        }
13193
13194        final AttachInfo ai = mAttachInfo;
13195        if (ai != null) {
13196            ai.mViewScrollChanged = true;
13197        }
13198
13199        if (mListenerInfo != null && mListenerInfo.mOnScrollChangeListener != null) {
13200            mListenerInfo.mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt);
13201        }
13202    }
13203
13204    /**
13205     * Interface definition for a callback to be invoked when the scroll
13206     * X or Y positions of a view change.
13207     * <p>
13208     * <b>Note:</b> Some views handle scrolling independently from View and may
13209     * have their own separate listeners for scroll-type events. For example,
13210     * {@link android.widget.ListView ListView} allows clients to register an
13211     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
13212     * to listen for changes in list scroll position.
13213     *
13214     * @see #setOnScrollChangeListener(View.OnScrollChangeListener)
13215     */
13216    public interface OnScrollChangeListener {
13217        /**
13218         * Called when the scroll position of a view changes.
13219         *
13220         * @param v The view whose scroll position has changed.
13221         * @param scrollX Current horizontal scroll origin.
13222         * @param scrollY Current vertical scroll origin.
13223         * @param oldScrollX Previous horizontal scroll origin.
13224         * @param oldScrollY Previous vertical scroll origin.
13225         */
13226        void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY);
13227    }
13228
13229    /**
13230     * Interface definition for a callback to be invoked when the layout bounds of a view
13231     * changes due to layout processing.
13232     */
13233    public interface OnLayoutChangeListener {
13234        /**
13235         * Called when the layout bounds of a view changes due to layout processing.
13236         *
13237         * @param v The view whose bounds have changed.
13238         * @param left The new value of the view's left property.
13239         * @param top The new value of the view's top property.
13240         * @param right The new value of the view's right property.
13241         * @param bottom The new value of the view's bottom property.
13242         * @param oldLeft The previous value of the view's left property.
13243         * @param oldTop The previous value of the view's top property.
13244         * @param oldRight The previous value of the view's right property.
13245         * @param oldBottom The previous value of the view's bottom property.
13246         */
13247        void onLayoutChange(View v, int left, int top, int right, int bottom,
13248            int oldLeft, int oldTop, int oldRight, int oldBottom);
13249    }
13250
13251    /**
13252     * This is called during layout when the size of this view has changed. If
13253     * you were just added to the view hierarchy, you're called with the old
13254     * values of 0.
13255     *
13256     * @param w Current width of this view.
13257     * @param h Current height of this view.
13258     * @param oldw Old width of this view.
13259     * @param oldh Old height of this view.
13260     */
13261    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
13262    }
13263
13264    /**
13265     * Called by draw to draw the child views. This may be overridden
13266     * by derived classes to gain control just before its children are drawn
13267     * (but after its own view has been drawn).
13268     * @param canvas the canvas on which to draw the view
13269     */
13270    protected void dispatchDraw(Canvas canvas) {
13271
13272    }
13273
13274    /**
13275     * Gets the parent of this view. Note that the parent is a
13276     * ViewParent and not necessarily a View.
13277     *
13278     * @return Parent of this view.
13279     */
13280    public final ViewParent getParent() {
13281        return mParent;
13282    }
13283
13284    /**
13285     * Set the horizontal scrolled position of your view. This will cause a call to
13286     * {@link #onScrollChanged(int, int, int, int)} and the view will be
13287     * invalidated.
13288     * @param value the x position to scroll to
13289     */
13290    public void setScrollX(int value) {
13291        scrollTo(value, mScrollY);
13292    }
13293
13294    /**
13295     * Set the vertical scrolled position of your view. This will cause a call to
13296     * {@link #onScrollChanged(int, int, int, int)} and the view will be
13297     * invalidated.
13298     * @param value the y position to scroll to
13299     */
13300    public void setScrollY(int value) {
13301        scrollTo(mScrollX, value);
13302    }
13303
13304    /**
13305     * Return the scrolled left position of this view. This is the left edge of
13306     * the displayed part of your view. You do not need to draw any pixels
13307     * farther left, since those are outside of the frame of your view on
13308     * screen.
13309     *
13310     * @return The left edge of the displayed part of your view, in pixels.
13311     */
13312    public final int getScrollX() {
13313        return mScrollX;
13314    }
13315
13316    /**
13317     * Return the scrolled top position of this view. This is the top edge of
13318     * the displayed part of your view. You do not need to draw any pixels above
13319     * it, since those are outside of the frame of your view on screen.
13320     *
13321     * @return The top edge of the displayed part of your view, in pixels.
13322     */
13323    public final int getScrollY() {
13324        return mScrollY;
13325    }
13326
13327    /**
13328     * Return the width of the your view.
13329     *
13330     * @return The width of your view, in pixels.
13331     */
13332    @ViewDebug.ExportedProperty(category = "layout")
13333    public final int getWidth() {
13334        return mRight - mLeft;
13335    }
13336
13337    /**
13338     * Return the height of your view.
13339     *
13340     * @return The height of your view, in pixels.
13341     */
13342    @ViewDebug.ExportedProperty(category = "layout")
13343    public final int getHeight() {
13344        return mBottom - mTop;
13345    }
13346
13347    /**
13348     * Return the visible drawing bounds of your view. Fills in the output
13349     * rectangle with the values from getScrollX(), getScrollY(),
13350     * getWidth(), and getHeight(). These bounds do not account for any
13351     * transformation properties currently set on the view, such as
13352     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
13353     *
13354     * @param outRect The (scrolled) drawing bounds of the view.
13355     */
13356    public void getDrawingRect(Rect outRect) {
13357        outRect.left = mScrollX;
13358        outRect.top = mScrollY;
13359        outRect.right = mScrollX + (mRight - mLeft);
13360        outRect.bottom = mScrollY + (mBottom - mTop);
13361    }
13362
13363    /**
13364     * Like {@link #getMeasuredWidthAndState()}, but only returns the
13365     * raw width component (that is the result is masked by
13366     * {@link #MEASURED_SIZE_MASK}).
13367     *
13368     * @return The raw measured width of this view.
13369     */
13370    public final int getMeasuredWidth() {
13371        return mMeasuredWidth & MEASURED_SIZE_MASK;
13372    }
13373
13374    /**
13375     * Return the full width measurement information for this view as computed
13376     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
13377     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
13378     * This should be used during measurement and layout calculations only. Use
13379     * {@link #getWidth()} to see how wide a view is after layout.
13380     *
13381     * @return The measured width of this view as a bit mask.
13382     */
13383    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
13384            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
13385                    name = "MEASURED_STATE_TOO_SMALL"),
13386    })
13387    public final int getMeasuredWidthAndState() {
13388        return mMeasuredWidth;
13389    }
13390
13391    /**
13392     * Like {@link #getMeasuredHeightAndState()}, but only returns the
13393     * raw height component (that is the result is masked by
13394     * {@link #MEASURED_SIZE_MASK}).
13395     *
13396     * @return The raw measured height of this view.
13397     */
13398    public final int getMeasuredHeight() {
13399        return mMeasuredHeight & MEASURED_SIZE_MASK;
13400    }
13401
13402    /**
13403     * Return the full height measurement information for this view as computed
13404     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
13405     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
13406     * This should be used during measurement and layout calculations only. Use
13407     * {@link #getHeight()} to see how wide a view is after layout.
13408     *
13409     * @return The measured height of this view as a bit mask.
13410     */
13411    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
13412            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
13413                    name = "MEASURED_STATE_TOO_SMALL"),
13414    })
13415    public final int getMeasuredHeightAndState() {
13416        return mMeasuredHeight;
13417    }
13418
13419    /**
13420     * Return only the state bits of {@link #getMeasuredWidthAndState()}
13421     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
13422     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
13423     * and the height component is at the shifted bits
13424     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
13425     */
13426    public final int getMeasuredState() {
13427        return (mMeasuredWidth&MEASURED_STATE_MASK)
13428                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
13429                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
13430    }
13431
13432    /**
13433     * The transform matrix of this view, which is calculated based on the current
13434     * rotation, scale, and pivot properties.
13435     *
13436     * @see #getRotation()
13437     * @see #getScaleX()
13438     * @see #getScaleY()
13439     * @see #getPivotX()
13440     * @see #getPivotY()
13441     * @return The current transform matrix for the view
13442     */
13443    public Matrix getMatrix() {
13444        ensureTransformationInfo();
13445        final Matrix matrix = mTransformationInfo.mMatrix;
13446        mRenderNode.getMatrix(matrix);
13447        return matrix;
13448    }
13449
13450    /**
13451     * Returns true if the transform matrix is the identity matrix.
13452     * Recomputes the matrix if necessary.
13453     *
13454     * @return True if the transform matrix is the identity matrix, false otherwise.
13455     */
13456    final boolean hasIdentityMatrix() {
13457        return mRenderNode.hasIdentityMatrix();
13458    }
13459
13460    void ensureTransformationInfo() {
13461        if (mTransformationInfo == null) {
13462            mTransformationInfo = new TransformationInfo();
13463        }
13464    }
13465
13466    /**
13467     * Utility method to retrieve the inverse of the current mMatrix property.
13468     * We cache the matrix to avoid recalculating it when transform properties
13469     * have not changed.
13470     *
13471     * @return The inverse of the current matrix of this view.
13472     * @hide
13473     */
13474    public final Matrix getInverseMatrix() {
13475        ensureTransformationInfo();
13476        if (mTransformationInfo.mInverseMatrix == null) {
13477            mTransformationInfo.mInverseMatrix = new Matrix();
13478        }
13479        final Matrix matrix = mTransformationInfo.mInverseMatrix;
13480        mRenderNode.getInverseMatrix(matrix);
13481        return matrix;
13482    }
13483
13484    /**
13485     * Gets the distance along the Z axis from the camera to this view.
13486     *
13487     * @see #setCameraDistance(float)
13488     *
13489     * @return The distance along the Z axis.
13490     */
13491    public float getCameraDistance() {
13492        final float dpi = mResources.getDisplayMetrics().densityDpi;
13493        return -(mRenderNode.getCameraDistance() * dpi);
13494    }
13495
13496    /**
13497     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
13498     * views are drawn) from the camera to this view. The camera's distance
13499     * affects 3D transformations, for instance rotations around the X and Y
13500     * axis. If the rotationX or rotationY properties are changed and this view is
13501     * large (more than half the size of the screen), it is recommended to always
13502     * use a camera distance that's greater than the height (X axis rotation) or
13503     * the width (Y axis rotation) of this view.</p>
13504     *
13505     * <p>The distance of the camera from the view plane can have an affect on the
13506     * perspective distortion of the view when it is rotated around the x or y axis.
13507     * For example, a large distance will result in a large viewing angle, and there
13508     * will not be much perspective distortion of the view as it rotates. A short
13509     * distance may cause much more perspective distortion upon rotation, and can
13510     * also result in some drawing artifacts if the rotated view ends up partially
13511     * behind the camera (which is why the recommendation is to use a distance at
13512     * least as far as the size of the view, if the view is to be rotated.)</p>
13513     *
13514     * <p>The distance is expressed in "depth pixels." The default distance depends
13515     * on the screen density. For instance, on a medium density display, the
13516     * default distance is 1280. On a high density display, the default distance
13517     * is 1920.</p>
13518     *
13519     * <p>If you want to specify a distance that leads to visually consistent
13520     * results across various densities, use the following formula:</p>
13521     * <pre>
13522     * float scale = context.getResources().getDisplayMetrics().density;
13523     * view.setCameraDistance(distance * scale);
13524     * </pre>
13525     *
13526     * <p>The density scale factor of a high density display is 1.5,
13527     * and 1920 = 1280 * 1.5.</p>
13528     *
13529     * @param distance The distance in "depth pixels", if negative the opposite
13530     *        value is used
13531     *
13532     * @see #setRotationX(float)
13533     * @see #setRotationY(float)
13534     */
13535    public void setCameraDistance(float distance) {
13536        final float dpi = mResources.getDisplayMetrics().densityDpi;
13537
13538        invalidateViewProperty(true, false);
13539        mRenderNode.setCameraDistance(-Math.abs(distance) / dpi);
13540        invalidateViewProperty(false, false);
13541
13542        invalidateParentIfNeededAndWasQuickRejected();
13543    }
13544
13545    /**
13546     * The degrees that the view is rotated around the pivot point.
13547     *
13548     * @see #setRotation(float)
13549     * @see #getPivotX()
13550     * @see #getPivotY()
13551     *
13552     * @return The degrees of rotation.
13553     */
13554    @ViewDebug.ExportedProperty(category = "drawing")
13555    public float getRotation() {
13556        return mRenderNode.getRotation();
13557    }
13558
13559    /**
13560     * Sets the degrees that the view is rotated around the pivot point. Increasing values
13561     * result in clockwise rotation.
13562     *
13563     * @param rotation The degrees of rotation.
13564     *
13565     * @see #getRotation()
13566     * @see #getPivotX()
13567     * @see #getPivotY()
13568     * @see #setRotationX(float)
13569     * @see #setRotationY(float)
13570     *
13571     * @attr ref android.R.styleable#View_rotation
13572     */
13573    public void setRotation(float rotation) {
13574        if (rotation != getRotation()) {
13575            // Double-invalidation is necessary to capture view's old and new areas
13576            invalidateViewProperty(true, false);
13577            mRenderNode.setRotation(rotation);
13578            invalidateViewProperty(false, true);
13579
13580            invalidateParentIfNeededAndWasQuickRejected();
13581            notifySubtreeAccessibilityStateChangedIfNeeded();
13582        }
13583    }
13584
13585    /**
13586     * The degrees that the view is rotated around the vertical axis through the pivot point.
13587     *
13588     * @see #getPivotX()
13589     * @see #getPivotY()
13590     * @see #setRotationY(float)
13591     *
13592     * @return The degrees of Y rotation.
13593     */
13594    @ViewDebug.ExportedProperty(category = "drawing")
13595    public float getRotationY() {
13596        return mRenderNode.getRotationY();
13597    }
13598
13599    /**
13600     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
13601     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
13602     * down the y axis.
13603     *
13604     * When rotating large views, it is recommended to adjust the camera distance
13605     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
13606     *
13607     * @param rotationY The degrees of Y rotation.
13608     *
13609     * @see #getRotationY()
13610     * @see #getPivotX()
13611     * @see #getPivotY()
13612     * @see #setRotation(float)
13613     * @see #setRotationX(float)
13614     * @see #setCameraDistance(float)
13615     *
13616     * @attr ref android.R.styleable#View_rotationY
13617     */
13618    public void setRotationY(float rotationY) {
13619        if (rotationY != getRotationY()) {
13620            invalidateViewProperty(true, false);
13621            mRenderNode.setRotationY(rotationY);
13622            invalidateViewProperty(false, true);
13623
13624            invalidateParentIfNeededAndWasQuickRejected();
13625            notifySubtreeAccessibilityStateChangedIfNeeded();
13626        }
13627    }
13628
13629    /**
13630     * The degrees that the view is rotated around the horizontal axis through the pivot point.
13631     *
13632     * @see #getPivotX()
13633     * @see #getPivotY()
13634     * @see #setRotationX(float)
13635     *
13636     * @return The degrees of X rotation.
13637     */
13638    @ViewDebug.ExportedProperty(category = "drawing")
13639    public float getRotationX() {
13640        return mRenderNode.getRotationX();
13641    }
13642
13643    /**
13644     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
13645     * Increasing values result in clockwise rotation from the viewpoint of looking down the
13646     * x axis.
13647     *
13648     * When rotating large views, it is recommended to adjust the camera distance
13649     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
13650     *
13651     * @param rotationX The degrees of X rotation.
13652     *
13653     * @see #getRotationX()
13654     * @see #getPivotX()
13655     * @see #getPivotY()
13656     * @see #setRotation(float)
13657     * @see #setRotationY(float)
13658     * @see #setCameraDistance(float)
13659     *
13660     * @attr ref android.R.styleable#View_rotationX
13661     */
13662    public void setRotationX(float rotationX) {
13663        if (rotationX != getRotationX()) {
13664            invalidateViewProperty(true, false);
13665            mRenderNode.setRotationX(rotationX);
13666            invalidateViewProperty(false, true);
13667
13668            invalidateParentIfNeededAndWasQuickRejected();
13669            notifySubtreeAccessibilityStateChangedIfNeeded();
13670        }
13671    }
13672
13673    /**
13674     * The amount that the view is scaled in x around the pivot point, as a proportion of
13675     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
13676     *
13677     * <p>By default, this is 1.0f.
13678     *
13679     * @see #getPivotX()
13680     * @see #getPivotY()
13681     * @return The scaling factor.
13682     */
13683    @ViewDebug.ExportedProperty(category = "drawing")
13684    public float getScaleX() {
13685        return mRenderNode.getScaleX();
13686    }
13687
13688    /**
13689     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
13690     * the view's unscaled width. A value of 1 means that no scaling is applied.
13691     *
13692     * @param scaleX The scaling factor.
13693     * @see #getPivotX()
13694     * @see #getPivotY()
13695     *
13696     * @attr ref android.R.styleable#View_scaleX
13697     */
13698    public void setScaleX(float scaleX) {
13699        if (scaleX != getScaleX()) {
13700            invalidateViewProperty(true, false);
13701            mRenderNode.setScaleX(scaleX);
13702            invalidateViewProperty(false, true);
13703
13704            invalidateParentIfNeededAndWasQuickRejected();
13705            notifySubtreeAccessibilityStateChangedIfNeeded();
13706        }
13707    }
13708
13709    /**
13710     * The amount that the view is scaled in y around the pivot point, as a proportion of
13711     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
13712     *
13713     * <p>By default, this is 1.0f.
13714     *
13715     * @see #getPivotX()
13716     * @see #getPivotY()
13717     * @return The scaling factor.
13718     */
13719    @ViewDebug.ExportedProperty(category = "drawing")
13720    public float getScaleY() {
13721        return mRenderNode.getScaleY();
13722    }
13723
13724    /**
13725     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
13726     * the view's unscaled width. A value of 1 means that no scaling is applied.
13727     *
13728     * @param scaleY The scaling factor.
13729     * @see #getPivotX()
13730     * @see #getPivotY()
13731     *
13732     * @attr ref android.R.styleable#View_scaleY
13733     */
13734    public void setScaleY(float scaleY) {
13735        if (scaleY != getScaleY()) {
13736            invalidateViewProperty(true, false);
13737            mRenderNode.setScaleY(scaleY);
13738            invalidateViewProperty(false, true);
13739
13740            invalidateParentIfNeededAndWasQuickRejected();
13741            notifySubtreeAccessibilityStateChangedIfNeeded();
13742        }
13743    }
13744
13745    /**
13746     * The x location of the point around which the view is {@link #setRotation(float) rotated}
13747     * and {@link #setScaleX(float) scaled}.
13748     *
13749     * @see #getRotation()
13750     * @see #getScaleX()
13751     * @see #getScaleY()
13752     * @see #getPivotY()
13753     * @return The x location of the pivot point.
13754     *
13755     * @attr ref android.R.styleable#View_transformPivotX
13756     */
13757    @ViewDebug.ExportedProperty(category = "drawing")
13758    public float getPivotX() {
13759        return mRenderNode.getPivotX();
13760    }
13761
13762    /**
13763     * Sets the x location of the point around which the view is
13764     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
13765     * By default, the pivot point is centered on the object.
13766     * Setting this property disables this behavior and causes the view to use only the
13767     * explicitly set pivotX and pivotY values.
13768     *
13769     * @param pivotX The x location of the pivot point.
13770     * @see #getRotation()
13771     * @see #getScaleX()
13772     * @see #getScaleY()
13773     * @see #getPivotY()
13774     *
13775     * @attr ref android.R.styleable#View_transformPivotX
13776     */
13777    public void setPivotX(float pivotX) {
13778        if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) {
13779            invalidateViewProperty(true, false);
13780            mRenderNode.setPivotX(pivotX);
13781            invalidateViewProperty(false, true);
13782
13783            invalidateParentIfNeededAndWasQuickRejected();
13784        }
13785    }
13786
13787    /**
13788     * The y location of the point around which the view is {@link #setRotation(float) rotated}
13789     * and {@link #setScaleY(float) scaled}.
13790     *
13791     * @see #getRotation()
13792     * @see #getScaleX()
13793     * @see #getScaleY()
13794     * @see #getPivotY()
13795     * @return The y location of the pivot point.
13796     *
13797     * @attr ref android.R.styleable#View_transformPivotY
13798     */
13799    @ViewDebug.ExportedProperty(category = "drawing")
13800    public float getPivotY() {
13801        return mRenderNode.getPivotY();
13802    }
13803
13804    /**
13805     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
13806     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
13807     * Setting this property disables this behavior and causes the view to use only the
13808     * explicitly set pivotX and pivotY values.
13809     *
13810     * @param pivotY The y location of the pivot point.
13811     * @see #getRotation()
13812     * @see #getScaleX()
13813     * @see #getScaleY()
13814     * @see #getPivotY()
13815     *
13816     * @attr ref android.R.styleable#View_transformPivotY
13817     */
13818    public void setPivotY(float pivotY) {
13819        if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) {
13820            invalidateViewProperty(true, false);
13821            mRenderNode.setPivotY(pivotY);
13822            invalidateViewProperty(false, true);
13823
13824            invalidateParentIfNeededAndWasQuickRejected();
13825        }
13826    }
13827
13828    /**
13829     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
13830     * completely transparent and 1 means the view is completely opaque.
13831     *
13832     * <p>By default this is 1.0f.
13833     * @return The opacity of the view.
13834     */
13835    @ViewDebug.ExportedProperty(category = "drawing")
13836    public float getAlpha() {
13837        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
13838    }
13839
13840    /**
13841     * Sets the behavior for overlapping rendering for this view (see {@link
13842     * #hasOverlappingRendering()} for more details on this behavior). Calling this method
13843     * is an alternative to overriding {@link #hasOverlappingRendering()} in a subclass,
13844     * providing the value which is then used internally. That is, when {@link
13845     * #forceHasOverlappingRendering(boolean)} is called, the value of {@link
13846     * #hasOverlappingRendering()} is ignored and the value passed into this method is used
13847     * instead.
13848     *
13849     * @param hasOverlappingRendering The value for overlapping rendering to be used internally
13850     * instead of that returned by {@link #hasOverlappingRendering()}.
13851     *
13852     * @attr ref android.R.styleable#View_forceHasOverlappingRendering
13853     */
13854    public void forceHasOverlappingRendering(boolean hasOverlappingRendering) {
13855        mPrivateFlags3 |= PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED;
13856        if (hasOverlappingRendering) {
13857            mPrivateFlags3 |= PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE;
13858        } else {
13859            mPrivateFlags3 &= ~PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE;
13860        }
13861    }
13862
13863    /**
13864     * Returns the value for overlapping rendering that is used internally. This is either
13865     * the value passed into {@link #forceHasOverlappingRendering(boolean)}, if called, or
13866     * the return value of {@link #hasOverlappingRendering()}, otherwise.
13867     *
13868     * @return The value for overlapping rendering being used internally.
13869     */
13870    public final boolean getHasOverlappingRendering() {
13871        return (mPrivateFlags3 & PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED) != 0 ?
13872                (mPrivateFlags3 & PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE) != 0 :
13873                hasOverlappingRendering();
13874    }
13875
13876    /**
13877     * Returns whether this View has content which overlaps.
13878     *
13879     * <p>This function, intended to be overridden by specific View types, is an optimization when
13880     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
13881     * an offscreen buffer and then composited into place, which can be expensive. If the view has
13882     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
13883     * directly. An example of overlapping rendering is a TextView with a background image, such as
13884     * a Button. An example of non-overlapping rendering is a TextView with no background, or an
13885     * ImageView with only the foreground image. The default implementation returns true; subclasses
13886     * should override if they have cases which can be optimized.</p>
13887     *
13888     * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas}
13889     * necessitates that a View return true if it uses the methods internally without passing the
13890     * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p>
13891     *
13892     * <p><strong>Note:</strong> The return value of this method is ignored if {@link
13893     * #forceHasOverlappingRendering(boolean)} has been called on this view.</p>
13894     *
13895     * @return true if the content in this view might overlap, false otherwise.
13896     */
13897    @ViewDebug.ExportedProperty(category = "drawing")
13898    public boolean hasOverlappingRendering() {
13899        return true;
13900    }
13901
13902    /**
13903     * Sets the opacity of the view to a value from 0 to 1, where 0 means the view is
13904     * completely transparent and 1 means the view is completely opaque.
13905     *
13906     * <p class="note"><strong>Note:</strong> setting alpha to a translucent value (0 < alpha < 1)
13907     * can have significant performance implications, especially for large views. It is best to use
13908     * the alpha property sparingly and transiently, as in the case of fading animations.</p>
13909     *
13910     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
13911     * strongly recommended for performance reasons to either override
13912     * {@link #hasOverlappingRendering()} to return <code>false</code> if appropriate, or setting a
13913     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view for the duration
13914     * of the animation. On versions {@link android.os.Build.VERSION_CODES#M} and below,
13915     * the default path for rendering an unlayered View with alpha could add multiple milliseconds
13916     * of rendering cost, even for simple or small views. Starting with
13917     * {@link android.os.Build.VERSION_CODES#M}, {@link #LAYER_TYPE_HARDWARE} is automatically
13918     * applied to the view at the rendering level.</p>
13919     *
13920     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
13921     * responsible for applying the opacity itself.</p>
13922     *
13923     * <p>On versions {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} and below, note that if
13924     * the view is backed by a {@link #setLayerType(int, android.graphics.Paint) layer} and is
13925     * associated with a {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an
13926     * alpha value less than 1.0 will supersede the alpha of the layer paint.</p>
13927     *
13928     * <p>Starting with {@link android.os.Build.VERSION_CODES#M}, setting a translucent alpha
13929     * value will clip a View to its bounds, unless the View returns <code>false</code> from
13930     * {@link #hasOverlappingRendering}.</p>
13931     *
13932     * @param alpha The opacity of the view.
13933     *
13934     * @see #hasOverlappingRendering()
13935     * @see #setLayerType(int, android.graphics.Paint)
13936     *
13937     * @attr ref android.R.styleable#View_alpha
13938     */
13939    public void setAlpha(@FloatRange(from=0.0, to=1.0) float alpha) {
13940        ensureTransformationInfo();
13941        if (mTransformationInfo.mAlpha != alpha) {
13942            // Report visibility changes, which can affect children, to accessibility
13943            if ((alpha == 0) ^ (mTransformationInfo.mAlpha == 0)) {
13944                notifySubtreeAccessibilityStateChangedIfNeeded();
13945            }
13946            mTransformationInfo.mAlpha = alpha;
13947            if (onSetAlpha((int) (alpha * 255))) {
13948                mPrivateFlags |= PFLAG_ALPHA_SET;
13949                // subclass is handling alpha - don't optimize rendering cache invalidation
13950                invalidateParentCaches();
13951                invalidate(true);
13952            } else {
13953                mPrivateFlags &= ~PFLAG_ALPHA_SET;
13954                invalidateViewProperty(true, false);
13955                mRenderNode.setAlpha(getFinalAlpha());
13956            }
13957        }
13958    }
13959
13960    /**
13961     * Faster version of setAlpha() which performs the same steps except there are
13962     * no calls to invalidate(). The caller of this function should perform proper invalidation
13963     * on the parent and this object. The return value indicates whether the subclass handles
13964     * alpha (the return value for onSetAlpha()).
13965     *
13966     * @param alpha The new value for the alpha property
13967     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
13968     *         the new value for the alpha property is different from the old value
13969     */
13970    boolean setAlphaNoInvalidation(float alpha) {
13971        ensureTransformationInfo();
13972        if (mTransformationInfo.mAlpha != alpha) {
13973            mTransformationInfo.mAlpha = alpha;
13974            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
13975            if (subclassHandlesAlpha) {
13976                mPrivateFlags |= PFLAG_ALPHA_SET;
13977                return true;
13978            } else {
13979                mPrivateFlags &= ~PFLAG_ALPHA_SET;
13980                mRenderNode.setAlpha(getFinalAlpha());
13981            }
13982        }
13983        return false;
13984    }
13985
13986    /**
13987     * This property is hidden and intended only for use by the Fade transition, which
13988     * animates it to produce a visual translucency that does not side-effect (or get
13989     * affected by) the real alpha property. This value is composited with the other
13990     * alpha value (and the AlphaAnimation value, when that is present) to produce
13991     * a final visual translucency result, which is what is passed into the DisplayList.
13992     *
13993     * @hide
13994     */
13995    public void setTransitionAlpha(float alpha) {
13996        ensureTransformationInfo();
13997        if (mTransformationInfo.mTransitionAlpha != alpha) {
13998            mTransformationInfo.mTransitionAlpha = alpha;
13999            mPrivateFlags &= ~PFLAG_ALPHA_SET;
14000            invalidateViewProperty(true, false);
14001            mRenderNode.setAlpha(getFinalAlpha());
14002        }
14003    }
14004
14005    /**
14006     * Calculates the visual alpha of this view, which is a combination of the actual
14007     * alpha value and the transitionAlpha value (if set).
14008     */
14009    private float getFinalAlpha() {
14010        if (mTransformationInfo != null) {
14011            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
14012        }
14013        return 1;
14014    }
14015
14016    /**
14017     * This property is hidden and intended only for use by the Fade transition, which
14018     * animates it to produce a visual translucency that does not side-effect (or get
14019     * affected by) the real alpha property. This value is composited with the other
14020     * alpha value (and the AlphaAnimation value, when that is present) to produce
14021     * a final visual translucency result, which is what is passed into the DisplayList.
14022     *
14023     * @hide
14024     */
14025    @ViewDebug.ExportedProperty(category = "drawing")
14026    public float getTransitionAlpha() {
14027        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
14028    }
14029
14030    /**
14031     * Top position of this view relative to its parent.
14032     *
14033     * @return The top of this view, in pixels.
14034     */
14035    @ViewDebug.CapturedViewProperty
14036    public final int getTop() {
14037        return mTop;
14038    }
14039
14040    /**
14041     * Sets the top position of this view relative to its parent. This method is meant to be called
14042     * by the layout system and should not generally be called otherwise, because the property
14043     * may be changed at any time by the layout.
14044     *
14045     * @param top The top of this view, in pixels.
14046     */
14047    public final void setTop(int top) {
14048        if (top != mTop) {
14049            final boolean matrixIsIdentity = hasIdentityMatrix();
14050            if (matrixIsIdentity) {
14051                if (mAttachInfo != null) {
14052                    int minTop;
14053                    int yLoc;
14054                    if (top < mTop) {
14055                        minTop = top;
14056                        yLoc = top - mTop;
14057                    } else {
14058                        minTop = mTop;
14059                        yLoc = 0;
14060                    }
14061                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
14062                }
14063            } else {
14064                // Double-invalidation is necessary to capture view's old and new areas
14065                invalidate(true);
14066            }
14067
14068            int width = mRight - mLeft;
14069            int oldHeight = mBottom - mTop;
14070
14071            mTop = top;
14072            mRenderNode.setTop(mTop);
14073
14074            sizeChange(width, mBottom - mTop, width, oldHeight);
14075
14076            if (!matrixIsIdentity) {
14077                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
14078                invalidate(true);
14079            }
14080            mBackgroundSizeChanged = true;
14081            mDefaultFocusHighlightSizeChanged = true;
14082            if (mForegroundInfo != null) {
14083                mForegroundInfo.mBoundsChanged = true;
14084            }
14085            invalidateParentIfNeeded();
14086            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
14087                // View was rejected last time it was drawn by its parent; this may have changed
14088                invalidateParentIfNeeded();
14089            }
14090        }
14091    }
14092
14093    /**
14094     * Bottom position of this view relative to its parent.
14095     *
14096     * @return The bottom of this view, in pixels.
14097     */
14098    @ViewDebug.CapturedViewProperty
14099    public final int getBottom() {
14100        return mBottom;
14101    }
14102
14103    /**
14104     * True if this view has changed since the last time being drawn.
14105     *
14106     * @return The dirty state of this view.
14107     */
14108    public boolean isDirty() {
14109        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
14110    }
14111
14112    /**
14113     * Sets the bottom position of this view relative to its parent. This method is meant to be
14114     * called by the layout system and should not generally be called otherwise, because the
14115     * property may be changed at any time by the layout.
14116     *
14117     * @param bottom The bottom of this view, in pixels.
14118     */
14119    public final void setBottom(int bottom) {
14120        if (bottom != mBottom) {
14121            final boolean matrixIsIdentity = hasIdentityMatrix();
14122            if (matrixIsIdentity) {
14123                if (mAttachInfo != null) {
14124                    int maxBottom;
14125                    if (bottom < mBottom) {
14126                        maxBottom = mBottom;
14127                    } else {
14128                        maxBottom = bottom;
14129                    }
14130                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
14131                }
14132            } else {
14133                // Double-invalidation is necessary to capture view's old and new areas
14134                invalidate(true);
14135            }
14136
14137            int width = mRight - mLeft;
14138            int oldHeight = mBottom - mTop;
14139
14140            mBottom = bottom;
14141            mRenderNode.setBottom(mBottom);
14142
14143            sizeChange(width, mBottom - mTop, width, oldHeight);
14144
14145            if (!matrixIsIdentity) {
14146                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
14147                invalidate(true);
14148            }
14149            mBackgroundSizeChanged = true;
14150            mDefaultFocusHighlightSizeChanged = true;
14151            if (mForegroundInfo != null) {
14152                mForegroundInfo.mBoundsChanged = true;
14153            }
14154            invalidateParentIfNeeded();
14155            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
14156                // View was rejected last time it was drawn by its parent; this may have changed
14157                invalidateParentIfNeeded();
14158            }
14159        }
14160    }
14161
14162    /**
14163     * Left position of this view relative to its parent.
14164     *
14165     * @return The left edge of this view, in pixels.
14166     */
14167    @ViewDebug.CapturedViewProperty
14168    public final int getLeft() {
14169        return mLeft;
14170    }
14171
14172    /**
14173     * Sets the left position of this view relative to its parent. This method is meant to be called
14174     * by the layout system and should not generally be called otherwise, because the property
14175     * may be changed at any time by the layout.
14176     *
14177     * @param left The left of this view, in pixels.
14178     */
14179    public final void setLeft(int left) {
14180        if (left != mLeft) {
14181            final boolean matrixIsIdentity = hasIdentityMatrix();
14182            if (matrixIsIdentity) {
14183                if (mAttachInfo != null) {
14184                    int minLeft;
14185                    int xLoc;
14186                    if (left < mLeft) {
14187                        minLeft = left;
14188                        xLoc = left - mLeft;
14189                    } else {
14190                        minLeft = mLeft;
14191                        xLoc = 0;
14192                    }
14193                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
14194                }
14195            } else {
14196                // Double-invalidation is necessary to capture view's old and new areas
14197                invalidate(true);
14198            }
14199
14200            int oldWidth = mRight - mLeft;
14201            int height = mBottom - mTop;
14202
14203            mLeft = left;
14204            mRenderNode.setLeft(left);
14205
14206            sizeChange(mRight - mLeft, height, oldWidth, height);
14207
14208            if (!matrixIsIdentity) {
14209                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
14210                invalidate(true);
14211            }
14212            mBackgroundSizeChanged = true;
14213            mDefaultFocusHighlightSizeChanged = true;
14214            if (mForegroundInfo != null) {
14215                mForegroundInfo.mBoundsChanged = true;
14216            }
14217            invalidateParentIfNeeded();
14218            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
14219                // View was rejected last time it was drawn by its parent; this may have changed
14220                invalidateParentIfNeeded();
14221            }
14222        }
14223    }
14224
14225    /**
14226     * Right position of this view relative to its parent.
14227     *
14228     * @return The right edge of this view, in pixels.
14229     */
14230    @ViewDebug.CapturedViewProperty
14231    public final int getRight() {
14232        return mRight;
14233    }
14234
14235    /**
14236     * Sets the right position of this view relative to its parent. This method is meant to be called
14237     * by the layout system and should not generally be called otherwise, because the property
14238     * may be changed at any time by the layout.
14239     *
14240     * @param right The right of this view, in pixels.
14241     */
14242    public final void setRight(int right) {
14243        if (right != mRight) {
14244            final boolean matrixIsIdentity = hasIdentityMatrix();
14245            if (matrixIsIdentity) {
14246                if (mAttachInfo != null) {
14247                    int maxRight;
14248                    if (right < mRight) {
14249                        maxRight = mRight;
14250                    } else {
14251                        maxRight = right;
14252                    }
14253                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
14254                }
14255            } else {
14256                // Double-invalidation is necessary to capture view's old and new areas
14257                invalidate(true);
14258            }
14259
14260            int oldWidth = mRight - mLeft;
14261            int height = mBottom - mTop;
14262
14263            mRight = right;
14264            mRenderNode.setRight(mRight);
14265
14266            sizeChange(mRight - mLeft, height, oldWidth, height);
14267
14268            if (!matrixIsIdentity) {
14269                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
14270                invalidate(true);
14271            }
14272            mBackgroundSizeChanged = true;
14273            mDefaultFocusHighlightSizeChanged = true;
14274            if (mForegroundInfo != null) {
14275                mForegroundInfo.mBoundsChanged = true;
14276            }
14277            invalidateParentIfNeeded();
14278            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
14279                // View was rejected last time it was drawn by its parent; this may have changed
14280                invalidateParentIfNeeded();
14281            }
14282        }
14283    }
14284
14285    /**
14286     * The visual x position of this view, in pixels. This is equivalent to the
14287     * {@link #setTranslationX(float) translationX} property plus the current
14288     * {@link #getLeft() left} property.
14289     *
14290     * @return The visual x position of this view, in pixels.
14291     */
14292    @ViewDebug.ExportedProperty(category = "drawing")
14293    public float getX() {
14294        return mLeft + getTranslationX();
14295    }
14296
14297    /**
14298     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
14299     * {@link #setTranslationX(float) translationX} property to be the difference between
14300     * the x value passed in and the current {@link #getLeft() left} property.
14301     *
14302     * @param x The visual x position of this view, in pixels.
14303     */
14304    public void setX(float x) {
14305        setTranslationX(x - mLeft);
14306    }
14307
14308    /**
14309     * The visual y position of this view, in pixels. This is equivalent to the
14310     * {@link #setTranslationY(float) translationY} property plus the current
14311     * {@link #getTop() top} property.
14312     *
14313     * @return The visual y position of this view, in pixels.
14314     */
14315    @ViewDebug.ExportedProperty(category = "drawing")
14316    public float getY() {
14317        return mTop + getTranslationY();
14318    }
14319
14320    /**
14321     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
14322     * {@link #setTranslationY(float) translationY} property to be the difference between
14323     * the y value passed in and the current {@link #getTop() top} property.
14324     *
14325     * @param y The visual y position of this view, in pixels.
14326     */
14327    public void setY(float y) {
14328        setTranslationY(y - mTop);
14329    }
14330
14331    /**
14332     * The visual z position of this view, in pixels. This is equivalent to the
14333     * {@link #setTranslationZ(float) translationZ} property plus the current
14334     * {@link #getElevation() elevation} property.
14335     *
14336     * @return The visual z position of this view, in pixels.
14337     */
14338    @ViewDebug.ExportedProperty(category = "drawing")
14339    public float getZ() {
14340        return getElevation() + getTranslationZ();
14341    }
14342
14343    /**
14344     * Sets the visual z position of this view, in pixels. This is equivalent to setting the
14345     * {@link #setTranslationZ(float) translationZ} property to be the difference between
14346     * the x value passed in and the current {@link #getElevation() elevation} property.
14347     *
14348     * @param z The visual z position of this view, in pixels.
14349     */
14350    public void setZ(float z) {
14351        setTranslationZ(z - getElevation());
14352    }
14353
14354    /**
14355     * The base elevation of this view relative to its parent, in pixels.
14356     *
14357     * @return The base depth position of the view, in pixels.
14358     */
14359    @ViewDebug.ExportedProperty(category = "drawing")
14360    public float getElevation() {
14361        return mRenderNode.getElevation();
14362    }
14363
14364    /**
14365     * Sets the base elevation of this view, in pixels.
14366     *
14367     * @attr ref android.R.styleable#View_elevation
14368     */
14369    public void setElevation(float elevation) {
14370        if (elevation != getElevation()) {
14371            invalidateViewProperty(true, false);
14372            mRenderNode.setElevation(elevation);
14373            invalidateViewProperty(false, true);
14374
14375            invalidateParentIfNeededAndWasQuickRejected();
14376        }
14377    }
14378
14379    /**
14380     * The horizontal location of this view relative to its {@link #getLeft() left} position.
14381     * This position is post-layout, in addition to wherever the object's
14382     * layout placed it.
14383     *
14384     * @return The horizontal position of this view relative to its left position, in pixels.
14385     */
14386    @ViewDebug.ExportedProperty(category = "drawing")
14387    public float getTranslationX() {
14388        return mRenderNode.getTranslationX();
14389    }
14390
14391    /**
14392     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
14393     * This effectively positions the object post-layout, in addition to wherever the object's
14394     * layout placed it.
14395     *
14396     * @param translationX The horizontal position of this view relative to its left position,
14397     * in pixels.
14398     *
14399     * @attr ref android.R.styleable#View_translationX
14400     */
14401    public void setTranslationX(float translationX) {
14402        if (translationX != getTranslationX()) {
14403            invalidateViewProperty(true, false);
14404            mRenderNode.setTranslationX(translationX);
14405            invalidateViewProperty(false, true);
14406
14407            invalidateParentIfNeededAndWasQuickRejected();
14408            notifySubtreeAccessibilityStateChangedIfNeeded();
14409        }
14410    }
14411
14412    /**
14413     * The vertical location of this view relative to its {@link #getTop() top} position.
14414     * This position is post-layout, in addition to wherever the object's
14415     * layout placed it.
14416     *
14417     * @return The vertical position of this view relative to its top position,
14418     * in pixels.
14419     */
14420    @ViewDebug.ExportedProperty(category = "drawing")
14421    public float getTranslationY() {
14422        return mRenderNode.getTranslationY();
14423    }
14424
14425    /**
14426     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
14427     * This effectively positions the object post-layout, in addition to wherever the object's
14428     * layout placed it.
14429     *
14430     * @param translationY The vertical position of this view relative to its top position,
14431     * in pixels.
14432     *
14433     * @attr ref android.R.styleable#View_translationY
14434     */
14435    public void setTranslationY(float translationY) {
14436        if (translationY != getTranslationY()) {
14437            invalidateViewProperty(true, false);
14438            mRenderNode.setTranslationY(translationY);
14439            invalidateViewProperty(false, true);
14440
14441            invalidateParentIfNeededAndWasQuickRejected();
14442            notifySubtreeAccessibilityStateChangedIfNeeded();
14443        }
14444    }
14445
14446    /**
14447     * The depth location of this view relative to its {@link #getElevation() elevation}.
14448     *
14449     * @return The depth of this view relative to its elevation.
14450     */
14451    @ViewDebug.ExportedProperty(category = "drawing")
14452    public float getTranslationZ() {
14453        return mRenderNode.getTranslationZ();
14454    }
14455
14456    /**
14457     * Sets the depth location of this view relative to its {@link #getElevation() elevation}.
14458     *
14459     * @attr ref android.R.styleable#View_translationZ
14460     */
14461    public void setTranslationZ(float translationZ) {
14462        if (translationZ != getTranslationZ()) {
14463            invalidateViewProperty(true, false);
14464            mRenderNode.setTranslationZ(translationZ);
14465            invalidateViewProperty(false, true);
14466
14467            invalidateParentIfNeededAndWasQuickRejected();
14468        }
14469    }
14470
14471    /** @hide */
14472    public void setAnimationMatrix(Matrix matrix) {
14473        invalidateViewProperty(true, false);
14474        mRenderNode.setAnimationMatrix(matrix);
14475        invalidateViewProperty(false, true);
14476
14477        invalidateParentIfNeededAndWasQuickRejected();
14478    }
14479
14480    /**
14481     * Returns the current StateListAnimator if exists.
14482     *
14483     * @return StateListAnimator or null if it does not exists
14484     * @see    #setStateListAnimator(android.animation.StateListAnimator)
14485     */
14486    public StateListAnimator getStateListAnimator() {
14487        return mStateListAnimator;
14488    }
14489
14490    /**
14491     * Attaches the provided StateListAnimator to this View.
14492     * <p>
14493     * Any previously attached StateListAnimator will be detached.
14494     *
14495     * @param stateListAnimator The StateListAnimator to update the view
14496     * @see android.animation.StateListAnimator
14497     */
14498    public void setStateListAnimator(StateListAnimator stateListAnimator) {
14499        if (mStateListAnimator == stateListAnimator) {
14500            return;
14501        }
14502        if (mStateListAnimator != null) {
14503            mStateListAnimator.setTarget(null);
14504        }
14505        mStateListAnimator = stateListAnimator;
14506        if (stateListAnimator != null) {
14507            stateListAnimator.setTarget(this);
14508            if (isAttachedToWindow()) {
14509                stateListAnimator.setState(getDrawableState());
14510            }
14511        }
14512    }
14513
14514    /**
14515     * Returns whether the Outline should be used to clip the contents of the View.
14516     * <p>
14517     * Note that this flag will only be respected if the View's Outline returns true from
14518     * {@link Outline#canClip()}.
14519     *
14520     * @see #setOutlineProvider(ViewOutlineProvider)
14521     * @see #setClipToOutline(boolean)
14522     */
14523    public final boolean getClipToOutline() {
14524        return mRenderNode.getClipToOutline();
14525    }
14526
14527    /**
14528     * Sets whether the View's Outline should be used to clip the contents of the View.
14529     * <p>
14530     * Only a single non-rectangular clip can be applied on a View at any time.
14531     * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float)
14532     * circular reveal} animation take priority over Outline clipping, and
14533     * child Outline clipping takes priority over Outline clipping done by a
14534     * parent.
14535     * <p>
14536     * Note that this flag will only be respected if the View's Outline returns true from
14537     * {@link Outline#canClip()}.
14538     *
14539     * @see #setOutlineProvider(ViewOutlineProvider)
14540     * @see #getClipToOutline()
14541     */
14542    public void setClipToOutline(boolean clipToOutline) {
14543        damageInParent();
14544        if (getClipToOutline() != clipToOutline) {
14545            mRenderNode.setClipToOutline(clipToOutline);
14546        }
14547    }
14548
14549    // correspond to the enum values of View_outlineProvider
14550    private static final int PROVIDER_BACKGROUND = 0;
14551    private static final int PROVIDER_NONE = 1;
14552    private static final int PROVIDER_BOUNDS = 2;
14553    private static final int PROVIDER_PADDED_BOUNDS = 3;
14554    private void setOutlineProviderFromAttribute(int providerInt) {
14555        switch (providerInt) {
14556            case PROVIDER_BACKGROUND:
14557                setOutlineProvider(ViewOutlineProvider.BACKGROUND);
14558                break;
14559            case PROVIDER_NONE:
14560                setOutlineProvider(null);
14561                break;
14562            case PROVIDER_BOUNDS:
14563                setOutlineProvider(ViewOutlineProvider.BOUNDS);
14564                break;
14565            case PROVIDER_PADDED_BOUNDS:
14566                setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS);
14567                break;
14568        }
14569    }
14570
14571    /**
14572     * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines
14573     * the shape of the shadow it casts, and enables outline clipping.
14574     * <p>
14575     * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline
14576     * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the
14577     * outline provider with this method allows this behavior to be overridden.
14578     * <p>
14579     * If the ViewOutlineProvider is null, if querying it for an outline returns false,
14580     * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast.
14581     * <p>
14582     * Only outlines that return true from {@link Outline#canClip()} may be used for clipping.
14583     *
14584     * @see #setClipToOutline(boolean)
14585     * @see #getClipToOutline()
14586     * @see #getOutlineProvider()
14587     */
14588    public void setOutlineProvider(ViewOutlineProvider provider) {
14589        mOutlineProvider = provider;
14590        invalidateOutline();
14591    }
14592
14593    /**
14594     * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline
14595     * that defines the shape of the shadow it casts, and enables outline clipping.
14596     *
14597     * @see #setOutlineProvider(ViewOutlineProvider)
14598     */
14599    public ViewOutlineProvider getOutlineProvider() {
14600        return mOutlineProvider;
14601    }
14602
14603    /**
14604     * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider}
14605     *
14606     * @see #setOutlineProvider(ViewOutlineProvider)
14607     */
14608    public void invalidateOutline() {
14609        rebuildOutline();
14610
14611        notifySubtreeAccessibilityStateChangedIfNeeded();
14612        invalidateViewProperty(false, false);
14613    }
14614
14615    /**
14616     * Internal version of {@link #invalidateOutline()} which invalidates the
14617     * outline without invalidating the view itself. This is intended to be called from
14618     * within methods in the View class itself which are the result of the view being
14619     * invalidated already. For example, when we are drawing the background of a View,
14620     * we invalidate the outline in case it changed in the meantime, but we do not
14621     * need to invalidate the view because we're already drawing the background as part
14622     * of drawing the view in response to an earlier invalidation of the view.
14623     */
14624    private void rebuildOutline() {
14625        // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow()
14626        if (mAttachInfo == null) return;
14627
14628        if (mOutlineProvider == null) {
14629            // no provider, remove outline
14630            mRenderNode.setOutline(null);
14631        } else {
14632            final Outline outline = mAttachInfo.mTmpOutline;
14633            outline.setEmpty();
14634            outline.setAlpha(1.0f);
14635
14636            mOutlineProvider.getOutline(this, outline);
14637            mRenderNode.setOutline(outline);
14638        }
14639    }
14640
14641    /**
14642     * HierarchyViewer only
14643     *
14644     * @hide
14645     */
14646    @ViewDebug.ExportedProperty(category = "drawing")
14647    public boolean hasShadow() {
14648        return mRenderNode.hasShadow();
14649    }
14650
14651
14652    /** @hide */
14653    public void setRevealClip(boolean shouldClip, float x, float y, float radius) {
14654        mRenderNode.setRevealClip(shouldClip, x, y, radius);
14655        invalidateViewProperty(false, false);
14656    }
14657
14658    /**
14659     * Hit rectangle in parent's coordinates
14660     *
14661     * @param outRect The hit rectangle of the view.
14662     */
14663    public void getHitRect(Rect outRect) {
14664        if (hasIdentityMatrix() || mAttachInfo == null) {
14665            outRect.set(mLeft, mTop, mRight, mBottom);
14666        } else {
14667            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
14668            tmpRect.set(0, 0, getWidth(), getHeight());
14669            getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect)
14670            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
14671                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
14672        }
14673    }
14674
14675    /**
14676     * Determines whether the given point, in local coordinates is inside the view.
14677     */
14678    /*package*/ final boolean pointInView(float localX, float localY) {
14679        return pointInView(localX, localY, 0);
14680    }
14681
14682    /**
14683     * Utility method to determine whether the given point, in local coordinates,
14684     * is inside the view, where the area of the view is expanded by the slop factor.
14685     * This method is called while processing touch-move events to determine if the event
14686     * is still within the view.
14687     *
14688     * @hide
14689     */
14690    public boolean pointInView(float localX, float localY, float slop) {
14691        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
14692                localY < ((mBottom - mTop) + slop);
14693    }
14694
14695    /**
14696     * When a view has focus and the user navigates away from it, the next view is searched for
14697     * starting from the rectangle filled in by this method.
14698     *
14699     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
14700     * of the view.  However, if your view maintains some idea of internal selection,
14701     * such as a cursor, or a selected row or column, you should override this method and
14702     * fill in a more specific rectangle.
14703     *
14704     * @param r The rectangle to fill in, in this view's coordinates.
14705     */
14706    public void getFocusedRect(Rect r) {
14707        getDrawingRect(r);
14708    }
14709
14710    /**
14711     * If some part of this view is not clipped by any of its parents, then
14712     * return that area in r in global (root) coordinates. To convert r to local
14713     * coordinates (without taking possible View rotations into account), offset
14714     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
14715     * If the view is completely clipped or translated out, return false.
14716     *
14717     * @param r If true is returned, r holds the global coordinates of the
14718     *        visible portion of this view.
14719     * @param globalOffset If true is returned, globalOffset holds the dx,dy
14720     *        between this view and its root. globalOffet may be null.
14721     * @return true if r is non-empty (i.e. part of the view is visible at the
14722     *         root level.
14723     */
14724    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
14725        int width = mRight - mLeft;
14726        int height = mBottom - mTop;
14727        if (width > 0 && height > 0) {
14728            r.set(0, 0, width, height);
14729            if (globalOffset != null) {
14730                globalOffset.set(-mScrollX, -mScrollY);
14731            }
14732            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
14733        }
14734        return false;
14735    }
14736
14737    public final boolean getGlobalVisibleRect(Rect r) {
14738        return getGlobalVisibleRect(r, null);
14739    }
14740
14741    public final boolean getLocalVisibleRect(Rect r) {
14742        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
14743        if (getGlobalVisibleRect(r, offset)) {
14744            r.offset(-offset.x, -offset.y); // make r local
14745            return true;
14746        }
14747        return false;
14748    }
14749
14750    /**
14751     * Offset this view's vertical location by the specified number of pixels.
14752     *
14753     * @param offset the number of pixels to offset the view by
14754     */
14755    public void offsetTopAndBottom(int offset) {
14756        if (offset != 0) {
14757            final boolean matrixIsIdentity = hasIdentityMatrix();
14758            if (matrixIsIdentity) {
14759                if (isHardwareAccelerated()) {
14760                    invalidateViewProperty(false, false);
14761                } else {
14762                    final ViewParent p = mParent;
14763                    if (p != null && mAttachInfo != null) {
14764                        final Rect r = mAttachInfo.mTmpInvalRect;
14765                        int minTop;
14766                        int maxBottom;
14767                        int yLoc;
14768                        if (offset < 0) {
14769                            minTop = mTop + offset;
14770                            maxBottom = mBottom;
14771                            yLoc = offset;
14772                        } else {
14773                            minTop = mTop;
14774                            maxBottom = mBottom + offset;
14775                            yLoc = 0;
14776                        }
14777                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
14778                        p.invalidateChild(this, r);
14779                    }
14780                }
14781            } else {
14782                invalidateViewProperty(false, false);
14783            }
14784
14785            mTop += offset;
14786            mBottom += offset;
14787            mRenderNode.offsetTopAndBottom(offset);
14788            if (isHardwareAccelerated()) {
14789                invalidateViewProperty(false, false);
14790                invalidateParentIfNeededAndWasQuickRejected();
14791            } else {
14792                if (!matrixIsIdentity) {
14793                    invalidateViewProperty(false, true);
14794                }
14795                invalidateParentIfNeeded();
14796            }
14797            notifySubtreeAccessibilityStateChangedIfNeeded();
14798        }
14799    }
14800
14801    /**
14802     * Offset this view's horizontal location by the specified amount of pixels.
14803     *
14804     * @param offset the number of pixels to offset the view by
14805     */
14806    public void offsetLeftAndRight(int offset) {
14807        if (offset != 0) {
14808            final boolean matrixIsIdentity = hasIdentityMatrix();
14809            if (matrixIsIdentity) {
14810                if (isHardwareAccelerated()) {
14811                    invalidateViewProperty(false, false);
14812                } else {
14813                    final ViewParent p = mParent;
14814                    if (p != null && mAttachInfo != null) {
14815                        final Rect r = mAttachInfo.mTmpInvalRect;
14816                        int minLeft;
14817                        int maxRight;
14818                        if (offset < 0) {
14819                            minLeft = mLeft + offset;
14820                            maxRight = mRight;
14821                        } else {
14822                            minLeft = mLeft;
14823                            maxRight = mRight + offset;
14824                        }
14825                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
14826                        p.invalidateChild(this, r);
14827                    }
14828                }
14829            } else {
14830                invalidateViewProperty(false, false);
14831            }
14832
14833            mLeft += offset;
14834            mRight += offset;
14835            mRenderNode.offsetLeftAndRight(offset);
14836            if (isHardwareAccelerated()) {
14837                invalidateViewProperty(false, false);
14838                invalidateParentIfNeededAndWasQuickRejected();
14839            } else {
14840                if (!matrixIsIdentity) {
14841                    invalidateViewProperty(false, true);
14842                }
14843                invalidateParentIfNeeded();
14844            }
14845            notifySubtreeAccessibilityStateChangedIfNeeded();
14846        }
14847    }
14848
14849    /**
14850     * Get the LayoutParams associated with this view. All views should have
14851     * layout parameters. These supply parameters to the <i>parent</i> of this
14852     * view specifying how it should be arranged. There are many subclasses of
14853     * ViewGroup.LayoutParams, and these correspond to the different subclasses
14854     * of ViewGroup that are responsible for arranging their children.
14855     *
14856     * This method may return null if this View is not attached to a parent
14857     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
14858     * was not invoked successfully. When a View is attached to a parent
14859     * ViewGroup, this method must not return null.
14860     *
14861     * @return The LayoutParams associated with this view, or null if no
14862     *         parameters have been set yet
14863     */
14864    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
14865    public ViewGroup.LayoutParams getLayoutParams() {
14866        return mLayoutParams;
14867    }
14868
14869    /**
14870     * Set the layout parameters associated with this view. These supply
14871     * parameters to the <i>parent</i> of this view specifying how it should be
14872     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
14873     * correspond to the different subclasses of ViewGroup that are responsible
14874     * for arranging their children.
14875     *
14876     * @param params The layout parameters for this view, cannot be null
14877     */
14878    public void setLayoutParams(ViewGroup.LayoutParams params) {
14879        if (params == null) {
14880            throw new NullPointerException("Layout parameters cannot be null");
14881        }
14882        mLayoutParams = params;
14883        resolveLayoutParams();
14884        if (mParent instanceof ViewGroup) {
14885            ((ViewGroup) mParent).onSetLayoutParams(this, params);
14886        }
14887        requestLayout();
14888    }
14889
14890    /**
14891     * Resolve the layout parameters depending on the resolved layout direction
14892     *
14893     * @hide
14894     */
14895    public void resolveLayoutParams() {
14896        if (mLayoutParams != null) {
14897            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
14898        }
14899    }
14900
14901    /**
14902     * Set the scrolled position of your view. This will cause a call to
14903     * {@link #onScrollChanged(int, int, int, int)} and the view will be
14904     * invalidated.
14905     * @param x the x position to scroll to
14906     * @param y the y position to scroll to
14907     */
14908    public void scrollTo(int x, int y) {
14909        if (mScrollX != x || mScrollY != y) {
14910            int oldX = mScrollX;
14911            int oldY = mScrollY;
14912            mScrollX = x;
14913            mScrollY = y;
14914            invalidateParentCaches();
14915            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
14916            if (!awakenScrollBars()) {
14917                postInvalidateOnAnimation();
14918            }
14919        }
14920    }
14921
14922    /**
14923     * Move the scrolled position of your view. This will cause a call to
14924     * {@link #onScrollChanged(int, int, int, int)} and the view will be
14925     * invalidated.
14926     * @param x the amount of pixels to scroll by horizontally
14927     * @param y the amount of pixels to scroll by vertically
14928     */
14929    public void scrollBy(int x, int y) {
14930        scrollTo(mScrollX + x, mScrollY + y);
14931    }
14932
14933    /**
14934     * <p>Trigger the scrollbars to draw. When invoked this method starts an
14935     * animation to fade the scrollbars out after a default delay. If a subclass
14936     * provides animated scrolling, the start delay should equal the duration
14937     * of the scrolling animation.</p>
14938     *
14939     * <p>The animation starts only if at least one of the scrollbars is
14940     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
14941     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
14942     * this method returns true, and false otherwise. If the animation is
14943     * started, this method calls {@link #invalidate()}; in that case the
14944     * caller should not call {@link #invalidate()}.</p>
14945     *
14946     * <p>This method should be invoked every time a subclass directly updates
14947     * the scroll parameters.</p>
14948     *
14949     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
14950     * and {@link #scrollTo(int, int)}.</p>
14951     *
14952     * @return true if the animation is played, false otherwise
14953     *
14954     * @see #awakenScrollBars(int)
14955     * @see #scrollBy(int, int)
14956     * @see #scrollTo(int, int)
14957     * @see #isHorizontalScrollBarEnabled()
14958     * @see #isVerticalScrollBarEnabled()
14959     * @see #setHorizontalScrollBarEnabled(boolean)
14960     * @see #setVerticalScrollBarEnabled(boolean)
14961     */
14962    protected boolean awakenScrollBars() {
14963        return mScrollCache != null &&
14964                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
14965    }
14966
14967    /**
14968     * Trigger the scrollbars to draw.
14969     * This method differs from awakenScrollBars() only in its default duration.
14970     * initialAwakenScrollBars() will show the scroll bars for longer than
14971     * usual to give the user more of a chance to notice them.
14972     *
14973     * @return true if the animation is played, false otherwise.
14974     */
14975    private boolean initialAwakenScrollBars() {
14976        return mScrollCache != null &&
14977                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
14978    }
14979
14980    /**
14981     * <p>
14982     * Trigger the scrollbars to draw. When invoked this method starts an
14983     * animation to fade the scrollbars out after a fixed delay. If a subclass
14984     * provides animated scrolling, the start delay should equal the duration of
14985     * the scrolling animation.
14986     * </p>
14987     *
14988     * <p>
14989     * The animation starts only if at least one of the scrollbars is enabled,
14990     * as specified by {@link #isHorizontalScrollBarEnabled()} and
14991     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
14992     * this method returns true, and false otherwise. If the animation is
14993     * started, this method calls {@link #invalidate()}; in that case the caller
14994     * should not call {@link #invalidate()}.
14995     * </p>
14996     *
14997     * <p>
14998     * This method should be invoked every time a subclass directly updates the
14999     * scroll parameters.
15000     * </p>
15001     *
15002     * @param startDelay the delay, in milliseconds, after which the animation
15003     *        should start; when the delay is 0, the animation starts
15004     *        immediately
15005     * @return true if the animation is played, false otherwise
15006     *
15007     * @see #scrollBy(int, int)
15008     * @see #scrollTo(int, int)
15009     * @see #isHorizontalScrollBarEnabled()
15010     * @see #isVerticalScrollBarEnabled()
15011     * @see #setHorizontalScrollBarEnabled(boolean)
15012     * @see #setVerticalScrollBarEnabled(boolean)
15013     */
15014    protected boolean awakenScrollBars(int startDelay) {
15015        return awakenScrollBars(startDelay, true);
15016    }
15017
15018    /**
15019     * <p>
15020     * Trigger the scrollbars to draw. When invoked this method starts an
15021     * animation to fade the scrollbars out after a fixed delay. If a subclass
15022     * provides animated scrolling, the start delay should equal the duration of
15023     * the scrolling animation.
15024     * </p>
15025     *
15026     * <p>
15027     * The animation starts only if at least one of the scrollbars is enabled,
15028     * as specified by {@link #isHorizontalScrollBarEnabled()} and
15029     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
15030     * this method returns true, and false otherwise. If the animation is
15031     * started, this method calls {@link #invalidate()} if the invalidate parameter
15032     * is set to true; in that case the caller
15033     * should not call {@link #invalidate()}.
15034     * </p>
15035     *
15036     * <p>
15037     * This method should be invoked every time a subclass directly updates the
15038     * scroll parameters.
15039     * </p>
15040     *
15041     * @param startDelay the delay, in milliseconds, after which the animation
15042     *        should start; when the delay is 0, the animation starts
15043     *        immediately
15044     *
15045     * @param invalidate Whether this method should call invalidate
15046     *
15047     * @return true if the animation is played, false otherwise
15048     *
15049     * @see #scrollBy(int, int)
15050     * @see #scrollTo(int, int)
15051     * @see #isHorizontalScrollBarEnabled()
15052     * @see #isVerticalScrollBarEnabled()
15053     * @see #setHorizontalScrollBarEnabled(boolean)
15054     * @see #setVerticalScrollBarEnabled(boolean)
15055     */
15056    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
15057        final ScrollabilityCache scrollCache = mScrollCache;
15058
15059        if (scrollCache == null || !scrollCache.fadeScrollBars) {
15060            return false;
15061        }
15062
15063        if (scrollCache.scrollBar == null) {
15064            scrollCache.scrollBar = new ScrollBarDrawable();
15065            scrollCache.scrollBar.setState(getDrawableState());
15066            scrollCache.scrollBar.setCallback(this);
15067        }
15068
15069        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
15070
15071            if (invalidate) {
15072                // Invalidate to show the scrollbars
15073                postInvalidateOnAnimation();
15074            }
15075
15076            if (scrollCache.state == ScrollabilityCache.OFF) {
15077                // FIXME: this is copied from WindowManagerService.
15078                // We should get this value from the system when it
15079                // is possible to do so.
15080                final int KEY_REPEAT_FIRST_DELAY = 750;
15081                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
15082            }
15083
15084            // Tell mScrollCache when we should start fading. This may
15085            // extend the fade start time if one was already scheduled
15086            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
15087            scrollCache.fadeStartTime = fadeStartTime;
15088            scrollCache.state = ScrollabilityCache.ON;
15089
15090            // Schedule our fader to run, unscheduling any old ones first
15091            if (mAttachInfo != null) {
15092                mAttachInfo.mHandler.removeCallbacks(scrollCache);
15093                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
15094            }
15095
15096            return true;
15097        }
15098
15099        return false;
15100    }
15101
15102    /**
15103     * Do not invalidate views which are not visible and which are not running an animation. They
15104     * will not get drawn and they should not set dirty flags as if they will be drawn
15105     */
15106    private boolean skipInvalidate() {
15107        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
15108                (!(mParent instanceof ViewGroup) ||
15109                        !((ViewGroup) mParent).isViewTransitioning(this));
15110    }
15111
15112    /**
15113     * Mark the area defined by dirty as needing to be drawn. If the view is
15114     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
15115     * point in the future.
15116     * <p>
15117     * This must be called from a UI thread. To call from a non-UI thread, call
15118     * {@link #postInvalidate()}.
15119     * <p>
15120     * <b>WARNING:</b> In API 19 and below, this method may be destructive to
15121     * {@code dirty}.
15122     *
15123     * @param dirty the rectangle representing the bounds of the dirty region
15124     */
15125    public void invalidate(Rect dirty) {
15126        final int scrollX = mScrollX;
15127        final int scrollY = mScrollY;
15128        invalidateInternal(dirty.left - scrollX, dirty.top - scrollY,
15129                dirty.right - scrollX, dirty.bottom - scrollY, true, false);
15130    }
15131
15132    /**
15133     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The
15134     * coordinates of the dirty rect are relative to the view. If the view is
15135     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
15136     * point in the future.
15137     * <p>
15138     * This must be called from a UI thread. To call from a non-UI thread, call
15139     * {@link #postInvalidate()}.
15140     *
15141     * @param l the left position of the dirty region
15142     * @param t the top position of the dirty region
15143     * @param r the right position of the dirty region
15144     * @param b the bottom position of the dirty region
15145     */
15146    public void invalidate(int l, int t, int r, int b) {
15147        final int scrollX = mScrollX;
15148        final int scrollY = mScrollY;
15149        invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false);
15150    }
15151
15152    /**
15153     * Invalidate the whole view. If the view is visible,
15154     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
15155     * the future.
15156     * <p>
15157     * This must be called from a UI thread. To call from a non-UI thread, call
15158     * {@link #postInvalidate()}.
15159     */
15160    public void invalidate() {
15161        invalidate(true);
15162    }
15163
15164    /**
15165     * This is where the invalidate() work actually happens. A full invalidate()
15166     * causes the drawing cache to be invalidated, but this function can be
15167     * called with invalidateCache set to false to skip that invalidation step
15168     * for cases that do not need it (for example, a component that remains at
15169     * the same dimensions with the same content).
15170     *
15171     * @param invalidateCache Whether the drawing cache for this view should be
15172     *            invalidated as well. This is usually true for a full
15173     *            invalidate, but may be set to false if the View's contents or
15174     *            dimensions have not changed.
15175     * @hide
15176     */
15177    public void invalidate(boolean invalidateCache) {
15178        invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
15179    }
15180
15181    void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
15182            boolean fullInvalidate) {
15183        if (mGhostView != null) {
15184            mGhostView.invalidate(true);
15185            return;
15186        }
15187
15188        if (skipInvalidate()) {
15189            return;
15190        }
15191
15192        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)
15193                || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID)
15194                || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED
15195                || (fullInvalidate && isOpaque() != mLastIsOpaque)) {
15196            if (fullInvalidate) {
15197                mLastIsOpaque = isOpaque();
15198                mPrivateFlags &= ~PFLAG_DRAWN;
15199            }
15200
15201            mPrivateFlags |= PFLAG_DIRTY;
15202
15203            if (invalidateCache) {
15204                mPrivateFlags |= PFLAG_INVALIDATED;
15205                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
15206            }
15207
15208            // Propagate the damage rectangle to the parent view.
15209            final AttachInfo ai = mAttachInfo;
15210            final ViewParent p = mParent;
15211            if (p != null && ai != null && l < r && t < b) {
15212                final Rect damage = ai.mTmpInvalRect;
15213                damage.set(l, t, r, b);
15214                p.invalidateChild(this, damage);
15215            }
15216
15217            // Damage the entire projection receiver, if necessary.
15218            if (mBackground != null && mBackground.isProjected()) {
15219                final View receiver = getProjectionReceiver();
15220                if (receiver != null) {
15221                    receiver.damageInParent();
15222                }
15223            }
15224        }
15225    }
15226
15227    /**
15228     * @return this view's projection receiver, or {@code null} if none exists
15229     */
15230    private View getProjectionReceiver() {
15231        ViewParent p = getParent();
15232        while (p != null && p instanceof View) {
15233            final View v = (View) p;
15234            if (v.isProjectionReceiver()) {
15235                return v;
15236            }
15237            p = p.getParent();
15238        }
15239
15240        return null;
15241    }
15242
15243    /**
15244     * @return whether the view is a projection receiver
15245     */
15246    private boolean isProjectionReceiver() {
15247        return mBackground != null;
15248    }
15249
15250    /**
15251     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
15252     * set any flags or handle all of the cases handled by the default invalidation methods.
15253     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
15254     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
15255     * walk up the hierarchy, transforming the dirty rect as necessary.
15256     *
15257     * The method also handles normal invalidation logic if display list properties are not
15258     * being used in this view. The invalidateParent and forceRedraw flags are used by that
15259     * backup approach, to handle these cases used in the various property-setting methods.
15260     *
15261     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
15262     * are not being used in this view
15263     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
15264     * list properties are not being used in this view
15265     */
15266    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
15267        if (!isHardwareAccelerated()
15268                || !mRenderNode.isValid()
15269                || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) {
15270            if (invalidateParent) {
15271                invalidateParentCaches();
15272            }
15273            if (forceRedraw) {
15274                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
15275            }
15276            invalidate(false);
15277        } else {
15278            damageInParent();
15279        }
15280    }
15281
15282    /**
15283     * Tells the parent view to damage this view's bounds.
15284     *
15285     * @hide
15286     */
15287    protected void damageInParent() {
15288        if (mParent != null && mAttachInfo != null) {
15289            mParent.onDescendantInvalidated(this, this);
15290        }
15291    }
15292
15293    /**
15294     * Utility method to transform a given Rect by the current matrix of this view.
15295     */
15296    void transformRect(final Rect rect) {
15297        if (!getMatrix().isIdentity()) {
15298            RectF boundingRect = mAttachInfo.mTmpTransformRect;
15299            boundingRect.set(rect);
15300            getMatrix().mapRect(boundingRect);
15301            rect.set((int) Math.floor(boundingRect.left),
15302                    (int) Math.floor(boundingRect.top),
15303                    (int) Math.ceil(boundingRect.right),
15304                    (int) Math.ceil(boundingRect.bottom));
15305        }
15306    }
15307
15308    /**
15309     * Used to indicate that the parent of this view should clear its caches. This functionality
15310     * is used to force the parent to rebuild its display list (when hardware-accelerated),
15311     * which is necessary when various parent-managed properties of the view change, such as
15312     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
15313     * clears the parent caches and does not causes an invalidate event.
15314     *
15315     * @hide
15316     */
15317    protected void invalidateParentCaches() {
15318        if (mParent instanceof View) {
15319            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
15320        }
15321    }
15322
15323    /**
15324     * Used to indicate that the parent of this view should be invalidated. This functionality
15325     * is used to force the parent to rebuild its display list (when hardware-accelerated),
15326     * which is necessary when various parent-managed properties of the view change, such as
15327     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
15328     * an invalidation event to the parent.
15329     *
15330     * @hide
15331     */
15332    protected void invalidateParentIfNeeded() {
15333        if (isHardwareAccelerated() && mParent instanceof View) {
15334            ((View) mParent).invalidate(true);
15335        }
15336    }
15337
15338    /**
15339     * @hide
15340     */
15341    protected void invalidateParentIfNeededAndWasQuickRejected() {
15342        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) {
15343            // View was rejected last time it was drawn by its parent; this may have changed
15344            invalidateParentIfNeeded();
15345        }
15346    }
15347
15348    /**
15349     * Indicates whether this View is opaque. An opaque View guarantees that it will
15350     * draw all the pixels overlapping its bounds using a fully opaque color.
15351     *
15352     * Subclasses of View should override this method whenever possible to indicate
15353     * whether an instance is opaque. Opaque Views are treated in a special way by
15354     * the View hierarchy, possibly allowing it to perform optimizations during
15355     * invalidate/draw passes.
15356     *
15357     * @return True if this View is guaranteed to be fully opaque, false otherwise.
15358     */
15359    @ViewDebug.ExportedProperty(category = "drawing")
15360    public boolean isOpaque() {
15361        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
15362                getFinalAlpha() >= 1.0f;
15363    }
15364
15365    /**
15366     * @hide
15367     */
15368    protected void computeOpaqueFlags() {
15369        // Opaque if:
15370        //   - Has a background
15371        //   - Background is opaque
15372        //   - Doesn't have scrollbars or scrollbars overlay
15373
15374        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
15375            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
15376        } else {
15377            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
15378        }
15379
15380        final int flags = mViewFlags;
15381        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
15382                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
15383                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
15384            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
15385        } else {
15386            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
15387        }
15388    }
15389
15390    /**
15391     * @hide
15392     */
15393    protected boolean hasOpaqueScrollbars() {
15394        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
15395    }
15396
15397    /**
15398     * @return A handler associated with the thread running the View. This
15399     * handler can be used to pump events in the UI events queue.
15400     */
15401    public Handler getHandler() {
15402        final AttachInfo attachInfo = mAttachInfo;
15403        if (attachInfo != null) {
15404            return attachInfo.mHandler;
15405        }
15406        return null;
15407    }
15408
15409    /**
15410     * Returns the queue of runnable for this view.
15411     *
15412     * @return the queue of runnables for this view
15413     */
15414    private HandlerActionQueue getRunQueue() {
15415        if (mRunQueue == null) {
15416            mRunQueue = new HandlerActionQueue();
15417        }
15418        return mRunQueue;
15419    }
15420
15421    /**
15422     * Gets the view root associated with the View.
15423     * @return The view root, or null if none.
15424     * @hide
15425     */
15426    public ViewRootImpl getViewRootImpl() {
15427        if (mAttachInfo != null) {
15428            return mAttachInfo.mViewRootImpl;
15429        }
15430        return null;
15431    }
15432
15433    /**
15434     * @hide
15435     */
15436    public ThreadedRenderer getThreadedRenderer() {
15437        return mAttachInfo != null ? mAttachInfo.mThreadedRenderer : null;
15438    }
15439
15440    /**
15441     * <p>Causes the Runnable to be added to the message queue.
15442     * The runnable will be run on the user interface thread.</p>
15443     *
15444     * @param action The Runnable that will be executed.
15445     *
15446     * @return Returns true if the Runnable was successfully placed in to the
15447     *         message queue.  Returns false on failure, usually because the
15448     *         looper processing the message queue is exiting.
15449     *
15450     * @see #postDelayed
15451     * @see #removeCallbacks
15452     */
15453    public boolean post(Runnable action) {
15454        final AttachInfo attachInfo = mAttachInfo;
15455        if (attachInfo != null) {
15456            return attachInfo.mHandler.post(action);
15457        }
15458
15459        // Postpone the runnable until we know on which thread it needs to run.
15460        // Assume that the runnable will be successfully placed after attach.
15461        getRunQueue().post(action);
15462        return true;
15463    }
15464
15465    /**
15466     * <p>Causes the Runnable to be added to the message queue, to be run
15467     * after the specified amount of time elapses.
15468     * The runnable will be run on the user interface thread.</p>
15469     *
15470     * @param action The Runnable that will be executed.
15471     * @param delayMillis The delay (in milliseconds) until the Runnable
15472     *        will be executed.
15473     *
15474     * @return true if the Runnable was successfully placed in to the
15475     *         message queue.  Returns false on failure, usually because the
15476     *         looper processing the message queue is exiting.  Note that a
15477     *         result of true does not mean the Runnable will be processed --
15478     *         if the looper is quit before the delivery time of the message
15479     *         occurs then the message will be dropped.
15480     *
15481     * @see #post
15482     * @see #removeCallbacks
15483     */
15484    public boolean postDelayed(Runnable action, long delayMillis) {
15485        final AttachInfo attachInfo = mAttachInfo;
15486        if (attachInfo != null) {
15487            return attachInfo.mHandler.postDelayed(action, delayMillis);
15488        }
15489
15490        // Postpone the runnable until we know on which thread it needs to run.
15491        // Assume that the runnable will be successfully placed after attach.
15492        getRunQueue().postDelayed(action, delayMillis);
15493        return true;
15494    }
15495
15496    /**
15497     * <p>Causes the Runnable to execute on the next animation time step.
15498     * The runnable will be run on the user interface thread.</p>
15499     *
15500     * @param action The Runnable that will be executed.
15501     *
15502     * @see #postOnAnimationDelayed
15503     * @see #removeCallbacks
15504     */
15505    public void postOnAnimation(Runnable action) {
15506        final AttachInfo attachInfo = mAttachInfo;
15507        if (attachInfo != null) {
15508            attachInfo.mViewRootImpl.mChoreographer.postCallback(
15509                    Choreographer.CALLBACK_ANIMATION, action, null);
15510        } else {
15511            // Postpone the runnable until we know
15512            // on which thread it needs to run.
15513            getRunQueue().post(action);
15514        }
15515    }
15516
15517    /**
15518     * <p>Causes the Runnable to execute on the next animation time step,
15519     * after the specified amount of time elapses.
15520     * The runnable will be run on the user interface thread.</p>
15521     *
15522     * @param action The Runnable that will be executed.
15523     * @param delayMillis The delay (in milliseconds) until the Runnable
15524     *        will be executed.
15525     *
15526     * @see #postOnAnimation
15527     * @see #removeCallbacks
15528     */
15529    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
15530        final AttachInfo attachInfo = mAttachInfo;
15531        if (attachInfo != null) {
15532            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
15533                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
15534        } else {
15535            // Postpone the runnable until we know
15536            // on which thread it needs to run.
15537            getRunQueue().postDelayed(action, delayMillis);
15538        }
15539    }
15540
15541    /**
15542     * <p>Removes the specified Runnable from the message queue.</p>
15543     *
15544     * @param action The Runnable to remove from the message handling queue
15545     *
15546     * @return true if this view could ask the Handler to remove the Runnable,
15547     *         false otherwise. When the returned value is true, the Runnable
15548     *         may or may not have been actually removed from the message queue
15549     *         (for instance, if the Runnable was not in the queue already.)
15550     *
15551     * @see #post
15552     * @see #postDelayed
15553     * @see #postOnAnimation
15554     * @see #postOnAnimationDelayed
15555     */
15556    public boolean removeCallbacks(Runnable action) {
15557        if (action != null) {
15558            final AttachInfo attachInfo = mAttachInfo;
15559            if (attachInfo != null) {
15560                attachInfo.mHandler.removeCallbacks(action);
15561                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15562                        Choreographer.CALLBACK_ANIMATION, action, null);
15563            }
15564            getRunQueue().removeCallbacks(action);
15565        }
15566        return true;
15567    }
15568
15569    /**
15570     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
15571     * Use this to invalidate the View from a non-UI thread.</p>
15572     *
15573     * <p>This method can be invoked from outside of the UI thread
15574     * only when this View is attached to a window.</p>
15575     *
15576     * @see #invalidate()
15577     * @see #postInvalidateDelayed(long)
15578     */
15579    public void postInvalidate() {
15580        postInvalidateDelayed(0);
15581    }
15582
15583    /**
15584     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
15585     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
15586     *
15587     * <p>This method can be invoked from outside of the UI thread
15588     * only when this View is attached to a window.</p>
15589     *
15590     * @param left The left coordinate of the rectangle to invalidate.
15591     * @param top The top coordinate of the rectangle to invalidate.
15592     * @param right The right coordinate of the rectangle to invalidate.
15593     * @param bottom The bottom coordinate of the rectangle to invalidate.
15594     *
15595     * @see #invalidate(int, int, int, int)
15596     * @see #invalidate(Rect)
15597     * @see #postInvalidateDelayed(long, int, int, int, int)
15598     */
15599    public void postInvalidate(int left, int top, int right, int bottom) {
15600        postInvalidateDelayed(0, left, top, right, bottom);
15601    }
15602
15603    /**
15604     * <p>Cause an invalidate to happen on a subsequent cycle through the event
15605     * loop. Waits for the specified amount of time.</p>
15606     *
15607     * <p>This method can be invoked from outside of the UI thread
15608     * only when this View is attached to a window.</p>
15609     *
15610     * @param delayMilliseconds the duration in milliseconds to delay the
15611     *         invalidation by
15612     *
15613     * @see #invalidate()
15614     * @see #postInvalidate()
15615     */
15616    public void postInvalidateDelayed(long delayMilliseconds) {
15617        // We try only with the AttachInfo because there's no point in invalidating
15618        // if we are not attached to our window
15619        final AttachInfo attachInfo = mAttachInfo;
15620        if (attachInfo != null) {
15621            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
15622        }
15623    }
15624
15625    /**
15626     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
15627     * through the event loop. Waits for the specified amount of time.</p>
15628     *
15629     * <p>This method can be invoked from outside of the UI thread
15630     * only when this View is attached to a window.</p>
15631     *
15632     * @param delayMilliseconds the duration in milliseconds to delay the
15633     *         invalidation by
15634     * @param left The left coordinate of the rectangle to invalidate.
15635     * @param top The top coordinate of the rectangle to invalidate.
15636     * @param right The right coordinate of the rectangle to invalidate.
15637     * @param bottom The bottom coordinate of the rectangle to invalidate.
15638     *
15639     * @see #invalidate(int, int, int, int)
15640     * @see #invalidate(Rect)
15641     * @see #postInvalidate(int, int, int, int)
15642     */
15643    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
15644            int right, int bottom) {
15645
15646        // We try only with the AttachInfo because there's no point in invalidating
15647        // if we are not attached to our window
15648        final AttachInfo attachInfo = mAttachInfo;
15649        if (attachInfo != null) {
15650            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
15651            info.target = this;
15652            info.left = left;
15653            info.top = top;
15654            info.right = right;
15655            info.bottom = bottom;
15656
15657            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
15658        }
15659    }
15660
15661    /**
15662     * <p>Cause an invalidate to happen on the next animation time step, typically the
15663     * next display frame.</p>
15664     *
15665     * <p>This method can be invoked from outside of the UI thread
15666     * only when this View is attached to a window.</p>
15667     *
15668     * @see #invalidate()
15669     */
15670    public void postInvalidateOnAnimation() {
15671        // We try only with the AttachInfo because there's no point in invalidating
15672        // if we are not attached to our window
15673        final AttachInfo attachInfo = mAttachInfo;
15674        if (attachInfo != null) {
15675            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
15676        }
15677    }
15678
15679    /**
15680     * <p>Cause an invalidate of the specified area to happen on the next animation
15681     * time step, typically the next display frame.</p>
15682     *
15683     * <p>This method can be invoked from outside of the UI thread
15684     * only when this View is attached to a window.</p>
15685     *
15686     * @param left The left coordinate of the rectangle to invalidate.
15687     * @param top The top coordinate of the rectangle to invalidate.
15688     * @param right The right coordinate of the rectangle to invalidate.
15689     * @param bottom The bottom coordinate of the rectangle to invalidate.
15690     *
15691     * @see #invalidate(int, int, int, int)
15692     * @see #invalidate(Rect)
15693     */
15694    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
15695        // We try only with the AttachInfo because there's no point in invalidating
15696        // if we are not attached to our window
15697        final AttachInfo attachInfo = mAttachInfo;
15698        if (attachInfo != null) {
15699            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
15700            info.target = this;
15701            info.left = left;
15702            info.top = top;
15703            info.right = right;
15704            info.bottom = bottom;
15705
15706            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
15707        }
15708    }
15709
15710    /**
15711     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
15712     * This event is sent at most once every
15713     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
15714     */
15715    private void postSendViewScrolledAccessibilityEventCallback() {
15716        if (mSendViewScrolledAccessibilityEvent == null) {
15717            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
15718        }
15719        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
15720            mSendViewScrolledAccessibilityEvent.mIsPending = true;
15721            postDelayed(mSendViewScrolledAccessibilityEvent,
15722                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
15723        }
15724    }
15725
15726    /**
15727     * Called by a parent to request that a child update its values for mScrollX
15728     * and mScrollY if necessary. This will typically be done if the child is
15729     * animating a scroll using a {@link android.widget.Scroller Scroller}
15730     * object.
15731     */
15732    public void computeScroll() {
15733    }
15734
15735    /**
15736     * <p>Indicate whether the horizontal edges are faded when the view is
15737     * scrolled horizontally.</p>
15738     *
15739     * @return true if the horizontal edges should are faded on scroll, false
15740     *         otherwise
15741     *
15742     * @see #setHorizontalFadingEdgeEnabled(boolean)
15743     *
15744     * @attr ref android.R.styleable#View_requiresFadingEdge
15745     */
15746    public boolean isHorizontalFadingEdgeEnabled() {
15747        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
15748    }
15749
15750    /**
15751     * <p>Define whether the horizontal edges should be faded when this view
15752     * is scrolled horizontally.</p>
15753     *
15754     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
15755     *                                    be faded when the view is scrolled
15756     *                                    horizontally
15757     *
15758     * @see #isHorizontalFadingEdgeEnabled()
15759     *
15760     * @attr ref android.R.styleable#View_requiresFadingEdge
15761     */
15762    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
15763        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
15764            if (horizontalFadingEdgeEnabled) {
15765                initScrollCache();
15766            }
15767
15768            mViewFlags ^= FADING_EDGE_HORIZONTAL;
15769        }
15770    }
15771
15772    /**
15773     * <p>Indicate whether the vertical edges are faded when the view is
15774     * scrolled horizontally.</p>
15775     *
15776     * @return true if the vertical edges should are faded on scroll, false
15777     *         otherwise
15778     *
15779     * @see #setVerticalFadingEdgeEnabled(boolean)
15780     *
15781     * @attr ref android.R.styleable#View_requiresFadingEdge
15782     */
15783    public boolean isVerticalFadingEdgeEnabled() {
15784        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
15785    }
15786
15787    /**
15788     * <p>Define whether the vertical edges should be faded when this view
15789     * is scrolled vertically.</p>
15790     *
15791     * @param verticalFadingEdgeEnabled true if the vertical edges should
15792     *                                  be faded when the view is scrolled
15793     *                                  vertically
15794     *
15795     * @see #isVerticalFadingEdgeEnabled()
15796     *
15797     * @attr ref android.R.styleable#View_requiresFadingEdge
15798     */
15799    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
15800        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
15801            if (verticalFadingEdgeEnabled) {
15802                initScrollCache();
15803            }
15804
15805            mViewFlags ^= FADING_EDGE_VERTICAL;
15806        }
15807    }
15808
15809    /**
15810     * Returns the strength, or intensity, of the top faded edge. The strength is
15811     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
15812     * returns 0.0 or 1.0 but no value in between.
15813     *
15814     * Subclasses should override this method to provide a smoother fade transition
15815     * when scrolling occurs.
15816     *
15817     * @return the intensity of the top fade as a float between 0.0f and 1.0f
15818     */
15819    protected float getTopFadingEdgeStrength() {
15820        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
15821    }
15822
15823    /**
15824     * Returns the strength, or intensity, of the bottom faded edge. The strength is
15825     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
15826     * returns 0.0 or 1.0 but no value in between.
15827     *
15828     * Subclasses should override this method to provide a smoother fade transition
15829     * when scrolling occurs.
15830     *
15831     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
15832     */
15833    protected float getBottomFadingEdgeStrength() {
15834        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
15835                computeVerticalScrollRange() ? 1.0f : 0.0f;
15836    }
15837
15838    /**
15839     * Returns the strength, or intensity, of the left faded edge. The strength is
15840     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
15841     * returns 0.0 or 1.0 but no value in between.
15842     *
15843     * Subclasses should override this method to provide a smoother fade transition
15844     * when scrolling occurs.
15845     *
15846     * @return the intensity of the left fade as a float between 0.0f and 1.0f
15847     */
15848    protected float getLeftFadingEdgeStrength() {
15849        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
15850    }
15851
15852    /**
15853     * Returns the strength, or intensity, of the right faded edge. The strength is
15854     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
15855     * returns 0.0 or 1.0 but no value in between.
15856     *
15857     * Subclasses should override this method to provide a smoother fade transition
15858     * when scrolling occurs.
15859     *
15860     * @return the intensity of the right fade as a float between 0.0f and 1.0f
15861     */
15862    protected float getRightFadingEdgeStrength() {
15863        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
15864                computeHorizontalScrollRange() ? 1.0f : 0.0f;
15865    }
15866
15867    /**
15868     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
15869     * scrollbar is not drawn by default.</p>
15870     *
15871     * @return true if the horizontal scrollbar should be painted, false
15872     *         otherwise
15873     *
15874     * @see #setHorizontalScrollBarEnabled(boolean)
15875     */
15876    public boolean isHorizontalScrollBarEnabled() {
15877        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
15878    }
15879
15880    /**
15881     * <p>Define whether the horizontal scrollbar should be drawn or not. The
15882     * scrollbar is not drawn by default.</p>
15883     *
15884     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
15885     *                                   be painted
15886     *
15887     * @see #isHorizontalScrollBarEnabled()
15888     */
15889    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
15890        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
15891            mViewFlags ^= SCROLLBARS_HORIZONTAL;
15892            computeOpaqueFlags();
15893            resolvePadding();
15894        }
15895    }
15896
15897    /**
15898     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
15899     * scrollbar is not drawn by default.</p>
15900     *
15901     * @return true if the vertical scrollbar should be painted, false
15902     *         otherwise
15903     *
15904     * @see #setVerticalScrollBarEnabled(boolean)
15905     */
15906    public boolean isVerticalScrollBarEnabled() {
15907        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
15908    }
15909
15910    /**
15911     * <p>Define whether the vertical scrollbar should be drawn or not. The
15912     * scrollbar is not drawn by default.</p>
15913     *
15914     * @param verticalScrollBarEnabled true if the vertical scrollbar should
15915     *                                 be painted
15916     *
15917     * @see #isVerticalScrollBarEnabled()
15918     */
15919    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
15920        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
15921            mViewFlags ^= SCROLLBARS_VERTICAL;
15922            computeOpaqueFlags();
15923            resolvePadding();
15924        }
15925    }
15926
15927    /**
15928     * @hide
15929     */
15930    protected void recomputePadding() {
15931        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
15932    }
15933
15934    /**
15935     * Define whether scrollbars will fade when the view is not scrolling.
15936     *
15937     * @param fadeScrollbars whether to enable fading
15938     *
15939     * @attr ref android.R.styleable#View_fadeScrollbars
15940     */
15941    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
15942        initScrollCache();
15943        final ScrollabilityCache scrollabilityCache = mScrollCache;
15944        scrollabilityCache.fadeScrollBars = fadeScrollbars;
15945        if (fadeScrollbars) {
15946            scrollabilityCache.state = ScrollabilityCache.OFF;
15947        } else {
15948            scrollabilityCache.state = ScrollabilityCache.ON;
15949        }
15950    }
15951
15952    /**
15953     *
15954     * Returns true if scrollbars will fade when this view is not scrolling
15955     *
15956     * @return true if scrollbar fading is enabled
15957     *
15958     * @attr ref android.R.styleable#View_fadeScrollbars
15959     */
15960    public boolean isScrollbarFadingEnabled() {
15961        return mScrollCache != null && mScrollCache.fadeScrollBars;
15962    }
15963
15964    /**
15965     *
15966     * Returns the delay before scrollbars fade.
15967     *
15968     * @return the delay before scrollbars fade
15969     *
15970     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
15971     */
15972    public int getScrollBarDefaultDelayBeforeFade() {
15973        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
15974                mScrollCache.scrollBarDefaultDelayBeforeFade;
15975    }
15976
15977    /**
15978     * Define the delay before scrollbars fade.
15979     *
15980     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
15981     *
15982     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
15983     */
15984    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
15985        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
15986    }
15987
15988    /**
15989     *
15990     * Returns the scrollbar fade duration.
15991     *
15992     * @return the scrollbar fade duration, in milliseconds
15993     *
15994     * @attr ref android.R.styleable#View_scrollbarFadeDuration
15995     */
15996    public int getScrollBarFadeDuration() {
15997        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
15998                mScrollCache.scrollBarFadeDuration;
15999    }
16000
16001    /**
16002     * Define the scrollbar fade duration.
16003     *
16004     * @param scrollBarFadeDuration - the scrollbar fade duration, in milliseconds
16005     *
16006     * @attr ref android.R.styleable#View_scrollbarFadeDuration
16007     */
16008    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
16009        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
16010    }
16011
16012    /**
16013     *
16014     * Returns the scrollbar size.
16015     *
16016     * @return the scrollbar size
16017     *
16018     * @attr ref android.R.styleable#View_scrollbarSize
16019     */
16020    public int getScrollBarSize() {
16021        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
16022                mScrollCache.scrollBarSize;
16023    }
16024
16025    /**
16026     * Define the scrollbar size.
16027     *
16028     * @param scrollBarSize - the scrollbar size
16029     *
16030     * @attr ref android.R.styleable#View_scrollbarSize
16031     */
16032    public void setScrollBarSize(int scrollBarSize) {
16033        getScrollCache().scrollBarSize = scrollBarSize;
16034    }
16035
16036    /**
16037     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
16038     * inset. When inset, they add to the padding of the view. And the scrollbars
16039     * can be drawn inside the padding area or on the edge of the view. For example,
16040     * if a view has a background drawable and you want to draw the scrollbars
16041     * inside the padding specified by the drawable, you can use
16042     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
16043     * appear at the edge of the view, ignoring the padding, then you can use
16044     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
16045     * @param style the style of the scrollbars. Should be one of
16046     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
16047     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
16048     * @see #SCROLLBARS_INSIDE_OVERLAY
16049     * @see #SCROLLBARS_INSIDE_INSET
16050     * @see #SCROLLBARS_OUTSIDE_OVERLAY
16051     * @see #SCROLLBARS_OUTSIDE_INSET
16052     *
16053     * @attr ref android.R.styleable#View_scrollbarStyle
16054     */
16055    public void setScrollBarStyle(@ScrollBarStyle int style) {
16056        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
16057            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
16058            computeOpaqueFlags();
16059            resolvePadding();
16060        }
16061    }
16062
16063    /**
16064     * <p>Returns the current scrollbar style.</p>
16065     * @return the current scrollbar style
16066     * @see #SCROLLBARS_INSIDE_OVERLAY
16067     * @see #SCROLLBARS_INSIDE_INSET
16068     * @see #SCROLLBARS_OUTSIDE_OVERLAY
16069     * @see #SCROLLBARS_OUTSIDE_INSET
16070     *
16071     * @attr ref android.R.styleable#View_scrollbarStyle
16072     */
16073    @ViewDebug.ExportedProperty(mapping = {
16074            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
16075            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
16076            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
16077            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
16078    })
16079    @ScrollBarStyle
16080    public int getScrollBarStyle() {
16081        return mViewFlags & SCROLLBARS_STYLE_MASK;
16082    }
16083
16084    /**
16085     * <p>Compute the horizontal range that the horizontal scrollbar
16086     * represents.</p>
16087     *
16088     * <p>The range is expressed in arbitrary units that must be the same as the
16089     * units used by {@link #computeHorizontalScrollExtent()} and
16090     * {@link #computeHorizontalScrollOffset()}.</p>
16091     *
16092     * <p>The default range is the drawing width of this view.</p>
16093     *
16094     * @return the total horizontal range represented by the horizontal
16095     *         scrollbar
16096     *
16097     * @see #computeHorizontalScrollExtent()
16098     * @see #computeHorizontalScrollOffset()
16099     * @see android.widget.ScrollBarDrawable
16100     */
16101    protected int computeHorizontalScrollRange() {
16102        return getWidth();
16103    }
16104
16105    /**
16106     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
16107     * within the horizontal range. This value is used to compute the position
16108     * of the thumb within the scrollbar's track.</p>
16109     *
16110     * <p>The range is expressed in arbitrary units that must be the same as the
16111     * units used by {@link #computeHorizontalScrollRange()} and
16112     * {@link #computeHorizontalScrollExtent()}.</p>
16113     *
16114     * <p>The default offset is the scroll offset of this view.</p>
16115     *
16116     * @return the horizontal offset of the scrollbar's thumb
16117     *
16118     * @see #computeHorizontalScrollRange()
16119     * @see #computeHorizontalScrollExtent()
16120     * @see android.widget.ScrollBarDrawable
16121     */
16122    protected int computeHorizontalScrollOffset() {
16123        return mScrollX;
16124    }
16125
16126    /**
16127     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
16128     * within the horizontal range. This value is used to compute the length
16129     * of the thumb within the scrollbar's track.</p>
16130     *
16131     * <p>The range is expressed in arbitrary units that must be the same as the
16132     * units used by {@link #computeHorizontalScrollRange()} and
16133     * {@link #computeHorizontalScrollOffset()}.</p>
16134     *
16135     * <p>The default extent is the drawing width of this view.</p>
16136     *
16137     * @return the horizontal extent of the scrollbar's thumb
16138     *
16139     * @see #computeHorizontalScrollRange()
16140     * @see #computeHorizontalScrollOffset()
16141     * @see android.widget.ScrollBarDrawable
16142     */
16143    protected int computeHorizontalScrollExtent() {
16144        return getWidth();
16145    }
16146
16147    /**
16148     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
16149     *
16150     * <p>The range is expressed in arbitrary units that must be the same as the
16151     * units used by {@link #computeVerticalScrollExtent()} and
16152     * {@link #computeVerticalScrollOffset()}.</p>
16153     *
16154     * @return the total vertical range represented by the vertical scrollbar
16155     *
16156     * <p>The default range is the drawing height of this view.</p>
16157     *
16158     * @see #computeVerticalScrollExtent()
16159     * @see #computeVerticalScrollOffset()
16160     * @see android.widget.ScrollBarDrawable
16161     */
16162    protected int computeVerticalScrollRange() {
16163        return getHeight();
16164    }
16165
16166    /**
16167     * <p>Compute the vertical offset of the vertical scrollbar's thumb
16168     * within the horizontal range. This value is used to compute the position
16169     * of the thumb within the scrollbar's track.</p>
16170     *
16171     * <p>The range is expressed in arbitrary units that must be the same as the
16172     * units used by {@link #computeVerticalScrollRange()} and
16173     * {@link #computeVerticalScrollExtent()}.</p>
16174     *
16175     * <p>The default offset is the scroll offset of this view.</p>
16176     *
16177     * @return the vertical offset of the scrollbar's thumb
16178     *
16179     * @see #computeVerticalScrollRange()
16180     * @see #computeVerticalScrollExtent()
16181     * @see android.widget.ScrollBarDrawable
16182     */
16183    protected int computeVerticalScrollOffset() {
16184        return mScrollY;
16185    }
16186
16187    /**
16188     * <p>Compute the vertical extent of the vertical scrollbar's thumb
16189     * within the vertical range. This value is used to compute the length
16190     * of the thumb within the scrollbar's track.</p>
16191     *
16192     * <p>The range is expressed in arbitrary units that must be the same as the
16193     * units used by {@link #computeVerticalScrollRange()} and
16194     * {@link #computeVerticalScrollOffset()}.</p>
16195     *
16196     * <p>The default extent is the drawing height of this view.</p>
16197     *
16198     * @return the vertical extent of the scrollbar's thumb
16199     *
16200     * @see #computeVerticalScrollRange()
16201     * @see #computeVerticalScrollOffset()
16202     * @see android.widget.ScrollBarDrawable
16203     */
16204    protected int computeVerticalScrollExtent() {
16205        return getHeight();
16206    }
16207
16208    /**
16209     * Check if this view can be scrolled horizontally in a certain direction.
16210     *
16211     * @param direction Negative to check scrolling left, positive to check scrolling right.
16212     * @return true if this view can be scrolled in the specified direction, false otherwise.
16213     */
16214    public boolean canScrollHorizontally(int direction) {
16215        final int offset = computeHorizontalScrollOffset();
16216        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
16217        if (range == 0) return false;
16218        if (direction < 0) {
16219            return offset > 0;
16220        } else {
16221            return offset < range - 1;
16222        }
16223    }
16224
16225    /**
16226     * Check if this view can be scrolled vertically in a certain direction.
16227     *
16228     * @param direction Negative to check scrolling up, positive to check scrolling down.
16229     * @return true if this view can be scrolled in the specified direction, false otherwise.
16230     */
16231    public boolean canScrollVertically(int direction) {
16232        final int offset = computeVerticalScrollOffset();
16233        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
16234        if (range == 0) return false;
16235        if (direction < 0) {
16236            return offset > 0;
16237        } else {
16238            return offset < range - 1;
16239        }
16240    }
16241
16242    void getScrollIndicatorBounds(@NonNull Rect out) {
16243        out.left = mScrollX;
16244        out.right = mScrollX + mRight - mLeft;
16245        out.top = mScrollY;
16246        out.bottom = mScrollY + mBottom - mTop;
16247    }
16248
16249    private void onDrawScrollIndicators(Canvas c) {
16250        if ((mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK) == 0) {
16251            // No scroll indicators enabled.
16252            return;
16253        }
16254
16255        final Drawable dr = mScrollIndicatorDrawable;
16256        if (dr == null) {
16257            // Scroll indicators aren't supported here.
16258            return;
16259        }
16260
16261        final int h = dr.getIntrinsicHeight();
16262        final int w = dr.getIntrinsicWidth();
16263        final Rect rect = mAttachInfo.mTmpInvalRect;
16264        getScrollIndicatorBounds(rect);
16265
16266        if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_TOP) != 0) {
16267            final boolean canScrollUp = canScrollVertically(-1);
16268            if (canScrollUp) {
16269                dr.setBounds(rect.left, rect.top, rect.right, rect.top + h);
16270                dr.draw(c);
16271            }
16272        }
16273
16274        if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_BOTTOM) != 0) {
16275            final boolean canScrollDown = canScrollVertically(1);
16276            if (canScrollDown) {
16277                dr.setBounds(rect.left, rect.bottom - h, rect.right, rect.bottom);
16278                dr.draw(c);
16279            }
16280        }
16281
16282        final int leftRtl;
16283        final int rightRtl;
16284        if (getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
16285            leftRtl = PFLAG3_SCROLL_INDICATOR_END;
16286            rightRtl = PFLAG3_SCROLL_INDICATOR_START;
16287        } else {
16288            leftRtl = PFLAG3_SCROLL_INDICATOR_START;
16289            rightRtl = PFLAG3_SCROLL_INDICATOR_END;
16290        }
16291
16292        final int leftMask = PFLAG3_SCROLL_INDICATOR_LEFT | leftRtl;
16293        if ((mPrivateFlags3 & leftMask) != 0) {
16294            final boolean canScrollLeft = canScrollHorizontally(-1);
16295            if (canScrollLeft) {
16296                dr.setBounds(rect.left, rect.top, rect.left + w, rect.bottom);
16297                dr.draw(c);
16298            }
16299        }
16300
16301        final int rightMask = PFLAG3_SCROLL_INDICATOR_RIGHT | rightRtl;
16302        if ((mPrivateFlags3 & rightMask) != 0) {
16303            final boolean canScrollRight = canScrollHorizontally(1);
16304            if (canScrollRight) {
16305                dr.setBounds(rect.right - w, rect.top, rect.right, rect.bottom);
16306                dr.draw(c);
16307            }
16308        }
16309    }
16310
16311    private void getHorizontalScrollBarBounds(@Nullable Rect drawBounds,
16312            @Nullable Rect touchBounds) {
16313        final Rect bounds = drawBounds != null ? drawBounds : touchBounds;
16314        if (bounds == null) {
16315            return;
16316        }
16317        final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
16318        final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled()
16319                && !isVerticalScrollBarHidden();
16320        final int size = getHorizontalScrollbarHeight();
16321        final int verticalScrollBarGap = drawVerticalScrollBar ?
16322                getVerticalScrollbarWidth() : 0;
16323        final int width = mRight - mLeft;
16324        final int height = mBottom - mTop;
16325        bounds.top = mScrollY + height - size - (mUserPaddingBottom & inside);
16326        bounds.left = mScrollX + (mPaddingLeft & inside);
16327        bounds.right = mScrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
16328        bounds.bottom = bounds.top + size;
16329
16330        if (touchBounds == null) {
16331            return;
16332        }
16333        if (touchBounds != bounds) {
16334            touchBounds.set(bounds);
16335        }
16336        final int minTouchTarget = mScrollCache.scrollBarMinTouchTarget;
16337        if (touchBounds.height() < minTouchTarget) {
16338            final int adjust = (minTouchTarget - touchBounds.height()) / 2;
16339            touchBounds.bottom = Math.min(touchBounds.bottom + adjust, mScrollY + height);
16340            touchBounds.top = touchBounds.bottom - minTouchTarget;
16341        }
16342        if (touchBounds.width() < minTouchTarget) {
16343            final int adjust = (minTouchTarget - touchBounds.width()) / 2;
16344            touchBounds.left -= adjust;
16345            touchBounds.right = touchBounds.left + minTouchTarget;
16346        }
16347    }
16348
16349    private void getVerticalScrollBarBounds(@Nullable Rect bounds, @Nullable Rect touchBounds) {
16350        if (mRoundScrollbarRenderer == null) {
16351            getStraightVerticalScrollBarBounds(bounds, touchBounds);
16352        } else {
16353            getRoundVerticalScrollBarBounds(bounds != null ? bounds : touchBounds);
16354        }
16355    }
16356
16357    private void getRoundVerticalScrollBarBounds(Rect bounds) {
16358        final int width = mRight - mLeft;
16359        final int height = mBottom - mTop;
16360        // Do not take padding into account as we always want the scrollbars
16361        // to hug the screen for round wearable devices.
16362        bounds.left = mScrollX;
16363        bounds.top = mScrollY;
16364        bounds.right = bounds.left + width;
16365        bounds.bottom = mScrollY + height;
16366    }
16367
16368    private void getStraightVerticalScrollBarBounds(@Nullable Rect drawBounds,
16369            @Nullable Rect touchBounds) {
16370        final Rect bounds = drawBounds != null ? drawBounds : touchBounds;
16371        if (bounds == null) {
16372            return;
16373        }
16374        final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
16375        final int size = getVerticalScrollbarWidth();
16376        int verticalScrollbarPosition = mVerticalScrollbarPosition;
16377        if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
16378            verticalScrollbarPosition = isLayoutRtl() ?
16379                    SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
16380        }
16381        final int width = mRight - mLeft;
16382        final int height = mBottom - mTop;
16383        switch (verticalScrollbarPosition) {
16384            default:
16385            case SCROLLBAR_POSITION_RIGHT:
16386                bounds.left = mScrollX + width - size - (mUserPaddingRight & inside);
16387                break;
16388            case SCROLLBAR_POSITION_LEFT:
16389                bounds.left = mScrollX + (mUserPaddingLeft & inside);
16390                break;
16391        }
16392        bounds.top = mScrollY + (mPaddingTop & inside);
16393        bounds.right = bounds.left + size;
16394        bounds.bottom = mScrollY + height - (mUserPaddingBottom & inside);
16395
16396        if (touchBounds == null) {
16397            return;
16398        }
16399        if (touchBounds != bounds) {
16400            touchBounds.set(bounds);
16401        }
16402        final int minTouchTarget = mScrollCache.scrollBarMinTouchTarget;
16403        if (touchBounds.width() < minTouchTarget) {
16404            final int adjust = (minTouchTarget - touchBounds.width()) / 2;
16405            if (verticalScrollbarPosition == SCROLLBAR_POSITION_RIGHT) {
16406                touchBounds.right = Math.min(touchBounds.right + adjust, mScrollX + width);
16407                touchBounds.left = touchBounds.right - minTouchTarget;
16408            } else {
16409                touchBounds.left = Math.max(touchBounds.left + adjust, mScrollX);
16410                touchBounds.right = touchBounds.left + minTouchTarget;
16411            }
16412        }
16413        if (touchBounds.height() < minTouchTarget) {
16414            final int adjust = (minTouchTarget - touchBounds.height()) / 2;
16415            touchBounds.top -= adjust;
16416            touchBounds.bottom = touchBounds.top + minTouchTarget;
16417        }
16418    }
16419
16420    /**
16421     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
16422     * scrollbars are painted only if they have been awakened first.</p>
16423     *
16424     * @param canvas the canvas on which to draw the scrollbars
16425     *
16426     * @see #awakenScrollBars(int)
16427     */
16428    protected final void onDrawScrollBars(Canvas canvas) {
16429        // scrollbars are drawn only when the animation is running
16430        final ScrollabilityCache cache = mScrollCache;
16431
16432        if (cache != null) {
16433
16434            int state = cache.state;
16435
16436            if (state == ScrollabilityCache.OFF) {
16437                return;
16438            }
16439
16440            boolean invalidate = false;
16441
16442            if (state == ScrollabilityCache.FADING) {
16443                // We're fading -- get our fade interpolation
16444                if (cache.interpolatorValues == null) {
16445                    cache.interpolatorValues = new float[1];
16446                }
16447
16448                float[] values = cache.interpolatorValues;
16449
16450                // Stops the animation if we're done
16451                if (cache.scrollBarInterpolator.timeToValues(values) ==
16452                        Interpolator.Result.FREEZE_END) {
16453                    cache.state = ScrollabilityCache.OFF;
16454                } else {
16455                    cache.scrollBar.mutate().setAlpha(Math.round(values[0]));
16456                }
16457
16458                // This will make the scroll bars inval themselves after
16459                // drawing. We only want this when we're fading so that
16460                // we prevent excessive redraws
16461                invalidate = true;
16462            } else {
16463                // We're just on -- but we may have been fading before so
16464                // reset alpha
16465                cache.scrollBar.mutate().setAlpha(255);
16466            }
16467
16468            final boolean drawHorizontalScrollBar = isHorizontalScrollBarEnabled();
16469            final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled()
16470                    && !isVerticalScrollBarHidden();
16471
16472            // Fork out the scroll bar drawing for round wearable devices.
16473            if (mRoundScrollbarRenderer != null) {
16474                if (drawVerticalScrollBar) {
16475                    final Rect bounds = cache.mScrollBarBounds;
16476                    getVerticalScrollBarBounds(bounds, null);
16477                    mRoundScrollbarRenderer.drawRoundScrollbars(
16478                            canvas, (float) cache.scrollBar.getAlpha() / 255f, bounds);
16479                    if (invalidate) {
16480                        invalidate();
16481                    }
16482                }
16483                // Do not draw horizontal scroll bars for round wearable devices.
16484            } else if (drawVerticalScrollBar || drawHorizontalScrollBar) {
16485                final ScrollBarDrawable scrollBar = cache.scrollBar;
16486
16487                if (drawHorizontalScrollBar) {
16488                    scrollBar.setParameters(computeHorizontalScrollRange(),
16489                            computeHorizontalScrollOffset(),
16490                            computeHorizontalScrollExtent(), false);
16491                    final Rect bounds = cache.mScrollBarBounds;
16492                    getHorizontalScrollBarBounds(bounds, null);
16493                    onDrawHorizontalScrollBar(canvas, scrollBar, bounds.left, bounds.top,
16494                            bounds.right, bounds.bottom);
16495                    if (invalidate) {
16496                        invalidate(bounds);
16497                    }
16498                }
16499
16500                if (drawVerticalScrollBar) {
16501                    scrollBar.setParameters(computeVerticalScrollRange(),
16502                            computeVerticalScrollOffset(),
16503                            computeVerticalScrollExtent(), true);
16504                    final Rect bounds = cache.mScrollBarBounds;
16505                    getVerticalScrollBarBounds(bounds, null);
16506                    onDrawVerticalScrollBar(canvas, scrollBar, bounds.left, bounds.top,
16507                            bounds.right, bounds.bottom);
16508                    if (invalidate) {
16509                        invalidate(bounds);
16510                    }
16511                }
16512            }
16513        }
16514    }
16515
16516    /**
16517     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
16518     * FastScroller is visible.
16519     * @return whether to temporarily hide the vertical scrollbar
16520     * @hide
16521     */
16522    protected boolean isVerticalScrollBarHidden() {
16523        return false;
16524    }
16525
16526    /**
16527     * <p>Draw the horizontal scrollbar if
16528     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
16529     *
16530     * @param canvas the canvas on which to draw the scrollbar
16531     * @param scrollBar the scrollbar's drawable
16532     *
16533     * @see #isHorizontalScrollBarEnabled()
16534     * @see #computeHorizontalScrollRange()
16535     * @see #computeHorizontalScrollExtent()
16536     * @see #computeHorizontalScrollOffset()
16537     * @see android.widget.ScrollBarDrawable
16538     * @hide
16539     */
16540    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
16541            int l, int t, int r, int b) {
16542        scrollBar.setBounds(l, t, r, b);
16543        scrollBar.draw(canvas);
16544    }
16545
16546    /**
16547     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
16548     * returns true.</p>
16549     *
16550     * @param canvas the canvas on which to draw the scrollbar
16551     * @param scrollBar the scrollbar's drawable
16552     *
16553     * @see #isVerticalScrollBarEnabled()
16554     * @see #computeVerticalScrollRange()
16555     * @see #computeVerticalScrollExtent()
16556     * @see #computeVerticalScrollOffset()
16557     * @see android.widget.ScrollBarDrawable
16558     * @hide
16559     */
16560    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
16561            int l, int t, int r, int b) {
16562        scrollBar.setBounds(l, t, r, b);
16563        scrollBar.draw(canvas);
16564    }
16565
16566    /**
16567     * Implement this to do your drawing.
16568     *
16569     * @param canvas the canvas on which the background will be drawn
16570     */
16571    protected void onDraw(Canvas canvas) {
16572    }
16573
16574    /*
16575     * Caller is responsible for calling requestLayout if necessary.
16576     * (This allows addViewInLayout to not request a new layout.)
16577     */
16578    void assignParent(ViewParent parent) {
16579        if (mParent == null) {
16580            mParent = parent;
16581        } else if (parent == null) {
16582            mParent = null;
16583        } else {
16584            throw new RuntimeException("view " + this + " being added, but"
16585                    + " it already has a parent");
16586        }
16587    }
16588
16589    /**
16590     * This is called when the view is attached to a window.  At this point it
16591     * has a Surface and will start drawing.  Note that this function is
16592     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
16593     * however it may be called any time before the first onDraw -- including
16594     * before or after {@link #onMeasure(int, int)}.
16595     *
16596     * @see #onDetachedFromWindow()
16597     */
16598    @CallSuper
16599    protected void onAttachedToWindow() {
16600        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
16601            mParent.requestTransparentRegion(this);
16602        }
16603
16604        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
16605
16606        jumpDrawablesToCurrentState();
16607
16608        resetSubtreeAccessibilityStateChanged();
16609
16610        // rebuild, since Outline not maintained while View is detached
16611        rebuildOutline();
16612
16613        if (isFocused()) {
16614            InputMethodManager imm = InputMethodManager.peekInstance();
16615            if (imm != null) {
16616                imm.focusIn(this);
16617            }
16618        }
16619    }
16620
16621    /**
16622     * Resolve all RTL related properties.
16623     *
16624     * @return true if resolution of RTL properties has been done
16625     *
16626     * @hide
16627     */
16628    public boolean resolveRtlPropertiesIfNeeded() {
16629        if (!needRtlPropertiesResolution()) return false;
16630
16631        // Order is important here: LayoutDirection MUST be resolved first
16632        if (!isLayoutDirectionResolved()) {
16633            resolveLayoutDirection();
16634            resolveLayoutParams();
16635        }
16636        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
16637        if (!isTextDirectionResolved()) {
16638            resolveTextDirection();
16639        }
16640        if (!isTextAlignmentResolved()) {
16641            resolveTextAlignment();
16642        }
16643        // Should resolve Drawables before Padding because we need the layout direction of the
16644        // Drawable to correctly resolve Padding.
16645        if (!areDrawablesResolved()) {
16646            resolveDrawables();
16647        }
16648        if (!isPaddingResolved()) {
16649            resolvePadding();
16650        }
16651        onRtlPropertiesChanged(getLayoutDirection());
16652        return true;
16653    }
16654
16655    /**
16656     * Reset resolution of all RTL related properties.
16657     *
16658     * @hide
16659     */
16660    public void resetRtlProperties() {
16661        resetResolvedLayoutDirection();
16662        resetResolvedTextDirection();
16663        resetResolvedTextAlignment();
16664        resetResolvedPadding();
16665        resetResolvedDrawables();
16666    }
16667
16668    /**
16669     * @see #onScreenStateChanged(int)
16670     */
16671    void dispatchScreenStateChanged(int screenState) {
16672        onScreenStateChanged(screenState);
16673    }
16674
16675    /**
16676     * This method is called whenever the state of the screen this view is
16677     * attached to changes. A state change will usually occurs when the screen
16678     * turns on or off (whether it happens automatically or the user does it
16679     * manually.)
16680     *
16681     * @param screenState The new state of the screen. Can be either
16682     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
16683     */
16684    public void onScreenStateChanged(int screenState) {
16685    }
16686
16687    /**
16688     * @see #onMovedToDisplay(int, Configuration)
16689     */
16690    void dispatchMovedToDisplay(Display display, Configuration config) {
16691        mAttachInfo.mDisplay = display;
16692        mAttachInfo.mDisplayState = display.getState();
16693        onMovedToDisplay(display.getDisplayId(), config);
16694    }
16695
16696    /**
16697     * Called by the system when the hosting activity is moved from one display to another without
16698     * recreation. This means that the activity is declared to handle all changes to configuration
16699     * that happened when it was switched to another display, so it wasn't destroyed and created
16700     * again.
16701     *
16702     * <p>This call will be followed by {@link #onConfigurationChanged(Configuration)} if the
16703     * applied configuration actually changed. It is up to app developer to choose whether to handle
16704     * the change in this method or in the following {@link #onConfigurationChanged(Configuration)}
16705     * call.
16706     *
16707     * <p>Use this callback to track changes to the displays if some functionality relies on an
16708     * association with some display properties.
16709     *
16710     * @param displayId The id of the display to which the view was moved.
16711     * @param config Configuration of the resources on new display after move.
16712     *
16713     * @see #onConfigurationChanged(Configuration)
16714     * @hide
16715     */
16716    public void onMovedToDisplay(int displayId, Configuration config) {
16717    }
16718
16719    /**
16720     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
16721     */
16722    private boolean hasRtlSupport() {
16723        return mContext.getApplicationInfo().hasRtlSupport();
16724    }
16725
16726    /**
16727     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
16728     * RTL not supported)
16729     */
16730    private boolean isRtlCompatibilityMode() {
16731        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
16732        return targetSdkVersion < Build.VERSION_CODES.JELLY_BEAN_MR1 || !hasRtlSupport();
16733    }
16734
16735    /**
16736     * @return true if RTL properties need resolution.
16737     *
16738     */
16739    private boolean needRtlPropertiesResolution() {
16740        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
16741    }
16742
16743    /**
16744     * Called when any RTL property (layout direction or text direction or text alignment) has
16745     * been changed.
16746     *
16747     * Subclasses need to override this method to take care of cached information that depends on the
16748     * resolved layout direction, or to inform child views that inherit their layout direction.
16749     *
16750     * The default implementation does nothing.
16751     *
16752     * @param layoutDirection the direction of the layout
16753     *
16754     * @see #LAYOUT_DIRECTION_LTR
16755     * @see #LAYOUT_DIRECTION_RTL
16756     */
16757    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
16758    }
16759
16760    /**
16761     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
16762     * that the parent directionality can and will be resolved before its children.
16763     *
16764     * @return true if resolution has been done, false otherwise.
16765     *
16766     * @hide
16767     */
16768    public boolean resolveLayoutDirection() {
16769        // Clear any previous layout direction resolution
16770        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
16771
16772        if (hasRtlSupport()) {
16773            // Set resolved depending on layout direction
16774            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
16775                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
16776                case LAYOUT_DIRECTION_INHERIT:
16777                    // We cannot resolve yet. LTR is by default and let the resolution happen again
16778                    // later to get the correct resolved value
16779                    if (!canResolveLayoutDirection()) return false;
16780
16781                    // Parent has not yet resolved, LTR is still the default
16782                    try {
16783                        if (!mParent.isLayoutDirectionResolved()) return false;
16784
16785                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
16786                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
16787                        }
16788                    } catch (AbstractMethodError e) {
16789                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
16790                                " does not fully implement ViewParent", e);
16791                    }
16792                    break;
16793                case LAYOUT_DIRECTION_RTL:
16794                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
16795                    break;
16796                case LAYOUT_DIRECTION_LOCALE:
16797                    if((LAYOUT_DIRECTION_RTL ==
16798                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
16799                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
16800                    }
16801                    break;
16802                default:
16803                    // Nothing to do, LTR by default
16804            }
16805        }
16806
16807        // Set to resolved
16808        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
16809        return true;
16810    }
16811
16812    /**
16813     * Check if layout direction resolution can be done.
16814     *
16815     * @return true if layout direction resolution can be done otherwise return false.
16816     */
16817    public boolean canResolveLayoutDirection() {
16818        switch (getRawLayoutDirection()) {
16819            case LAYOUT_DIRECTION_INHERIT:
16820                if (mParent != null) {
16821                    try {
16822                        return mParent.canResolveLayoutDirection();
16823                    } catch (AbstractMethodError e) {
16824                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
16825                                " does not fully implement ViewParent", e);
16826                    }
16827                }
16828                return false;
16829
16830            default:
16831                return true;
16832        }
16833    }
16834
16835    /**
16836     * Reset the resolved layout direction. Layout direction will be resolved during a call to
16837     * {@link #onMeasure(int, int)}.
16838     *
16839     * @hide
16840     */
16841    public void resetResolvedLayoutDirection() {
16842        // Reset the current resolved bits
16843        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
16844    }
16845
16846    /**
16847     * @return true if the layout direction is inherited.
16848     *
16849     * @hide
16850     */
16851    public boolean isLayoutDirectionInherited() {
16852        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
16853    }
16854
16855    /**
16856     * @return true if layout direction has been resolved.
16857     */
16858    public boolean isLayoutDirectionResolved() {
16859        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
16860    }
16861
16862    /**
16863     * Return if padding has been resolved
16864     *
16865     * @hide
16866     */
16867    boolean isPaddingResolved() {
16868        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
16869    }
16870
16871    /**
16872     * Resolves padding depending on layout direction, if applicable, and
16873     * recomputes internal padding values to adjust for scroll bars.
16874     *
16875     * @hide
16876     */
16877    public void resolvePadding() {
16878        final int resolvedLayoutDirection = getLayoutDirection();
16879
16880        if (!isRtlCompatibilityMode()) {
16881            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
16882            // If start / end padding are defined, they will be resolved (hence overriding) to
16883            // left / right or right / left depending on the resolved layout direction.
16884            // If start / end padding are not defined, use the left / right ones.
16885            if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
16886                Rect padding = sThreadLocal.get();
16887                if (padding == null) {
16888                    padding = new Rect();
16889                    sThreadLocal.set(padding);
16890                }
16891                mBackground.getPadding(padding);
16892                if (!mLeftPaddingDefined) {
16893                    mUserPaddingLeftInitial = padding.left;
16894                }
16895                if (!mRightPaddingDefined) {
16896                    mUserPaddingRightInitial = padding.right;
16897                }
16898            }
16899            switch (resolvedLayoutDirection) {
16900                case LAYOUT_DIRECTION_RTL:
16901                    if (mUserPaddingStart != UNDEFINED_PADDING) {
16902                        mUserPaddingRight = mUserPaddingStart;
16903                    } else {
16904                        mUserPaddingRight = mUserPaddingRightInitial;
16905                    }
16906                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
16907                        mUserPaddingLeft = mUserPaddingEnd;
16908                    } else {
16909                        mUserPaddingLeft = mUserPaddingLeftInitial;
16910                    }
16911                    break;
16912                case LAYOUT_DIRECTION_LTR:
16913                default:
16914                    if (mUserPaddingStart != UNDEFINED_PADDING) {
16915                        mUserPaddingLeft = mUserPaddingStart;
16916                    } else {
16917                        mUserPaddingLeft = mUserPaddingLeftInitial;
16918                    }
16919                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
16920                        mUserPaddingRight = mUserPaddingEnd;
16921                    } else {
16922                        mUserPaddingRight = mUserPaddingRightInitial;
16923                    }
16924            }
16925
16926            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
16927        }
16928
16929        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
16930        onRtlPropertiesChanged(resolvedLayoutDirection);
16931
16932        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
16933    }
16934
16935    /**
16936     * Reset the resolved layout direction.
16937     *
16938     * @hide
16939     */
16940    public void resetResolvedPadding() {
16941        resetResolvedPaddingInternal();
16942    }
16943
16944    /**
16945     * Used when we only want to reset *this* view's padding and not trigger overrides
16946     * in ViewGroup that reset children too.
16947     */
16948    void resetResolvedPaddingInternal() {
16949        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
16950    }
16951
16952    /**
16953     * This is called when the view is detached from a window.  At this point it
16954     * no longer has a surface for drawing.
16955     *
16956     * @see #onAttachedToWindow()
16957     */
16958    @CallSuper
16959    protected void onDetachedFromWindow() {
16960    }
16961
16962    /**
16963     * This is a framework-internal mirror of onDetachedFromWindow() that's called
16964     * after onDetachedFromWindow().
16965     *
16966     * If you override this you *MUST* call super.onDetachedFromWindowInternal()!
16967     * The super method should be called at the end of the overridden method to ensure
16968     * subclasses are destroyed first
16969     *
16970     * @hide
16971     */
16972    @CallSuper
16973    protected void onDetachedFromWindowInternal() {
16974        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
16975        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
16976        mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH;
16977
16978        removeUnsetPressCallback();
16979        removeLongPressCallback();
16980        removePerformClickCallback();
16981        removeSendViewScrolledAccessibilityEventCallback();
16982        stopNestedScroll();
16983
16984        // Anything that started animating right before detach should already
16985        // be in its final state when re-attached.
16986        jumpDrawablesToCurrentState();
16987
16988        destroyDrawingCache();
16989
16990        cleanupDraw();
16991        mCurrentAnimation = null;
16992
16993        if ((mViewFlags & TOOLTIP) == TOOLTIP) {
16994            hideTooltip();
16995        }
16996    }
16997
16998    private void cleanupDraw() {
16999        resetDisplayList();
17000        if (mAttachInfo != null) {
17001            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
17002        }
17003    }
17004
17005    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
17006    }
17007
17008    /**
17009     * @return The number of times this view has been attached to a window
17010     */
17011    protected int getWindowAttachCount() {
17012        return mWindowAttachCount;
17013    }
17014
17015    /**
17016     * Retrieve a unique token identifying the window this view is attached to.
17017     * @return Return the window's token for use in
17018     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
17019     */
17020    public IBinder getWindowToken() {
17021        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
17022    }
17023
17024    /**
17025     * Retrieve the {@link WindowId} for the window this view is
17026     * currently attached to.
17027     */
17028    public WindowId getWindowId() {
17029        if (mAttachInfo == null) {
17030            return null;
17031        }
17032        if (mAttachInfo.mWindowId == null) {
17033            try {
17034                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
17035                        mAttachInfo.mWindowToken);
17036                mAttachInfo.mWindowId = new WindowId(
17037                        mAttachInfo.mIWindowId);
17038            } catch (RemoteException e) {
17039            }
17040        }
17041        return mAttachInfo.mWindowId;
17042    }
17043
17044    /**
17045     * Retrieve a unique token identifying the top-level "real" window of
17046     * the window that this view is attached to.  That is, this is like
17047     * {@link #getWindowToken}, except if the window this view in is a panel
17048     * window (attached to another containing window), then the token of
17049     * the containing window is returned instead.
17050     *
17051     * @return Returns the associated window token, either
17052     * {@link #getWindowToken()} or the containing window's token.
17053     */
17054    public IBinder getApplicationWindowToken() {
17055        AttachInfo ai = mAttachInfo;
17056        if (ai != null) {
17057            IBinder appWindowToken = ai.mPanelParentWindowToken;
17058            if (appWindowToken == null) {
17059                appWindowToken = ai.mWindowToken;
17060            }
17061            return appWindowToken;
17062        }
17063        return null;
17064    }
17065
17066    /**
17067     * Gets the logical display to which the view's window has been attached.
17068     *
17069     * @return The logical display, or null if the view is not currently attached to a window.
17070     */
17071    public Display getDisplay() {
17072        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
17073    }
17074
17075    /**
17076     * Retrieve private session object this view hierarchy is using to
17077     * communicate with the window manager.
17078     * @return the session object to communicate with the window manager
17079     */
17080    /*package*/ IWindowSession getWindowSession() {
17081        return mAttachInfo != null ? mAttachInfo.mSession : null;
17082    }
17083
17084    /**
17085     * Return the visibility value of the least visible component passed.
17086     */
17087    int combineVisibility(int vis1, int vis2) {
17088        // This works because VISIBLE < INVISIBLE < GONE.
17089        return Math.max(vis1, vis2);
17090    }
17091
17092    /**
17093     * @param info the {@link android.view.View.AttachInfo} to associated with
17094     *        this view
17095     */
17096    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
17097        mAttachInfo = info;
17098        if (mOverlay != null) {
17099            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
17100        }
17101        mWindowAttachCount++;
17102        // We will need to evaluate the drawable state at least once.
17103        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
17104        if (mFloatingTreeObserver != null) {
17105            info.mTreeObserver.merge(mFloatingTreeObserver);
17106            mFloatingTreeObserver = null;
17107        }
17108
17109        registerPendingFrameMetricsObservers();
17110
17111        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
17112            mAttachInfo.mScrollContainers.add(this);
17113            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
17114        }
17115        // Transfer all pending runnables.
17116        if (mRunQueue != null) {
17117            mRunQueue.executeActions(info.mHandler);
17118            mRunQueue = null;
17119        }
17120        performCollectViewAttributes(mAttachInfo, visibility);
17121        onAttachedToWindow();
17122
17123        ListenerInfo li = mListenerInfo;
17124        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
17125                li != null ? li.mOnAttachStateChangeListeners : null;
17126        if (listeners != null && listeners.size() > 0) {
17127            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
17128            // perform the dispatching. The iterator is a safe guard against listeners that
17129            // could mutate the list by calling the various add/remove methods. This prevents
17130            // the array from being modified while we iterate it.
17131            for (OnAttachStateChangeListener listener : listeners) {
17132                listener.onViewAttachedToWindow(this);
17133            }
17134        }
17135
17136        int vis = info.mWindowVisibility;
17137        if (vis != GONE) {
17138            onWindowVisibilityChanged(vis);
17139            if (isShown()) {
17140                // Calling onVisibilityAggregated directly here since the subtree will also
17141                // receive dispatchAttachedToWindow and this same call
17142                onVisibilityAggregated(vis == VISIBLE);
17143            }
17144        }
17145
17146        // Send onVisibilityChanged directly instead of dispatchVisibilityChanged.
17147        // As all views in the subtree will already receive dispatchAttachedToWindow
17148        // traversing the subtree again here is not desired.
17149        onVisibilityChanged(this, visibility);
17150
17151        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
17152            // If nobody has evaluated the drawable state yet, then do it now.
17153            refreshDrawableState();
17154        }
17155        needGlobalAttributesUpdate(false);
17156
17157        notifyEnterOrExitForAutoFillIfNeeded(true);
17158    }
17159
17160    void dispatchDetachedFromWindow() {
17161        AttachInfo info = mAttachInfo;
17162        if (info != null) {
17163            int vis = info.mWindowVisibility;
17164            if (vis != GONE) {
17165                onWindowVisibilityChanged(GONE);
17166                if (isShown()) {
17167                    // Invoking onVisibilityAggregated directly here since the subtree
17168                    // will also receive detached from window
17169                    onVisibilityAggregated(false);
17170                }
17171            }
17172        }
17173
17174        onDetachedFromWindow();
17175        onDetachedFromWindowInternal();
17176
17177        InputMethodManager imm = InputMethodManager.peekInstance();
17178        if (imm != null) {
17179            imm.onViewDetachedFromWindow(this);
17180        }
17181
17182        ListenerInfo li = mListenerInfo;
17183        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
17184                li != null ? li.mOnAttachStateChangeListeners : null;
17185        if (listeners != null && listeners.size() > 0) {
17186            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
17187            // perform the dispatching. The iterator is a safe guard against listeners that
17188            // could mutate the list by calling the various add/remove methods. This prevents
17189            // the array from being modified while we iterate it.
17190            for (OnAttachStateChangeListener listener : listeners) {
17191                listener.onViewDetachedFromWindow(this);
17192            }
17193        }
17194
17195        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
17196            mAttachInfo.mScrollContainers.remove(this);
17197            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
17198        }
17199
17200        mAttachInfo = null;
17201        if (mOverlay != null) {
17202            mOverlay.getOverlayView().dispatchDetachedFromWindow();
17203        }
17204
17205        notifyEnterOrExitForAutoFillIfNeeded(false);
17206    }
17207
17208    /**
17209     * Cancel any deferred high-level input events that were previously posted to the event queue.
17210     *
17211     * <p>Many views post high-level events such as click handlers to the event queue
17212     * to run deferred in order to preserve a desired user experience - clearing visible
17213     * pressed states before executing, etc. This method will abort any events of this nature
17214     * that are currently in flight.</p>
17215     *
17216     * <p>Custom views that generate their own high-level deferred input events should override
17217     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
17218     *
17219     * <p>This will also cancel pending input events for any child views.</p>
17220     *
17221     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
17222     * This will not impact newer events posted after this call that may occur as a result of
17223     * lower-level input events still waiting in the queue. If you are trying to prevent
17224     * double-submitted  events for the duration of some sort of asynchronous transaction
17225     * you should also take other steps to protect against unexpected double inputs e.g. calling
17226     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
17227     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
17228     */
17229    public final void cancelPendingInputEvents() {
17230        dispatchCancelPendingInputEvents();
17231    }
17232
17233    /**
17234     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
17235     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
17236     */
17237    void dispatchCancelPendingInputEvents() {
17238        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
17239        onCancelPendingInputEvents();
17240        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
17241            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
17242                    " did not call through to super.onCancelPendingInputEvents()");
17243        }
17244    }
17245
17246    /**
17247     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
17248     * a parent view.
17249     *
17250     * <p>This method is responsible for removing any pending high-level input events that were
17251     * posted to the event queue to run later. Custom view classes that post their own deferred
17252     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
17253     * {@link android.os.Handler} should override this method, call
17254     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
17255     * </p>
17256     */
17257    public void onCancelPendingInputEvents() {
17258        removePerformClickCallback();
17259        cancelLongPress();
17260        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
17261    }
17262
17263    /**
17264     * Store this view hierarchy's frozen state into the given container.
17265     *
17266     * @param container The SparseArray in which to save the view's state.
17267     *
17268     * @see #restoreHierarchyState(android.util.SparseArray)
17269     * @see #dispatchSaveInstanceState(android.util.SparseArray)
17270     * @see #onSaveInstanceState()
17271     */
17272    public void saveHierarchyState(SparseArray<Parcelable> container) {
17273        dispatchSaveInstanceState(container);
17274    }
17275
17276    /**
17277     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
17278     * this view and its children. May be overridden to modify how freezing happens to a
17279     * view's children; for example, some views may want to not store state for their children.
17280     *
17281     * @param container The SparseArray in which to save the view's state.
17282     *
17283     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
17284     * @see #saveHierarchyState(android.util.SparseArray)
17285     * @see #onSaveInstanceState()
17286     */
17287    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
17288        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
17289            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
17290            Parcelable state = onSaveInstanceState();
17291            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
17292                throw new IllegalStateException(
17293                        "Derived class did not call super.onSaveInstanceState()");
17294            }
17295            if (state != null) {
17296                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
17297                // + ": " + state);
17298                container.put(mID, state);
17299            }
17300        }
17301    }
17302
17303    /**
17304     * Hook allowing a view to generate a representation of its internal state
17305     * that can later be used to create a new instance with that same state.
17306     * This state should only contain information that is not persistent or can
17307     * not be reconstructed later. For example, you will never store your
17308     * current position on screen because that will be computed again when a
17309     * new instance of the view is placed in its view hierarchy.
17310     * <p>
17311     * Some examples of things you may store here: the current cursor position
17312     * in a text view (but usually not the text itself since that is stored in a
17313     * content provider or other persistent storage), the currently selected
17314     * item in a list view.
17315     *
17316     * @return Returns a Parcelable object containing the view's current dynamic
17317     *         state, or null if there is nothing interesting to save. The
17318     *         default implementation returns null.
17319     * @see #onRestoreInstanceState(android.os.Parcelable)
17320     * @see #saveHierarchyState(android.util.SparseArray)
17321     * @see #dispatchSaveInstanceState(android.util.SparseArray)
17322     * @see #setSaveEnabled(boolean)
17323     */
17324    @CallSuper
17325    protected Parcelable onSaveInstanceState() {
17326        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
17327        if (mStartActivityRequestWho != null || isAutofilled()
17328                || mAccessibilityViewId > LAST_APP_ACCESSIBILITY_ID) {
17329            BaseSavedState state = new BaseSavedState(AbsSavedState.EMPTY_STATE);
17330
17331            if (mStartActivityRequestWho != null) {
17332                state.mSavedData |= BaseSavedState.START_ACTIVITY_REQUESTED_WHO_SAVED;
17333            }
17334
17335            if (isAutofilled()) {
17336                state.mSavedData |= BaseSavedState.IS_AUTOFILLED;
17337            }
17338
17339            if (mAccessibilityViewId > LAST_APP_ACCESSIBILITY_ID) {
17340                state.mSavedData |= BaseSavedState.ACCESSIBILITY_ID;
17341            }
17342
17343            state.mStartActivityRequestWhoSaved = mStartActivityRequestWho;
17344            state.mIsAutofilled = isAutofilled();
17345            state.mAccessibilityViewId = mAccessibilityViewId;
17346            return state;
17347        }
17348        return BaseSavedState.EMPTY_STATE;
17349    }
17350
17351    /**
17352     * Restore this view hierarchy's frozen state from the given container.
17353     *
17354     * @param container The SparseArray which holds previously frozen states.
17355     *
17356     * @see #saveHierarchyState(android.util.SparseArray)
17357     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
17358     * @see #onRestoreInstanceState(android.os.Parcelable)
17359     */
17360    public void restoreHierarchyState(SparseArray<Parcelable> container) {
17361        dispatchRestoreInstanceState(container);
17362    }
17363
17364    /**
17365     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
17366     * state for this view and its children. May be overridden to modify how restoring
17367     * happens to a view's children; for example, some views may want to not store state
17368     * for their children.
17369     *
17370     * @param container The SparseArray which holds previously saved state.
17371     *
17372     * @see #dispatchSaveInstanceState(android.util.SparseArray)
17373     * @see #restoreHierarchyState(android.util.SparseArray)
17374     * @see #onRestoreInstanceState(android.os.Parcelable)
17375     */
17376    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
17377        if (mID != NO_ID) {
17378            Parcelable state = container.get(mID);
17379            if (state != null) {
17380                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
17381                // + ": " + state);
17382                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
17383                onRestoreInstanceState(state);
17384                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
17385                    throw new IllegalStateException(
17386                            "Derived class did not call super.onRestoreInstanceState()");
17387                }
17388            }
17389        }
17390    }
17391
17392    /**
17393     * Hook allowing a view to re-apply a representation of its internal state that had previously
17394     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
17395     * null state.
17396     *
17397     * @param state The frozen state that had previously been returned by
17398     *        {@link #onSaveInstanceState}.
17399     *
17400     * @see #onSaveInstanceState()
17401     * @see #restoreHierarchyState(android.util.SparseArray)
17402     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
17403     */
17404    @CallSuper
17405    protected void onRestoreInstanceState(Parcelable state) {
17406        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
17407        if (state != null && !(state instanceof AbsSavedState)) {
17408            throw new IllegalArgumentException("Wrong state class, expecting View State but "
17409                    + "received " + state.getClass().toString() + " instead. This usually happens "
17410                    + "when two views of different type have the same id in the same hierarchy. "
17411                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
17412                    + "other views do not use the same id.");
17413        }
17414        if (state != null && state instanceof BaseSavedState) {
17415            BaseSavedState baseState = (BaseSavedState) state;
17416
17417            if ((baseState.mSavedData & BaseSavedState.START_ACTIVITY_REQUESTED_WHO_SAVED) != 0) {
17418                mStartActivityRequestWho = baseState.mStartActivityRequestWhoSaved;
17419            }
17420            if ((baseState.mSavedData & BaseSavedState.IS_AUTOFILLED) != 0) {
17421                setAutofilled(baseState.mIsAutofilled);
17422            }
17423            if ((baseState.mSavedData & BaseSavedState.ACCESSIBILITY_ID) != 0) {
17424                mAccessibilityViewId = baseState.mAccessibilityViewId;
17425            }
17426        }
17427    }
17428
17429    /**
17430     * <p>Return the time at which the drawing of the view hierarchy started.</p>
17431     *
17432     * @return the drawing start time in milliseconds
17433     */
17434    public long getDrawingTime() {
17435        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
17436    }
17437
17438    /**
17439     * <p>Enables or disables the duplication of the parent's state into this view. When
17440     * duplication is enabled, this view gets its drawable state from its parent rather
17441     * than from its own internal properties.</p>
17442     *
17443     * <p>Note: in the current implementation, setting this property to true after the
17444     * view was added to a ViewGroup might have no effect at all. This property should
17445     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
17446     *
17447     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
17448     * property is enabled, an exception will be thrown.</p>
17449     *
17450     * <p>Note: if the child view uses and updates additional states which are unknown to the
17451     * parent, these states should not be affected by this method.</p>
17452     *
17453     * @param enabled True to enable duplication of the parent's drawable state, false
17454     *                to disable it.
17455     *
17456     * @see #getDrawableState()
17457     * @see #isDuplicateParentStateEnabled()
17458     */
17459    public void setDuplicateParentStateEnabled(boolean enabled) {
17460        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
17461    }
17462
17463    /**
17464     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
17465     *
17466     * @return True if this view's drawable state is duplicated from the parent,
17467     *         false otherwise
17468     *
17469     * @see #getDrawableState()
17470     * @see #setDuplicateParentStateEnabled(boolean)
17471     */
17472    public boolean isDuplicateParentStateEnabled() {
17473        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
17474    }
17475
17476    /**
17477     * <p>Specifies the type of layer backing this view. The layer can be
17478     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
17479     * {@link #LAYER_TYPE_HARDWARE}.</p>
17480     *
17481     * <p>A layer is associated with an optional {@link android.graphics.Paint}
17482     * instance that controls how the layer is composed on screen. The following
17483     * properties of the paint are taken into account when composing the layer:</p>
17484     * <ul>
17485     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
17486     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
17487     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
17488     * </ul>
17489     *
17490     * <p>If this view has an alpha value set to < 1.0 by calling
17491     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superseded
17492     * by this view's alpha value.</p>
17493     *
17494     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
17495     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
17496     * for more information on when and how to use layers.</p>
17497     *
17498     * @param layerType The type of layer to use with this view, must be one of
17499     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
17500     *        {@link #LAYER_TYPE_HARDWARE}
17501     * @param paint The paint used to compose the layer. This argument is optional
17502     *        and can be null. It is ignored when the layer type is
17503     *        {@link #LAYER_TYPE_NONE}
17504     *
17505     * @see #getLayerType()
17506     * @see #LAYER_TYPE_NONE
17507     * @see #LAYER_TYPE_SOFTWARE
17508     * @see #LAYER_TYPE_HARDWARE
17509     * @see #setAlpha(float)
17510     *
17511     * @attr ref android.R.styleable#View_layerType
17512     */
17513    public void setLayerType(int layerType, @Nullable Paint paint) {
17514        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
17515            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
17516                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
17517        }
17518
17519        boolean typeChanged = mRenderNode.setLayerType(layerType);
17520
17521        if (!typeChanged) {
17522            setLayerPaint(paint);
17523            return;
17524        }
17525
17526        if (layerType != LAYER_TYPE_SOFTWARE) {
17527            // Destroy any previous software drawing cache if present
17528            // NOTE: even if previous layer type is HW, we do this to ensure we've cleaned up
17529            // drawing cache created in View#draw when drawing to a SW canvas.
17530            destroyDrawingCache();
17531        }
17532
17533        mLayerType = layerType;
17534        mLayerPaint = mLayerType == LAYER_TYPE_NONE ? null : paint;
17535        mRenderNode.setLayerPaint(mLayerPaint);
17536
17537        // draw() behaves differently if we are on a layer, so we need to
17538        // invalidate() here
17539        invalidateParentCaches();
17540        invalidate(true);
17541    }
17542
17543    /**
17544     * Updates the {@link Paint} object used with the current layer (used only if the current
17545     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
17546     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
17547     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
17548     * ensure that the view gets redrawn immediately.
17549     *
17550     * <p>A layer is associated with an optional {@link android.graphics.Paint}
17551     * instance that controls how the layer is composed on screen. The following
17552     * properties of the paint are taken into account when composing the layer:</p>
17553     * <ul>
17554     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
17555     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
17556     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
17557     * </ul>
17558     *
17559     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
17560     * alpha value of the layer's paint is superseded by this view's alpha value.</p>
17561     *
17562     * @param paint The paint used to compose the layer. This argument is optional
17563     *        and can be null. It is ignored when the layer type is
17564     *        {@link #LAYER_TYPE_NONE}
17565     *
17566     * @see #setLayerType(int, android.graphics.Paint)
17567     */
17568    public void setLayerPaint(@Nullable Paint paint) {
17569        int layerType = getLayerType();
17570        if (layerType != LAYER_TYPE_NONE) {
17571            mLayerPaint = paint;
17572            if (layerType == LAYER_TYPE_HARDWARE) {
17573                if (mRenderNode.setLayerPaint(paint)) {
17574                    invalidateViewProperty(false, false);
17575                }
17576            } else {
17577                invalidate();
17578            }
17579        }
17580    }
17581
17582    /**
17583     * Indicates what type of layer is currently associated with this view. By default
17584     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
17585     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
17586     * for more information on the different types of layers.
17587     *
17588     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
17589     *         {@link #LAYER_TYPE_HARDWARE}
17590     *
17591     * @see #setLayerType(int, android.graphics.Paint)
17592     * @see #buildLayer()
17593     * @see #LAYER_TYPE_NONE
17594     * @see #LAYER_TYPE_SOFTWARE
17595     * @see #LAYER_TYPE_HARDWARE
17596     */
17597    public int getLayerType() {
17598        return mLayerType;
17599    }
17600
17601    /**
17602     * Forces this view's layer to be created and this view to be rendered
17603     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
17604     * invoking this method will have no effect.
17605     *
17606     * This method can for instance be used to render a view into its layer before
17607     * starting an animation. If this view is complex, rendering into the layer
17608     * before starting the animation will avoid skipping frames.
17609     *
17610     * @throws IllegalStateException If this view is not attached to a window
17611     *
17612     * @see #setLayerType(int, android.graphics.Paint)
17613     */
17614    public void buildLayer() {
17615        if (mLayerType == LAYER_TYPE_NONE) return;
17616
17617        final AttachInfo attachInfo = mAttachInfo;
17618        if (attachInfo == null) {
17619            throw new IllegalStateException("This view must be attached to a window first");
17620        }
17621
17622        if (getWidth() == 0 || getHeight() == 0) {
17623            return;
17624        }
17625
17626        switch (mLayerType) {
17627            case LAYER_TYPE_HARDWARE:
17628                updateDisplayListIfDirty();
17629                if (attachInfo.mThreadedRenderer != null && mRenderNode.isValid()) {
17630                    attachInfo.mThreadedRenderer.buildLayer(mRenderNode);
17631                }
17632                break;
17633            case LAYER_TYPE_SOFTWARE:
17634                buildDrawingCache(true);
17635                break;
17636        }
17637    }
17638
17639    /**
17640     * Destroys all hardware rendering resources. This method is invoked
17641     * when the system needs to reclaim resources. Upon execution of this
17642     * method, you should free any OpenGL resources created by the view.
17643     *
17644     * Note: you <strong>must</strong> call
17645     * <code>super.destroyHardwareResources()</code> when overriding
17646     * this method.
17647     *
17648     * @hide
17649     */
17650    @CallSuper
17651    protected void destroyHardwareResources() {
17652        if (mOverlay != null) {
17653            mOverlay.getOverlayView().destroyHardwareResources();
17654        }
17655        if (mGhostView != null) {
17656            mGhostView.destroyHardwareResources();
17657        }
17658    }
17659
17660    /**
17661     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
17662     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
17663     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
17664     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
17665     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
17666     * null.</p>
17667     *
17668     * <p>Enabling the drawing cache is similar to
17669     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
17670     * acceleration is turned off. When hardware acceleration is turned on, enabling the
17671     * drawing cache has no effect on rendering because the system uses a different mechanism
17672     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
17673     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
17674     * for information on how to enable software and hardware layers.</p>
17675     *
17676     * <p>This API can be used to manually generate
17677     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
17678     * {@link #getDrawingCache()}.</p>
17679     *
17680     * @param enabled true to enable the drawing cache, false otherwise
17681     *
17682     * @see #isDrawingCacheEnabled()
17683     * @see #getDrawingCache()
17684     * @see #buildDrawingCache()
17685     * @see #setLayerType(int, android.graphics.Paint)
17686     */
17687    public void setDrawingCacheEnabled(boolean enabled) {
17688        mCachingFailed = false;
17689        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
17690    }
17691
17692    /**
17693     * <p>Indicates whether the drawing cache is enabled for this view.</p>
17694     *
17695     * @return true if the drawing cache is enabled
17696     *
17697     * @see #setDrawingCacheEnabled(boolean)
17698     * @see #getDrawingCache()
17699     */
17700    @ViewDebug.ExportedProperty(category = "drawing")
17701    public boolean isDrawingCacheEnabled() {
17702        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
17703    }
17704
17705    /**
17706     * Debugging utility which recursively outputs the dirty state of a view and its
17707     * descendants.
17708     *
17709     * @hide
17710     */
17711    @SuppressWarnings({"UnusedDeclaration"})
17712    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
17713        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
17714                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
17715                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
17716                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
17717        if (clear) {
17718            mPrivateFlags &= clearMask;
17719        }
17720        if (this instanceof ViewGroup) {
17721            ViewGroup parent = (ViewGroup) this;
17722            final int count = parent.getChildCount();
17723            for (int i = 0; i < count; i++) {
17724                final View child = parent.getChildAt(i);
17725                child.outputDirtyFlags(indent + "  ", clear, clearMask);
17726            }
17727        }
17728    }
17729
17730    /**
17731     * This method is used by ViewGroup to cause its children to restore or recreate their
17732     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
17733     * to recreate its own display list, which would happen if it went through the normal
17734     * draw/dispatchDraw mechanisms.
17735     *
17736     * @hide
17737     */
17738    protected void dispatchGetDisplayList() {}
17739
17740    /**
17741     * A view that is not attached or hardware accelerated cannot create a display list.
17742     * This method checks these conditions and returns the appropriate result.
17743     *
17744     * @return true if view has the ability to create a display list, false otherwise.
17745     *
17746     * @hide
17747     */
17748    public boolean canHaveDisplayList() {
17749        return !(mAttachInfo == null || mAttachInfo.mThreadedRenderer == null);
17750    }
17751
17752    /**
17753     * Gets the RenderNode for the view, and updates its DisplayList (if needed and supported)
17754     * @hide
17755     */
17756    @NonNull
17757    public RenderNode updateDisplayListIfDirty() {
17758        final RenderNode renderNode = mRenderNode;
17759        if (!canHaveDisplayList()) {
17760            // can't populate RenderNode, don't try
17761            return renderNode;
17762        }
17763
17764        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0
17765                || !renderNode.isValid()
17766                || (mRecreateDisplayList)) {
17767            // Don't need to recreate the display list, just need to tell our
17768            // children to restore/recreate theirs
17769            if (renderNode.isValid()
17770                    && !mRecreateDisplayList) {
17771                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
17772                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17773                dispatchGetDisplayList();
17774
17775                return renderNode; // no work needed
17776            }
17777
17778            // If we got here, we're recreating it. Mark it as such to ensure that
17779            // we copy in child display lists into ours in drawChild()
17780            mRecreateDisplayList = true;
17781
17782            int width = mRight - mLeft;
17783            int height = mBottom - mTop;
17784            int layerType = getLayerType();
17785
17786            final DisplayListCanvas canvas = renderNode.start(width, height);
17787            canvas.setHighContrastText(mAttachInfo.mHighContrastText);
17788
17789            try {
17790                if (layerType == LAYER_TYPE_SOFTWARE) {
17791                    buildDrawingCache(true);
17792                    Bitmap cache = getDrawingCache(true);
17793                    if (cache != null) {
17794                        canvas.drawBitmap(cache, 0, 0, mLayerPaint);
17795                    }
17796                } else {
17797                    computeScroll();
17798
17799                    canvas.translate(-mScrollX, -mScrollY);
17800                    mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
17801                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17802
17803                    // Fast path for layouts with no backgrounds
17804                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
17805                        dispatchDraw(canvas);
17806                        drawAutofilledHighlight(canvas);
17807                        if (mOverlay != null && !mOverlay.isEmpty()) {
17808                            mOverlay.getOverlayView().draw(canvas);
17809                        }
17810                        if (debugDraw()) {
17811                            debugDrawFocus(canvas);
17812                        }
17813                    } else {
17814                        draw(canvas);
17815                    }
17816                }
17817            } finally {
17818                renderNode.end(canvas);
17819                setDisplayListProperties(renderNode);
17820            }
17821        } else {
17822            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
17823            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
17824        }
17825        return renderNode;
17826    }
17827
17828    private void resetDisplayList() {
17829        mRenderNode.discardDisplayList();
17830        if (mBackgroundRenderNode != null) {
17831            mBackgroundRenderNode.discardDisplayList();
17832        }
17833    }
17834
17835    /**
17836     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
17837     *
17838     * @return A non-scaled bitmap representing this view or null if cache is disabled.
17839     *
17840     * @see #getDrawingCache(boolean)
17841     */
17842    public Bitmap getDrawingCache() {
17843        return getDrawingCache(false);
17844    }
17845
17846    /**
17847     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
17848     * is null when caching is disabled. If caching is enabled and the cache is not ready,
17849     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
17850     * draw from the cache when the cache is enabled. To benefit from the cache, you must
17851     * request the drawing cache by calling this method and draw it on screen if the
17852     * returned bitmap is not null.</p>
17853     *
17854     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
17855     * this method will create a bitmap of the same size as this view. Because this bitmap
17856     * will be drawn scaled by the parent ViewGroup, the result on screen might show
17857     * scaling artifacts. To avoid such artifacts, you should call this method by setting
17858     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
17859     * size than the view. This implies that your application must be able to handle this
17860     * size.</p>
17861     *
17862     * @param autoScale Indicates whether the generated bitmap should be scaled based on
17863     *        the current density of the screen when the application is in compatibility
17864     *        mode.
17865     *
17866     * @return A bitmap representing this view or null if cache is disabled.
17867     *
17868     * @see #setDrawingCacheEnabled(boolean)
17869     * @see #isDrawingCacheEnabled()
17870     * @see #buildDrawingCache(boolean)
17871     * @see #destroyDrawingCache()
17872     */
17873    public Bitmap getDrawingCache(boolean autoScale) {
17874        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
17875            return null;
17876        }
17877        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
17878            buildDrawingCache(autoScale);
17879        }
17880        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
17881    }
17882
17883    /**
17884     * <p>Frees the resources used by the drawing cache. If you call
17885     * {@link #buildDrawingCache()} manually without calling
17886     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
17887     * should cleanup the cache with this method afterwards.</p>
17888     *
17889     * @see #setDrawingCacheEnabled(boolean)
17890     * @see #buildDrawingCache()
17891     * @see #getDrawingCache()
17892     */
17893    public void destroyDrawingCache() {
17894        if (mDrawingCache != null) {
17895            mDrawingCache.recycle();
17896            mDrawingCache = null;
17897        }
17898        if (mUnscaledDrawingCache != null) {
17899            mUnscaledDrawingCache.recycle();
17900            mUnscaledDrawingCache = null;
17901        }
17902    }
17903
17904    /**
17905     * Setting a solid background color for the drawing cache's bitmaps will improve
17906     * performance and memory usage. Note, though that this should only be used if this
17907     * view will always be drawn on top of a solid color.
17908     *
17909     * @param color The background color to use for the drawing cache's bitmap
17910     *
17911     * @see #setDrawingCacheEnabled(boolean)
17912     * @see #buildDrawingCache()
17913     * @see #getDrawingCache()
17914     */
17915    public void setDrawingCacheBackgroundColor(@ColorInt int color) {
17916        if (color != mDrawingCacheBackgroundColor) {
17917            mDrawingCacheBackgroundColor = color;
17918            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
17919        }
17920    }
17921
17922    /**
17923     * @see #setDrawingCacheBackgroundColor(int)
17924     *
17925     * @return The background color to used for the drawing cache's bitmap
17926     */
17927    @ColorInt
17928    public int getDrawingCacheBackgroundColor() {
17929        return mDrawingCacheBackgroundColor;
17930    }
17931
17932    /**
17933     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
17934     *
17935     * @see #buildDrawingCache(boolean)
17936     */
17937    public void buildDrawingCache() {
17938        buildDrawingCache(false);
17939    }
17940
17941    /**
17942     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
17943     *
17944     * <p>If you call {@link #buildDrawingCache()} manually without calling
17945     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
17946     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
17947     *
17948     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
17949     * this method will create a bitmap of the same size as this view. Because this bitmap
17950     * will be drawn scaled by the parent ViewGroup, the result on screen might show
17951     * scaling artifacts. To avoid such artifacts, you should call this method by setting
17952     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
17953     * size than the view. This implies that your application must be able to handle this
17954     * size.</p>
17955     *
17956     * <p>You should avoid calling this method when hardware acceleration is enabled. If
17957     * you do not need the drawing cache bitmap, calling this method will increase memory
17958     * usage and cause the view to be rendered in software once, thus negatively impacting
17959     * performance.</p>
17960     *
17961     * @see #getDrawingCache()
17962     * @see #destroyDrawingCache()
17963     */
17964    public void buildDrawingCache(boolean autoScale) {
17965        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
17966                mDrawingCache == null : mUnscaledDrawingCache == null)) {
17967            if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) {
17968                Trace.traceBegin(Trace.TRACE_TAG_VIEW,
17969                        "buildDrawingCache/SW Layer for " + getClass().getSimpleName());
17970            }
17971            try {
17972                buildDrawingCacheImpl(autoScale);
17973            } finally {
17974                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
17975            }
17976        }
17977    }
17978
17979    /**
17980     * private, internal implementation of buildDrawingCache, used to enable tracing
17981     */
17982    private void buildDrawingCacheImpl(boolean autoScale) {
17983        mCachingFailed = false;
17984
17985        int width = mRight - mLeft;
17986        int height = mBottom - mTop;
17987
17988        final AttachInfo attachInfo = mAttachInfo;
17989        final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
17990
17991        if (autoScale && scalingRequired) {
17992            width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
17993            height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
17994        }
17995
17996        final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
17997        final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
17998        final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
17999
18000        final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
18001        final long drawingCacheSize =
18002                ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
18003        if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
18004            if (width > 0 && height > 0) {
18005                Log.w(VIEW_LOG_TAG, getClass().getSimpleName() + " not displayed because it is"
18006                        + " too large to fit into a software layer (or drawing cache), needs "
18007                        + projectedBitmapSize + " bytes, only "
18008                        + drawingCacheSize + " available");
18009            }
18010            destroyDrawingCache();
18011            mCachingFailed = true;
18012            return;
18013        }
18014
18015        boolean clear = true;
18016        Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
18017
18018        if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
18019            Bitmap.Config quality;
18020            if (!opaque) {
18021                // Never pick ARGB_4444 because it looks awful
18022                // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
18023                switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
18024                    case DRAWING_CACHE_QUALITY_AUTO:
18025                    case DRAWING_CACHE_QUALITY_LOW:
18026                    case DRAWING_CACHE_QUALITY_HIGH:
18027                    default:
18028                        quality = Bitmap.Config.ARGB_8888;
18029                        break;
18030                }
18031            } else {
18032                // Optimization for translucent windows
18033                // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
18034                quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
18035            }
18036
18037            // Try to cleanup memory
18038            if (bitmap != null) bitmap.recycle();
18039
18040            try {
18041                bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
18042                        width, height, quality);
18043                bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
18044                if (autoScale) {
18045                    mDrawingCache = bitmap;
18046                } else {
18047                    mUnscaledDrawingCache = bitmap;
18048                }
18049                if (opaque && use32BitCache) bitmap.setHasAlpha(false);
18050            } catch (OutOfMemoryError e) {
18051                // If there is not enough memory to create the bitmap cache, just
18052                // ignore the issue as bitmap caches are not required to draw the
18053                // view hierarchy
18054                if (autoScale) {
18055                    mDrawingCache = null;
18056                } else {
18057                    mUnscaledDrawingCache = null;
18058                }
18059                mCachingFailed = true;
18060                return;
18061            }
18062
18063            clear = drawingCacheBackgroundColor != 0;
18064        }
18065
18066        Canvas canvas;
18067        if (attachInfo != null) {
18068            canvas = attachInfo.mCanvas;
18069            if (canvas == null) {
18070                canvas = new Canvas();
18071            }
18072            canvas.setBitmap(bitmap);
18073            // Temporarily clobber the cached Canvas in case one of our children
18074            // is also using a drawing cache. Without this, the children would
18075            // steal the canvas by attaching their own bitmap to it and bad, bad
18076            // thing would happen (invisible views, corrupted drawings, etc.)
18077            attachInfo.mCanvas = null;
18078        } else {
18079            // This case should hopefully never or seldom happen
18080            canvas = new Canvas(bitmap);
18081        }
18082
18083        if (clear) {
18084            bitmap.eraseColor(drawingCacheBackgroundColor);
18085        }
18086
18087        computeScroll();
18088        final int restoreCount = canvas.save();
18089
18090        if (autoScale && scalingRequired) {
18091            final float scale = attachInfo.mApplicationScale;
18092            canvas.scale(scale, scale);
18093        }
18094
18095        canvas.translate(-mScrollX, -mScrollY);
18096
18097        mPrivateFlags |= PFLAG_DRAWN;
18098        if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
18099                mLayerType != LAYER_TYPE_NONE) {
18100            mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
18101        }
18102
18103        // Fast path for layouts with no backgrounds
18104        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
18105            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
18106            dispatchDraw(canvas);
18107            drawAutofilledHighlight(canvas);
18108            if (mOverlay != null && !mOverlay.isEmpty()) {
18109                mOverlay.getOverlayView().draw(canvas);
18110            }
18111        } else {
18112            draw(canvas);
18113        }
18114
18115        canvas.restoreToCount(restoreCount);
18116        canvas.setBitmap(null);
18117
18118        if (attachInfo != null) {
18119            // Restore the cached Canvas for our siblings
18120            attachInfo.mCanvas = canvas;
18121        }
18122    }
18123
18124    /**
18125     * Create a snapshot of the view into a bitmap.  We should probably make
18126     * some form of this public, but should think about the API.
18127     *
18128     * @hide
18129     */
18130    public Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
18131        int width = mRight - mLeft;
18132        int height = mBottom - mTop;
18133
18134        final AttachInfo attachInfo = mAttachInfo;
18135        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
18136        width = (int) ((width * scale) + 0.5f);
18137        height = (int) ((height * scale) + 0.5f);
18138
18139        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
18140                width > 0 ? width : 1, height > 0 ? height : 1, quality);
18141        if (bitmap == null) {
18142            throw new OutOfMemoryError();
18143        }
18144
18145        Resources resources = getResources();
18146        if (resources != null) {
18147            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
18148        }
18149
18150        Canvas canvas;
18151        if (attachInfo != null) {
18152            canvas = attachInfo.mCanvas;
18153            if (canvas == null) {
18154                canvas = new Canvas();
18155            }
18156            canvas.setBitmap(bitmap);
18157            // Temporarily clobber the cached Canvas in case one of our children
18158            // is also using a drawing cache. Without this, the children would
18159            // steal the canvas by attaching their own bitmap to it and bad, bad
18160            // things would happen (invisible views, corrupted drawings, etc.)
18161            attachInfo.mCanvas = null;
18162        } else {
18163            // This case should hopefully never or seldom happen
18164            canvas = new Canvas(bitmap);
18165        }
18166        boolean enabledHwBitmapsInSwMode = canvas.isHwBitmapsInSwModeEnabled();
18167        canvas.setHwBitmapsInSwModeEnabled(true);
18168        if ((backgroundColor & 0xff000000) != 0) {
18169            bitmap.eraseColor(backgroundColor);
18170        }
18171
18172        computeScroll();
18173        final int restoreCount = canvas.save();
18174        canvas.scale(scale, scale);
18175        canvas.translate(-mScrollX, -mScrollY);
18176
18177        // Temporarily remove the dirty mask
18178        int flags = mPrivateFlags;
18179        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
18180
18181        // Fast path for layouts with no backgrounds
18182        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
18183            dispatchDraw(canvas);
18184            drawAutofilledHighlight(canvas);
18185            if (mOverlay != null && !mOverlay.isEmpty()) {
18186                mOverlay.getOverlayView().draw(canvas);
18187            }
18188        } else {
18189            draw(canvas);
18190        }
18191
18192        mPrivateFlags = flags;
18193
18194        canvas.restoreToCount(restoreCount);
18195        canvas.setBitmap(null);
18196        canvas.setHwBitmapsInSwModeEnabled(enabledHwBitmapsInSwMode);
18197
18198        if (attachInfo != null) {
18199            // Restore the cached Canvas for our siblings
18200            attachInfo.mCanvas = canvas;
18201        }
18202
18203        return bitmap;
18204    }
18205
18206    /**
18207     * Indicates whether this View is currently in edit mode. A View is usually
18208     * in edit mode when displayed within a developer tool. For instance, if
18209     * this View is being drawn by a visual user interface builder, this method
18210     * should return true.
18211     *
18212     * Subclasses should check the return value of this method to provide
18213     * different behaviors if their normal behavior might interfere with the
18214     * host environment. For instance: the class spawns a thread in its
18215     * constructor, the drawing code relies on device-specific features, etc.
18216     *
18217     * This method is usually checked in the drawing code of custom widgets.
18218     *
18219     * @return True if this View is in edit mode, false otherwise.
18220     */
18221    public boolean isInEditMode() {
18222        return false;
18223    }
18224
18225    /**
18226     * If the View draws content inside its padding and enables fading edges,
18227     * it needs to support padding offsets. Padding offsets are added to the
18228     * fading edges to extend the length of the fade so that it covers pixels
18229     * drawn inside the padding.
18230     *
18231     * Subclasses of this class should override this method if they need
18232     * to draw content inside the padding.
18233     *
18234     * @return True if padding offset must be applied, false otherwise.
18235     *
18236     * @see #getLeftPaddingOffset()
18237     * @see #getRightPaddingOffset()
18238     * @see #getTopPaddingOffset()
18239     * @see #getBottomPaddingOffset()
18240     *
18241     * @since CURRENT
18242     */
18243    protected boolean isPaddingOffsetRequired() {
18244        return false;
18245    }
18246
18247    /**
18248     * Amount by which to extend the left fading region. Called only when
18249     * {@link #isPaddingOffsetRequired()} returns true.
18250     *
18251     * @return The left padding offset in pixels.
18252     *
18253     * @see #isPaddingOffsetRequired()
18254     *
18255     * @since CURRENT
18256     */
18257    protected int getLeftPaddingOffset() {
18258        return 0;
18259    }
18260
18261    /**
18262     * Amount by which to extend the right fading region. Called only when
18263     * {@link #isPaddingOffsetRequired()} returns true.
18264     *
18265     * @return The right padding offset in pixels.
18266     *
18267     * @see #isPaddingOffsetRequired()
18268     *
18269     * @since CURRENT
18270     */
18271    protected int getRightPaddingOffset() {
18272        return 0;
18273    }
18274
18275    /**
18276     * Amount by which to extend the top fading region. Called only when
18277     * {@link #isPaddingOffsetRequired()} returns true.
18278     *
18279     * @return The top padding offset in pixels.
18280     *
18281     * @see #isPaddingOffsetRequired()
18282     *
18283     * @since CURRENT
18284     */
18285    protected int getTopPaddingOffset() {
18286        return 0;
18287    }
18288
18289    /**
18290     * Amount by which to extend the bottom fading region. Called only when
18291     * {@link #isPaddingOffsetRequired()} returns true.
18292     *
18293     * @return The bottom padding offset in pixels.
18294     *
18295     * @see #isPaddingOffsetRequired()
18296     *
18297     * @since CURRENT
18298     */
18299    protected int getBottomPaddingOffset() {
18300        return 0;
18301    }
18302
18303    /**
18304     * @hide
18305     * @param offsetRequired
18306     */
18307    protected int getFadeTop(boolean offsetRequired) {
18308        int top = mPaddingTop;
18309        if (offsetRequired) top += getTopPaddingOffset();
18310        return top;
18311    }
18312
18313    /**
18314     * @hide
18315     * @param offsetRequired
18316     */
18317    protected int getFadeHeight(boolean offsetRequired) {
18318        int padding = mPaddingTop;
18319        if (offsetRequired) padding += getTopPaddingOffset();
18320        return mBottom - mTop - mPaddingBottom - padding;
18321    }
18322
18323    /**
18324     * <p>Indicates whether this view is attached to a hardware accelerated
18325     * window or not.</p>
18326     *
18327     * <p>Even if this method returns true, it does not mean that every call
18328     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
18329     * accelerated {@link android.graphics.Canvas}. For instance, if this view
18330     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
18331     * window is hardware accelerated,
18332     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
18333     * return false, and this method will return true.</p>
18334     *
18335     * @return True if the view is attached to a window and the window is
18336     *         hardware accelerated; false in any other case.
18337     */
18338    @ViewDebug.ExportedProperty(category = "drawing")
18339    public boolean isHardwareAccelerated() {
18340        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
18341    }
18342
18343    /**
18344     * Sets a rectangular area on this view to which the view will be clipped
18345     * when it is drawn. Setting the value to null will remove the clip bounds
18346     * and the view will draw normally, using its full bounds.
18347     *
18348     * @param clipBounds The rectangular area, in the local coordinates of
18349     * this view, to which future drawing operations will be clipped.
18350     */
18351    public void setClipBounds(Rect clipBounds) {
18352        if (clipBounds == mClipBounds
18353                || (clipBounds != null && clipBounds.equals(mClipBounds))) {
18354            return;
18355        }
18356        if (clipBounds != null) {
18357            if (mClipBounds == null) {
18358                mClipBounds = new Rect(clipBounds);
18359            } else {
18360                mClipBounds.set(clipBounds);
18361            }
18362        } else {
18363            mClipBounds = null;
18364        }
18365        mRenderNode.setClipBounds(mClipBounds);
18366        invalidateViewProperty(false, false);
18367    }
18368
18369    /**
18370     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
18371     *
18372     * @return A copy of the current clip bounds if clip bounds are set,
18373     * otherwise null.
18374     */
18375    public Rect getClipBounds() {
18376        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
18377    }
18378
18379
18380    /**
18381     * Populates an output rectangle with the clip bounds of the view,
18382     * returning {@code true} if successful or {@code false} if the view's
18383     * clip bounds are {@code null}.
18384     *
18385     * @param outRect rectangle in which to place the clip bounds of the view
18386     * @return {@code true} if successful or {@code false} if the view's
18387     *         clip bounds are {@code null}
18388     */
18389    public boolean getClipBounds(Rect outRect) {
18390        if (mClipBounds != null) {
18391            outRect.set(mClipBounds);
18392            return true;
18393        }
18394        return false;
18395    }
18396
18397    /**
18398     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
18399     * case of an active Animation being run on the view.
18400     */
18401    private boolean applyLegacyAnimation(ViewGroup parent, long drawingTime,
18402            Animation a, boolean scalingRequired) {
18403        Transformation invalidationTransform;
18404        final int flags = parent.mGroupFlags;
18405        final boolean initialized = a.isInitialized();
18406        if (!initialized) {
18407            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
18408            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
18409            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
18410            onAnimationStart();
18411        }
18412
18413        final Transformation t = parent.getChildTransformation();
18414        boolean more = a.getTransformation(drawingTime, t, 1f);
18415        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
18416            if (parent.mInvalidationTransformation == null) {
18417                parent.mInvalidationTransformation = new Transformation();
18418            }
18419            invalidationTransform = parent.mInvalidationTransformation;
18420            a.getTransformation(drawingTime, invalidationTransform, 1f);
18421        } else {
18422            invalidationTransform = t;
18423        }
18424
18425        if (more) {
18426            if (!a.willChangeBounds()) {
18427                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
18428                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
18429                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
18430                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
18431                    // The child need to draw an animation, potentially offscreen, so
18432                    // make sure we do not cancel invalidate requests
18433                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
18434                    parent.invalidate(mLeft, mTop, mRight, mBottom);
18435                }
18436            } else {
18437                if (parent.mInvalidateRegion == null) {
18438                    parent.mInvalidateRegion = new RectF();
18439                }
18440                final RectF region = parent.mInvalidateRegion;
18441                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
18442                        invalidationTransform);
18443
18444                // The child need to draw an animation, potentially offscreen, so
18445                // make sure we do not cancel invalidate requests
18446                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
18447
18448                final int left = mLeft + (int) region.left;
18449                final int top = mTop + (int) region.top;
18450                parent.invalidate(left, top, left + (int) (region.width() + .5f),
18451                        top + (int) (region.height() + .5f));
18452            }
18453        }
18454        return more;
18455    }
18456
18457    /**
18458     * This method is called by getDisplayList() when a display list is recorded for a View.
18459     * It pushes any properties to the RenderNode that aren't managed by the RenderNode.
18460     */
18461    void setDisplayListProperties(RenderNode renderNode) {
18462        if (renderNode != null) {
18463            renderNode.setHasOverlappingRendering(getHasOverlappingRendering());
18464            renderNode.setClipToBounds(mParent instanceof ViewGroup
18465                    && ((ViewGroup) mParent).getClipChildren());
18466
18467            float alpha = 1;
18468            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
18469                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
18470                ViewGroup parentVG = (ViewGroup) mParent;
18471                final Transformation t = parentVG.getChildTransformation();
18472                if (parentVG.getChildStaticTransformation(this, t)) {
18473                    final int transformType = t.getTransformationType();
18474                    if (transformType != Transformation.TYPE_IDENTITY) {
18475                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
18476                            alpha = t.getAlpha();
18477                        }
18478                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
18479                            renderNode.setStaticMatrix(t.getMatrix());
18480                        }
18481                    }
18482                }
18483            }
18484            if (mTransformationInfo != null) {
18485                alpha *= getFinalAlpha();
18486                if (alpha < 1) {
18487                    final int multipliedAlpha = (int) (255 * alpha);
18488                    if (onSetAlpha(multipliedAlpha)) {
18489                        alpha = 1;
18490                    }
18491                }
18492                renderNode.setAlpha(alpha);
18493            } else if (alpha < 1) {
18494                renderNode.setAlpha(alpha);
18495            }
18496        }
18497    }
18498
18499    /**
18500     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
18501     *
18502     * This is where the View specializes rendering behavior based on layer type,
18503     * and hardware acceleration.
18504     */
18505    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
18506        final boolean hardwareAcceleratedCanvas = canvas.isHardwareAccelerated();
18507        /* If an attached view draws to a HW canvas, it may use its RenderNode + DisplayList.
18508         *
18509         * If a view is dettached, its DisplayList shouldn't exist. If the canvas isn't
18510         * HW accelerated, it can't handle drawing RenderNodes.
18511         */
18512        boolean drawingWithRenderNode = mAttachInfo != null
18513                && mAttachInfo.mHardwareAccelerated
18514                && hardwareAcceleratedCanvas;
18515
18516        boolean more = false;
18517        final boolean childHasIdentityMatrix = hasIdentityMatrix();
18518        final int parentFlags = parent.mGroupFlags;
18519
18520        if ((parentFlags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) != 0) {
18521            parent.getChildTransformation().clear();
18522            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
18523        }
18524
18525        Transformation transformToApply = null;
18526        boolean concatMatrix = false;
18527        final boolean scalingRequired = mAttachInfo != null && mAttachInfo.mScalingRequired;
18528        final Animation a = getAnimation();
18529        if (a != null) {
18530            more = applyLegacyAnimation(parent, drawingTime, a, scalingRequired);
18531            concatMatrix = a.willChangeTransformationMatrix();
18532            if (concatMatrix) {
18533                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
18534            }
18535            transformToApply = parent.getChildTransformation();
18536        } else {
18537            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) {
18538                // No longer animating: clear out old animation matrix
18539                mRenderNode.setAnimationMatrix(null);
18540                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
18541            }
18542            if (!drawingWithRenderNode
18543                    && (parentFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
18544                final Transformation t = parent.getChildTransformation();
18545                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
18546                if (hasTransform) {
18547                    final int transformType = t.getTransformationType();
18548                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
18549                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
18550                }
18551            }
18552        }
18553
18554        concatMatrix |= !childHasIdentityMatrix;
18555
18556        // Sets the flag as early as possible to allow draw() implementations
18557        // to call invalidate() successfully when doing animations
18558        mPrivateFlags |= PFLAG_DRAWN;
18559
18560        if (!concatMatrix &&
18561                (parentFlags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
18562                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
18563                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
18564                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
18565            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
18566            return more;
18567        }
18568        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
18569
18570        if (hardwareAcceleratedCanvas) {
18571            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
18572            // retain the flag's value temporarily in the mRecreateDisplayList flag
18573            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) != 0;
18574            mPrivateFlags &= ~PFLAG_INVALIDATED;
18575        }
18576
18577        RenderNode renderNode = null;
18578        Bitmap cache = null;
18579        int layerType = getLayerType(); // TODO: signify cache state with just 'cache' local
18580        if (layerType == LAYER_TYPE_SOFTWARE || !drawingWithRenderNode) {
18581             if (layerType != LAYER_TYPE_NONE) {
18582                 // If not drawing with RenderNode, treat HW layers as SW
18583                 layerType = LAYER_TYPE_SOFTWARE;
18584                 buildDrawingCache(true);
18585            }
18586            cache = getDrawingCache(true);
18587        }
18588
18589        if (drawingWithRenderNode) {
18590            // Delay getting the display list until animation-driven alpha values are
18591            // set up and possibly passed on to the view
18592            renderNode = updateDisplayListIfDirty();
18593            if (!renderNode.isValid()) {
18594                // Uncommon, but possible. If a view is removed from the hierarchy during the call
18595                // to getDisplayList(), the display list will be marked invalid and we should not
18596                // try to use it again.
18597                renderNode = null;
18598                drawingWithRenderNode = false;
18599            }
18600        }
18601
18602        int sx = 0;
18603        int sy = 0;
18604        if (!drawingWithRenderNode) {
18605            computeScroll();
18606            sx = mScrollX;
18607            sy = mScrollY;
18608        }
18609
18610        final boolean drawingWithDrawingCache = cache != null && !drawingWithRenderNode;
18611        final boolean offsetForScroll = cache == null && !drawingWithRenderNode;
18612
18613        int restoreTo = -1;
18614        if (!drawingWithRenderNode || transformToApply != null) {
18615            restoreTo = canvas.save();
18616        }
18617        if (offsetForScroll) {
18618            canvas.translate(mLeft - sx, mTop - sy);
18619        } else {
18620            if (!drawingWithRenderNode) {
18621                canvas.translate(mLeft, mTop);
18622            }
18623            if (scalingRequired) {
18624                if (drawingWithRenderNode) {
18625                    // TODO: Might not need this if we put everything inside the DL
18626                    restoreTo = canvas.save();
18627                }
18628                // mAttachInfo cannot be null, otherwise scalingRequired == false
18629                final float scale = 1.0f / mAttachInfo.mApplicationScale;
18630                canvas.scale(scale, scale);
18631            }
18632        }
18633
18634        float alpha = drawingWithRenderNode ? 1 : (getAlpha() * getTransitionAlpha());
18635        if (transformToApply != null
18636                || alpha < 1
18637                || !hasIdentityMatrix()
18638                || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
18639            if (transformToApply != null || !childHasIdentityMatrix) {
18640                int transX = 0;
18641                int transY = 0;
18642
18643                if (offsetForScroll) {
18644                    transX = -sx;
18645                    transY = -sy;
18646                }
18647
18648                if (transformToApply != null) {
18649                    if (concatMatrix) {
18650                        if (drawingWithRenderNode) {
18651                            renderNode.setAnimationMatrix(transformToApply.getMatrix());
18652                        } else {
18653                            // Undo the scroll translation, apply the transformation matrix,
18654                            // then redo the scroll translate to get the correct result.
18655                            canvas.translate(-transX, -transY);
18656                            canvas.concat(transformToApply.getMatrix());
18657                            canvas.translate(transX, transY);
18658                        }
18659                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
18660                    }
18661
18662                    float transformAlpha = transformToApply.getAlpha();
18663                    if (transformAlpha < 1) {
18664                        alpha *= transformAlpha;
18665                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
18666                    }
18667                }
18668
18669                if (!childHasIdentityMatrix && !drawingWithRenderNode) {
18670                    canvas.translate(-transX, -transY);
18671                    canvas.concat(getMatrix());
18672                    canvas.translate(transX, transY);
18673                }
18674            }
18675
18676            // Deal with alpha if it is or used to be <1
18677            if (alpha < 1 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
18678                if (alpha < 1) {
18679                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
18680                } else {
18681                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
18682                }
18683                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
18684                if (!drawingWithDrawingCache) {
18685                    final int multipliedAlpha = (int) (255 * alpha);
18686                    if (!onSetAlpha(multipliedAlpha)) {
18687                        if (drawingWithRenderNode) {
18688                            renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha());
18689                        } else if (layerType == LAYER_TYPE_NONE) {
18690                            canvas.saveLayerAlpha(sx, sy, sx + getWidth(), sy + getHeight(),
18691                                    multipliedAlpha);
18692                        }
18693                    } else {
18694                        // Alpha is handled by the child directly, clobber the layer's alpha
18695                        mPrivateFlags |= PFLAG_ALPHA_SET;
18696                    }
18697                }
18698            }
18699        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
18700            onSetAlpha(255);
18701            mPrivateFlags &= ~PFLAG_ALPHA_SET;
18702        }
18703
18704        if (!drawingWithRenderNode) {
18705            // apply clips directly, since RenderNode won't do it for this draw
18706            if ((parentFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 && cache == null) {
18707                if (offsetForScroll) {
18708                    canvas.clipRect(sx, sy, sx + getWidth(), sy + getHeight());
18709                } else {
18710                    if (!scalingRequired || cache == null) {
18711                        canvas.clipRect(0, 0, getWidth(), getHeight());
18712                    } else {
18713                        canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
18714                    }
18715                }
18716            }
18717
18718            if (mClipBounds != null) {
18719                // clip bounds ignore scroll
18720                canvas.clipRect(mClipBounds);
18721            }
18722        }
18723
18724        if (!drawingWithDrawingCache) {
18725            if (drawingWithRenderNode) {
18726                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
18727                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
18728            } else {
18729                // Fast path for layouts with no backgrounds
18730                if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
18731                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
18732                    dispatchDraw(canvas);
18733                } else {
18734                    draw(canvas);
18735                }
18736            }
18737        } else if (cache != null) {
18738            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
18739            if (layerType == LAYER_TYPE_NONE || mLayerPaint == null) {
18740                // no layer paint, use temporary paint to draw bitmap
18741                Paint cachePaint = parent.mCachePaint;
18742                if (cachePaint == null) {
18743                    cachePaint = new Paint();
18744                    cachePaint.setDither(false);
18745                    parent.mCachePaint = cachePaint;
18746                }
18747                cachePaint.setAlpha((int) (alpha * 255));
18748                canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
18749            } else {
18750                // use layer paint to draw the bitmap, merging the two alphas, but also restore
18751                int layerPaintAlpha = mLayerPaint.getAlpha();
18752                if (alpha < 1) {
18753                    mLayerPaint.setAlpha((int) (alpha * layerPaintAlpha));
18754                }
18755                canvas.drawBitmap(cache, 0.0f, 0.0f, mLayerPaint);
18756                if (alpha < 1) {
18757                    mLayerPaint.setAlpha(layerPaintAlpha);
18758                }
18759            }
18760        }
18761
18762        if (restoreTo >= 0) {
18763            canvas.restoreToCount(restoreTo);
18764        }
18765
18766        if (a != null && !more) {
18767            if (!hardwareAcceleratedCanvas && !a.getFillAfter()) {
18768                onSetAlpha(255);
18769            }
18770            parent.finishAnimatingView(this, a);
18771        }
18772
18773        if (more && hardwareAcceleratedCanvas) {
18774            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
18775                // alpha animations should cause the child to recreate its display list
18776                invalidate(true);
18777            }
18778        }
18779
18780        mRecreateDisplayList = false;
18781
18782        return more;
18783    }
18784
18785    static Paint getDebugPaint() {
18786        if (sDebugPaint == null) {
18787            sDebugPaint = new Paint();
18788            sDebugPaint.setAntiAlias(false);
18789        }
18790        return sDebugPaint;
18791    }
18792
18793    final int dipsToPixels(int dips) {
18794        float scale = getContext().getResources().getDisplayMetrics().density;
18795        return (int) (dips * scale + 0.5f);
18796    }
18797
18798    final private void debugDrawFocus(Canvas canvas) {
18799        if (isFocused()) {
18800            final int cornerSquareSize = dipsToPixels(DEBUG_CORNERS_SIZE_DIP);
18801            final int l = mScrollX;
18802            final int r = l + mRight - mLeft;
18803            final int t = mScrollY;
18804            final int b = t + mBottom - mTop;
18805
18806            final Paint paint = getDebugPaint();
18807            paint.setColor(DEBUG_CORNERS_COLOR);
18808
18809            // Draw squares in corners.
18810            paint.setStyle(Paint.Style.FILL);
18811            canvas.drawRect(l, t, l + cornerSquareSize, t + cornerSquareSize, paint);
18812            canvas.drawRect(r - cornerSquareSize, t, r, t + cornerSquareSize, paint);
18813            canvas.drawRect(l, b - cornerSquareSize, l + cornerSquareSize, b, paint);
18814            canvas.drawRect(r - cornerSquareSize, b - cornerSquareSize, r, b, paint);
18815
18816            // Draw big X across the view.
18817            paint.setStyle(Paint.Style.STROKE);
18818            canvas.drawLine(l, t, r, b, paint);
18819            canvas.drawLine(l, b, r, t, paint);
18820        }
18821    }
18822
18823    /**
18824     * Manually render this view (and all of its children) to the given Canvas.
18825     * The view must have already done a full layout before this function is
18826     * called.  When implementing a view, implement
18827     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
18828     * If you do need to override this method, call the superclass version.
18829     *
18830     * @param canvas The Canvas to which the View is rendered.
18831     */
18832    @CallSuper
18833    public void draw(Canvas canvas) {
18834        final int privateFlags = mPrivateFlags;
18835        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
18836                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
18837        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
18838
18839        /*
18840         * Draw traversal performs several drawing steps which must be executed
18841         * in the appropriate order:
18842         *
18843         *      1. Draw the background
18844         *      2. If necessary, save the canvas' layers to prepare for fading
18845         *      3. Draw view's content
18846         *      4. Draw children
18847         *      5. If necessary, draw the fading edges and restore layers
18848         *      6. Draw decorations (scrollbars for instance)
18849         */
18850
18851        // Step 1, draw the background, if needed
18852        int saveCount;
18853
18854        if (!dirtyOpaque) {
18855            drawBackground(canvas);
18856        }
18857
18858        // skip step 2 & 5 if possible (common case)
18859        final int viewFlags = mViewFlags;
18860        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
18861        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
18862        if (!verticalEdges && !horizontalEdges) {
18863            // Step 3, draw the content
18864            if (!dirtyOpaque) onDraw(canvas);
18865
18866            // Step 4, draw the children
18867            dispatchDraw(canvas);
18868
18869            drawAutofilledHighlight(canvas);
18870
18871            // Overlay is part of the content and draws beneath Foreground
18872            if (mOverlay != null && !mOverlay.isEmpty()) {
18873                mOverlay.getOverlayView().dispatchDraw(canvas);
18874            }
18875
18876            // Step 6, draw decorations (foreground, scrollbars)
18877            onDrawForeground(canvas);
18878
18879            // Step 7, draw the default focus highlight
18880            drawDefaultFocusHighlight(canvas);
18881
18882            if (debugDraw()) {
18883                debugDrawFocus(canvas);
18884            }
18885
18886            // we're done...
18887            return;
18888        }
18889
18890        /*
18891         * Here we do the full fledged routine...
18892         * (this is an uncommon case where speed matters less,
18893         * this is why we repeat some of the tests that have been
18894         * done above)
18895         */
18896
18897        boolean drawTop = false;
18898        boolean drawBottom = false;
18899        boolean drawLeft = false;
18900        boolean drawRight = false;
18901
18902        float topFadeStrength = 0.0f;
18903        float bottomFadeStrength = 0.0f;
18904        float leftFadeStrength = 0.0f;
18905        float rightFadeStrength = 0.0f;
18906
18907        // Step 2, save the canvas' layers
18908        int paddingLeft = mPaddingLeft;
18909
18910        final boolean offsetRequired = isPaddingOffsetRequired();
18911        if (offsetRequired) {
18912            paddingLeft += getLeftPaddingOffset();
18913        }
18914
18915        int left = mScrollX + paddingLeft;
18916        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
18917        int top = mScrollY + getFadeTop(offsetRequired);
18918        int bottom = top + getFadeHeight(offsetRequired);
18919
18920        if (offsetRequired) {
18921            right += getRightPaddingOffset();
18922            bottom += getBottomPaddingOffset();
18923        }
18924
18925        final ScrollabilityCache scrollabilityCache = mScrollCache;
18926        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
18927        int length = (int) fadeHeight;
18928
18929        // clip the fade length if top and bottom fades overlap
18930        // overlapping fades produce odd-looking artifacts
18931        if (verticalEdges && (top + length > bottom - length)) {
18932            length = (bottom - top) / 2;
18933        }
18934
18935        // also clip horizontal fades if necessary
18936        if (horizontalEdges && (left + length > right - length)) {
18937            length = (right - left) / 2;
18938        }
18939
18940        if (verticalEdges) {
18941            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
18942            drawTop = topFadeStrength * fadeHeight > 1.0f;
18943            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
18944            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
18945        }
18946
18947        if (horizontalEdges) {
18948            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
18949            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
18950            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
18951            drawRight = rightFadeStrength * fadeHeight > 1.0f;
18952        }
18953
18954        saveCount = canvas.getSaveCount();
18955
18956        int solidColor = getSolidColor();
18957        if (solidColor == 0) {
18958            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
18959
18960            if (drawTop) {
18961                canvas.saveLayer(left, top, right, top + length, null, flags);
18962            }
18963
18964            if (drawBottom) {
18965                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
18966            }
18967
18968            if (drawLeft) {
18969                canvas.saveLayer(left, top, left + length, bottom, null, flags);
18970            }
18971
18972            if (drawRight) {
18973                canvas.saveLayer(right - length, top, right, bottom, null, flags);
18974            }
18975        } else {
18976            scrollabilityCache.setFadeColor(solidColor);
18977        }
18978
18979        // Step 3, draw the content
18980        if (!dirtyOpaque) onDraw(canvas);
18981
18982        // Step 4, draw the children
18983        dispatchDraw(canvas);
18984
18985        // Step 5, draw the fade effect and restore layers
18986        final Paint p = scrollabilityCache.paint;
18987        final Matrix matrix = scrollabilityCache.matrix;
18988        final Shader fade = scrollabilityCache.shader;
18989
18990        if (drawTop) {
18991            matrix.setScale(1, fadeHeight * topFadeStrength);
18992            matrix.postTranslate(left, top);
18993            fade.setLocalMatrix(matrix);
18994            p.setShader(fade);
18995            canvas.drawRect(left, top, right, top + length, p);
18996        }
18997
18998        if (drawBottom) {
18999            matrix.setScale(1, fadeHeight * bottomFadeStrength);
19000            matrix.postRotate(180);
19001            matrix.postTranslate(left, bottom);
19002            fade.setLocalMatrix(matrix);
19003            p.setShader(fade);
19004            canvas.drawRect(left, bottom - length, right, bottom, p);
19005        }
19006
19007        if (drawLeft) {
19008            matrix.setScale(1, fadeHeight * leftFadeStrength);
19009            matrix.postRotate(-90);
19010            matrix.postTranslate(left, top);
19011            fade.setLocalMatrix(matrix);
19012            p.setShader(fade);
19013            canvas.drawRect(left, top, left + length, bottom, p);
19014        }
19015
19016        if (drawRight) {
19017            matrix.setScale(1, fadeHeight * rightFadeStrength);
19018            matrix.postRotate(90);
19019            matrix.postTranslate(right, top);
19020            fade.setLocalMatrix(matrix);
19021            p.setShader(fade);
19022            canvas.drawRect(right - length, top, right, bottom, p);
19023        }
19024
19025        canvas.restoreToCount(saveCount);
19026
19027        drawAutofilledHighlight(canvas);
19028
19029        // Overlay is part of the content and draws beneath Foreground
19030        if (mOverlay != null && !mOverlay.isEmpty()) {
19031            mOverlay.getOverlayView().dispatchDraw(canvas);
19032        }
19033
19034        // Step 6, draw decorations (foreground, scrollbars)
19035        onDrawForeground(canvas);
19036
19037        if (debugDraw()) {
19038            debugDrawFocus(canvas);
19039        }
19040    }
19041
19042    /**
19043     * Draws the background onto the specified canvas.
19044     *
19045     * @param canvas Canvas on which to draw the background
19046     */
19047    private void drawBackground(Canvas canvas) {
19048        final Drawable background = mBackground;
19049        if (background == null) {
19050            return;
19051        }
19052
19053        setBackgroundBounds();
19054
19055        // Attempt to use a display list if requested.
19056        if (canvas.isHardwareAccelerated() && mAttachInfo != null
19057                && mAttachInfo.mThreadedRenderer != null) {
19058            mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode);
19059
19060            final RenderNode renderNode = mBackgroundRenderNode;
19061            if (renderNode != null && renderNode.isValid()) {
19062                setBackgroundRenderNodeProperties(renderNode);
19063                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
19064                return;
19065            }
19066        }
19067
19068        final int scrollX = mScrollX;
19069        final int scrollY = mScrollY;
19070        if ((scrollX | scrollY) == 0) {
19071            background.draw(canvas);
19072        } else {
19073            canvas.translate(scrollX, scrollY);
19074            background.draw(canvas);
19075            canvas.translate(-scrollX, -scrollY);
19076        }
19077    }
19078
19079    /**
19080     * Sets the correct background bounds and rebuilds the outline, if needed.
19081     * <p/>
19082     * This is called by LayoutLib.
19083     */
19084    void setBackgroundBounds() {
19085        if (mBackgroundSizeChanged && mBackground != null) {
19086            mBackground.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
19087            mBackgroundSizeChanged = false;
19088            rebuildOutline();
19089        }
19090    }
19091
19092    private void setBackgroundRenderNodeProperties(RenderNode renderNode) {
19093        renderNode.setTranslationX(mScrollX);
19094        renderNode.setTranslationY(mScrollY);
19095    }
19096
19097    /**
19098     * Creates a new display list or updates the existing display list for the
19099     * specified Drawable.
19100     *
19101     * @param drawable Drawable for which to create a display list
19102     * @param renderNode Existing RenderNode, or {@code null}
19103     * @return A valid display list for the specified drawable
19104     */
19105    private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) {
19106        if (renderNode == null) {
19107            renderNode = RenderNode.create(drawable.getClass().getName(), this);
19108        }
19109
19110        final Rect bounds = drawable.getBounds();
19111        final int width = bounds.width();
19112        final int height = bounds.height();
19113        final DisplayListCanvas canvas = renderNode.start(width, height);
19114
19115        // Reverse left/top translation done by drawable canvas, which will
19116        // instead be applied by rendernode's LTRB bounds below. This way, the
19117        // drawable's bounds match with its rendernode bounds and its content
19118        // will lie within those bounds in the rendernode tree.
19119        canvas.translate(-bounds.left, -bounds.top);
19120
19121        try {
19122            drawable.draw(canvas);
19123        } finally {
19124            renderNode.end(canvas);
19125        }
19126
19127        // Set up drawable properties that are view-independent.
19128        renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
19129        renderNode.setProjectBackwards(drawable.isProjected());
19130        renderNode.setProjectionReceiver(true);
19131        renderNode.setClipToBounds(false);
19132        return renderNode;
19133    }
19134
19135    /**
19136     * Returns the overlay for this view, creating it if it does not yet exist.
19137     * Adding drawables to the overlay will cause them to be displayed whenever
19138     * the view itself is redrawn. Objects in the overlay should be actively
19139     * managed: remove them when they should not be displayed anymore. The
19140     * overlay will always have the same size as its host view.
19141     *
19142     * <p>Note: Overlays do not currently work correctly with {@link
19143     * SurfaceView} or {@link TextureView}; contents in overlays for these
19144     * types of views may not display correctly.</p>
19145     *
19146     * @return The ViewOverlay object for this view.
19147     * @see ViewOverlay
19148     */
19149    public ViewOverlay getOverlay() {
19150        if (mOverlay == null) {
19151            mOverlay = new ViewOverlay(mContext, this);
19152        }
19153        return mOverlay;
19154    }
19155
19156    /**
19157     * Override this if your view is known to always be drawn on top of a solid color background,
19158     * and needs to draw fading edges. Returning a non-zero color enables the view system to
19159     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
19160     * should be set to 0xFF.
19161     *
19162     * @see #setVerticalFadingEdgeEnabled(boolean)
19163     * @see #setHorizontalFadingEdgeEnabled(boolean)
19164     *
19165     * @return The known solid color background for this view, or 0 if the color may vary
19166     */
19167    @ViewDebug.ExportedProperty(category = "drawing")
19168    @ColorInt
19169    public int getSolidColor() {
19170        return 0;
19171    }
19172
19173    /**
19174     * Build a human readable string representation of the specified view flags.
19175     *
19176     * @param flags the view flags to convert to a string
19177     * @return a String representing the supplied flags
19178     */
19179    private static String printFlags(int flags) {
19180        String output = "";
19181        int numFlags = 0;
19182        if ((flags & FOCUSABLE) == FOCUSABLE) {
19183            output += "TAKES_FOCUS";
19184            numFlags++;
19185        }
19186
19187        switch (flags & VISIBILITY_MASK) {
19188        case INVISIBLE:
19189            if (numFlags > 0) {
19190                output += " ";
19191            }
19192            output += "INVISIBLE";
19193            // USELESS HERE numFlags++;
19194            break;
19195        case GONE:
19196            if (numFlags > 0) {
19197                output += " ";
19198            }
19199            output += "GONE";
19200            // USELESS HERE numFlags++;
19201            break;
19202        default:
19203            break;
19204        }
19205        return output;
19206    }
19207
19208    /**
19209     * Build a human readable string representation of the specified private
19210     * view flags.
19211     *
19212     * @param privateFlags the private view flags to convert to a string
19213     * @return a String representing the supplied flags
19214     */
19215    private static String printPrivateFlags(int privateFlags) {
19216        String output = "";
19217        int numFlags = 0;
19218
19219        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
19220            output += "WANTS_FOCUS";
19221            numFlags++;
19222        }
19223
19224        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
19225            if (numFlags > 0) {
19226                output += " ";
19227            }
19228            output += "FOCUSED";
19229            numFlags++;
19230        }
19231
19232        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
19233            if (numFlags > 0) {
19234                output += " ";
19235            }
19236            output += "SELECTED";
19237            numFlags++;
19238        }
19239
19240        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
19241            if (numFlags > 0) {
19242                output += " ";
19243            }
19244            output += "IS_ROOT_NAMESPACE";
19245            numFlags++;
19246        }
19247
19248        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
19249            if (numFlags > 0) {
19250                output += " ";
19251            }
19252            output += "HAS_BOUNDS";
19253            numFlags++;
19254        }
19255
19256        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
19257            if (numFlags > 0) {
19258                output += " ";
19259            }
19260            output += "DRAWN";
19261            // USELESS HERE numFlags++;
19262        }
19263        return output;
19264    }
19265
19266    /**
19267     * <p>Indicates whether or not this view's layout will be requested during
19268     * the next hierarchy layout pass.</p>
19269     *
19270     * @return true if the layout will be forced during next layout pass
19271     */
19272    public boolean isLayoutRequested() {
19273        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
19274    }
19275
19276    /**
19277     * Return true if o is a ViewGroup that is laying out using optical bounds.
19278     * @hide
19279     */
19280    public static boolean isLayoutModeOptical(Object o) {
19281        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
19282    }
19283
19284    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
19285        Insets parentInsets = mParent instanceof View ?
19286                ((View) mParent).getOpticalInsets() : Insets.NONE;
19287        Insets childInsets = getOpticalInsets();
19288        return setFrame(
19289                left   + parentInsets.left - childInsets.left,
19290                top    + parentInsets.top  - childInsets.top,
19291                right  + parentInsets.left + childInsets.right,
19292                bottom + parentInsets.top  + childInsets.bottom);
19293    }
19294
19295    /**
19296     * Assign a size and position to a view and all of its
19297     * descendants
19298     *
19299     * <p>This is the second phase of the layout mechanism.
19300     * (The first is measuring). In this phase, each parent calls
19301     * layout on all of its children to position them.
19302     * This is typically done using the child measurements
19303     * that were stored in the measure pass().</p>
19304     *
19305     * <p>Derived classes should not override this method.
19306     * Derived classes with children should override
19307     * onLayout. In that method, they should
19308     * call layout on each of their children.</p>
19309     *
19310     * @param l Left position, relative to parent
19311     * @param t Top position, relative to parent
19312     * @param r Right position, relative to parent
19313     * @param b Bottom position, relative to parent
19314     */
19315    @SuppressWarnings({"unchecked"})
19316    public void layout(int l, int t, int r, int b) {
19317        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
19318            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
19319            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
19320        }
19321
19322        int oldL = mLeft;
19323        int oldT = mTop;
19324        int oldB = mBottom;
19325        int oldR = mRight;
19326
19327        boolean changed = isLayoutModeOptical(mParent) ?
19328                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
19329
19330        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
19331            onLayout(changed, l, t, r, b);
19332
19333            if (shouldDrawRoundScrollbar()) {
19334                if(mRoundScrollbarRenderer == null) {
19335                    mRoundScrollbarRenderer = new RoundScrollbarRenderer(this);
19336                }
19337            } else {
19338                mRoundScrollbarRenderer = null;
19339            }
19340
19341            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
19342
19343            ListenerInfo li = mListenerInfo;
19344            if (li != null && li.mOnLayoutChangeListeners != null) {
19345                ArrayList<OnLayoutChangeListener> listenersCopy =
19346                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
19347                int numListeners = listenersCopy.size();
19348                for (int i = 0; i < numListeners; ++i) {
19349                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
19350                }
19351            }
19352        }
19353
19354        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
19355        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
19356
19357        if ((mPrivateFlags3 & PFLAG3_NOTIFY_AUTOFILL_ENTER_ON_LAYOUT) != 0) {
19358            mPrivateFlags3 &= ~PFLAG3_NOTIFY_AUTOFILL_ENTER_ON_LAYOUT;
19359            notifyEnterOrExitForAutoFillIfNeeded(true);
19360        }
19361    }
19362
19363    /**
19364     * Called from layout when this view should
19365     * assign a size and position to each of its children.
19366     *
19367     * Derived classes with children should override
19368     * this method and call layout on each of
19369     * their children.
19370     * @param changed This is a new size or position for this view
19371     * @param left Left position, relative to parent
19372     * @param top Top position, relative to parent
19373     * @param right Right position, relative to parent
19374     * @param bottom Bottom position, relative to parent
19375     */
19376    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
19377    }
19378
19379    /**
19380     * Assign a size and position to this view.
19381     *
19382     * This is called from layout.
19383     *
19384     * @param left Left position, relative to parent
19385     * @param top Top position, relative to parent
19386     * @param right Right position, relative to parent
19387     * @param bottom Bottom position, relative to parent
19388     * @return true if the new size and position are different than the
19389     *         previous ones
19390     * {@hide}
19391     */
19392    protected boolean setFrame(int left, int top, int right, int bottom) {
19393        boolean changed = false;
19394
19395        if (DBG) {
19396            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
19397                    + right + "," + bottom + ")");
19398        }
19399
19400        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
19401            changed = true;
19402
19403            // Remember our drawn bit
19404            int drawn = mPrivateFlags & PFLAG_DRAWN;
19405
19406            int oldWidth = mRight - mLeft;
19407            int oldHeight = mBottom - mTop;
19408            int newWidth = right - left;
19409            int newHeight = bottom - top;
19410            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
19411
19412            // Invalidate our old position
19413            invalidate(sizeChanged);
19414
19415            mLeft = left;
19416            mTop = top;
19417            mRight = right;
19418            mBottom = bottom;
19419            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
19420
19421            mPrivateFlags |= PFLAG_HAS_BOUNDS;
19422
19423
19424            if (sizeChanged) {
19425                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
19426            }
19427
19428            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) {
19429                // If we are visible, force the DRAWN bit to on so that
19430                // this invalidate will go through (at least to our parent).
19431                // This is because someone may have invalidated this view
19432                // before this call to setFrame came in, thereby clearing
19433                // the DRAWN bit.
19434                mPrivateFlags |= PFLAG_DRAWN;
19435                invalidate(sizeChanged);
19436                // parent display list may need to be recreated based on a change in the bounds
19437                // of any child
19438                invalidateParentCaches();
19439            }
19440
19441            // Reset drawn bit to original value (invalidate turns it off)
19442            mPrivateFlags |= drawn;
19443
19444            mBackgroundSizeChanged = true;
19445            mDefaultFocusHighlightSizeChanged = true;
19446            if (mForegroundInfo != null) {
19447                mForegroundInfo.mBoundsChanged = true;
19448            }
19449
19450            notifySubtreeAccessibilityStateChangedIfNeeded();
19451        }
19452        return changed;
19453    }
19454
19455    /**
19456     * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}.
19457     * @hide
19458     */
19459    public void setLeftTopRightBottom(int left, int top, int right, int bottom) {
19460        setFrame(left, top, right, bottom);
19461    }
19462
19463    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
19464        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
19465        if (mOverlay != null) {
19466            mOverlay.getOverlayView().setRight(newWidth);
19467            mOverlay.getOverlayView().setBottom(newHeight);
19468        }
19469        rebuildOutline();
19470    }
19471
19472    /**
19473     * Finalize inflating a view from XML.  This is called as the last phase
19474     * of inflation, after all child views have been added.
19475     *
19476     * <p>Even if the subclass overrides onFinishInflate, they should always be
19477     * sure to call the super method, so that we get called.
19478     */
19479    @CallSuper
19480    protected void onFinishInflate() {
19481    }
19482
19483    /**
19484     * Returns the resources associated with this view.
19485     *
19486     * @return Resources object.
19487     */
19488    public Resources getResources() {
19489        return mResources;
19490    }
19491
19492    /**
19493     * Invalidates the specified Drawable.
19494     *
19495     * @param drawable the drawable to invalidate
19496     */
19497    @Override
19498    public void invalidateDrawable(@NonNull Drawable drawable) {
19499        if (verifyDrawable(drawable)) {
19500            final Rect dirty = drawable.getDirtyBounds();
19501            final int scrollX = mScrollX;
19502            final int scrollY = mScrollY;
19503
19504            invalidate(dirty.left + scrollX, dirty.top + scrollY,
19505                    dirty.right + scrollX, dirty.bottom + scrollY);
19506            rebuildOutline();
19507        }
19508    }
19509
19510    /**
19511     * Schedules an action on a drawable to occur at a specified time.
19512     *
19513     * @param who the recipient of the action
19514     * @param what the action to run on the drawable
19515     * @param when the time at which the action must occur. Uses the
19516     *        {@link SystemClock#uptimeMillis} timebase.
19517     */
19518    @Override
19519    public void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when) {
19520        if (verifyDrawable(who) && what != null) {
19521            final long delay = when - SystemClock.uptimeMillis();
19522            if (mAttachInfo != null) {
19523                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
19524                        Choreographer.CALLBACK_ANIMATION, what, who,
19525                        Choreographer.subtractFrameDelay(delay));
19526            } else {
19527                // Postpone the runnable until we know
19528                // on which thread it needs to run.
19529                getRunQueue().postDelayed(what, delay);
19530            }
19531        }
19532    }
19533
19534    /**
19535     * Cancels a scheduled action on a drawable.
19536     *
19537     * @param who the recipient of the action
19538     * @param what the action to cancel
19539     */
19540    @Override
19541    public void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what) {
19542        if (verifyDrawable(who) && what != null) {
19543            if (mAttachInfo != null) {
19544                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
19545                        Choreographer.CALLBACK_ANIMATION, what, who);
19546            }
19547            getRunQueue().removeCallbacks(what);
19548        }
19549    }
19550
19551    /**
19552     * Unschedule any events associated with the given Drawable.  This can be
19553     * used when selecting a new Drawable into a view, so that the previous
19554     * one is completely unscheduled.
19555     *
19556     * @param who The Drawable to unschedule.
19557     *
19558     * @see #drawableStateChanged
19559     */
19560    public void unscheduleDrawable(Drawable who) {
19561        if (mAttachInfo != null && who != null) {
19562            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
19563                    Choreographer.CALLBACK_ANIMATION, null, who);
19564        }
19565    }
19566
19567    /**
19568     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
19569     * that the View directionality can and will be resolved before its Drawables.
19570     *
19571     * Will call {@link View#onResolveDrawables} when resolution is done.
19572     *
19573     * @hide
19574     */
19575    protected void resolveDrawables() {
19576        // Drawables resolution may need to happen before resolving the layout direction (which is
19577        // done only during the measure() call).
19578        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
19579        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
19580        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
19581        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
19582        // direction to be resolved as its resolved value will be the same as its raw value.
19583        if (!isLayoutDirectionResolved() &&
19584                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
19585            return;
19586        }
19587
19588        final int layoutDirection = isLayoutDirectionResolved() ?
19589                getLayoutDirection() : getRawLayoutDirection();
19590
19591        if (mBackground != null) {
19592            mBackground.setLayoutDirection(layoutDirection);
19593        }
19594        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
19595            mForegroundInfo.mDrawable.setLayoutDirection(layoutDirection);
19596        }
19597        if (mDefaultFocusHighlight != null) {
19598            mDefaultFocusHighlight.setLayoutDirection(layoutDirection);
19599        }
19600        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
19601        onResolveDrawables(layoutDirection);
19602    }
19603
19604    boolean areDrawablesResolved() {
19605        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
19606    }
19607
19608    /**
19609     * Called when layout direction has been resolved.
19610     *
19611     * The default implementation does nothing.
19612     *
19613     * @param layoutDirection The resolved layout direction.
19614     *
19615     * @see #LAYOUT_DIRECTION_LTR
19616     * @see #LAYOUT_DIRECTION_RTL
19617     *
19618     * @hide
19619     */
19620    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
19621    }
19622
19623    /**
19624     * @hide
19625     */
19626    protected void resetResolvedDrawables() {
19627        resetResolvedDrawablesInternal();
19628    }
19629
19630    void resetResolvedDrawablesInternal() {
19631        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
19632    }
19633
19634    /**
19635     * If your view subclass is displaying its own Drawable objects, it should
19636     * override this function and return true for any Drawable it is
19637     * displaying.  This allows animations for those drawables to be
19638     * scheduled.
19639     *
19640     * <p>Be sure to call through to the super class when overriding this
19641     * function.
19642     *
19643     * @param who The Drawable to verify.  Return true if it is one you are
19644     *            displaying, else return the result of calling through to the
19645     *            super class.
19646     *
19647     * @return boolean If true than the Drawable is being displayed in the
19648     *         view; else false and it is not allowed to animate.
19649     *
19650     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
19651     * @see #drawableStateChanged()
19652     */
19653    @CallSuper
19654    protected boolean verifyDrawable(@NonNull Drawable who) {
19655        // Avoid verifying the scroll bar drawable so that we don't end up in
19656        // an invalidation loop. This effectively prevents the scroll bar
19657        // drawable from triggering invalidations and scheduling runnables.
19658        return who == mBackground || (mForegroundInfo != null && mForegroundInfo.mDrawable == who)
19659                || (mDefaultFocusHighlight == who);
19660    }
19661
19662    /**
19663     * This function is called whenever the state of the view changes in such
19664     * a way that it impacts the state of drawables being shown.
19665     * <p>
19666     * If the View has a StateListAnimator, it will also be called to run necessary state
19667     * change animations.
19668     * <p>
19669     * Be sure to call through to the superclass when overriding this function.
19670     *
19671     * @see Drawable#setState(int[])
19672     */
19673    @CallSuper
19674    protected void drawableStateChanged() {
19675        final int[] state = getDrawableState();
19676        boolean changed = false;
19677
19678        final Drawable bg = mBackground;
19679        if (bg != null && bg.isStateful()) {
19680            changed |= bg.setState(state);
19681        }
19682
19683        final Drawable hl = mDefaultFocusHighlight;
19684        if (hl != null && hl.isStateful()) {
19685            changed |= hl.setState(state);
19686        }
19687
19688        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
19689        if (fg != null && fg.isStateful()) {
19690            changed |= fg.setState(state);
19691        }
19692
19693        if (mScrollCache != null) {
19694            final Drawable scrollBar = mScrollCache.scrollBar;
19695            if (scrollBar != null && scrollBar.isStateful()) {
19696                changed |= scrollBar.setState(state)
19697                        && mScrollCache.state != ScrollabilityCache.OFF;
19698            }
19699        }
19700
19701        if (mStateListAnimator != null) {
19702            mStateListAnimator.setState(state);
19703        }
19704
19705        if (changed) {
19706            invalidate();
19707        }
19708    }
19709
19710    /**
19711     * This function is called whenever the view hotspot changes and needs to
19712     * be propagated to drawables or child views managed by the view.
19713     * <p>
19714     * Dispatching to child views is handled by
19715     * {@link #dispatchDrawableHotspotChanged(float, float)}.
19716     * <p>
19717     * Be sure to call through to the superclass when overriding this function.
19718     *
19719     * @param x hotspot x coordinate
19720     * @param y hotspot y coordinate
19721     */
19722    @CallSuper
19723    public void drawableHotspotChanged(float x, float y) {
19724        if (mBackground != null) {
19725            mBackground.setHotspot(x, y);
19726        }
19727        if (mDefaultFocusHighlight != null) {
19728            mDefaultFocusHighlight.setHotspot(x, y);
19729        }
19730        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
19731            mForegroundInfo.mDrawable.setHotspot(x, y);
19732        }
19733
19734        dispatchDrawableHotspotChanged(x, y);
19735    }
19736
19737    /**
19738     * Dispatches drawableHotspotChanged to all of this View's children.
19739     *
19740     * @param x hotspot x coordinate
19741     * @param y hotspot y coordinate
19742     * @see #drawableHotspotChanged(float, float)
19743     */
19744    public void dispatchDrawableHotspotChanged(float x, float y) {
19745    }
19746
19747    /**
19748     * Call this to force a view to update its drawable state. This will cause
19749     * drawableStateChanged to be called on this view. Views that are interested
19750     * in the new state should call getDrawableState.
19751     *
19752     * @see #drawableStateChanged
19753     * @see #getDrawableState
19754     */
19755    public void refreshDrawableState() {
19756        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
19757        drawableStateChanged();
19758
19759        ViewParent parent = mParent;
19760        if (parent != null) {
19761            parent.childDrawableStateChanged(this);
19762        }
19763    }
19764
19765    /**
19766     * Create a default focus highlight if it doesn't exist.
19767     * @return a default focus highlight.
19768     */
19769    private Drawable getDefaultFocusHighlightDrawable() {
19770        if (mDefaultFocusHighlightCache == null) {
19771            if (mContext != null) {
19772                final int[] attrs = new int[] { android.R.attr.selectableItemBackground };
19773                final TypedArray ta = mContext.obtainStyledAttributes(attrs);
19774                mDefaultFocusHighlightCache = ta.getDrawable(0);
19775                ta.recycle();
19776            }
19777        }
19778        return mDefaultFocusHighlightCache;
19779    }
19780
19781    /**
19782     * Set the current default focus highlight.
19783     * @param highlight the highlight drawable, or {@code null} if it's no longer needed.
19784     */
19785    private void setDefaultFocusHighlight(Drawable highlight) {
19786        mDefaultFocusHighlight = highlight;
19787        mDefaultFocusHighlightSizeChanged = true;
19788        if (highlight != null) {
19789            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
19790                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
19791            }
19792            highlight.setLayoutDirection(getLayoutDirection());
19793            if (highlight.isStateful()) {
19794                highlight.setState(getDrawableState());
19795            }
19796            if (isAttachedToWindow()) {
19797                highlight.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
19798            }
19799            // Set callback last, since the view may still be initializing.
19800            highlight.setCallback(this);
19801        } else if ((mViewFlags & WILL_NOT_DRAW) != 0 && mBackground == null
19802                && (mForegroundInfo == null || mForegroundInfo.mDrawable == null)) {
19803            mPrivateFlags |= PFLAG_SKIP_DRAW;
19804        }
19805        requestLayout();
19806        invalidate();
19807    }
19808
19809    /**
19810     * Check whether we need to draw a default focus highlight when this view gets focused,
19811     * which requires:
19812     * <ul>
19813     *     <li>In the background, {@link android.R.attr#state_focused} is not defined.</li>
19814     *     <li>This view is not in touch mode.</li>
19815     *     <li>This view doesn't opt out for a default focus highlight, via
19816     *         {@link #setDefaultFocusHighlightEnabled(boolean)}.</li>
19817     *     <li>This view is attached to window.</li>
19818     * </ul>
19819     * @return {@code true} if a default focus highlight is needed.
19820     */
19821    private boolean isDefaultFocusHighlightNeeded(Drawable background) {
19822        final boolean hasFocusStateSpecified = background == null || !background.isStateful()
19823                || !background.hasFocusStateSpecified();
19824        return !isInTouchMode() && getDefaultFocusHighlightEnabled() && hasFocusStateSpecified
19825                && isAttachedToWindow() && sUseDefaultFocusHighlight;
19826    }
19827
19828    /**
19829     * When this view is focused, switches on/off the default focused highlight.
19830     * <p>
19831     * This always happens when this view is focused, and only at this moment the default focus
19832     * highlight can be visible.
19833     */
19834    private void switchDefaultFocusHighlight() {
19835        if (isFocused()) {
19836            final boolean needed = isDefaultFocusHighlightNeeded(mBackground);
19837            final boolean active = mDefaultFocusHighlight != null;
19838            if (needed && !active) {
19839                setDefaultFocusHighlight(getDefaultFocusHighlightDrawable());
19840            } else if (!needed && active) {
19841                // The highlight is no longer needed, so tear it down.
19842                setDefaultFocusHighlight(null);
19843            }
19844        }
19845    }
19846
19847    /**
19848     * Draw the default focus highlight onto the canvas.
19849     * @param canvas the canvas where we're drawing the highlight.
19850     */
19851    private void drawDefaultFocusHighlight(Canvas canvas) {
19852        if (mDefaultFocusHighlight != null) {
19853            if (mDefaultFocusHighlightSizeChanged) {
19854                mDefaultFocusHighlightSizeChanged = false;
19855                final int l = mScrollX;
19856                final int r = l + mRight - mLeft;
19857                final int t = mScrollY;
19858                final int b = t + mBottom - mTop;
19859                mDefaultFocusHighlight.setBounds(l, t, r, b);
19860            }
19861            mDefaultFocusHighlight.draw(canvas);
19862        }
19863    }
19864
19865    /**
19866     * Return an array of resource IDs of the drawable states representing the
19867     * current state of the view.
19868     *
19869     * @return The current drawable state
19870     *
19871     * @see Drawable#setState(int[])
19872     * @see #drawableStateChanged()
19873     * @see #onCreateDrawableState(int)
19874     */
19875    public final int[] getDrawableState() {
19876        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
19877            return mDrawableState;
19878        } else {
19879            mDrawableState = onCreateDrawableState(0);
19880            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
19881            return mDrawableState;
19882        }
19883    }
19884
19885    /**
19886     * Generate the new {@link android.graphics.drawable.Drawable} state for
19887     * this view. This is called by the view
19888     * system when the cached Drawable state is determined to be invalid.  To
19889     * retrieve the current state, you should use {@link #getDrawableState}.
19890     *
19891     * @param extraSpace if non-zero, this is the number of extra entries you
19892     * would like in the returned array in which you can place your own
19893     * states.
19894     *
19895     * @return Returns an array holding the current {@link Drawable} state of
19896     * the view.
19897     *
19898     * @see #mergeDrawableStates(int[], int[])
19899     */
19900    protected int[] onCreateDrawableState(int extraSpace) {
19901        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
19902                mParent instanceof View) {
19903            return ((View) mParent).onCreateDrawableState(extraSpace);
19904        }
19905
19906        int[] drawableState;
19907
19908        int privateFlags = mPrivateFlags;
19909
19910        int viewStateIndex = 0;
19911        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= StateSet.VIEW_STATE_PRESSED;
19912        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= StateSet.VIEW_STATE_ENABLED;
19913        if (isFocused()) viewStateIndex |= StateSet.VIEW_STATE_FOCUSED;
19914        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= StateSet.VIEW_STATE_SELECTED;
19915        if (hasWindowFocus()) viewStateIndex |= StateSet.VIEW_STATE_WINDOW_FOCUSED;
19916        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= StateSet.VIEW_STATE_ACTIVATED;
19917        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
19918                ThreadedRenderer.isAvailable()) {
19919            // This is set if HW acceleration is requested, even if the current
19920            // process doesn't allow it.  This is just to allow app preview
19921            // windows to better match their app.
19922            viewStateIndex |= StateSet.VIEW_STATE_ACCELERATED;
19923        }
19924        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= StateSet.VIEW_STATE_HOVERED;
19925
19926        final int privateFlags2 = mPrivateFlags2;
19927        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) {
19928            viewStateIndex |= StateSet.VIEW_STATE_DRAG_CAN_ACCEPT;
19929        }
19930        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) {
19931            viewStateIndex |= StateSet.VIEW_STATE_DRAG_HOVERED;
19932        }
19933
19934        drawableState = StateSet.get(viewStateIndex);
19935
19936        //noinspection ConstantIfStatement
19937        if (false) {
19938            Log.i("View", "drawableStateIndex=" + viewStateIndex);
19939            Log.i("View", toString()
19940                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
19941                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
19942                    + " fo=" + hasFocus()
19943                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
19944                    + " wf=" + hasWindowFocus()
19945                    + ": " + Arrays.toString(drawableState));
19946        }
19947
19948        if (extraSpace == 0) {
19949            return drawableState;
19950        }
19951
19952        final int[] fullState;
19953        if (drawableState != null) {
19954            fullState = new int[drawableState.length + extraSpace];
19955            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
19956        } else {
19957            fullState = new int[extraSpace];
19958        }
19959
19960        return fullState;
19961    }
19962
19963    /**
19964     * Merge your own state values in <var>additionalState</var> into the base
19965     * state values <var>baseState</var> that were returned by
19966     * {@link #onCreateDrawableState(int)}.
19967     *
19968     * @param baseState The base state values returned by
19969     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
19970     * own additional state values.
19971     *
19972     * @param additionalState The additional state values you would like
19973     * added to <var>baseState</var>; this array is not modified.
19974     *
19975     * @return As a convenience, the <var>baseState</var> array you originally
19976     * passed into the function is returned.
19977     *
19978     * @see #onCreateDrawableState(int)
19979     */
19980    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
19981        final int N = baseState.length;
19982        int i = N - 1;
19983        while (i >= 0 && baseState[i] == 0) {
19984            i--;
19985        }
19986        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
19987        return baseState;
19988    }
19989
19990    /**
19991     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
19992     * on all Drawable objects associated with this view.
19993     * <p>
19994     * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator
19995     * attached to this view.
19996     */
19997    @CallSuper
19998    public void jumpDrawablesToCurrentState() {
19999        if (mBackground != null) {
20000            mBackground.jumpToCurrentState();
20001        }
20002        if (mStateListAnimator != null) {
20003            mStateListAnimator.jumpToCurrentState();
20004        }
20005        if (mDefaultFocusHighlight != null) {
20006            mDefaultFocusHighlight.jumpToCurrentState();
20007        }
20008        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
20009            mForegroundInfo.mDrawable.jumpToCurrentState();
20010        }
20011    }
20012
20013    /**
20014     * Sets the background color for this view.
20015     * @param color the color of the background
20016     */
20017    @RemotableViewMethod
20018    public void setBackgroundColor(@ColorInt int color) {
20019        if (mBackground instanceof ColorDrawable) {
20020            ((ColorDrawable) mBackground.mutate()).setColor(color);
20021            computeOpaqueFlags();
20022            mBackgroundResource = 0;
20023        } else {
20024            setBackground(new ColorDrawable(color));
20025        }
20026    }
20027
20028    /**
20029     * Set the background to a given resource. The resource should refer to
20030     * a Drawable object or 0 to remove the background.
20031     * @param resid The identifier of the resource.
20032     *
20033     * @attr ref android.R.styleable#View_background
20034     */
20035    @RemotableViewMethod
20036    public void setBackgroundResource(@DrawableRes int resid) {
20037        if (resid != 0 && resid == mBackgroundResource) {
20038            return;
20039        }
20040
20041        Drawable d = null;
20042        if (resid != 0) {
20043            d = mContext.getDrawable(resid);
20044        }
20045        setBackground(d);
20046
20047        mBackgroundResource = resid;
20048    }
20049
20050    /**
20051     * Set the background to a given Drawable, or remove the background. If the
20052     * background has padding, this View's padding is set to the background's
20053     * padding. However, when a background is removed, this View's padding isn't
20054     * touched. If setting the padding is desired, please use
20055     * {@link #setPadding(int, int, int, int)}.
20056     *
20057     * @param background The Drawable to use as the background, or null to remove the
20058     *        background
20059     */
20060    public void setBackground(Drawable background) {
20061        //noinspection deprecation
20062        setBackgroundDrawable(background);
20063    }
20064
20065    /**
20066     * @deprecated use {@link #setBackground(Drawable)} instead
20067     */
20068    @Deprecated
20069    public void setBackgroundDrawable(Drawable background) {
20070        computeOpaqueFlags();
20071
20072        if (background == mBackground) {
20073            return;
20074        }
20075
20076        boolean requestLayout = false;
20077
20078        mBackgroundResource = 0;
20079
20080        /*
20081         * Regardless of whether we're setting a new background or not, we want
20082         * to clear the previous drawable. setVisible first while we still have the callback set.
20083         */
20084        if (mBackground != null) {
20085            if (isAttachedToWindow()) {
20086                mBackground.setVisible(false, false);
20087            }
20088            mBackground.setCallback(null);
20089            unscheduleDrawable(mBackground);
20090        }
20091
20092        if (background != null) {
20093            Rect padding = sThreadLocal.get();
20094            if (padding == null) {
20095                padding = new Rect();
20096                sThreadLocal.set(padding);
20097            }
20098            resetResolvedDrawablesInternal();
20099            background.setLayoutDirection(getLayoutDirection());
20100            if (background.getPadding(padding)) {
20101                resetResolvedPaddingInternal();
20102                switch (background.getLayoutDirection()) {
20103                    case LAYOUT_DIRECTION_RTL:
20104                        mUserPaddingLeftInitial = padding.right;
20105                        mUserPaddingRightInitial = padding.left;
20106                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
20107                        break;
20108                    case LAYOUT_DIRECTION_LTR:
20109                    default:
20110                        mUserPaddingLeftInitial = padding.left;
20111                        mUserPaddingRightInitial = padding.right;
20112                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
20113                }
20114                mLeftPaddingDefined = false;
20115                mRightPaddingDefined = false;
20116            }
20117
20118            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
20119            // if it has a different minimum size, we should layout again
20120            if (mBackground == null
20121                    || mBackground.getMinimumHeight() != background.getMinimumHeight()
20122                    || mBackground.getMinimumWidth() != background.getMinimumWidth()) {
20123                requestLayout = true;
20124            }
20125
20126            // Set mBackground before we set this as the callback and start making other
20127            // background drawable state change calls. In particular, the setVisible call below
20128            // can result in drawables attempting to start animations or otherwise invalidate,
20129            // which requires the view set as the callback (us) to recognize the drawable as
20130            // belonging to it as per verifyDrawable.
20131            mBackground = background;
20132            if (background.isStateful()) {
20133                background.setState(getDrawableState());
20134            }
20135            if (isAttachedToWindow()) {
20136                background.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
20137            }
20138
20139            applyBackgroundTint();
20140
20141            // Set callback last, since the view may still be initializing.
20142            background.setCallback(this);
20143
20144            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
20145                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
20146                requestLayout = true;
20147            }
20148        } else {
20149            /* Remove the background */
20150            mBackground = null;
20151            if ((mViewFlags & WILL_NOT_DRAW) != 0
20152                    && (mDefaultFocusHighlight == null)
20153                    && (mForegroundInfo == null || mForegroundInfo.mDrawable == null)) {
20154                mPrivateFlags |= PFLAG_SKIP_DRAW;
20155            }
20156
20157            /*
20158             * When the background is set, we try to apply its padding to this
20159             * View. When the background is removed, we don't touch this View's
20160             * padding. This is noted in the Javadocs. Hence, we don't need to
20161             * requestLayout(), the invalidate() below is sufficient.
20162             */
20163
20164            // The old background's minimum size could have affected this
20165            // View's layout, so let's requestLayout
20166            requestLayout = true;
20167        }
20168
20169        computeOpaqueFlags();
20170
20171        if (requestLayout) {
20172            requestLayout();
20173        }
20174
20175        mBackgroundSizeChanged = true;
20176        invalidate(true);
20177        invalidateOutline();
20178    }
20179
20180    /**
20181     * Gets the background drawable
20182     *
20183     * @return The drawable used as the background for this view, if any.
20184     *
20185     * @see #setBackground(Drawable)
20186     *
20187     * @attr ref android.R.styleable#View_background
20188     */
20189    public Drawable getBackground() {
20190        return mBackground;
20191    }
20192
20193    /**
20194     * Applies a tint to the background drawable. Does not modify the current tint
20195     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
20196     * <p>
20197     * Subsequent calls to {@link #setBackground(Drawable)} will automatically
20198     * mutate the drawable and apply the specified tint and tint mode using
20199     * {@link Drawable#setTintList(ColorStateList)}.
20200     *
20201     * @param tint the tint to apply, may be {@code null} to clear tint
20202     *
20203     * @attr ref android.R.styleable#View_backgroundTint
20204     * @see #getBackgroundTintList()
20205     * @see Drawable#setTintList(ColorStateList)
20206     */
20207    public void setBackgroundTintList(@Nullable ColorStateList tint) {
20208        if (mBackgroundTint == null) {
20209            mBackgroundTint = new TintInfo();
20210        }
20211        mBackgroundTint.mTintList = tint;
20212        mBackgroundTint.mHasTintList = true;
20213
20214        applyBackgroundTint();
20215    }
20216
20217    /**
20218     * Return the tint applied to the background drawable, if specified.
20219     *
20220     * @return the tint applied to the background drawable
20221     * @attr ref android.R.styleable#View_backgroundTint
20222     * @see #setBackgroundTintList(ColorStateList)
20223     */
20224    @Nullable
20225    public ColorStateList getBackgroundTintList() {
20226        return mBackgroundTint != null ? mBackgroundTint.mTintList : null;
20227    }
20228
20229    /**
20230     * Specifies the blending mode used to apply the tint specified by
20231     * {@link #setBackgroundTintList(ColorStateList)}} to the background
20232     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
20233     *
20234     * @param tintMode the blending mode used to apply the tint, may be
20235     *                 {@code null} to clear tint
20236     * @attr ref android.R.styleable#View_backgroundTintMode
20237     * @see #getBackgroundTintMode()
20238     * @see Drawable#setTintMode(PorterDuff.Mode)
20239     */
20240    public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) {
20241        if (mBackgroundTint == null) {
20242            mBackgroundTint = new TintInfo();
20243        }
20244        mBackgroundTint.mTintMode = tintMode;
20245        mBackgroundTint.mHasTintMode = true;
20246
20247        applyBackgroundTint();
20248    }
20249
20250    /**
20251     * Return the blending mode used to apply the tint to the background
20252     * drawable, if specified.
20253     *
20254     * @return the blending mode used to apply the tint to the background
20255     *         drawable
20256     * @attr ref android.R.styleable#View_backgroundTintMode
20257     * @see #setBackgroundTintMode(PorterDuff.Mode)
20258     */
20259    @Nullable
20260    public PorterDuff.Mode getBackgroundTintMode() {
20261        return mBackgroundTint != null ? mBackgroundTint.mTintMode : null;
20262    }
20263
20264    private void applyBackgroundTint() {
20265        if (mBackground != null && mBackgroundTint != null) {
20266            final TintInfo tintInfo = mBackgroundTint;
20267            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
20268                mBackground = mBackground.mutate();
20269
20270                if (tintInfo.mHasTintList) {
20271                    mBackground.setTintList(tintInfo.mTintList);
20272                }
20273
20274                if (tintInfo.mHasTintMode) {
20275                    mBackground.setTintMode(tintInfo.mTintMode);
20276                }
20277
20278                // The drawable (or one of its children) may not have been
20279                // stateful before applying the tint, so let's try again.
20280                if (mBackground.isStateful()) {
20281                    mBackground.setState(getDrawableState());
20282                }
20283            }
20284        }
20285    }
20286
20287    /**
20288     * Returns the drawable used as the foreground of this View. The
20289     * foreground drawable, if non-null, is always drawn on top of the view's content.
20290     *
20291     * @return a Drawable or null if no foreground was set
20292     *
20293     * @see #onDrawForeground(Canvas)
20294     */
20295    public Drawable getForeground() {
20296        return mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
20297    }
20298
20299    /**
20300     * Supply a Drawable that is to be rendered on top of all of the content in the view.
20301     *
20302     * @param foreground the Drawable to be drawn on top of the children
20303     *
20304     * @attr ref android.R.styleable#View_foreground
20305     */
20306    public void setForeground(Drawable foreground) {
20307        if (mForegroundInfo == null) {
20308            if (foreground == null) {
20309                // Nothing to do.
20310                return;
20311            }
20312            mForegroundInfo = new ForegroundInfo();
20313        }
20314
20315        if (foreground == mForegroundInfo.mDrawable) {
20316            // Nothing to do
20317            return;
20318        }
20319
20320        if (mForegroundInfo.mDrawable != null) {
20321            if (isAttachedToWindow()) {
20322                mForegroundInfo.mDrawable.setVisible(false, false);
20323            }
20324            mForegroundInfo.mDrawable.setCallback(null);
20325            unscheduleDrawable(mForegroundInfo.mDrawable);
20326        }
20327
20328        mForegroundInfo.mDrawable = foreground;
20329        mForegroundInfo.mBoundsChanged = true;
20330        if (foreground != null) {
20331            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
20332                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
20333            }
20334            foreground.setLayoutDirection(getLayoutDirection());
20335            if (foreground.isStateful()) {
20336                foreground.setState(getDrawableState());
20337            }
20338            applyForegroundTint();
20339            if (isAttachedToWindow()) {
20340                foreground.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
20341            }
20342            // Set callback last, since the view may still be initializing.
20343            foreground.setCallback(this);
20344        } else if ((mViewFlags & WILL_NOT_DRAW) != 0 && mBackground == null
20345                && (mDefaultFocusHighlight == null)) {
20346            mPrivateFlags |= PFLAG_SKIP_DRAW;
20347        }
20348        requestLayout();
20349        invalidate();
20350    }
20351
20352    /**
20353     * Magic bit used to support features of framework-internal window decor implementation details.
20354     * This used to live exclusively in FrameLayout.
20355     *
20356     * @return true if the foreground should draw inside the padding region or false
20357     *         if it should draw inset by the view's padding
20358     * @hide internal use only; only used by FrameLayout and internal screen layouts.
20359     */
20360    public boolean isForegroundInsidePadding() {
20361        return mForegroundInfo != null ? mForegroundInfo.mInsidePadding : true;
20362    }
20363
20364    /**
20365     * Describes how the foreground is positioned.
20366     *
20367     * @return foreground gravity.
20368     *
20369     * @see #setForegroundGravity(int)
20370     *
20371     * @attr ref android.R.styleable#View_foregroundGravity
20372     */
20373    public int getForegroundGravity() {
20374        return mForegroundInfo != null ? mForegroundInfo.mGravity
20375                : Gravity.START | Gravity.TOP;
20376    }
20377
20378    /**
20379     * Describes how the foreground is positioned. Defaults to START and TOP.
20380     *
20381     * @param gravity see {@link android.view.Gravity}
20382     *
20383     * @see #getForegroundGravity()
20384     *
20385     * @attr ref android.R.styleable#View_foregroundGravity
20386     */
20387    public void setForegroundGravity(int gravity) {
20388        if (mForegroundInfo == null) {
20389            mForegroundInfo = new ForegroundInfo();
20390        }
20391
20392        if (mForegroundInfo.mGravity != gravity) {
20393            if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) {
20394                gravity |= Gravity.START;
20395            }
20396
20397            if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) {
20398                gravity |= Gravity.TOP;
20399            }
20400
20401            mForegroundInfo.mGravity = gravity;
20402            requestLayout();
20403        }
20404    }
20405
20406    /**
20407     * Applies a tint to the foreground drawable. Does not modify the current tint
20408     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
20409     * <p>
20410     * Subsequent calls to {@link #setForeground(Drawable)} will automatically
20411     * mutate the drawable and apply the specified tint and tint mode using
20412     * {@link Drawable#setTintList(ColorStateList)}.
20413     *
20414     * @param tint the tint to apply, may be {@code null} to clear tint
20415     *
20416     * @attr ref android.R.styleable#View_foregroundTint
20417     * @see #getForegroundTintList()
20418     * @see Drawable#setTintList(ColorStateList)
20419     */
20420    public void setForegroundTintList(@Nullable ColorStateList tint) {
20421        if (mForegroundInfo == null) {
20422            mForegroundInfo = new ForegroundInfo();
20423        }
20424        if (mForegroundInfo.mTintInfo == null) {
20425            mForegroundInfo.mTintInfo = new TintInfo();
20426        }
20427        mForegroundInfo.mTintInfo.mTintList = tint;
20428        mForegroundInfo.mTintInfo.mHasTintList = true;
20429
20430        applyForegroundTint();
20431    }
20432
20433    /**
20434     * Return the tint applied to the foreground drawable, if specified.
20435     *
20436     * @return the tint applied to the foreground drawable
20437     * @attr ref android.R.styleable#View_foregroundTint
20438     * @see #setForegroundTintList(ColorStateList)
20439     */
20440    @Nullable
20441    public ColorStateList getForegroundTintList() {
20442        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
20443                ? mForegroundInfo.mTintInfo.mTintList : null;
20444    }
20445
20446    /**
20447     * Specifies the blending mode used to apply the tint specified by
20448     * {@link #setForegroundTintList(ColorStateList)}} to the background
20449     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
20450     *
20451     * @param tintMode the blending mode used to apply the tint, may be
20452     *                 {@code null} to clear tint
20453     * @attr ref android.R.styleable#View_foregroundTintMode
20454     * @see #getForegroundTintMode()
20455     * @see Drawable#setTintMode(PorterDuff.Mode)
20456     */
20457    public void setForegroundTintMode(@Nullable PorterDuff.Mode tintMode) {
20458        if (mForegroundInfo == null) {
20459            mForegroundInfo = new ForegroundInfo();
20460        }
20461        if (mForegroundInfo.mTintInfo == null) {
20462            mForegroundInfo.mTintInfo = new TintInfo();
20463        }
20464        mForegroundInfo.mTintInfo.mTintMode = tintMode;
20465        mForegroundInfo.mTintInfo.mHasTintMode = true;
20466
20467        applyForegroundTint();
20468    }
20469
20470    /**
20471     * Return the blending mode used to apply the tint to the foreground
20472     * drawable, if specified.
20473     *
20474     * @return the blending mode used to apply the tint to the foreground
20475     *         drawable
20476     * @attr ref android.R.styleable#View_foregroundTintMode
20477     * @see #setForegroundTintMode(PorterDuff.Mode)
20478     */
20479    @Nullable
20480    public PorterDuff.Mode getForegroundTintMode() {
20481        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
20482                ? mForegroundInfo.mTintInfo.mTintMode : null;
20483    }
20484
20485    private void applyForegroundTint() {
20486        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
20487                && mForegroundInfo.mTintInfo != null) {
20488            final TintInfo tintInfo = mForegroundInfo.mTintInfo;
20489            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
20490                mForegroundInfo.mDrawable = mForegroundInfo.mDrawable.mutate();
20491
20492                if (tintInfo.mHasTintList) {
20493                    mForegroundInfo.mDrawable.setTintList(tintInfo.mTintList);
20494                }
20495
20496                if (tintInfo.mHasTintMode) {
20497                    mForegroundInfo.mDrawable.setTintMode(tintInfo.mTintMode);
20498                }
20499
20500                // The drawable (or one of its children) may not have been
20501                // stateful before applying the tint, so let's try again.
20502                if (mForegroundInfo.mDrawable.isStateful()) {
20503                    mForegroundInfo.mDrawable.setState(getDrawableState());
20504                }
20505            }
20506        }
20507    }
20508
20509    /**
20510     * Get the drawable to be overlayed when a view is autofilled
20511     *
20512     * @return The drawable
20513     *
20514     * @throws IllegalStateException if the drawable could not be found.
20515     */
20516    @Nullable private Drawable getAutofilledDrawable() {
20517        // Lazily load the isAutofilled drawable.
20518        if (mAttachInfo.mAutofilledDrawable == null) {
20519            Context rootContext = getRootView().getContext();
20520            TypedArray a = rootContext.getTheme().obtainStyledAttributes(AUTOFILL_HIGHLIGHT_ATTR);
20521            int attributeResourceId = a.getResourceId(0, 0);
20522            mAttachInfo.mAutofilledDrawable = rootContext.getDrawable(attributeResourceId);
20523            a.recycle();
20524        }
20525
20526        return mAttachInfo.mAutofilledDrawable;
20527    }
20528
20529    /**
20530     * Draw {@link View#isAutofilled()} highlight over view if the view is autofilled.
20531     *
20532     * @param canvas The canvas to draw on
20533     */
20534    private void drawAutofilledHighlight(@NonNull Canvas canvas) {
20535        if (isAutofilled()) {
20536            Drawable autofilledHighlight = getAutofilledDrawable();
20537
20538            if (autofilledHighlight != null) {
20539                autofilledHighlight.setBounds(0, 0, getWidth(), getHeight());
20540                autofilledHighlight.draw(canvas);
20541            }
20542        }
20543    }
20544
20545    /**
20546     * Draw any foreground content for this view.
20547     *
20548     * <p>Foreground content may consist of scroll bars, a {@link #setForeground foreground}
20549     * drawable or other view-specific decorations. The foreground is drawn on top of the
20550     * primary view content.</p>
20551     *
20552     * @param canvas canvas to draw into
20553     */
20554    public void onDrawForeground(Canvas canvas) {
20555        onDrawScrollIndicators(canvas);
20556        onDrawScrollBars(canvas);
20557
20558        final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
20559        if (foreground != null) {
20560            if (mForegroundInfo.mBoundsChanged) {
20561                mForegroundInfo.mBoundsChanged = false;
20562                final Rect selfBounds = mForegroundInfo.mSelfBounds;
20563                final Rect overlayBounds = mForegroundInfo.mOverlayBounds;
20564
20565                if (mForegroundInfo.mInsidePadding) {
20566                    selfBounds.set(0, 0, getWidth(), getHeight());
20567                } else {
20568                    selfBounds.set(getPaddingLeft(), getPaddingTop(),
20569                            getWidth() - getPaddingRight(), getHeight() - getPaddingBottom());
20570                }
20571
20572                final int ld = getLayoutDirection();
20573                Gravity.apply(mForegroundInfo.mGravity, foreground.getIntrinsicWidth(),
20574                        foreground.getIntrinsicHeight(), selfBounds, overlayBounds, ld);
20575                foreground.setBounds(overlayBounds);
20576            }
20577
20578            foreground.draw(canvas);
20579        }
20580    }
20581
20582    /**
20583     * Sets the padding. The view may add on the space required to display
20584     * the scrollbars, depending on the style and visibility of the scrollbars.
20585     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
20586     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
20587     * from the values set in this call.
20588     *
20589     * @attr ref android.R.styleable#View_padding
20590     * @attr ref android.R.styleable#View_paddingBottom
20591     * @attr ref android.R.styleable#View_paddingLeft
20592     * @attr ref android.R.styleable#View_paddingRight
20593     * @attr ref android.R.styleable#View_paddingTop
20594     * @param left the left padding in pixels
20595     * @param top the top padding in pixels
20596     * @param right the right padding in pixels
20597     * @param bottom the bottom padding in pixels
20598     */
20599    public void setPadding(int left, int top, int right, int bottom) {
20600        resetResolvedPaddingInternal();
20601
20602        mUserPaddingStart = UNDEFINED_PADDING;
20603        mUserPaddingEnd = UNDEFINED_PADDING;
20604
20605        mUserPaddingLeftInitial = left;
20606        mUserPaddingRightInitial = right;
20607
20608        mLeftPaddingDefined = true;
20609        mRightPaddingDefined = true;
20610
20611        internalSetPadding(left, top, right, bottom);
20612    }
20613
20614    /**
20615     * @hide
20616     */
20617    protected void internalSetPadding(int left, int top, int right, int bottom) {
20618        mUserPaddingLeft = left;
20619        mUserPaddingRight = right;
20620        mUserPaddingBottom = bottom;
20621
20622        final int viewFlags = mViewFlags;
20623        boolean changed = false;
20624
20625        // Common case is there are no scroll bars.
20626        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
20627            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
20628                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
20629                        ? 0 : getVerticalScrollbarWidth();
20630                switch (mVerticalScrollbarPosition) {
20631                    case SCROLLBAR_POSITION_DEFAULT:
20632                        if (isLayoutRtl()) {
20633                            left += offset;
20634                        } else {
20635                            right += offset;
20636                        }
20637                        break;
20638                    case SCROLLBAR_POSITION_RIGHT:
20639                        right += offset;
20640                        break;
20641                    case SCROLLBAR_POSITION_LEFT:
20642                        left += offset;
20643                        break;
20644                }
20645            }
20646            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
20647                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
20648                        ? 0 : getHorizontalScrollbarHeight();
20649            }
20650        }
20651
20652        if (mPaddingLeft != left) {
20653            changed = true;
20654            mPaddingLeft = left;
20655        }
20656        if (mPaddingTop != top) {
20657            changed = true;
20658            mPaddingTop = top;
20659        }
20660        if (mPaddingRight != right) {
20661            changed = true;
20662            mPaddingRight = right;
20663        }
20664        if (mPaddingBottom != bottom) {
20665            changed = true;
20666            mPaddingBottom = bottom;
20667        }
20668
20669        if (changed) {
20670            requestLayout();
20671            invalidateOutline();
20672        }
20673    }
20674
20675    /**
20676     * Sets the relative padding. The view may add on the space required to display
20677     * the scrollbars, depending on the style and visibility of the scrollbars.
20678     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
20679     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
20680     * from the values set in this call.
20681     *
20682     * @attr ref android.R.styleable#View_padding
20683     * @attr ref android.R.styleable#View_paddingBottom
20684     * @attr ref android.R.styleable#View_paddingStart
20685     * @attr ref android.R.styleable#View_paddingEnd
20686     * @attr ref android.R.styleable#View_paddingTop
20687     * @param start the start padding in pixels
20688     * @param top the top padding in pixels
20689     * @param end the end padding in pixels
20690     * @param bottom the bottom padding in pixels
20691     */
20692    public void setPaddingRelative(int start, int top, int end, int bottom) {
20693        resetResolvedPaddingInternal();
20694
20695        mUserPaddingStart = start;
20696        mUserPaddingEnd = end;
20697        mLeftPaddingDefined = true;
20698        mRightPaddingDefined = true;
20699
20700        switch(getLayoutDirection()) {
20701            case LAYOUT_DIRECTION_RTL:
20702                mUserPaddingLeftInitial = end;
20703                mUserPaddingRightInitial = start;
20704                internalSetPadding(end, top, start, bottom);
20705                break;
20706            case LAYOUT_DIRECTION_LTR:
20707            default:
20708                mUserPaddingLeftInitial = start;
20709                mUserPaddingRightInitial = end;
20710                internalSetPadding(start, top, end, bottom);
20711        }
20712    }
20713
20714    /**
20715     * Returns the top padding of this view.
20716     *
20717     * @return the top padding in pixels
20718     */
20719    public int getPaddingTop() {
20720        return mPaddingTop;
20721    }
20722
20723    /**
20724     * Returns the bottom padding of this view. If there are inset and enabled
20725     * scrollbars, this value may include the space required to display the
20726     * scrollbars as well.
20727     *
20728     * @return the bottom padding in pixels
20729     */
20730    public int getPaddingBottom() {
20731        return mPaddingBottom;
20732    }
20733
20734    /**
20735     * Returns the left padding of this view. If there are inset and enabled
20736     * scrollbars, this value may include the space required to display the
20737     * scrollbars as well.
20738     *
20739     * @return the left padding in pixels
20740     */
20741    public int getPaddingLeft() {
20742        if (!isPaddingResolved()) {
20743            resolvePadding();
20744        }
20745        return mPaddingLeft;
20746    }
20747
20748    /**
20749     * Returns the start padding of this view depending on its resolved layout direction.
20750     * If there are inset and enabled scrollbars, this value may include the space
20751     * required to display the scrollbars as well.
20752     *
20753     * @return the start padding in pixels
20754     */
20755    public int getPaddingStart() {
20756        if (!isPaddingResolved()) {
20757            resolvePadding();
20758        }
20759        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
20760                mPaddingRight : mPaddingLeft;
20761    }
20762
20763    /**
20764     * Returns the right padding of this view. If there are inset and enabled
20765     * scrollbars, this value may include the space required to display the
20766     * scrollbars as well.
20767     *
20768     * @return the right padding in pixels
20769     */
20770    public int getPaddingRight() {
20771        if (!isPaddingResolved()) {
20772            resolvePadding();
20773        }
20774        return mPaddingRight;
20775    }
20776
20777    /**
20778     * Returns the end padding of this view depending on its resolved layout direction.
20779     * If there are inset and enabled scrollbars, this value may include the space
20780     * required to display the scrollbars as well.
20781     *
20782     * @return the end padding in pixels
20783     */
20784    public int getPaddingEnd() {
20785        if (!isPaddingResolved()) {
20786            resolvePadding();
20787        }
20788        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
20789                mPaddingLeft : mPaddingRight;
20790    }
20791
20792    /**
20793     * Return if the padding has been set through relative values
20794     * {@link #setPaddingRelative(int, int, int, int)} or through
20795     * @attr ref android.R.styleable#View_paddingStart or
20796     * @attr ref android.R.styleable#View_paddingEnd
20797     *
20798     * @return true if the padding is relative or false if it is not.
20799     */
20800    public boolean isPaddingRelative() {
20801        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
20802    }
20803
20804    Insets computeOpticalInsets() {
20805        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
20806    }
20807
20808    /**
20809     * @hide
20810     */
20811    public void resetPaddingToInitialValues() {
20812        if (isRtlCompatibilityMode()) {
20813            mPaddingLeft = mUserPaddingLeftInitial;
20814            mPaddingRight = mUserPaddingRightInitial;
20815            return;
20816        }
20817        if (isLayoutRtl()) {
20818            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
20819            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
20820        } else {
20821            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
20822            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
20823        }
20824    }
20825
20826    /**
20827     * @hide
20828     */
20829    public Insets getOpticalInsets() {
20830        if (mLayoutInsets == null) {
20831            mLayoutInsets = computeOpticalInsets();
20832        }
20833        return mLayoutInsets;
20834    }
20835
20836    /**
20837     * Set this view's optical insets.
20838     *
20839     * <p>This method should be treated similarly to setMeasuredDimension and not as a general
20840     * property. Views that compute their own optical insets should call it as part of measurement.
20841     * This method does not request layout. If you are setting optical insets outside of
20842     * measure/layout itself you will want to call requestLayout() yourself.
20843     * </p>
20844     * @hide
20845     */
20846    public void setOpticalInsets(Insets insets) {
20847        mLayoutInsets = insets;
20848    }
20849
20850    /**
20851     * Changes the selection state of this view. A view can be selected or not.
20852     * Note that selection is not the same as focus. Views are typically
20853     * selected in the context of an AdapterView like ListView or GridView;
20854     * the selected view is the view that is highlighted.
20855     *
20856     * @param selected true if the view must be selected, false otherwise
20857     */
20858    public void setSelected(boolean selected) {
20859        //noinspection DoubleNegation
20860        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
20861            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
20862            if (!selected) resetPressedState();
20863            invalidate(true);
20864            refreshDrawableState();
20865            dispatchSetSelected(selected);
20866            if (selected) {
20867                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
20868            } else {
20869                notifyViewAccessibilityStateChangedIfNeeded(
20870                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
20871            }
20872        }
20873    }
20874
20875    /**
20876     * Dispatch setSelected to all of this View's children.
20877     *
20878     * @see #setSelected(boolean)
20879     *
20880     * @param selected The new selected state
20881     */
20882    protected void dispatchSetSelected(boolean selected) {
20883    }
20884
20885    /**
20886     * Indicates the selection state of this view.
20887     *
20888     * @return true if the view is selected, false otherwise
20889     */
20890    @ViewDebug.ExportedProperty
20891    public boolean isSelected() {
20892        return (mPrivateFlags & PFLAG_SELECTED) != 0;
20893    }
20894
20895    /**
20896     * Changes the activated state of this view. A view can be activated or not.
20897     * Note that activation is not the same as selection.  Selection is
20898     * a transient property, representing the view (hierarchy) the user is
20899     * currently interacting with.  Activation is a longer-term state that the
20900     * user can move views in and out of.  For example, in a list view with
20901     * single or multiple selection enabled, the views in the current selection
20902     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
20903     * here.)  The activated state is propagated down to children of the view it
20904     * is set on.
20905     *
20906     * @param activated true if the view must be activated, false otherwise
20907     */
20908    public void setActivated(boolean activated) {
20909        //noinspection DoubleNegation
20910        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
20911            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
20912            invalidate(true);
20913            refreshDrawableState();
20914            dispatchSetActivated(activated);
20915        }
20916    }
20917
20918    /**
20919     * Dispatch setActivated to all of this View's children.
20920     *
20921     * @see #setActivated(boolean)
20922     *
20923     * @param activated The new activated state
20924     */
20925    protected void dispatchSetActivated(boolean activated) {
20926    }
20927
20928    /**
20929     * Indicates the activation state of this view.
20930     *
20931     * @return true if the view is activated, false otherwise
20932     */
20933    @ViewDebug.ExportedProperty
20934    public boolean isActivated() {
20935        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
20936    }
20937
20938    /**
20939     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
20940     * observer can be used to get notifications when global events, like
20941     * layout, happen.
20942     *
20943     * The returned ViewTreeObserver observer is not guaranteed to remain
20944     * valid for the lifetime of this View. If the caller of this method keeps
20945     * a long-lived reference to ViewTreeObserver, it should always check for
20946     * the return value of {@link ViewTreeObserver#isAlive()}.
20947     *
20948     * @return The ViewTreeObserver for this view's hierarchy.
20949     */
20950    public ViewTreeObserver getViewTreeObserver() {
20951        if (mAttachInfo != null) {
20952            return mAttachInfo.mTreeObserver;
20953        }
20954        if (mFloatingTreeObserver == null) {
20955            mFloatingTreeObserver = new ViewTreeObserver(mContext);
20956        }
20957        return mFloatingTreeObserver;
20958    }
20959
20960    /**
20961     * <p>Finds the topmost view in the current view hierarchy.</p>
20962     *
20963     * @return the topmost view containing this view
20964     */
20965    public View getRootView() {
20966        if (mAttachInfo != null) {
20967            final View v = mAttachInfo.mRootView;
20968            if (v != null) {
20969                return v;
20970            }
20971        }
20972
20973        View parent = this;
20974
20975        while (parent.mParent != null && parent.mParent instanceof View) {
20976            parent = (View) parent.mParent;
20977        }
20978
20979        return parent;
20980    }
20981
20982    /**
20983     * Transforms a motion event from view-local coordinates to on-screen
20984     * coordinates.
20985     *
20986     * @param ev the view-local motion event
20987     * @return false if the transformation could not be applied
20988     * @hide
20989     */
20990    public boolean toGlobalMotionEvent(MotionEvent ev) {
20991        final AttachInfo info = mAttachInfo;
20992        if (info == null) {
20993            return false;
20994        }
20995
20996        final Matrix m = info.mTmpMatrix;
20997        m.set(Matrix.IDENTITY_MATRIX);
20998        transformMatrixToGlobal(m);
20999        ev.transform(m);
21000        return true;
21001    }
21002
21003    /**
21004     * Transforms a motion event from on-screen coordinates to view-local
21005     * coordinates.
21006     *
21007     * @param ev the on-screen motion event
21008     * @return false if the transformation could not be applied
21009     * @hide
21010     */
21011    public boolean toLocalMotionEvent(MotionEvent ev) {
21012        final AttachInfo info = mAttachInfo;
21013        if (info == null) {
21014            return false;
21015        }
21016
21017        final Matrix m = info.mTmpMatrix;
21018        m.set(Matrix.IDENTITY_MATRIX);
21019        transformMatrixToLocal(m);
21020        ev.transform(m);
21021        return true;
21022    }
21023
21024    /**
21025     * Modifies the input matrix such that it maps view-local coordinates to
21026     * on-screen coordinates.
21027     *
21028     * @param m input matrix to modify
21029     * @hide
21030     */
21031    public void transformMatrixToGlobal(Matrix m) {
21032        final ViewParent parent = mParent;
21033        if (parent instanceof View) {
21034            final View vp = (View) parent;
21035            vp.transformMatrixToGlobal(m);
21036            m.preTranslate(-vp.mScrollX, -vp.mScrollY);
21037        } else if (parent instanceof ViewRootImpl) {
21038            final ViewRootImpl vr = (ViewRootImpl) parent;
21039            vr.transformMatrixToGlobal(m);
21040            m.preTranslate(0, -vr.mCurScrollY);
21041        }
21042
21043        m.preTranslate(mLeft, mTop);
21044
21045        if (!hasIdentityMatrix()) {
21046            m.preConcat(getMatrix());
21047        }
21048    }
21049
21050    /**
21051     * Modifies the input matrix such that it maps on-screen coordinates to
21052     * view-local coordinates.
21053     *
21054     * @param m input matrix to modify
21055     * @hide
21056     */
21057    public void transformMatrixToLocal(Matrix m) {
21058        final ViewParent parent = mParent;
21059        if (parent instanceof View) {
21060            final View vp = (View) parent;
21061            vp.transformMatrixToLocal(m);
21062            m.postTranslate(vp.mScrollX, vp.mScrollY);
21063        } else if (parent instanceof ViewRootImpl) {
21064            final ViewRootImpl vr = (ViewRootImpl) parent;
21065            vr.transformMatrixToLocal(m);
21066            m.postTranslate(0, vr.mCurScrollY);
21067        }
21068
21069        m.postTranslate(-mLeft, -mTop);
21070
21071        if (!hasIdentityMatrix()) {
21072            m.postConcat(getInverseMatrix());
21073        }
21074    }
21075
21076    /**
21077     * @hide
21078     */
21079    @ViewDebug.ExportedProperty(category = "layout", indexMapping = {
21080            @ViewDebug.IntToString(from = 0, to = "x"),
21081            @ViewDebug.IntToString(from = 1, to = "y")
21082    })
21083    public int[] getLocationOnScreen() {
21084        int[] location = new int[2];
21085        getLocationOnScreen(location);
21086        return location;
21087    }
21088
21089    /**
21090     * <p>Computes the coordinates of this view on the screen. The argument
21091     * must be an array of two integers. After the method returns, the array
21092     * contains the x and y location in that order.</p>
21093     *
21094     * @param outLocation an array of two integers in which to hold the coordinates
21095     */
21096    public void getLocationOnScreen(@Size(2) int[] outLocation) {
21097        getLocationInWindow(outLocation);
21098
21099        final AttachInfo info = mAttachInfo;
21100        if (info != null) {
21101            outLocation[0] += info.mWindowLeft;
21102            outLocation[1] += info.mWindowTop;
21103        }
21104    }
21105
21106    /**
21107     * <p>Computes the coordinates of this view in its window. The argument
21108     * must be an array of two integers. After the method returns, the array
21109     * contains the x and y location in that order.</p>
21110     *
21111     * @param outLocation an array of two integers in which to hold the coordinates
21112     */
21113    public void getLocationInWindow(@Size(2) int[] outLocation) {
21114        if (outLocation == null || outLocation.length < 2) {
21115            throw new IllegalArgumentException("outLocation must be an array of two integers");
21116        }
21117
21118        outLocation[0] = 0;
21119        outLocation[1] = 0;
21120
21121        transformFromViewToWindowSpace(outLocation);
21122    }
21123
21124    /** @hide */
21125    public void transformFromViewToWindowSpace(@Size(2) int[] inOutLocation) {
21126        if (inOutLocation == null || inOutLocation.length < 2) {
21127            throw new IllegalArgumentException("inOutLocation must be an array of two integers");
21128        }
21129
21130        if (mAttachInfo == null) {
21131            // When the view is not attached to a window, this method does not make sense
21132            inOutLocation[0] = inOutLocation[1] = 0;
21133            return;
21134        }
21135
21136        float position[] = mAttachInfo.mTmpTransformLocation;
21137        position[0] = inOutLocation[0];
21138        position[1] = inOutLocation[1];
21139
21140        if (!hasIdentityMatrix()) {
21141            getMatrix().mapPoints(position);
21142        }
21143
21144        position[0] += mLeft;
21145        position[1] += mTop;
21146
21147        ViewParent viewParent = mParent;
21148        while (viewParent instanceof View) {
21149            final View view = (View) viewParent;
21150
21151            position[0] -= view.mScrollX;
21152            position[1] -= view.mScrollY;
21153
21154            if (!view.hasIdentityMatrix()) {
21155                view.getMatrix().mapPoints(position);
21156            }
21157
21158            position[0] += view.mLeft;
21159            position[1] += view.mTop;
21160
21161            viewParent = view.mParent;
21162         }
21163
21164        if (viewParent instanceof ViewRootImpl) {
21165            // *cough*
21166            final ViewRootImpl vr = (ViewRootImpl) viewParent;
21167            position[1] -= vr.mCurScrollY;
21168        }
21169
21170        inOutLocation[0] = Math.round(position[0]);
21171        inOutLocation[1] = Math.round(position[1]);
21172    }
21173
21174    /**
21175     * @param id the id of the view to be found
21176     * @return the view of the specified id, null if cannot be found
21177     * @hide
21178     */
21179    protected <T extends View> T findViewTraversal(@IdRes int id) {
21180        if (id == mID) {
21181            return (T) this;
21182        }
21183        return null;
21184    }
21185
21186    /**
21187     * @param tag the tag of the view to be found
21188     * @return the view of specified tag, null if cannot be found
21189     * @hide
21190     */
21191    protected <T extends View> T findViewWithTagTraversal(Object tag) {
21192        if (tag != null && tag.equals(mTag)) {
21193            return (T) this;
21194        }
21195        return null;
21196    }
21197
21198    /**
21199     * @param predicate The predicate to evaluate.
21200     * @param childToSkip If not null, ignores this child during the recursive traversal.
21201     * @return The first view that matches the predicate or null.
21202     * @hide
21203     */
21204    protected <T extends View> T findViewByPredicateTraversal(Predicate<View> predicate,
21205            View childToSkip) {
21206        if (predicate.test(this)) {
21207            return (T) this;
21208        }
21209        return null;
21210    }
21211
21212    /**
21213     * Finds the first descendant view with the given ID, the view itself if
21214     * the ID matches {@link #getId()}, or {@code null} if the ID is invalid
21215     * (< 0) or there is no matching view in the hierarchy.
21216     * <p>
21217     * <strong>Note:</strong> In most cases -- depending on compiler support --
21218     * the resulting view is automatically cast to the target class type. If
21219     * the target class type is unconstrained, an explicit cast may be
21220     * necessary.
21221     *
21222     * @param id the ID to search for
21223     * @return a view with given ID if found, or {@code null} otherwise
21224     * @see View#findViewById(int)
21225     */
21226    @Nullable
21227    public final <T extends View> T findViewById(@IdRes int id) {
21228        if (id == NO_ID) {
21229            return null;
21230        }
21231        return findViewTraversal(id);
21232    }
21233
21234    /**
21235     * Finds a view by its unuque and stable accessibility id.
21236     *
21237     * @param accessibilityId The searched accessibility id.
21238     * @return The found view.
21239     */
21240    final <T extends View> T  findViewByAccessibilityId(int accessibilityId) {
21241        if (accessibilityId < 0) {
21242            return null;
21243        }
21244        T view = findViewByAccessibilityIdTraversal(accessibilityId);
21245        if (view != null) {
21246            return view.includeForAccessibility() ? view : null;
21247        }
21248        return null;
21249    }
21250
21251    /**
21252     * Performs the traversal to find a view by its unuque and stable accessibility id.
21253     *
21254     * <strong>Note:</strong>This method does not stop at the root namespace
21255     * boundary since the user can touch the screen at an arbitrary location
21256     * potentially crossing the root namespace bounday which will send an
21257     * accessibility event to accessibility services and they should be able
21258     * to obtain the event source. Also accessibility ids are guaranteed to be
21259     * unique in the window.
21260     *
21261     * @param accessibilityId The accessibility id.
21262     * @return The found view.
21263     * @hide
21264     */
21265    public <T extends View> T findViewByAccessibilityIdTraversal(int accessibilityId) {
21266        if (getAccessibilityViewId() == accessibilityId) {
21267            return (T) this;
21268        }
21269        return null;
21270    }
21271
21272    /**
21273     * Look for a child view with the given tag.  If this view has the given
21274     * tag, return this view.
21275     *
21276     * @param tag The tag to search for, using "tag.equals(getTag())".
21277     * @return The View that has the given tag in the hierarchy or null
21278     */
21279    public final <T extends View> T findViewWithTag(Object tag) {
21280        if (tag == null) {
21281            return null;
21282        }
21283        return findViewWithTagTraversal(tag);
21284    }
21285
21286    /**
21287     * Look for a child view that matches the specified predicate.
21288     * If this view matches the predicate, return this view.
21289     *
21290     * @param predicate The predicate to evaluate.
21291     * @return The first view that matches the predicate or null.
21292     * @hide
21293     */
21294    public final <T extends View> T findViewByPredicate(Predicate<View> predicate) {
21295        return findViewByPredicateTraversal(predicate, null);
21296    }
21297
21298    /**
21299     * Look for a child view that matches the specified predicate,
21300     * starting with the specified view and its descendents and then
21301     * recusively searching the ancestors and siblings of that view
21302     * until this view is reached.
21303     *
21304     * This method is useful in cases where the predicate does not match
21305     * a single unique view (perhaps multiple views use the same id)
21306     * and we are trying to find the view that is "closest" in scope to the
21307     * starting view.
21308     *
21309     * @param start The view to start from.
21310     * @param predicate The predicate to evaluate.
21311     * @return The first view that matches the predicate or null.
21312     * @hide
21313     */
21314    public final <T extends View> T findViewByPredicateInsideOut(
21315            View start, Predicate<View> predicate) {
21316        View childToSkip = null;
21317        for (;;) {
21318            T view = start.findViewByPredicateTraversal(predicate, childToSkip);
21319            if (view != null || start == this) {
21320                return view;
21321            }
21322
21323            ViewParent parent = start.getParent();
21324            if (parent == null || !(parent instanceof View)) {
21325                return null;
21326            }
21327
21328            childToSkip = start;
21329            start = (View) parent;
21330        }
21331    }
21332
21333    /**
21334     * Sets the identifier for this view. The identifier does not have to be
21335     * unique in this view's hierarchy. The identifier should be a positive
21336     * number.
21337     *
21338     * @see #NO_ID
21339     * @see #getId()
21340     * @see #findViewById(int)
21341     *
21342     * @param id a number used to identify the view
21343     *
21344     * @attr ref android.R.styleable#View_id
21345     */
21346    public void setId(@IdRes int id) {
21347        mID = id;
21348        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
21349            mID = generateViewId();
21350        }
21351    }
21352
21353    /**
21354     * {@hide}
21355     *
21356     * @param isRoot true if the view belongs to the root namespace, false
21357     *        otherwise
21358     */
21359    public void setIsRootNamespace(boolean isRoot) {
21360        if (isRoot) {
21361            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
21362        } else {
21363            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
21364        }
21365    }
21366
21367    /**
21368     * {@hide}
21369     *
21370     * @return true if the view belongs to the root namespace, false otherwise
21371     */
21372    public boolean isRootNamespace() {
21373        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
21374    }
21375
21376    /**
21377     * Returns this view's identifier.
21378     *
21379     * @return a positive integer used to identify the view or {@link #NO_ID}
21380     *         if the view has no ID
21381     *
21382     * @see #setId(int)
21383     * @see #findViewById(int)
21384     * @attr ref android.R.styleable#View_id
21385     */
21386    @IdRes
21387    @ViewDebug.CapturedViewProperty
21388    public int getId() {
21389        return mID;
21390    }
21391
21392    /**
21393     * Returns this view's tag.
21394     *
21395     * @return the Object stored in this view as a tag, or {@code null} if not
21396     *         set
21397     *
21398     * @see #setTag(Object)
21399     * @see #getTag(int)
21400     */
21401    @ViewDebug.ExportedProperty
21402    public Object getTag() {
21403        return mTag;
21404    }
21405
21406    /**
21407     * Sets the tag associated with this view. A tag can be used to mark
21408     * a view in its hierarchy and does not have to be unique within the
21409     * hierarchy. Tags can also be used to store data within a view without
21410     * resorting to another data structure.
21411     *
21412     * @param tag an Object to tag the view with
21413     *
21414     * @see #getTag()
21415     * @see #setTag(int, Object)
21416     */
21417    public void setTag(final Object tag) {
21418        mTag = tag;
21419    }
21420
21421    /**
21422     * Returns the tag associated with this view and the specified key.
21423     *
21424     * @param key The key identifying the tag
21425     *
21426     * @return the Object stored in this view as a tag, or {@code null} if not
21427     *         set
21428     *
21429     * @see #setTag(int, Object)
21430     * @see #getTag()
21431     */
21432    public Object getTag(int key) {
21433        if (mKeyedTags != null) return mKeyedTags.get(key);
21434        return null;
21435    }
21436
21437    /**
21438     * Sets a tag associated with this view and a key. A tag can be used
21439     * to mark a view in its hierarchy and does not have to be unique within
21440     * the hierarchy. Tags can also be used to store data within a view
21441     * without resorting to another data structure.
21442     *
21443     * The specified key should be an id declared in the resources of the
21444     * application to ensure it is unique (see the <a
21445     * href="{@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
21446     * Keys identified as belonging to
21447     * the Android framework or not associated with any package will cause
21448     * an {@link IllegalArgumentException} to be thrown.
21449     *
21450     * @param key The key identifying the tag
21451     * @param tag An Object to tag the view with
21452     *
21453     * @throws IllegalArgumentException If they specified key is not valid
21454     *
21455     * @see #setTag(Object)
21456     * @see #getTag(int)
21457     */
21458    public void setTag(int key, final Object tag) {
21459        // If the package id is 0x00 or 0x01, it's either an undefined package
21460        // or a framework id
21461        if ((key >>> 24) < 2) {
21462            throw new IllegalArgumentException("The key must be an application-specific "
21463                    + "resource id.");
21464        }
21465
21466        setKeyedTag(key, tag);
21467    }
21468
21469    /**
21470     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
21471     * framework id.
21472     *
21473     * @hide
21474     */
21475    public void setTagInternal(int key, Object tag) {
21476        if ((key >>> 24) != 0x1) {
21477            throw new IllegalArgumentException("The key must be a framework-specific "
21478                    + "resource id.");
21479        }
21480
21481        setKeyedTag(key, tag);
21482    }
21483
21484    private void setKeyedTag(int key, Object tag) {
21485        if (mKeyedTags == null) {
21486            mKeyedTags = new SparseArray<Object>(2);
21487        }
21488
21489        mKeyedTags.put(key, tag);
21490    }
21491
21492    /**
21493     * Prints information about this view in the log output, with the tag
21494     * {@link #VIEW_LOG_TAG}.
21495     *
21496     * @hide
21497     */
21498    public void debug() {
21499        debug(0);
21500    }
21501
21502    /**
21503     * Prints information about this view in the log output, with the tag
21504     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
21505     * indentation defined by the <code>depth</code>.
21506     *
21507     * @param depth the indentation level
21508     *
21509     * @hide
21510     */
21511    protected void debug(int depth) {
21512        String output = debugIndent(depth - 1);
21513
21514        output += "+ " + this;
21515        int id = getId();
21516        if (id != -1) {
21517            output += " (id=" + id + ")";
21518        }
21519        Object tag = getTag();
21520        if (tag != null) {
21521            output += " (tag=" + tag + ")";
21522        }
21523        Log.d(VIEW_LOG_TAG, output);
21524
21525        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
21526            output = debugIndent(depth) + " FOCUSED";
21527            Log.d(VIEW_LOG_TAG, output);
21528        }
21529
21530        output = debugIndent(depth);
21531        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
21532                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
21533                + "} ";
21534        Log.d(VIEW_LOG_TAG, output);
21535
21536        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
21537                || mPaddingBottom != 0) {
21538            output = debugIndent(depth);
21539            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
21540                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
21541            Log.d(VIEW_LOG_TAG, output);
21542        }
21543
21544        output = debugIndent(depth);
21545        output += "mMeasureWidth=" + mMeasuredWidth +
21546                " mMeasureHeight=" + mMeasuredHeight;
21547        Log.d(VIEW_LOG_TAG, output);
21548
21549        output = debugIndent(depth);
21550        if (mLayoutParams == null) {
21551            output += "BAD! no layout params";
21552        } else {
21553            output = mLayoutParams.debug(output);
21554        }
21555        Log.d(VIEW_LOG_TAG, output);
21556
21557        output = debugIndent(depth);
21558        output += "flags={";
21559        output += View.printFlags(mViewFlags);
21560        output += "}";
21561        Log.d(VIEW_LOG_TAG, output);
21562
21563        output = debugIndent(depth);
21564        output += "privateFlags={";
21565        output += View.printPrivateFlags(mPrivateFlags);
21566        output += "}";
21567        Log.d(VIEW_LOG_TAG, output);
21568    }
21569
21570    /**
21571     * Creates a string of whitespaces used for indentation.
21572     *
21573     * @param depth the indentation level
21574     * @return a String containing (depth * 2 + 3) * 2 white spaces
21575     *
21576     * @hide
21577     */
21578    protected static String debugIndent(int depth) {
21579        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
21580        for (int i = 0; i < (depth * 2) + 3; i++) {
21581            spaces.append(' ').append(' ');
21582        }
21583        return spaces.toString();
21584    }
21585
21586    /**
21587     * <p>Return the offset of the widget's text baseline from the widget's top
21588     * boundary. If this widget does not support baseline alignment, this
21589     * method returns -1. </p>
21590     *
21591     * @return the offset of the baseline within the widget's bounds or -1
21592     *         if baseline alignment is not supported
21593     */
21594    @ViewDebug.ExportedProperty(category = "layout")
21595    public int getBaseline() {
21596        return -1;
21597    }
21598
21599    /**
21600     * Returns whether the view hierarchy is currently undergoing a layout pass. This
21601     * information is useful to avoid situations such as calling {@link #requestLayout()} during
21602     * a layout pass.
21603     *
21604     * @return whether the view hierarchy is currently undergoing a layout pass
21605     */
21606    public boolean isInLayout() {
21607        ViewRootImpl viewRoot = getViewRootImpl();
21608        return (viewRoot != null && viewRoot.isInLayout());
21609    }
21610
21611    /**
21612     * Call this when something has changed which has invalidated the
21613     * layout of this view. This will schedule a layout pass of the view
21614     * tree. This should not be called while the view hierarchy is currently in a layout
21615     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
21616     * end of the current layout pass (and then layout will run again) or after the current
21617     * frame is drawn and the next layout occurs.
21618     *
21619     * <p>Subclasses which override this method should call the superclass method to
21620     * handle possible request-during-layout errors correctly.</p>
21621     */
21622    @CallSuper
21623    public void requestLayout() {
21624        if (mMeasureCache != null) mMeasureCache.clear();
21625
21626        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
21627            // Only trigger request-during-layout logic if this is the view requesting it,
21628            // not the views in its parent hierarchy
21629            ViewRootImpl viewRoot = getViewRootImpl();
21630            if (viewRoot != null && viewRoot.isInLayout()) {
21631                if (!viewRoot.requestLayoutDuringLayout(this)) {
21632                    return;
21633                }
21634            }
21635            mAttachInfo.mViewRequestingLayout = this;
21636        }
21637
21638        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
21639        mPrivateFlags |= PFLAG_INVALIDATED;
21640
21641        if (mParent != null && !mParent.isLayoutRequested()) {
21642            mParent.requestLayout();
21643        }
21644        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
21645            mAttachInfo.mViewRequestingLayout = null;
21646        }
21647    }
21648
21649    /**
21650     * Forces this view to be laid out during the next layout pass.
21651     * This method does not call requestLayout() or forceLayout()
21652     * on the parent.
21653     */
21654    public void forceLayout() {
21655        if (mMeasureCache != null) mMeasureCache.clear();
21656
21657        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
21658        mPrivateFlags |= PFLAG_INVALIDATED;
21659    }
21660
21661    /**
21662     * <p>
21663     * This is called to find out how big a view should be. The parent
21664     * supplies constraint information in the width and height parameters.
21665     * </p>
21666     *
21667     * <p>
21668     * The actual measurement work of a view is performed in
21669     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
21670     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
21671     * </p>
21672     *
21673     *
21674     * @param widthMeasureSpec Horizontal space requirements as imposed by the
21675     *        parent
21676     * @param heightMeasureSpec Vertical space requirements as imposed by the
21677     *        parent
21678     *
21679     * @see #onMeasure(int, int)
21680     */
21681    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
21682        boolean optical = isLayoutModeOptical(this);
21683        if (optical != isLayoutModeOptical(mParent)) {
21684            Insets insets = getOpticalInsets();
21685            int oWidth  = insets.left + insets.right;
21686            int oHeight = insets.top  + insets.bottom;
21687            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
21688            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
21689        }
21690
21691        // Suppress sign extension for the low bytes
21692        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
21693        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
21694
21695        final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
21696
21697        // Optimize layout by avoiding an extra EXACTLY pass when the view is
21698        // already measured as the correct size. In API 23 and below, this
21699        // extra pass is required to make LinearLayout re-distribute weight.
21700        final boolean specChanged = widthMeasureSpec != mOldWidthMeasureSpec
21701                || heightMeasureSpec != mOldHeightMeasureSpec;
21702        final boolean isSpecExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY
21703                && MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY;
21704        final boolean matchesSpecSize = getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec)
21705                && getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec);
21706        final boolean needsLayout = specChanged
21707                && (sAlwaysRemeasureExactly || !isSpecExactly || !matchesSpecSize);
21708
21709        if (forceLayout || needsLayout) {
21710            // first clears the measured dimension flag
21711            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
21712
21713            resolveRtlPropertiesIfNeeded();
21714
21715            int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key);
21716            if (cacheIndex < 0 || sIgnoreMeasureCache) {
21717                // measure ourselves, this should set the measured dimension flag back
21718                onMeasure(widthMeasureSpec, heightMeasureSpec);
21719                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
21720            } else {
21721                long value = mMeasureCache.valueAt(cacheIndex);
21722                // Casting a long to int drops the high 32 bits, no mask needed
21723                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
21724                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
21725            }
21726
21727            // flag not set, setMeasuredDimension() was not invoked, we raise
21728            // an exception to warn the developer
21729            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
21730                throw new IllegalStateException("View with id " + getId() + ": "
21731                        + getClass().getName() + "#onMeasure() did not set the"
21732                        + " measured dimension by calling"
21733                        + " setMeasuredDimension()");
21734            }
21735
21736            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
21737        }
21738
21739        mOldWidthMeasureSpec = widthMeasureSpec;
21740        mOldHeightMeasureSpec = heightMeasureSpec;
21741
21742        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
21743                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
21744    }
21745
21746    /**
21747     * <p>
21748     * Measure the view and its content to determine the measured width and the
21749     * measured height. This method is invoked by {@link #measure(int, int)} and
21750     * should be overridden by subclasses to provide accurate and efficient
21751     * measurement of their contents.
21752     * </p>
21753     *
21754     * <p>
21755     * <strong>CONTRACT:</strong> When overriding this method, you
21756     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
21757     * measured width and height of this view. Failure to do so will trigger an
21758     * <code>IllegalStateException</code>, thrown by
21759     * {@link #measure(int, int)}. Calling the superclass'
21760     * {@link #onMeasure(int, int)} is a valid use.
21761     * </p>
21762     *
21763     * <p>
21764     * The base class implementation of measure defaults to the background size,
21765     * unless a larger size is allowed by the MeasureSpec. Subclasses should
21766     * override {@link #onMeasure(int, int)} to provide better measurements of
21767     * their content.
21768     * </p>
21769     *
21770     * <p>
21771     * If this method is overridden, it is the subclass's responsibility to make
21772     * sure the measured height and width are at least the view's minimum height
21773     * and width ({@link #getSuggestedMinimumHeight()} and
21774     * {@link #getSuggestedMinimumWidth()}).
21775     * </p>
21776     *
21777     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
21778     *                         The requirements are encoded with
21779     *                         {@link android.view.View.MeasureSpec}.
21780     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
21781     *                         The requirements are encoded with
21782     *                         {@link android.view.View.MeasureSpec}.
21783     *
21784     * @see #getMeasuredWidth()
21785     * @see #getMeasuredHeight()
21786     * @see #setMeasuredDimension(int, int)
21787     * @see #getSuggestedMinimumHeight()
21788     * @see #getSuggestedMinimumWidth()
21789     * @see android.view.View.MeasureSpec#getMode(int)
21790     * @see android.view.View.MeasureSpec#getSize(int)
21791     */
21792    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
21793        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
21794                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
21795    }
21796
21797    /**
21798     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
21799     * measured width and measured height. Failing to do so will trigger an
21800     * exception at measurement time.</p>
21801     *
21802     * @param measuredWidth The measured width of this view.  May be a complex
21803     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
21804     * {@link #MEASURED_STATE_TOO_SMALL}.
21805     * @param measuredHeight The measured height of this view.  May be a complex
21806     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
21807     * {@link #MEASURED_STATE_TOO_SMALL}.
21808     */
21809    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
21810        boolean optical = isLayoutModeOptical(this);
21811        if (optical != isLayoutModeOptical(mParent)) {
21812            Insets insets = getOpticalInsets();
21813            int opticalWidth  = insets.left + insets.right;
21814            int opticalHeight = insets.top  + insets.bottom;
21815
21816            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
21817            measuredHeight += optical ? opticalHeight : -opticalHeight;
21818        }
21819        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
21820    }
21821
21822    /**
21823     * Sets the measured dimension without extra processing for things like optical bounds.
21824     * Useful for reapplying consistent values that have already been cooked with adjustments
21825     * for optical bounds, etc. such as those from the measurement cache.
21826     *
21827     * @param measuredWidth The measured width of this view.  May be a complex
21828     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
21829     * {@link #MEASURED_STATE_TOO_SMALL}.
21830     * @param measuredHeight The measured height of this view.  May be a complex
21831     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
21832     * {@link #MEASURED_STATE_TOO_SMALL}.
21833     */
21834    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
21835        mMeasuredWidth = measuredWidth;
21836        mMeasuredHeight = measuredHeight;
21837
21838        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
21839    }
21840
21841    /**
21842     * Merge two states as returned by {@link #getMeasuredState()}.
21843     * @param curState The current state as returned from a view or the result
21844     * of combining multiple views.
21845     * @param newState The new view state to combine.
21846     * @return Returns a new integer reflecting the combination of the two
21847     * states.
21848     */
21849    public static int combineMeasuredStates(int curState, int newState) {
21850        return curState | newState;
21851    }
21852
21853    /**
21854     * Version of {@link #resolveSizeAndState(int, int, int)}
21855     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
21856     */
21857    public static int resolveSize(int size, int measureSpec) {
21858        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
21859    }
21860
21861    /**
21862     * Utility to reconcile a desired size and state, with constraints imposed
21863     * by a MeasureSpec. Will take the desired size, unless a different size
21864     * is imposed by the constraints. The returned value is a compound integer,
21865     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
21866     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the
21867     * resulting size is smaller than the size the view wants to be.
21868     *
21869     * @param size How big the view wants to be.
21870     * @param measureSpec Constraints imposed by the parent.
21871     * @param childMeasuredState Size information bit mask for the view's
21872     *                           children.
21873     * @return Size information bit mask as defined by
21874     *         {@link #MEASURED_SIZE_MASK} and
21875     *         {@link #MEASURED_STATE_TOO_SMALL}.
21876     */
21877    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
21878        final int specMode = MeasureSpec.getMode(measureSpec);
21879        final int specSize = MeasureSpec.getSize(measureSpec);
21880        final int result;
21881        switch (specMode) {
21882            case MeasureSpec.AT_MOST:
21883                if (specSize < size) {
21884                    result = specSize | MEASURED_STATE_TOO_SMALL;
21885                } else {
21886                    result = size;
21887                }
21888                break;
21889            case MeasureSpec.EXACTLY:
21890                result = specSize;
21891                break;
21892            case MeasureSpec.UNSPECIFIED:
21893            default:
21894                result = size;
21895        }
21896        return result | (childMeasuredState & MEASURED_STATE_MASK);
21897    }
21898
21899    /**
21900     * Utility to return a default size. Uses the supplied size if the
21901     * MeasureSpec imposed no constraints. Will get larger if allowed
21902     * by the MeasureSpec.
21903     *
21904     * @param size Default size for this view
21905     * @param measureSpec Constraints imposed by the parent
21906     * @return The size this view should be.
21907     */
21908    public static int getDefaultSize(int size, int measureSpec) {
21909        int result = size;
21910        int specMode = MeasureSpec.getMode(measureSpec);
21911        int specSize = MeasureSpec.getSize(measureSpec);
21912
21913        switch (specMode) {
21914        case MeasureSpec.UNSPECIFIED:
21915            result = size;
21916            break;
21917        case MeasureSpec.AT_MOST:
21918        case MeasureSpec.EXACTLY:
21919            result = specSize;
21920            break;
21921        }
21922        return result;
21923    }
21924
21925    /**
21926     * Returns the suggested minimum height that the view should use. This
21927     * returns the maximum of the view's minimum height
21928     * and the background's minimum height
21929     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
21930     * <p>
21931     * When being used in {@link #onMeasure(int, int)}, the caller should still
21932     * ensure the returned height is within the requirements of the parent.
21933     *
21934     * @return The suggested minimum height of the view.
21935     */
21936    protected int getSuggestedMinimumHeight() {
21937        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
21938
21939    }
21940
21941    /**
21942     * Returns the suggested minimum width that the view should use. This
21943     * returns the maximum of the view's minimum width
21944     * and the background's minimum width
21945     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
21946     * <p>
21947     * When being used in {@link #onMeasure(int, int)}, the caller should still
21948     * ensure the returned width is within the requirements of the parent.
21949     *
21950     * @return The suggested minimum width of the view.
21951     */
21952    protected int getSuggestedMinimumWidth() {
21953        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
21954    }
21955
21956    /**
21957     * Returns the minimum height of the view.
21958     *
21959     * @return the minimum height the view will try to be, in pixels
21960     *
21961     * @see #setMinimumHeight(int)
21962     *
21963     * @attr ref android.R.styleable#View_minHeight
21964     */
21965    public int getMinimumHeight() {
21966        return mMinHeight;
21967    }
21968
21969    /**
21970     * Sets the minimum height of the view. It is not guaranteed the view will
21971     * be able to achieve this minimum height (for example, if its parent layout
21972     * constrains it with less available height).
21973     *
21974     * @param minHeight The minimum height the view will try to be, in pixels
21975     *
21976     * @see #getMinimumHeight()
21977     *
21978     * @attr ref android.R.styleable#View_minHeight
21979     */
21980    @RemotableViewMethod
21981    public void setMinimumHeight(int minHeight) {
21982        mMinHeight = minHeight;
21983        requestLayout();
21984    }
21985
21986    /**
21987     * Returns the minimum width of the view.
21988     *
21989     * @return the minimum width the view will try to be, in pixels
21990     *
21991     * @see #setMinimumWidth(int)
21992     *
21993     * @attr ref android.R.styleable#View_minWidth
21994     */
21995    public int getMinimumWidth() {
21996        return mMinWidth;
21997    }
21998
21999    /**
22000     * Sets the minimum width of the view. It is not guaranteed the view will
22001     * be able to achieve this minimum width (for example, if its parent layout
22002     * constrains it with less available width).
22003     *
22004     * @param minWidth The minimum width the view will try to be, in pixels
22005     *
22006     * @see #getMinimumWidth()
22007     *
22008     * @attr ref android.R.styleable#View_minWidth
22009     */
22010    public void setMinimumWidth(int minWidth) {
22011        mMinWidth = minWidth;
22012        requestLayout();
22013
22014    }
22015
22016    /**
22017     * Get the animation currently associated with this view.
22018     *
22019     * @return The animation that is currently playing or
22020     *         scheduled to play for this view.
22021     */
22022    public Animation getAnimation() {
22023        return mCurrentAnimation;
22024    }
22025
22026    /**
22027     * Start the specified animation now.
22028     *
22029     * @param animation the animation to start now
22030     */
22031    public void startAnimation(Animation animation) {
22032        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
22033        setAnimation(animation);
22034        invalidateParentCaches();
22035        invalidate(true);
22036    }
22037
22038    /**
22039     * Cancels any animations for this view.
22040     */
22041    public void clearAnimation() {
22042        if (mCurrentAnimation != null) {
22043            mCurrentAnimation.detach();
22044        }
22045        mCurrentAnimation = null;
22046        invalidateParentIfNeeded();
22047    }
22048
22049    /**
22050     * Sets the next animation to play for this view.
22051     * If you want the animation to play immediately, use
22052     * {@link #startAnimation(android.view.animation.Animation)} instead.
22053     * This method provides allows fine-grained
22054     * control over the start time and invalidation, but you
22055     * must make sure that 1) the animation has a start time set, and
22056     * 2) the view's parent (which controls animations on its children)
22057     * will be invalidated when the animation is supposed to
22058     * start.
22059     *
22060     * @param animation The next animation, or null.
22061     */
22062    public void setAnimation(Animation animation) {
22063        mCurrentAnimation = animation;
22064
22065        if (animation != null) {
22066            // If the screen is off assume the animation start time is now instead of
22067            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
22068            // would cause the animation to start when the screen turns back on
22069            if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF
22070                    && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
22071                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
22072            }
22073            animation.reset();
22074        }
22075    }
22076
22077    /**
22078     * Invoked by a parent ViewGroup to notify the start of the animation
22079     * currently associated with this view. If you override this method,
22080     * always call super.onAnimationStart();
22081     *
22082     * @see #setAnimation(android.view.animation.Animation)
22083     * @see #getAnimation()
22084     */
22085    @CallSuper
22086    protected void onAnimationStart() {
22087        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
22088    }
22089
22090    /**
22091     * Invoked by a parent ViewGroup to notify the end of the animation
22092     * currently associated with this view. If you override this method,
22093     * always call super.onAnimationEnd();
22094     *
22095     * @see #setAnimation(android.view.animation.Animation)
22096     * @see #getAnimation()
22097     */
22098    @CallSuper
22099    protected void onAnimationEnd() {
22100        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
22101    }
22102
22103    /**
22104     * Invoked if there is a Transform that involves alpha. Subclass that can
22105     * draw themselves with the specified alpha should return true, and then
22106     * respect that alpha when their onDraw() is called. If this returns false
22107     * then the view may be redirected to draw into an offscreen buffer to
22108     * fulfill the request, which will look fine, but may be slower than if the
22109     * subclass handles it internally. The default implementation returns false.
22110     *
22111     * @param alpha The alpha (0..255) to apply to the view's drawing
22112     * @return true if the view can draw with the specified alpha.
22113     */
22114    protected boolean onSetAlpha(int alpha) {
22115        return false;
22116    }
22117
22118    /**
22119     * This is used by the RootView to perform an optimization when
22120     * the view hierarchy contains one or several SurfaceView.
22121     * SurfaceView is always considered transparent, but its children are not,
22122     * therefore all View objects remove themselves from the global transparent
22123     * region (passed as a parameter to this function).
22124     *
22125     * @param region The transparent region for this ViewAncestor (window).
22126     *
22127     * @return Returns true if the effective visibility of the view at this
22128     * point is opaque, regardless of the transparent region; returns false
22129     * if it is possible for underlying windows to be seen behind the view.
22130     *
22131     * {@hide}
22132     */
22133    public boolean gatherTransparentRegion(Region region) {
22134        final AttachInfo attachInfo = mAttachInfo;
22135        if (region != null && attachInfo != null) {
22136            final int pflags = mPrivateFlags;
22137            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
22138                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
22139                // remove it from the transparent region.
22140                final int[] location = attachInfo.mTransparentLocation;
22141                getLocationInWindow(location);
22142                // When a view has Z value, then it will be better to leave some area below the view
22143                // for drawing shadow. The shadow outset is proportional to the Z value. Note that
22144                // the bottom part needs more offset than the left, top and right parts due to the
22145                // spot light effects.
22146                int shadowOffset = getZ() > 0 ? (int) getZ() : 0;
22147                region.op(location[0] - shadowOffset, location[1] - shadowOffset,
22148                        location[0] + mRight - mLeft + shadowOffset,
22149                        location[1] + mBottom - mTop + (shadowOffset * 3), Region.Op.DIFFERENCE);
22150            } else {
22151                if (mBackground != null && mBackground.getOpacity() != PixelFormat.TRANSPARENT) {
22152                    // The SKIP_DRAW flag IS set and the background drawable exists, we remove
22153                    // the background drawable's non-transparent parts from this transparent region.
22154                    applyDrawableToTransparentRegion(mBackground, region);
22155                }
22156                if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
22157                        && mForegroundInfo.mDrawable.getOpacity() != PixelFormat.TRANSPARENT) {
22158                    // Similarly, we remove the foreground drawable's non-transparent parts.
22159                    applyDrawableToTransparentRegion(mForegroundInfo.mDrawable, region);
22160                }
22161                if (mDefaultFocusHighlight != null
22162                        && mDefaultFocusHighlight.getOpacity() != PixelFormat.TRANSPARENT) {
22163                    // Similarly, we remove the default focus highlight's non-transparent parts.
22164                    applyDrawableToTransparentRegion(mDefaultFocusHighlight, region);
22165                }
22166            }
22167        }
22168        return true;
22169    }
22170
22171    /**
22172     * Play a sound effect for this view.
22173     *
22174     * <p>The framework will play sound effects for some built in actions, such as
22175     * clicking, but you may wish to play these effects in your widget,
22176     * for instance, for internal navigation.
22177     *
22178     * <p>The sound effect will only be played if sound effects are enabled by the user, and
22179     * {@link #isSoundEffectsEnabled()} is true.
22180     *
22181     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
22182     */
22183    public void playSoundEffect(int soundConstant) {
22184        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
22185            return;
22186        }
22187        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
22188    }
22189
22190    /**
22191     * BZZZTT!!1!
22192     *
22193     * <p>Provide haptic feedback to the user for this view.
22194     *
22195     * <p>The framework will provide haptic feedback for some built in actions,
22196     * such as long presses, but you may wish to provide feedback for your
22197     * own widget.
22198     *
22199     * <p>The feedback will only be performed if
22200     * {@link #isHapticFeedbackEnabled()} is true.
22201     *
22202     * @param feedbackConstant One of the constants defined in
22203     * {@link HapticFeedbackConstants}
22204     */
22205    public boolean performHapticFeedback(int feedbackConstant) {
22206        return performHapticFeedback(feedbackConstant, 0);
22207    }
22208
22209    /**
22210     * BZZZTT!!1!
22211     *
22212     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
22213     *
22214     * @param feedbackConstant One of the constants defined in
22215     * {@link HapticFeedbackConstants}
22216     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
22217     */
22218    public boolean performHapticFeedback(int feedbackConstant, int flags) {
22219        if (mAttachInfo == null) {
22220            return false;
22221        }
22222        //noinspection SimplifiableIfStatement
22223        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
22224                && !isHapticFeedbackEnabled()) {
22225            return false;
22226        }
22227        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
22228                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
22229    }
22230
22231    /**
22232     * Request that the visibility of the status bar or other screen/window
22233     * decorations be changed.
22234     *
22235     * <p>This method is used to put the over device UI into temporary modes
22236     * where the user's attention is focused more on the application content,
22237     * by dimming or hiding surrounding system affordances.  This is typically
22238     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
22239     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
22240     * to be placed behind the action bar (and with these flags other system
22241     * affordances) so that smooth transitions between hiding and showing them
22242     * can be done.
22243     *
22244     * <p>Two representative examples of the use of system UI visibility is
22245     * implementing a content browsing application (like a magazine reader)
22246     * and a video playing application.
22247     *
22248     * <p>The first code shows a typical implementation of a View in a content
22249     * browsing application.  In this implementation, the application goes
22250     * into a content-oriented mode by hiding the status bar and action bar,
22251     * and putting the navigation elements into lights out mode.  The user can
22252     * then interact with content while in this mode.  Such an application should
22253     * provide an easy way for the user to toggle out of the mode (such as to
22254     * check information in the status bar or access notifications).  In the
22255     * implementation here, this is done simply by tapping on the content.
22256     *
22257     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
22258     *      content}
22259     *
22260     * <p>This second code sample shows a typical implementation of a View
22261     * in a video playing application.  In this situation, while the video is
22262     * playing the application would like to go into a complete full-screen mode,
22263     * to use as much of the display as possible for the video.  When in this state
22264     * the user can not interact with the application; the system intercepts
22265     * touching on the screen to pop the UI out of full screen mode.  See
22266     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
22267     *
22268     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
22269     *      content}
22270     *
22271     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
22272     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
22273     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
22274     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
22275     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
22276     */
22277    public void setSystemUiVisibility(int visibility) {
22278        if (visibility != mSystemUiVisibility) {
22279            mSystemUiVisibility = visibility;
22280            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
22281                mParent.recomputeViewAttributes(this);
22282            }
22283        }
22284    }
22285
22286    /**
22287     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
22288     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
22289     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
22290     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
22291     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
22292     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
22293     */
22294    public int getSystemUiVisibility() {
22295        return mSystemUiVisibility;
22296    }
22297
22298    /**
22299     * Returns the current system UI visibility that is currently set for
22300     * the entire window.  This is the combination of the
22301     * {@link #setSystemUiVisibility(int)} values supplied by all of the
22302     * views in the window.
22303     */
22304    public int getWindowSystemUiVisibility() {
22305        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
22306    }
22307
22308    /**
22309     * Override to find out when the window's requested system UI visibility
22310     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
22311     * This is different from the callbacks received through
22312     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
22313     * in that this is only telling you about the local request of the window,
22314     * not the actual values applied by the system.
22315     */
22316    public void onWindowSystemUiVisibilityChanged(int visible) {
22317    }
22318
22319    /**
22320     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
22321     * the view hierarchy.
22322     */
22323    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
22324        onWindowSystemUiVisibilityChanged(visible);
22325    }
22326
22327    /**
22328     * Set a listener to receive callbacks when the visibility of the system bar changes.
22329     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
22330     */
22331    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
22332        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
22333        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
22334            mParent.recomputeViewAttributes(this);
22335        }
22336    }
22337
22338    /**
22339     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
22340     * the view hierarchy.
22341     */
22342    public void dispatchSystemUiVisibilityChanged(int visibility) {
22343        ListenerInfo li = mListenerInfo;
22344        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
22345            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
22346                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
22347        }
22348    }
22349
22350    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
22351        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
22352        if (val != mSystemUiVisibility) {
22353            setSystemUiVisibility(val);
22354            return true;
22355        }
22356        return false;
22357    }
22358
22359    /** @hide */
22360    public void setDisabledSystemUiVisibility(int flags) {
22361        if (mAttachInfo != null) {
22362            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
22363                mAttachInfo.mDisabledSystemUiVisibility = flags;
22364                if (mParent != null) {
22365                    mParent.recomputeViewAttributes(this);
22366                }
22367            }
22368        }
22369    }
22370
22371    /**
22372     * Creates an image that the system displays during the drag and drop
22373     * operation. This is called a &quot;drag shadow&quot;. The default implementation
22374     * for a DragShadowBuilder based on a View returns an image that has exactly the same
22375     * appearance as the given View. The default also positions the center of the drag shadow
22376     * directly under the touch point. If no View is provided (the constructor with no parameters
22377     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
22378     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overridden, then the
22379     * default is an invisible drag shadow.
22380     * <p>
22381     * You are not required to use the View you provide to the constructor as the basis of the
22382     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
22383     * anything you want as the drag shadow.
22384     * </p>
22385     * <p>
22386     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
22387     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
22388     *  size and position of the drag shadow. It uses this data to construct a
22389     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
22390     *  so that your application can draw the shadow image in the Canvas.
22391     * </p>
22392     *
22393     * <div class="special reference">
22394     * <h3>Developer Guides</h3>
22395     * <p>For a guide to implementing drag and drop features, read the
22396     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
22397     * </div>
22398     */
22399    public static class DragShadowBuilder {
22400        private final WeakReference<View> mView;
22401
22402        /**
22403         * Constructs a shadow image builder based on a View. By default, the resulting drag
22404         * shadow will have the same appearance and dimensions as the View, with the touch point
22405         * over the center of the View.
22406         * @param view A View. Any View in scope can be used.
22407         */
22408        public DragShadowBuilder(View view) {
22409            mView = new WeakReference<View>(view);
22410        }
22411
22412        /**
22413         * Construct a shadow builder object with no associated View.  This
22414         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
22415         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
22416         * to supply the drag shadow's dimensions and appearance without
22417         * reference to any View object. If they are not overridden, then the result is an
22418         * invisible drag shadow.
22419         */
22420        public DragShadowBuilder() {
22421            mView = new WeakReference<View>(null);
22422        }
22423
22424        /**
22425         * Returns the View object that had been passed to the
22426         * {@link #View.DragShadowBuilder(View)}
22427         * constructor.  If that View parameter was {@code null} or if the
22428         * {@link #View.DragShadowBuilder()}
22429         * constructor was used to instantiate the builder object, this method will return
22430         * null.
22431         *
22432         * @return The View object associate with this builder object.
22433         */
22434        @SuppressWarnings({"JavadocReference"})
22435        final public View getView() {
22436            return mView.get();
22437        }
22438
22439        /**
22440         * Provides the metrics for the shadow image. These include the dimensions of
22441         * the shadow image, and the point within that shadow that should
22442         * be centered under the touch location while dragging.
22443         * <p>
22444         * The default implementation sets the dimensions of the shadow to be the
22445         * same as the dimensions of the View itself and centers the shadow under
22446         * the touch point.
22447         * </p>
22448         *
22449         * @param outShadowSize A {@link android.graphics.Point} containing the width and height
22450         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
22451         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
22452         * image.
22453         *
22454         * @param outShadowTouchPoint A {@link android.graphics.Point} for the position within the
22455         * shadow image that should be underneath the touch point during the drag and drop
22456         * operation. Your application must set {@link android.graphics.Point#x} to the
22457         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
22458         */
22459        public void onProvideShadowMetrics(Point outShadowSize, Point outShadowTouchPoint) {
22460            final View view = mView.get();
22461            if (view != null) {
22462                outShadowSize.set(view.getWidth(), view.getHeight());
22463                outShadowTouchPoint.set(outShadowSize.x / 2, outShadowSize.y / 2);
22464            } else {
22465                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
22466            }
22467        }
22468
22469        /**
22470         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
22471         * based on the dimensions it received from the
22472         * {@link #onProvideShadowMetrics(Point, Point)} callback.
22473         *
22474         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
22475         */
22476        public void onDrawShadow(Canvas canvas) {
22477            final View view = mView.get();
22478            if (view != null) {
22479                view.draw(canvas);
22480            } else {
22481                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
22482            }
22483        }
22484    }
22485
22486    /**
22487     * @deprecated Use {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)
22488     * startDragAndDrop()} for newer platform versions.
22489     */
22490    @Deprecated
22491    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
22492                                   Object myLocalState, int flags) {
22493        return startDragAndDrop(data, shadowBuilder, myLocalState, flags);
22494    }
22495
22496    /**
22497     * Starts a drag and drop operation. When your application calls this method, it passes a
22498     * {@link android.view.View.DragShadowBuilder} object to the system. The
22499     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
22500     * to get metrics for the drag shadow, and then calls the object's
22501     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
22502     * <p>
22503     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
22504     *  drag events to all the View objects in your application that are currently visible. It does
22505     *  this either by calling the View object's drag listener (an implementation of
22506     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
22507     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
22508     *  Both are passed a {@link android.view.DragEvent} object that has a
22509     *  {@link android.view.DragEvent#getAction()} value of
22510     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
22511     * </p>
22512     * <p>
22513     * Your application can invoke {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object,
22514     * int) startDragAndDrop()} on any attached View object. The View object does not need to be
22515     * the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to be related
22516     * to the View the user selected for dragging.
22517     * </p>
22518     * @param data A {@link android.content.ClipData} object pointing to the data to be
22519     * transferred by the drag and drop operation.
22520     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
22521     * drag shadow.
22522     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
22523     * drop operation. When dispatching drag events to views in the same activity this object
22524     * will be available through {@link android.view.DragEvent#getLocalState()}. Views in other
22525     * activities will not have access to this data ({@link android.view.DragEvent#getLocalState()}
22526     * will return null).
22527     * <p>
22528     * myLocalState is a lightweight mechanism for the sending information from the dragged View
22529     * to the target Views. For example, it can contain flags that differentiate between a
22530     * a copy operation and a move operation.
22531     * </p>
22532     * @param flags Flags that control the drag and drop operation. This can be set to 0 for no
22533     * flags, or any combination of the following:
22534     *     <ul>
22535     *         <li>{@link #DRAG_FLAG_GLOBAL}</li>
22536     *         <li>{@link #DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION}</li>
22537     *         <li>{@link #DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION}</li>
22538     *         <li>{@link #DRAG_FLAG_GLOBAL_URI_READ}</li>
22539     *         <li>{@link #DRAG_FLAG_GLOBAL_URI_WRITE}</li>
22540     *         <li>{@link #DRAG_FLAG_OPAQUE}</li>
22541     *     </ul>
22542     * @return {@code true} if the method completes successfully, or
22543     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
22544     * do a drag, and so no drag operation is in progress.
22545     */
22546    public final boolean startDragAndDrop(ClipData data, DragShadowBuilder shadowBuilder,
22547            Object myLocalState, int flags) {
22548        if (ViewDebug.DEBUG_DRAG) {
22549            Log.d(VIEW_LOG_TAG, "startDragAndDrop: data=" + data + " flags=" + flags);
22550        }
22551        if (mAttachInfo == null) {
22552            Log.w(VIEW_LOG_TAG, "startDragAndDrop called on a detached view.");
22553            return false;
22554        }
22555
22556        if (data != null) {
22557            data.prepareToLeaveProcess((flags & View.DRAG_FLAG_GLOBAL) != 0);
22558        }
22559
22560        boolean okay = false;
22561
22562        Point shadowSize = new Point();
22563        Point shadowTouchPoint = new Point();
22564        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
22565
22566        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
22567                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
22568            throw new IllegalStateException("Drag shadow dimensions must not be negative");
22569        }
22570
22571        if (ViewDebug.DEBUG_DRAG) {
22572            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
22573                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
22574        }
22575        if (mAttachInfo.mDragSurface != null) {
22576            mAttachInfo.mDragSurface.release();
22577        }
22578        mAttachInfo.mDragSurface = new Surface();
22579        try {
22580            mAttachInfo.mDragToken = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
22581                    flags, shadowSize.x, shadowSize.y, mAttachInfo.mDragSurface);
22582            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token="
22583                    + mAttachInfo.mDragToken + " surface=" + mAttachInfo.mDragSurface);
22584            if (mAttachInfo.mDragToken != null) {
22585                Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null);
22586                try {
22587                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
22588                    shadowBuilder.onDrawShadow(canvas);
22589                } finally {
22590                    mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas);
22591                }
22592
22593                final ViewRootImpl root = getViewRootImpl();
22594
22595                // Cache the local state object for delivery with DragEvents
22596                root.setLocalDragState(myLocalState);
22597
22598                // repurpose 'shadowSize' for the last touch point
22599                root.getLastTouchPoint(shadowSize);
22600
22601                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, mAttachInfo.mDragToken,
22602                        root.getLastTouchSource(), shadowSize.x, shadowSize.y,
22603                        shadowTouchPoint.x, shadowTouchPoint.y, data);
22604                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
22605            }
22606        } catch (Exception e) {
22607            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
22608            mAttachInfo.mDragSurface.destroy();
22609            mAttachInfo.mDragSurface = null;
22610        }
22611
22612        return okay;
22613    }
22614
22615    /**
22616     * Cancels an ongoing drag and drop operation.
22617     * <p>
22618     * A {@link android.view.DragEvent} object with
22619     * {@link android.view.DragEvent#getAction()} value of
22620     * {@link android.view.DragEvent#ACTION_DRAG_ENDED} and
22621     * {@link android.view.DragEvent#getResult()} value of {@code false}
22622     * will be sent to every
22623     * View that received {@link android.view.DragEvent#ACTION_DRAG_STARTED}
22624     * even if they are not currently visible.
22625     * </p>
22626     * <p>
22627     * This method can be called on any View in the same window as the View on which
22628     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int) startDragAndDrop}
22629     * was called.
22630     * </p>
22631     */
22632    public final void cancelDragAndDrop() {
22633        if (ViewDebug.DEBUG_DRAG) {
22634            Log.d(VIEW_LOG_TAG, "cancelDragAndDrop");
22635        }
22636        if (mAttachInfo == null) {
22637            Log.w(VIEW_LOG_TAG, "cancelDragAndDrop called on a detached view.");
22638            return;
22639        }
22640        if (mAttachInfo.mDragToken != null) {
22641            try {
22642                mAttachInfo.mSession.cancelDragAndDrop(mAttachInfo.mDragToken);
22643            } catch (Exception e) {
22644                Log.e(VIEW_LOG_TAG, "Unable to cancel drag", e);
22645            }
22646            mAttachInfo.mDragToken = null;
22647        } else {
22648            Log.e(VIEW_LOG_TAG, "No active drag to cancel");
22649        }
22650    }
22651
22652    /**
22653     * Updates the drag shadow for the ongoing drag and drop operation.
22654     *
22655     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
22656     * new drag shadow.
22657     */
22658    public final void updateDragShadow(DragShadowBuilder shadowBuilder) {
22659        if (ViewDebug.DEBUG_DRAG) {
22660            Log.d(VIEW_LOG_TAG, "updateDragShadow");
22661        }
22662        if (mAttachInfo == null) {
22663            Log.w(VIEW_LOG_TAG, "updateDragShadow called on a detached view.");
22664            return;
22665        }
22666        if (mAttachInfo.mDragToken != null) {
22667            try {
22668                Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null);
22669                try {
22670                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
22671                    shadowBuilder.onDrawShadow(canvas);
22672                } finally {
22673                    mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas);
22674                }
22675            } catch (Exception e) {
22676                Log.e(VIEW_LOG_TAG, "Unable to update drag shadow", e);
22677            }
22678        } else {
22679            Log.e(VIEW_LOG_TAG, "No active drag");
22680        }
22681    }
22682
22683    /**
22684     * Starts a move from {startX, startY}, the amount of the movement will be the offset
22685     * between {startX, startY} and the new cursor positon.
22686     * @param startX horizontal coordinate where the move started.
22687     * @param startY vertical coordinate where the move started.
22688     * @return whether moving was started successfully.
22689     * @hide
22690     */
22691    public final boolean startMovingTask(float startX, float startY) {
22692        if (ViewDebug.DEBUG_POSITIONING) {
22693            Log.d(VIEW_LOG_TAG, "startMovingTask: {" + startX + "," + startY + "}");
22694        }
22695        try {
22696            return mAttachInfo.mSession.startMovingTask(mAttachInfo.mWindow, startX, startY);
22697        } catch (RemoteException e) {
22698            Log.e(VIEW_LOG_TAG, "Unable to start moving", e);
22699        }
22700        return false;
22701    }
22702
22703    /**
22704     * Handles drag events sent by the system following a call to
22705     * {@link android.view.View#startDragAndDrop(ClipData,DragShadowBuilder,Object,int)
22706     * startDragAndDrop()}.
22707     *<p>
22708     * When the system calls this method, it passes a
22709     * {@link android.view.DragEvent} object. A call to
22710     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
22711     * in DragEvent. The method uses these to determine what is happening in the drag and drop
22712     * operation.
22713     * @param event The {@link android.view.DragEvent} sent by the system.
22714     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
22715     * in DragEvent, indicating the type of drag event represented by this object.
22716     * @return {@code true} if the method was successful, otherwise {@code false}.
22717     * <p>
22718     *  The method should return {@code true} in response to an action type of
22719     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
22720     *  operation.
22721     * </p>
22722     * <p>
22723     *  The method should also return {@code true} in response to an action type of
22724     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
22725     *  {@code false} if it didn't.
22726     * </p>
22727     * <p>
22728     *  For all other events, the return value is ignored.
22729     * </p>
22730     */
22731    public boolean onDragEvent(DragEvent event) {
22732        return false;
22733    }
22734
22735    // Dispatches ACTION_DRAG_ENTERED and ACTION_DRAG_EXITED events for pre-Nougat apps.
22736    boolean dispatchDragEnterExitInPreN(DragEvent event) {
22737        return callDragEventHandler(event);
22738    }
22739
22740    /**
22741     * Detects if this View is enabled and has a drag event listener.
22742     * If both are true, then it calls the drag event listener with the
22743     * {@link android.view.DragEvent} it received. If the drag event listener returns
22744     * {@code true}, then dispatchDragEvent() returns {@code true}.
22745     * <p>
22746     * For all other cases, the method calls the
22747     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
22748     * method and returns its result.
22749     * </p>
22750     * <p>
22751     * This ensures that a drag event is always consumed, even if the View does not have a drag
22752     * event listener. However, if the View has a listener and the listener returns true, then
22753     * onDragEvent() is not called.
22754     * </p>
22755     */
22756    public boolean dispatchDragEvent(DragEvent event) {
22757        event.mEventHandlerWasCalled = true;
22758        if (event.mAction == DragEvent.ACTION_DRAG_LOCATION ||
22759            event.mAction == DragEvent.ACTION_DROP) {
22760            // About to deliver an event with coordinates to this view. Notify that now this view
22761            // has drag focus. This will send exit/enter events as needed.
22762            getViewRootImpl().setDragFocus(this, event);
22763        }
22764        return callDragEventHandler(event);
22765    }
22766
22767    final boolean callDragEventHandler(DragEvent event) {
22768        final boolean result;
22769
22770        ListenerInfo li = mListenerInfo;
22771        //noinspection SimplifiableIfStatement
22772        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
22773                && li.mOnDragListener.onDrag(this, event)) {
22774            result = true;
22775        } else {
22776            result = onDragEvent(event);
22777        }
22778
22779        switch (event.mAction) {
22780            case DragEvent.ACTION_DRAG_ENTERED: {
22781                mPrivateFlags2 |= View.PFLAG2_DRAG_HOVERED;
22782                refreshDrawableState();
22783            } break;
22784            case DragEvent.ACTION_DRAG_EXITED: {
22785                mPrivateFlags2 &= ~View.PFLAG2_DRAG_HOVERED;
22786                refreshDrawableState();
22787            } break;
22788            case DragEvent.ACTION_DRAG_ENDED: {
22789                mPrivateFlags2 &= ~View.DRAG_MASK;
22790                refreshDrawableState();
22791            } break;
22792        }
22793
22794        return result;
22795    }
22796
22797    boolean canAcceptDrag() {
22798        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
22799    }
22800
22801    /**
22802     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
22803     * it is ever exposed at all.
22804     * @hide
22805     */
22806    public void onCloseSystemDialogs(String reason) {
22807    }
22808
22809    /**
22810     * Given a Drawable whose bounds have been set to draw into this view,
22811     * update a Region being computed for
22812     * {@link #gatherTransparentRegion(android.graphics.Region)} so
22813     * that any non-transparent parts of the Drawable are removed from the
22814     * given transparent region.
22815     *
22816     * @param dr The Drawable whose transparency is to be applied to the region.
22817     * @param region A Region holding the current transparency information,
22818     * where any parts of the region that are set are considered to be
22819     * transparent.  On return, this region will be modified to have the
22820     * transparency information reduced by the corresponding parts of the
22821     * Drawable that are not transparent.
22822     * {@hide}
22823     */
22824    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
22825        if (DBG) {
22826            Log.i("View", "Getting transparent region for: " + this);
22827        }
22828        final Region r = dr.getTransparentRegion();
22829        final Rect db = dr.getBounds();
22830        final AttachInfo attachInfo = mAttachInfo;
22831        if (r != null && attachInfo != null) {
22832            final int w = getRight()-getLeft();
22833            final int h = getBottom()-getTop();
22834            if (db.left > 0) {
22835                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
22836                r.op(0, 0, db.left, h, Region.Op.UNION);
22837            }
22838            if (db.right < w) {
22839                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
22840                r.op(db.right, 0, w, h, Region.Op.UNION);
22841            }
22842            if (db.top > 0) {
22843                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
22844                r.op(0, 0, w, db.top, Region.Op.UNION);
22845            }
22846            if (db.bottom < h) {
22847                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
22848                r.op(0, db.bottom, w, h, Region.Op.UNION);
22849            }
22850            final int[] location = attachInfo.mTransparentLocation;
22851            getLocationInWindow(location);
22852            r.translate(location[0], location[1]);
22853            region.op(r, Region.Op.INTERSECT);
22854        } else {
22855            region.op(db, Region.Op.DIFFERENCE);
22856        }
22857    }
22858
22859    private void checkForLongClick(int delayOffset, float x, float y) {
22860        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE || (mViewFlags & TOOLTIP) == TOOLTIP) {
22861            mHasPerformedLongPress = false;
22862
22863            if (mPendingCheckForLongPress == null) {
22864                mPendingCheckForLongPress = new CheckForLongPress();
22865            }
22866            mPendingCheckForLongPress.setAnchor(x, y);
22867            mPendingCheckForLongPress.rememberWindowAttachCount();
22868            mPendingCheckForLongPress.rememberPressedState();
22869            postDelayed(mPendingCheckForLongPress,
22870                    ViewConfiguration.getLongPressTimeout() - delayOffset);
22871        }
22872    }
22873
22874    /**
22875     * Inflate a view from an XML resource.  This convenience method wraps the {@link
22876     * LayoutInflater} class, which provides a full range of options for view inflation.
22877     *
22878     * @param context The Context object for your activity or application.
22879     * @param resource The resource ID to inflate
22880     * @param root A view group that will be the parent.  Used to properly inflate the
22881     * layout_* parameters.
22882     * @see LayoutInflater
22883     */
22884    public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
22885        LayoutInflater factory = LayoutInflater.from(context);
22886        return factory.inflate(resource, root);
22887    }
22888
22889    /**
22890     * Scroll the view with standard behavior for scrolling beyond the normal
22891     * content boundaries. Views that call this method should override
22892     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
22893     * results of an over-scroll operation.
22894     *
22895     * Views can use this method to handle any touch or fling-based scrolling.
22896     *
22897     * @param deltaX Change in X in pixels
22898     * @param deltaY Change in Y in pixels
22899     * @param scrollX Current X scroll value in pixels before applying deltaX
22900     * @param scrollY Current Y scroll value in pixels before applying deltaY
22901     * @param scrollRangeX Maximum content scroll range along the X axis
22902     * @param scrollRangeY Maximum content scroll range along the Y axis
22903     * @param maxOverScrollX Number of pixels to overscroll by in either direction
22904     *          along the X axis.
22905     * @param maxOverScrollY Number of pixels to overscroll by in either direction
22906     *          along the Y axis.
22907     * @param isTouchEvent true if this scroll operation is the result of a touch event.
22908     * @return true if scrolling was clamped to an over-scroll boundary along either
22909     *          axis, false otherwise.
22910     */
22911    @SuppressWarnings({"UnusedParameters"})
22912    protected boolean overScrollBy(int deltaX, int deltaY,
22913            int scrollX, int scrollY,
22914            int scrollRangeX, int scrollRangeY,
22915            int maxOverScrollX, int maxOverScrollY,
22916            boolean isTouchEvent) {
22917        final int overScrollMode = mOverScrollMode;
22918        final boolean canScrollHorizontal =
22919                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
22920        final boolean canScrollVertical =
22921                computeVerticalScrollRange() > computeVerticalScrollExtent();
22922        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
22923                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
22924        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
22925                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
22926
22927        int newScrollX = scrollX + deltaX;
22928        if (!overScrollHorizontal) {
22929            maxOverScrollX = 0;
22930        }
22931
22932        int newScrollY = scrollY + deltaY;
22933        if (!overScrollVertical) {
22934            maxOverScrollY = 0;
22935        }
22936
22937        // Clamp values if at the limits and record
22938        final int left = -maxOverScrollX;
22939        final int right = maxOverScrollX + scrollRangeX;
22940        final int top = -maxOverScrollY;
22941        final int bottom = maxOverScrollY + scrollRangeY;
22942
22943        boolean clampedX = false;
22944        if (newScrollX > right) {
22945            newScrollX = right;
22946            clampedX = true;
22947        } else if (newScrollX < left) {
22948            newScrollX = left;
22949            clampedX = true;
22950        }
22951
22952        boolean clampedY = false;
22953        if (newScrollY > bottom) {
22954            newScrollY = bottom;
22955            clampedY = true;
22956        } else if (newScrollY < top) {
22957            newScrollY = top;
22958            clampedY = true;
22959        }
22960
22961        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
22962
22963        return clampedX || clampedY;
22964    }
22965
22966    /**
22967     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
22968     * respond to the results of an over-scroll operation.
22969     *
22970     * @param scrollX New X scroll value in pixels
22971     * @param scrollY New Y scroll value in pixels
22972     * @param clampedX True if scrollX was clamped to an over-scroll boundary
22973     * @param clampedY True if scrollY was clamped to an over-scroll boundary
22974     */
22975    protected void onOverScrolled(int scrollX, int scrollY,
22976            boolean clampedX, boolean clampedY) {
22977        // Intentionally empty.
22978    }
22979
22980    /**
22981     * Returns the over-scroll mode for this view. The result will be
22982     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
22983     * (allow over-scrolling only if the view content is larger than the container),
22984     * or {@link #OVER_SCROLL_NEVER}.
22985     *
22986     * @return This view's over-scroll mode.
22987     */
22988    public int getOverScrollMode() {
22989        return mOverScrollMode;
22990    }
22991
22992    /**
22993     * Set the over-scroll mode for this view. Valid over-scroll modes are
22994     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
22995     * (allow over-scrolling only if the view content is larger than the container),
22996     * or {@link #OVER_SCROLL_NEVER}.
22997     *
22998     * Setting the over-scroll mode of a view will have an effect only if the
22999     * view is capable of scrolling.
23000     *
23001     * @param overScrollMode The new over-scroll mode for this view.
23002     */
23003    public void setOverScrollMode(int overScrollMode) {
23004        if (overScrollMode != OVER_SCROLL_ALWAYS &&
23005                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
23006                overScrollMode != OVER_SCROLL_NEVER) {
23007            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
23008        }
23009        mOverScrollMode = overScrollMode;
23010    }
23011
23012    /**
23013     * Enable or disable nested scrolling for this view.
23014     *
23015     * <p>If this property is set to true the view will be permitted to initiate nested
23016     * scrolling operations with a compatible parent view in the current hierarchy. If this
23017     * view does not implement nested scrolling this will have no effect. Disabling nested scrolling
23018     * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping}
23019     * the nested scroll.</p>
23020     *
23021     * @param enabled true to enable nested scrolling, false to disable
23022     *
23023     * @see #isNestedScrollingEnabled()
23024     */
23025    public void setNestedScrollingEnabled(boolean enabled) {
23026        if (enabled) {
23027            mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED;
23028        } else {
23029            stopNestedScroll();
23030            mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED;
23031        }
23032    }
23033
23034    /**
23035     * Returns true if nested scrolling is enabled for this view.
23036     *
23037     * <p>If nested scrolling is enabled and this View class implementation supports it,
23038     * this view will act as a nested scrolling child view when applicable, forwarding data
23039     * about the scroll operation in progress to a compatible and cooperating nested scrolling
23040     * parent.</p>
23041     *
23042     * @return true if nested scrolling is enabled
23043     *
23044     * @see #setNestedScrollingEnabled(boolean)
23045     */
23046    public boolean isNestedScrollingEnabled() {
23047        return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) ==
23048                PFLAG3_NESTED_SCROLLING_ENABLED;
23049    }
23050
23051    /**
23052     * Begin a nestable scroll operation along the given axes.
23053     *
23054     * <p>A view starting a nested scroll promises to abide by the following contract:</p>
23055     *
23056     * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case
23057     * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}.
23058     * In the case of touch scrolling the nested scroll will be terminated automatically in
23059     * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}.
23060     * In the event of programmatic scrolling the caller must explicitly call
23061     * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p>
23062     *
23063     * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found.
23064     * If it returns false the caller may ignore the rest of this contract until the next scroll.
23065     * Calling startNestedScroll while a nested scroll is already in progress will return true.</p>
23066     *
23067     * <p>At each incremental step of the scroll the caller should invoke
23068     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll}
23069     * once it has calculated the requested scrolling delta. If it returns true the nested scrolling
23070     * parent at least partially consumed the scroll and the caller should adjust the amount it
23071     * scrolls by.</p>
23072     *
23073     * <p>After applying the remainder of the scroll delta the caller should invoke
23074     * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing
23075     * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat
23076     * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}.
23077     * </p>
23078     *
23079     * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or
23080     *             {@link #SCROLL_AXIS_VERTICAL}.
23081     * @return true if a cooperative parent was found and nested scrolling has been enabled for
23082     *         the current gesture.
23083     *
23084     * @see #stopNestedScroll()
23085     * @see #dispatchNestedPreScroll(int, int, int[], int[])
23086     * @see #dispatchNestedScroll(int, int, int, int, int[])
23087     */
23088    public boolean startNestedScroll(int axes) {
23089        if (hasNestedScrollingParent()) {
23090            // Already in progress
23091            return true;
23092        }
23093        if (isNestedScrollingEnabled()) {
23094            ViewParent p = getParent();
23095            View child = this;
23096            while (p != null) {
23097                try {
23098                    if (p.onStartNestedScroll(child, this, axes)) {
23099                        mNestedScrollingParent = p;
23100                        p.onNestedScrollAccepted(child, this, axes);
23101                        return true;
23102                    }
23103                } catch (AbstractMethodError e) {
23104                    Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " +
23105                            "method onStartNestedScroll", e);
23106                    // Allow the search upward to continue
23107                }
23108                if (p instanceof View) {
23109                    child = (View) p;
23110                }
23111                p = p.getParent();
23112            }
23113        }
23114        return false;
23115    }
23116
23117    /**
23118     * Stop a nested scroll in progress.
23119     *
23120     * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p>
23121     *
23122     * @see #startNestedScroll(int)
23123     */
23124    public void stopNestedScroll() {
23125        if (mNestedScrollingParent != null) {
23126            mNestedScrollingParent.onStopNestedScroll(this);
23127            mNestedScrollingParent = null;
23128        }
23129    }
23130
23131    /**
23132     * Returns true if this view has a nested scrolling parent.
23133     *
23134     * <p>The presence of a nested scrolling parent indicates that this view has initiated
23135     * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p>
23136     *
23137     * @return whether this view has a nested scrolling parent
23138     */
23139    public boolean hasNestedScrollingParent() {
23140        return mNestedScrollingParent != null;
23141    }
23142
23143    /**
23144     * Dispatch one step of a nested scroll in progress.
23145     *
23146     * <p>Implementations of views that support nested scrolling should call this to report
23147     * info about a scroll in progress to the current nested scrolling parent. If a nested scroll
23148     * is not currently in progress or nested scrolling is not
23149     * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p>
23150     *
23151     * <p>Compatible View implementations should also call
23152     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before
23153     * consuming a component of the scroll event themselves.</p>
23154     *
23155     * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step
23156     * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step
23157     * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view
23158     * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view
23159     * @param offsetInWindow Optional. If not null, on return this will contain the offset
23160     *                       in local view coordinates of this view from before this operation
23161     *                       to after it completes. View implementations may use this to adjust
23162     *                       expected input coordinate tracking.
23163     * @return true if the event was dispatched, false if it could not be dispatched.
23164     * @see #dispatchNestedPreScroll(int, int, int[], int[])
23165     */
23166    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed,
23167            int dxUnconsumed, int dyUnconsumed, @Nullable @Size(2) int[] offsetInWindow) {
23168        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
23169            if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) {
23170                int startX = 0;
23171                int startY = 0;
23172                if (offsetInWindow != null) {
23173                    getLocationInWindow(offsetInWindow);
23174                    startX = offsetInWindow[0];
23175                    startY = offsetInWindow[1];
23176                }
23177
23178                mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed,
23179                        dxUnconsumed, dyUnconsumed);
23180
23181                if (offsetInWindow != null) {
23182                    getLocationInWindow(offsetInWindow);
23183                    offsetInWindow[0] -= startX;
23184                    offsetInWindow[1] -= startY;
23185                }
23186                return true;
23187            } else if (offsetInWindow != null) {
23188                // No motion, no dispatch. Keep offsetInWindow up to date.
23189                offsetInWindow[0] = 0;
23190                offsetInWindow[1] = 0;
23191            }
23192        }
23193        return false;
23194    }
23195
23196    /**
23197     * Dispatch one step of a nested scroll in progress before this view consumes any portion of it.
23198     *
23199     * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch.
23200     * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested
23201     * scrolling operation to consume some or all of the scroll operation before the child view
23202     * consumes it.</p>
23203     *
23204     * @param dx Horizontal scroll distance in pixels
23205     * @param dy Vertical scroll distance in pixels
23206     * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx
23207     *                 and consumed[1] the consumed dy.
23208     * @param offsetInWindow Optional. If not null, on return this will contain the offset
23209     *                       in local view coordinates of this view from before this operation
23210     *                       to after it completes. View implementations may use this to adjust
23211     *                       expected input coordinate tracking.
23212     * @return true if the parent consumed some or all of the scroll delta
23213     * @see #dispatchNestedScroll(int, int, int, int, int[])
23214     */
23215    public boolean dispatchNestedPreScroll(int dx, int dy,
23216            @Nullable @Size(2) int[] consumed, @Nullable @Size(2) int[] offsetInWindow) {
23217        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
23218            if (dx != 0 || dy != 0) {
23219                int startX = 0;
23220                int startY = 0;
23221                if (offsetInWindow != null) {
23222                    getLocationInWindow(offsetInWindow);
23223                    startX = offsetInWindow[0];
23224                    startY = offsetInWindow[1];
23225                }
23226
23227                if (consumed == null) {
23228                    if (mTempNestedScrollConsumed == null) {
23229                        mTempNestedScrollConsumed = new int[2];
23230                    }
23231                    consumed = mTempNestedScrollConsumed;
23232                }
23233                consumed[0] = 0;
23234                consumed[1] = 0;
23235                mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed);
23236
23237                if (offsetInWindow != null) {
23238                    getLocationInWindow(offsetInWindow);
23239                    offsetInWindow[0] -= startX;
23240                    offsetInWindow[1] -= startY;
23241                }
23242                return consumed[0] != 0 || consumed[1] != 0;
23243            } else if (offsetInWindow != null) {
23244                offsetInWindow[0] = 0;
23245                offsetInWindow[1] = 0;
23246            }
23247        }
23248        return false;
23249    }
23250
23251    /**
23252     * Dispatch a fling to a nested scrolling parent.
23253     *
23254     * <p>This method should be used to indicate that a nested scrolling child has detected
23255     * suitable conditions for a fling. Generally this means that a touch scroll has ended with a
23256     * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds
23257     * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity}
23258     * along a scrollable axis.</p>
23259     *
23260     * <p>If a nested scrolling child view would normally fling but it is at the edge of
23261     * its own content, it can use this method to delegate the fling to its nested scrolling
23262     * parent instead. The parent may optionally consume the fling or observe a child fling.</p>
23263     *
23264     * @param velocityX Horizontal fling velocity in pixels per second
23265     * @param velocityY Vertical fling velocity in pixels per second
23266     * @param consumed true if the child consumed the fling, false otherwise
23267     * @return true if the nested scrolling parent consumed or otherwise reacted to the fling
23268     */
23269    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
23270        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
23271            return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed);
23272        }
23273        return false;
23274    }
23275
23276    /**
23277     * Dispatch a fling to a nested scrolling parent before it is processed by this view.
23278     *
23279     * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch
23280     * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code>
23281     * offsets an opportunity for the parent view in a nested fling to fully consume the fling
23282     * before the child view consumes it. If this method returns <code>true</code>, a nested
23283     * parent view consumed the fling and this view should not scroll as a result.</p>
23284     *
23285     * <p>For a better user experience, only one view in a nested scrolling chain should consume
23286     * the fling at a time. If a parent view consumed the fling this method will return false.
23287     * Custom view implementations should account for this in two ways:</p>
23288     *
23289     * <ul>
23290     *     <li>If a custom view is paged and needs to settle to a fixed page-point, do not
23291     *     call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid
23292     *     position regardless.</li>
23293     *     <li>If a nested parent does consume the fling, this view should not scroll at all,
23294     *     even to settle back to a valid idle position.</li>
23295     * </ul>
23296     *
23297     * <p>Views should also not offer fling velocities to nested parent views along an axis
23298     * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView}
23299     * should not offer a horizontal fling velocity to its parents since scrolling along that
23300     * axis is not permitted and carrying velocity along that motion does not make sense.</p>
23301     *
23302     * @param velocityX Horizontal fling velocity in pixels per second
23303     * @param velocityY Vertical fling velocity in pixels per second
23304     * @return true if a nested scrolling parent consumed the fling
23305     */
23306    public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
23307        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
23308            return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY);
23309        }
23310        return false;
23311    }
23312
23313    /**
23314     * Gets a scale factor that determines the distance the view should scroll
23315     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
23316     * @return The vertical scroll scale factor.
23317     * @hide
23318     */
23319    protected float getVerticalScrollFactor() {
23320        if (mVerticalScrollFactor == 0) {
23321            TypedValue outValue = new TypedValue();
23322            if (!mContext.getTheme().resolveAttribute(
23323                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
23324                throw new IllegalStateException(
23325                        "Expected theme to define listPreferredItemHeight.");
23326            }
23327            mVerticalScrollFactor = outValue.getDimension(
23328                    mContext.getResources().getDisplayMetrics());
23329        }
23330        return mVerticalScrollFactor;
23331    }
23332
23333    /**
23334     * Gets a scale factor that determines the distance the view should scroll
23335     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
23336     * @return The horizontal scroll scale factor.
23337     * @hide
23338     */
23339    protected float getHorizontalScrollFactor() {
23340        // TODO: Should use something else.
23341        return getVerticalScrollFactor();
23342    }
23343
23344    /**
23345     * Return the value specifying the text direction or policy that was set with
23346     * {@link #setTextDirection(int)}.
23347     *
23348     * @return the defined text direction. It can be one of:
23349     *
23350     * {@link #TEXT_DIRECTION_INHERIT},
23351     * {@link #TEXT_DIRECTION_FIRST_STRONG},
23352     * {@link #TEXT_DIRECTION_ANY_RTL},
23353     * {@link #TEXT_DIRECTION_LTR},
23354     * {@link #TEXT_DIRECTION_RTL},
23355     * {@link #TEXT_DIRECTION_LOCALE},
23356     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
23357     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
23358     *
23359     * @attr ref android.R.styleable#View_textDirection
23360     *
23361     * @hide
23362     */
23363    @ViewDebug.ExportedProperty(category = "text", mapping = {
23364            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
23365            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
23366            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
23367            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
23368            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
23369            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
23370            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
23371            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
23372    })
23373    public int getRawTextDirection() {
23374        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
23375    }
23376
23377    /**
23378     * Set the text direction.
23379     *
23380     * @param textDirection the direction to set. Should be one of:
23381     *
23382     * {@link #TEXT_DIRECTION_INHERIT},
23383     * {@link #TEXT_DIRECTION_FIRST_STRONG},
23384     * {@link #TEXT_DIRECTION_ANY_RTL},
23385     * {@link #TEXT_DIRECTION_LTR},
23386     * {@link #TEXT_DIRECTION_RTL},
23387     * {@link #TEXT_DIRECTION_LOCALE}
23388     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
23389     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL},
23390     *
23391     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
23392     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
23393     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
23394     *
23395     * @attr ref android.R.styleable#View_textDirection
23396     */
23397    public void setTextDirection(int textDirection) {
23398        if (getRawTextDirection() != textDirection) {
23399            // Reset the current text direction and the resolved one
23400            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
23401            resetResolvedTextDirection();
23402            // Set the new text direction
23403            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
23404            // Do resolution
23405            resolveTextDirection();
23406            // Notify change
23407            onRtlPropertiesChanged(getLayoutDirection());
23408            // Refresh
23409            requestLayout();
23410            invalidate(true);
23411        }
23412    }
23413
23414    /**
23415     * Return the resolved text direction.
23416     *
23417     * @return the resolved text direction. Returns one of:
23418     *
23419     * {@link #TEXT_DIRECTION_FIRST_STRONG},
23420     * {@link #TEXT_DIRECTION_ANY_RTL},
23421     * {@link #TEXT_DIRECTION_LTR},
23422     * {@link #TEXT_DIRECTION_RTL},
23423     * {@link #TEXT_DIRECTION_LOCALE},
23424     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
23425     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
23426     *
23427     * @attr ref android.R.styleable#View_textDirection
23428     */
23429    @ViewDebug.ExportedProperty(category = "text", mapping = {
23430            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
23431            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
23432            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
23433            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
23434            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
23435            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
23436            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
23437            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
23438    })
23439    public int getTextDirection() {
23440        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
23441    }
23442
23443    /**
23444     * Resolve the text direction.
23445     *
23446     * @return true if resolution has been done, false otherwise.
23447     *
23448     * @hide
23449     */
23450    public boolean resolveTextDirection() {
23451        // Reset any previous text direction resolution
23452        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
23453
23454        if (hasRtlSupport()) {
23455            // Set resolved text direction flag depending on text direction flag
23456            final int textDirection = getRawTextDirection();
23457            switch(textDirection) {
23458                case TEXT_DIRECTION_INHERIT:
23459                    if (!canResolveTextDirection()) {
23460                        // We cannot do the resolution if there is no parent, so use the default one
23461                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
23462                        // Resolution will need to happen again later
23463                        return false;
23464                    }
23465
23466                    // Parent has not yet resolved, so we still return the default
23467                    try {
23468                        if (!mParent.isTextDirectionResolved()) {
23469                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
23470                            // Resolution will need to happen again later
23471                            return false;
23472                        }
23473                    } catch (AbstractMethodError e) {
23474                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
23475                                " does not fully implement ViewParent", e);
23476                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
23477                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
23478                        return true;
23479                    }
23480
23481                    // Set current resolved direction to the same value as the parent's one
23482                    int parentResolvedDirection;
23483                    try {
23484                        parentResolvedDirection = mParent.getTextDirection();
23485                    } catch (AbstractMethodError e) {
23486                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
23487                                " does not fully implement ViewParent", e);
23488                        parentResolvedDirection = TEXT_DIRECTION_LTR;
23489                    }
23490                    switch (parentResolvedDirection) {
23491                        case TEXT_DIRECTION_FIRST_STRONG:
23492                        case TEXT_DIRECTION_ANY_RTL:
23493                        case TEXT_DIRECTION_LTR:
23494                        case TEXT_DIRECTION_RTL:
23495                        case TEXT_DIRECTION_LOCALE:
23496                        case TEXT_DIRECTION_FIRST_STRONG_LTR:
23497                        case TEXT_DIRECTION_FIRST_STRONG_RTL:
23498                            mPrivateFlags2 |=
23499                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
23500                            break;
23501                        default:
23502                            // Default resolved direction is "first strong" heuristic
23503                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
23504                    }
23505                    break;
23506                case TEXT_DIRECTION_FIRST_STRONG:
23507                case TEXT_DIRECTION_ANY_RTL:
23508                case TEXT_DIRECTION_LTR:
23509                case TEXT_DIRECTION_RTL:
23510                case TEXT_DIRECTION_LOCALE:
23511                case TEXT_DIRECTION_FIRST_STRONG_LTR:
23512                case TEXT_DIRECTION_FIRST_STRONG_RTL:
23513                    // Resolved direction is the same as text direction
23514                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
23515                    break;
23516                default:
23517                    // Default resolved direction is "first strong" heuristic
23518                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
23519            }
23520        } else {
23521            // Default resolved direction is "first strong" heuristic
23522            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
23523        }
23524
23525        // Set to resolved
23526        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
23527        return true;
23528    }
23529
23530    /**
23531     * Check if text direction resolution can be done.
23532     *
23533     * @return true if text direction resolution can be done otherwise return false.
23534     */
23535    public boolean canResolveTextDirection() {
23536        switch (getRawTextDirection()) {
23537            case TEXT_DIRECTION_INHERIT:
23538                if (mParent != null) {
23539                    try {
23540                        return mParent.canResolveTextDirection();
23541                    } catch (AbstractMethodError e) {
23542                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
23543                                " does not fully implement ViewParent", e);
23544                    }
23545                }
23546                return false;
23547
23548            default:
23549                return true;
23550        }
23551    }
23552
23553    /**
23554     * Reset resolved text direction. Text direction will be resolved during a call to
23555     * {@link #onMeasure(int, int)}.
23556     *
23557     * @hide
23558     */
23559    public void resetResolvedTextDirection() {
23560        // Reset any previous text direction resolution
23561        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
23562        // Set to default value
23563        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
23564    }
23565
23566    /**
23567     * @return true if text direction is inherited.
23568     *
23569     * @hide
23570     */
23571    public boolean isTextDirectionInherited() {
23572        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
23573    }
23574
23575    /**
23576     * @return true if text direction is resolved.
23577     */
23578    public boolean isTextDirectionResolved() {
23579        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
23580    }
23581
23582    /**
23583     * Return the value specifying the text alignment or policy that was set with
23584     * {@link #setTextAlignment(int)}.
23585     *
23586     * @return the defined text alignment. It can be one of:
23587     *
23588     * {@link #TEXT_ALIGNMENT_INHERIT},
23589     * {@link #TEXT_ALIGNMENT_GRAVITY},
23590     * {@link #TEXT_ALIGNMENT_CENTER},
23591     * {@link #TEXT_ALIGNMENT_TEXT_START},
23592     * {@link #TEXT_ALIGNMENT_TEXT_END},
23593     * {@link #TEXT_ALIGNMENT_VIEW_START},
23594     * {@link #TEXT_ALIGNMENT_VIEW_END}
23595     *
23596     * @attr ref android.R.styleable#View_textAlignment
23597     *
23598     * @hide
23599     */
23600    @ViewDebug.ExportedProperty(category = "text", mapping = {
23601            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
23602            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
23603            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
23604            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
23605            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
23606            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
23607            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
23608    })
23609    @TextAlignment
23610    public int getRawTextAlignment() {
23611        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
23612    }
23613
23614    /**
23615     * Set the text alignment.
23616     *
23617     * @param textAlignment The text alignment to set. Should be one of
23618     *
23619     * {@link #TEXT_ALIGNMENT_INHERIT},
23620     * {@link #TEXT_ALIGNMENT_GRAVITY},
23621     * {@link #TEXT_ALIGNMENT_CENTER},
23622     * {@link #TEXT_ALIGNMENT_TEXT_START},
23623     * {@link #TEXT_ALIGNMENT_TEXT_END},
23624     * {@link #TEXT_ALIGNMENT_VIEW_START},
23625     * {@link #TEXT_ALIGNMENT_VIEW_END}
23626     *
23627     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
23628     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
23629     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
23630     *
23631     * @attr ref android.R.styleable#View_textAlignment
23632     */
23633    public void setTextAlignment(@TextAlignment int textAlignment) {
23634        if (textAlignment != getRawTextAlignment()) {
23635            // Reset the current and resolved text alignment
23636            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
23637            resetResolvedTextAlignment();
23638            // Set the new text alignment
23639            mPrivateFlags2 |=
23640                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
23641            // Do resolution
23642            resolveTextAlignment();
23643            // Notify change
23644            onRtlPropertiesChanged(getLayoutDirection());
23645            // Refresh
23646            requestLayout();
23647            invalidate(true);
23648        }
23649    }
23650
23651    /**
23652     * Return the resolved text alignment.
23653     *
23654     * @return the resolved text alignment. Returns one of:
23655     *
23656     * {@link #TEXT_ALIGNMENT_GRAVITY},
23657     * {@link #TEXT_ALIGNMENT_CENTER},
23658     * {@link #TEXT_ALIGNMENT_TEXT_START},
23659     * {@link #TEXT_ALIGNMENT_TEXT_END},
23660     * {@link #TEXT_ALIGNMENT_VIEW_START},
23661     * {@link #TEXT_ALIGNMENT_VIEW_END}
23662     *
23663     * @attr ref android.R.styleable#View_textAlignment
23664     */
23665    @ViewDebug.ExportedProperty(category = "text", mapping = {
23666            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
23667            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
23668            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
23669            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
23670            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
23671            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
23672            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
23673    })
23674    @TextAlignment
23675    public int getTextAlignment() {
23676        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
23677                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
23678    }
23679
23680    /**
23681     * Resolve the text alignment.
23682     *
23683     * @return true if resolution has been done, false otherwise.
23684     *
23685     * @hide
23686     */
23687    public boolean resolveTextAlignment() {
23688        // Reset any previous text alignment resolution
23689        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
23690
23691        if (hasRtlSupport()) {
23692            // Set resolved text alignment flag depending on text alignment flag
23693            final int textAlignment = getRawTextAlignment();
23694            switch (textAlignment) {
23695                case TEXT_ALIGNMENT_INHERIT:
23696                    // Check if we can resolve the text alignment
23697                    if (!canResolveTextAlignment()) {
23698                        // We cannot do the resolution if there is no parent so use the default
23699                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
23700                        // Resolution will need to happen again later
23701                        return false;
23702                    }
23703
23704                    // Parent has not yet resolved, so we still return the default
23705                    try {
23706                        if (!mParent.isTextAlignmentResolved()) {
23707                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
23708                            // Resolution will need to happen again later
23709                            return false;
23710                        }
23711                    } catch (AbstractMethodError e) {
23712                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
23713                                " does not fully implement ViewParent", e);
23714                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
23715                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
23716                        return true;
23717                    }
23718
23719                    int parentResolvedTextAlignment;
23720                    try {
23721                        parentResolvedTextAlignment = mParent.getTextAlignment();
23722                    } catch (AbstractMethodError e) {
23723                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
23724                                " does not fully implement ViewParent", e);
23725                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
23726                    }
23727                    switch (parentResolvedTextAlignment) {
23728                        case TEXT_ALIGNMENT_GRAVITY:
23729                        case TEXT_ALIGNMENT_TEXT_START:
23730                        case TEXT_ALIGNMENT_TEXT_END:
23731                        case TEXT_ALIGNMENT_CENTER:
23732                        case TEXT_ALIGNMENT_VIEW_START:
23733                        case TEXT_ALIGNMENT_VIEW_END:
23734                            // Resolved text alignment is the same as the parent resolved
23735                            // text alignment
23736                            mPrivateFlags2 |=
23737                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
23738                            break;
23739                        default:
23740                            // Use default resolved text alignment
23741                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
23742                    }
23743                    break;
23744                case TEXT_ALIGNMENT_GRAVITY:
23745                case TEXT_ALIGNMENT_TEXT_START:
23746                case TEXT_ALIGNMENT_TEXT_END:
23747                case TEXT_ALIGNMENT_CENTER:
23748                case TEXT_ALIGNMENT_VIEW_START:
23749                case TEXT_ALIGNMENT_VIEW_END:
23750                    // Resolved text alignment is the same as text alignment
23751                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
23752                    break;
23753                default:
23754                    // Use default resolved text alignment
23755                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
23756            }
23757        } else {
23758            // Use default resolved text alignment
23759            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
23760        }
23761
23762        // Set the resolved
23763        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
23764        return true;
23765    }
23766
23767    /**
23768     * Check if text alignment resolution can be done.
23769     *
23770     * @return true if text alignment resolution can be done otherwise return false.
23771     */
23772    public boolean canResolveTextAlignment() {
23773        switch (getRawTextAlignment()) {
23774            case TEXT_DIRECTION_INHERIT:
23775                if (mParent != null) {
23776                    try {
23777                        return mParent.canResolveTextAlignment();
23778                    } catch (AbstractMethodError e) {
23779                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
23780                                " does not fully implement ViewParent", e);
23781                    }
23782                }
23783                return false;
23784
23785            default:
23786                return true;
23787        }
23788    }
23789
23790    /**
23791     * Reset resolved text alignment. Text alignment will be resolved during a call to
23792     * {@link #onMeasure(int, int)}.
23793     *
23794     * @hide
23795     */
23796    public void resetResolvedTextAlignment() {
23797        // Reset any previous text alignment resolution
23798        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
23799        // Set to default
23800        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
23801    }
23802
23803    /**
23804     * @return true if text alignment is inherited.
23805     *
23806     * @hide
23807     */
23808    public boolean isTextAlignmentInherited() {
23809        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
23810    }
23811
23812    /**
23813     * @return true if text alignment is resolved.
23814     */
23815    public boolean isTextAlignmentResolved() {
23816        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
23817    }
23818
23819    /**
23820     * Generate a value suitable for use in {@link #setId(int)}.
23821     * This value will not collide with ID values generated at build time by aapt for R.id.
23822     *
23823     * @return a generated ID value
23824     */
23825    public static int generateViewId() {
23826        for (;;) {
23827            final int result = sNextGeneratedId.get();
23828            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
23829            int newValue = result + 1;
23830            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
23831            if (sNextGeneratedId.compareAndSet(result, newValue)) {
23832                return result;
23833            }
23834        }
23835    }
23836
23837    private static boolean isViewIdGenerated(int id) {
23838        return (id & 0xFF000000) == 0 && (id & 0x00FFFFFF) != 0;
23839    }
23840
23841    /**
23842     * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions.
23843     * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and
23844     *                           a normal View or a ViewGroup with
23845     *                           {@link android.view.ViewGroup#isTransitionGroup()} true.
23846     * @hide
23847     */
23848    public void captureTransitioningViews(List<View> transitioningViews) {
23849        if (getVisibility() == View.VISIBLE) {
23850            transitioningViews.add(this);
23851        }
23852    }
23853
23854    /**
23855     * Adds all Views that have {@link #getTransitionName()} non-null to namedElements.
23856     * @param namedElements Will contain all Views in the hierarchy having a transitionName.
23857     * @hide
23858     */
23859    public void findNamedViews(Map<String, View> namedElements) {
23860        if (getVisibility() == VISIBLE || mGhostView != null) {
23861            String transitionName = getTransitionName();
23862            if (transitionName != null) {
23863                namedElements.put(transitionName, this);
23864            }
23865        }
23866    }
23867
23868    /**
23869     * Returns the pointer icon for the motion event, or null if it doesn't specify the icon.
23870     * The default implementation does not care the location or event types, but some subclasses
23871     * may use it (such as WebViews).
23872     * @param event The MotionEvent from a mouse
23873     * @param pointerIndex The index of the pointer for which to retrieve the {@link PointerIcon}.
23874     *                     This will be between 0 and {@link MotionEvent#getPointerCount()}.
23875     * @see PointerIcon
23876     */
23877    public PointerIcon onResolvePointerIcon(MotionEvent event, int pointerIndex) {
23878        final float x = event.getX(pointerIndex);
23879        final float y = event.getY(pointerIndex);
23880        if (isDraggingScrollBar() || isOnScrollbarThumb(x, y)) {
23881            return PointerIcon.getSystemIcon(mContext, PointerIcon.TYPE_ARROW);
23882        }
23883        return mPointerIcon;
23884    }
23885
23886    /**
23887     * Set the pointer icon for the current view.
23888     * Passing {@code null} will restore the pointer icon to its default value.
23889     * @param pointerIcon A PointerIcon instance which will be shown when the mouse hovers.
23890     */
23891    public void setPointerIcon(PointerIcon pointerIcon) {
23892        mPointerIcon = pointerIcon;
23893        if (mAttachInfo == null || mAttachInfo.mHandlingPointerEvent) {
23894            return;
23895        }
23896        try {
23897            mAttachInfo.mSession.updatePointerIcon(mAttachInfo.mWindow);
23898        } catch (RemoteException e) {
23899        }
23900    }
23901
23902    /**
23903     * Gets the pointer icon for the current view.
23904     */
23905    public PointerIcon getPointerIcon() {
23906        return mPointerIcon;
23907    }
23908
23909    /**
23910     * Checks pointer capture status.
23911     *
23912     * @return true if the view has pointer capture.
23913     * @see #requestPointerCapture()
23914     * @see #hasPointerCapture()
23915     */
23916    public boolean hasPointerCapture() {
23917        final ViewRootImpl viewRootImpl = getViewRootImpl();
23918        if (viewRootImpl == null) {
23919            return false;
23920        }
23921        return viewRootImpl.hasPointerCapture();
23922    }
23923
23924    /**
23925     * Requests pointer capture mode.
23926     * <p>
23927     * When the window has pointer capture, the mouse pointer icon will disappear and will not
23928     * change its position. Further mouse will be dispatched with the source
23929     * {@link InputDevice#SOURCE_MOUSE_RELATIVE}, and relative position changes will be available
23930     * through {@link MotionEvent#getX} and {@link MotionEvent#getY}. Non-mouse events
23931     * (touchscreens, or stylus) will not be affected.
23932     * <p>
23933     * If the window already has pointer capture, this call does nothing.
23934     * <p>
23935     * The capture may be released through {@link #releasePointerCapture()}, or will be lost
23936     * automatically when the window loses focus.
23937     *
23938     * @see #releasePointerCapture()
23939     * @see #hasPointerCapture()
23940     */
23941    public void requestPointerCapture() {
23942        final ViewRootImpl viewRootImpl = getViewRootImpl();
23943        if (viewRootImpl != null) {
23944            viewRootImpl.requestPointerCapture(true);
23945        }
23946    }
23947
23948
23949    /**
23950     * Releases the pointer capture.
23951     * <p>
23952     * If the window does not have pointer capture, this call will do nothing.
23953     * @see #requestPointerCapture()
23954     * @see #hasPointerCapture()
23955     */
23956    public void releasePointerCapture() {
23957        final ViewRootImpl viewRootImpl = getViewRootImpl();
23958        if (viewRootImpl != null) {
23959            viewRootImpl.requestPointerCapture(false);
23960        }
23961    }
23962
23963    /**
23964     * Called when the window has just acquired or lost pointer capture.
23965     *
23966     * @param hasCapture True if the view now has pointerCapture, false otherwise.
23967     */
23968    @CallSuper
23969    public void onPointerCaptureChange(boolean hasCapture) {
23970    }
23971
23972    /**
23973     * @see #onPointerCaptureChange
23974     */
23975    public void dispatchPointerCaptureChanged(boolean hasCapture) {
23976        onPointerCaptureChange(hasCapture);
23977    }
23978
23979    /**
23980     * Implement this method to handle captured pointer events
23981     *
23982     * @param event The captured pointer event.
23983     * @return True if the event was handled, false otherwise.
23984     * @see #requestPointerCapture()
23985     */
23986    public boolean onCapturedPointerEvent(MotionEvent event) {
23987        return false;
23988    }
23989
23990    /**
23991     * Interface definition for a callback to be invoked when a captured pointer event
23992     * is being dispatched this view. The callback will be invoked before the event is
23993     * given to the view.
23994     */
23995    public interface OnCapturedPointerListener {
23996        /**
23997         * Called when a captured pointer event is dispatched to a view.
23998         * @param view The view this event has been dispatched to.
23999         * @param event The captured event.
24000         * @return True if the listener has consumed the event, false otherwise.
24001         */
24002        boolean onCapturedPointer(View view, MotionEvent event);
24003    }
24004
24005    /**
24006     * Set a listener to receive callbacks when the pointer capture state of a view changes.
24007     * @param l  The {@link OnCapturedPointerListener} to receive callbacks.
24008     */
24009    public void setOnCapturedPointerListener(OnCapturedPointerListener l) {
24010        getListenerInfo().mOnCapturedPointerListener = l;
24011    }
24012
24013    // Properties
24014    //
24015    /**
24016     * A Property wrapper around the <code>alpha</code> functionality handled by the
24017     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
24018     */
24019    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
24020        @Override
24021        public void setValue(View object, float value) {
24022            object.setAlpha(value);
24023        }
24024
24025        @Override
24026        public Float get(View object) {
24027            return object.getAlpha();
24028        }
24029    };
24030
24031    /**
24032     * A Property wrapper around the <code>translationX</code> functionality handled by the
24033     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
24034     */
24035    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
24036        @Override
24037        public void setValue(View object, float value) {
24038            object.setTranslationX(value);
24039        }
24040
24041                @Override
24042        public Float get(View object) {
24043            return object.getTranslationX();
24044        }
24045    };
24046
24047    /**
24048     * A Property wrapper around the <code>translationY</code> functionality handled by the
24049     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
24050     */
24051    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
24052        @Override
24053        public void setValue(View object, float value) {
24054            object.setTranslationY(value);
24055        }
24056
24057        @Override
24058        public Float get(View object) {
24059            return object.getTranslationY();
24060        }
24061    };
24062
24063    /**
24064     * A Property wrapper around the <code>translationZ</code> functionality handled by the
24065     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
24066     */
24067    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
24068        @Override
24069        public void setValue(View object, float value) {
24070            object.setTranslationZ(value);
24071        }
24072
24073        @Override
24074        public Float get(View object) {
24075            return object.getTranslationZ();
24076        }
24077    };
24078
24079    /**
24080     * A Property wrapper around the <code>x</code> functionality handled by the
24081     * {@link View#setX(float)} and {@link View#getX()} methods.
24082     */
24083    public static final Property<View, Float> X = new FloatProperty<View>("x") {
24084        @Override
24085        public void setValue(View object, float value) {
24086            object.setX(value);
24087        }
24088
24089        @Override
24090        public Float get(View object) {
24091            return object.getX();
24092        }
24093    };
24094
24095    /**
24096     * A Property wrapper around the <code>y</code> functionality handled by the
24097     * {@link View#setY(float)} and {@link View#getY()} methods.
24098     */
24099    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
24100        @Override
24101        public void setValue(View object, float value) {
24102            object.setY(value);
24103        }
24104
24105        @Override
24106        public Float get(View object) {
24107            return object.getY();
24108        }
24109    };
24110
24111    /**
24112     * A Property wrapper around the <code>z</code> functionality handled by the
24113     * {@link View#setZ(float)} and {@link View#getZ()} methods.
24114     */
24115    public static final Property<View, Float> Z = new FloatProperty<View>("z") {
24116        @Override
24117        public void setValue(View object, float value) {
24118            object.setZ(value);
24119        }
24120
24121        @Override
24122        public Float get(View object) {
24123            return object.getZ();
24124        }
24125    };
24126
24127    /**
24128     * A Property wrapper around the <code>rotation</code> functionality handled by the
24129     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
24130     */
24131    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
24132        @Override
24133        public void setValue(View object, float value) {
24134            object.setRotation(value);
24135        }
24136
24137        @Override
24138        public Float get(View object) {
24139            return object.getRotation();
24140        }
24141    };
24142
24143    /**
24144     * A Property wrapper around the <code>rotationX</code> functionality handled by the
24145     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
24146     */
24147    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
24148        @Override
24149        public void setValue(View object, float value) {
24150            object.setRotationX(value);
24151        }
24152
24153        @Override
24154        public Float get(View object) {
24155            return object.getRotationX();
24156        }
24157    };
24158
24159    /**
24160     * A Property wrapper around the <code>rotationY</code> functionality handled by the
24161     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
24162     */
24163    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
24164        @Override
24165        public void setValue(View object, float value) {
24166            object.setRotationY(value);
24167        }
24168
24169        @Override
24170        public Float get(View object) {
24171            return object.getRotationY();
24172        }
24173    };
24174
24175    /**
24176     * A Property wrapper around the <code>scaleX</code> functionality handled by the
24177     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
24178     */
24179    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
24180        @Override
24181        public void setValue(View object, float value) {
24182            object.setScaleX(value);
24183        }
24184
24185        @Override
24186        public Float get(View object) {
24187            return object.getScaleX();
24188        }
24189    };
24190
24191    /**
24192     * A Property wrapper around the <code>scaleY</code> functionality handled by the
24193     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
24194     */
24195    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
24196        @Override
24197        public void setValue(View object, float value) {
24198            object.setScaleY(value);
24199        }
24200
24201        @Override
24202        public Float get(View object) {
24203            return object.getScaleY();
24204        }
24205    };
24206
24207    /**
24208     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
24209     * Each MeasureSpec represents a requirement for either the width or the height.
24210     * A MeasureSpec is comprised of a size and a mode. There are three possible
24211     * modes:
24212     * <dl>
24213     * <dt>UNSPECIFIED</dt>
24214     * <dd>
24215     * The parent has not imposed any constraint on the child. It can be whatever size
24216     * it wants.
24217     * </dd>
24218     *
24219     * <dt>EXACTLY</dt>
24220     * <dd>
24221     * The parent has determined an exact size for the child. The child is going to be
24222     * given those bounds regardless of how big it wants to be.
24223     * </dd>
24224     *
24225     * <dt>AT_MOST</dt>
24226     * <dd>
24227     * The child can be as large as it wants up to the specified size.
24228     * </dd>
24229     * </dl>
24230     *
24231     * MeasureSpecs are implemented as ints to reduce object allocation. This class
24232     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
24233     */
24234    public static class MeasureSpec {
24235        private static final int MODE_SHIFT = 30;
24236        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
24237
24238        /** @hide */
24239        @IntDef({UNSPECIFIED, EXACTLY, AT_MOST})
24240        @Retention(RetentionPolicy.SOURCE)
24241        public @interface MeasureSpecMode {}
24242
24243        /**
24244         * Measure specification mode: The parent has not imposed any constraint
24245         * on the child. It can be whatever size it wants.
24246         */
24247        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
24248
24249        /**
24250         * Measure specification mode: The parent has determined an exact size
24251         * for the child. The child is going to be given those bounds regardless
24252         * of how big it wants to be.
24253         */
24254        public static final int EXACTLY     = 1 << MODE_SHIFT;
24255
24256        /**
24257         * Measure specification mode: The child can be as large as it wants up
24258         * to the specified size.
24259         */
24260        public static final int AT_MOST     = 2 << MODE_SHIFT;
24261
24262        /**
24263         * Creates a measure specification based on the supplied size and mode.
24264         *
24265         * The mode must always be one of the following:
24266         * <ul>
24267         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
24268         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
24269         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
24270         * </ul>
24271         *
24272         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
24273         * implementation was such that the order of arguments did not matter
24274         * and overflow in either value could impact the resulting MeasureSpec.
24275         * {@link android.widget.RelativeLayout} was affected by this bug.
24276         * Apps targeting API levels greater than 17 will get the fixed, more strict
24277         * behavior.</p>
24278         *
24279         * @param size the size of the measure specification
24280         * @param mode the mode of the measure specification
24281         * @return the measure specification based on size and mode
24282         */
24283        public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size,
24284                                          @MeasureSpecMode int mode) {
24285            if (sUseBrokenMakeMeasureSpec) {
24286                return size + mode;
24287            } else {
24288                return (size & ~MODE_MASK) | (mode & MODE_MASK);
24289            }
24290        }
24291
24292        /**
24293         * Like {@link #makeMeasureSpec(int, int)}, but any spec with a mode of UNSPECIFIED
24294         * will automatically get a size of 0. Older apps expect this.
24295         *
24296         * @hide internal use only for compatibility with system widgets and older apps
24297         */
24298        public static int makeSafeMeasureSpec(int size, int mode) {
24299            if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) {
24300                return 0;
24301            }
24302            return makeMeasureSpec(size, mode);
24303        }
24304
24305        /**
24306         * Extracts the mode from the supplied measure specification.
24307         *
24308         * @param measureSpec the measure specification to extract the mode from
24309         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
24310         *         {@link android.view.View.MeasureSpec#AT_MOST} or
24311         *         {@link android.view.View.MeasureSpec#EXACTLY}
24312         */
24313        @MeasureSpecMode
24314        public static int getMode(int measureSpec) {
24315            //noinspection ResourceType
24316            return (measureSpec & MODE_MASK);
24317        }
24318
24319        /**
24320         * Extracts the size from the supplied measure specification.
24321         *
24322         * @param measureSpec the measure specification to extract the size from
24323         * @return the size in pixels defined in the supplied measure specification
24324         */
24325        public static int getSize(int measureSpec) {
24326            return (measureSpec & ~MODE_MASK);
24327        }
24328
24329        static int adjust(int measureSpec, int delta) {
24330            final int mode = getMode(measureSpec);
24331            int size = getSize(measureSpec);
24332            if (mode == UNSPECIFIED) {
24333                // No need to adjust size for UNSPECIFIED mode.
24334                return makeMeasureSpec(size, UNSPECIFIED);
24335            }
24336            size += delta;
24337            if (size < 0) {
24338                Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
24339                        ") spec: " + toString(measureSpec) + " delta: " + delta);
24340                size = 0;
24341            }
24342            return makeMeasureSpec(size, mode);
24343        }
24344
24345        /**
24346         * Returns a String representation of the specified measure
24347         * specification.
24348         *
24349         * @param measureSpec the measure specification to convert to a String
24350         * @return a String with the following format: "MeasureSpec: MODE SIZE"
24351         */
24352        public static String toString(int measureSpec) {
24353            int mode = getMode(measureSpec);
24354            int size = getSize(measureSpec);
24355
24356            StringBuilder sb = new StringBuilder("MeasureSpec: ");
24357
24358            if (mode == UNSPECIFIED)
24359                sb.append("UNSPECIFIED ");
24360            else if (mode == EXACTLY)
24361                sb.append("EXACTLY ");
24362            else if (mode == AT_MOST)
24363                sb.append("AT_MOST ");
24364            else
24365                sb.append(mode).append(" ");
24366
24367            sb.append(size);
24368            return sb.toString();
24369        }
24370    }
24371
24372    private final class CheckForLongPress implements Runnable {
24373        private int mOriginalWindowAttachCount;
24374        private float mX;
24375        private float mY;
24376        private boolean mOriginalPressedState;
24377
24378        @Override
24379        public void run() {
24380            if ((mOriginalPressedState == isPressed()) && (mParent != null)
24381                    && mOriginalWindowAttachCount == mWindowAttachCount) {
24382                if (performLongClick(mX, mY)) {
24383                    mHasPerformedLongPress = true;
24384                }
24385            }
24386        }
24387
24388        public void setAnchor(float x, float y) {
24389            mX = x;
24390            mY = y;
24391        }
24392
24393        public void rememberWindowAttachCount() {
24394            mOriginalWindowAttachCount = mWindowAttachCount;
24395        }
24396
24397        public void rememberPressedState() {
24398            mOriginalPressedState = isPressed();
24399        }
24400    }
24401
24402    private final class CheckForTap implements Runnable {
24403        public float x;
24404        public float y;
24405
24406        @Override
24407        public void run() {
24408            mPrivateFlags &= ~PFLAG_PREPRESSED;
24409            setPressed(true, x, y);
24410            checkForLongClick(ViewConfiguration.getTapTimeout(), x, y);
24411        }
24412    }
24413
24414    private final class PerformClick implements Runnable {
24415        @Override
24416        public void run() {
24417            performClick();
24418        }
24419    }
24420
24421    /**
24422     * This method returns a ViewPropertyAnimator object, which can be used to animate
24423     * specific properties on this View.
24424     *
24425     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
24426     */
24427    public ViewPropertyAnimator animate() {
24428        if (mAnimator == null) {
24429            mAnimator = new ViewPropertyAnimator(this);
24430        }
24431        return mAnimator;
24432    }
24433
24434    /**
24435     * Sets the name of the View to be used to identify Views in Transitions.
24436     * Names should be unique in the View hierarchy.
24437     *
24438     * @param transitionName The name of the View to uniquely identify it for Transitions.
24439     */
24440    public final void setTransitionName(String transitionName) {
24441        mTransitionName = transitionName;
24442    }
24443
24444    /**
24445     * Returns the name of the View to be used to identify Views in Transitions.
24446     * Names should be unique in the View hierarchy.
24447     *
24448     * <p>This returns null if the View has not been given a name.</p>
24449     *
24450     * @return The name used of the View to be used to identify Views in Transitions or null
24451     * if no name has been given.
24452     */
24453    @ViewDebug.ExportedProperty
24454    public String getTransitionName() {
24455        return mTransitionName;
24456    }
24457
24458    /**
24459     * @hide
24460     */
24461    public void requestKeyboardShortcuts(List<KeyboardShortcutGroup> data, int deviceId) {
24462        // Do nothing.
24463    }
24464
24465    /**
24466     * Interface definition for a callback to be invoked when a hardware key event is
24467     * dispatched to this view. The callback will be invoked before the key event is
24468     * given to the view. This is only useful for hardware keyboards; a software input
24469     * method has no obligation to trigger this listener.
24470     */
24471    public interface OnKeyListener {
24472        /**
24473         * Called when a hardware key is dispatched to a view. This allows listeners to
24474         * get a chance to respond before the target view.
24475         * <p>Key presses in software keyboards will generally NOT trigger this method,
24476         * although some may elect to do so in some situations. Do not assume a
24477         * software input method has to be key-based; even if it is, it may use key presses
24478         * in a different way than you expect, so there is no way to reliably catch soft
24479         * input key presses.
24480         *
24481         * @param v The view the key has been dispatched to.
24482         * @param keyCode The code for the physical key that was pressed
24483         * @param event The KeyEvent object containing full information about
24484         *        the event.
24485         * @return True if the listener has consumed the event, false otherwise.
24486         */
24487        boolean onKey(View v, int keyCode, KeyEvent event);
24488    }
24489
24490    /**
24491     * Interface definition for a callback to be invoked when a touch event is
24492     * dispatched to this view. The callback will be invoked before the touch
24493     * event is given to the view.
24494     */
24495    public interface OnTouchListener {
24496        /**
24497         * Called when a touch event is dispatched to a view. This allows listeners to
24498         * get a chance to respond before the target view.
24499         *
24500         * @param v The view the touch event has been dispatched to.
24501         * @param event The MotionEvent object containing full information about
24502         *        the event.
24503         * @return True if the listener has consumed the event, false otherwise.
24504         */
24505        boolean onTouch(View v, MotionEvent event);
24506    }
24507
24508    /**
24509     * Interface definition for a callback to be invoked when a hover event is
24510     * dispatched to this view. The callback will be invoked before the hover
24511     * event is given to the view.
24512     */
24513    public interface OnHoverListener {
24514        /**
24515         * Called when a hover event is dispatched to a view. This allows listeners to
24516         * get a chance to respond before the target view.
24517         *
24518         * @param v The view the hover event has been dispatched to.
24519         * @param event The MotionEvent object containing full information about
24520         *        the event.
24521         * @return True if the listener has consumed the event, false otherwise.
24522         */
24523        boolean onHover(View v, MotionEvent event);
24524    }
24525
24526    /**
24527     * Interface definition for a callback to be invoked when a generic motion event is
24528     * dispatched to this view. The callback will be invoked before the generic motion
24529     * event is given to the view.
24530     */
24531    public interface OnGenericMotionListener {
24532        /**
24533         * Called when a generic motion event is dispatched to a view. This allows listeners to
24534         * get a chance to respond before the target view.
24535         *
24536         * @param v The view the generic motion event has been dispatched to.
24537         * @param event The MotionEvent object containing full information about
24538         *        the event.
24539         * @return True if the listener has consumed the event, false otherwise.
24540         */
24541        boolean onGenericMotion(View v, MotionEvent event);
24542    }
24543
24544    /**
24545     * Interface definition for a callback to be invoked when a view has been clicked and held.
24546     */
24547    public interface OnLongClickListener {
24548        /**
24549         * Called when a view has been clicked and held.
24550         *
24551         * @param v The view that was clicked and held.
24552         *
24553         * @return true if the callback consumed the long click, false otherwise.
24554         */
24555        boolean onLongClick(View v);
24556    }
24557
24558    /**
24559     * Interface definition for a callback to be invoked when a drag is being dispatched
24560     * to this view.  The callback will be invoked before the hosting view's own
24561     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
24562     * onDrag(event) behavior, it should return 'false' from this callback.
24563     *
24564     * <div class="special reference">
24565     * <h3>Developer Guides</h3>
24566     * <p>For a guide to implementing drag and drop features, read the
24567     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
24568     * </div>
24569     */
24570    public interface OnDragListener {
24571        /**
24572         * Called when a drag event is dispatched to a view. This allows listeners
24573         * to get a chance to override base View behavior.
24574         *
24575         * @param v The View that received the drag event.
24576         * @param event The {@link android.view.DragEvent} object for the drag event.
24577         * @return {@code true} if the drag event was handled successfully, or {@code false}
24578         * if the drag event was not handled. Note that {@code false} will trigger the View
24579         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
24580         */
24581        boolean onDrag(View v, DragEvent event);
24582    }
24583
24584    /**
24585     * Interface definition for a callback to be invoked when the focus state of
24586     * a view changed.
24587     */
24588    public interface OnFocusChangeListener {
24589        /**
24590         * Called when the focus state of a view has changed.
24591         *
24592         * @param v The view whose state has changed.
24593         * @param hasFocus The new focus state of v.
24594         */
24595        void onFocusChange(View v, boolean hasFocus);
24596    }
24597
24598    /**
24599     * Interface definition for a callback to be invoked when a view is clicked.
24600     */
24601    public interface OnClickListener {
24602        /**
24603         * Called when a view has been clicked.
24604         *
24605         * @param v The view that was clicked.
24606         */
24607        void onClick(View v);
24608    }
24609
24610    /**
24611     * Interface definition for a callback to be invoked when a view is context clicked.
24612     */
24613    public interface OnContextClickListener {
24614        /**
24615         * Called when a view is context clicked.
24616         *
24617         * @param v The view that has been context clicked.
24618         * @return true if the callback consumed the context click, false otherwise.
24619         */
24620        boolean onContextClick(View v);
24621    }
24622
24623    /**
24624     * Interface definition for a callback to be invoked when the context menu
24625     * for this view is being built.
24626     */
24627    public interface OnCreateContextMenuListener {
24628        /**
24629         * Called when the context menu for this view is being built. It is not
24630         * safe to hold onto the menu after this method returns.
24631         *
24632         * @param menu The context menu that is being built
24633         * @param v The view for which the context menu is being built
24634         * @param menuInfo Extra information about the item for which the
24635         *            context menu should be shown. This information will vary
24636         *            depending on the class of v.
24637         */
24638        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
24639    }
24640
24641    /**
24642     * Interface definition for a callback to be invoked when the status bar changes
24643     * visibility.  This reports <strong>global</strong> changes to the system UI
24644     * state, not what the application is requesting.
24645     *
24646     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
24647     */
24648    public interface OnSystemUiVisibilityChangeListener {
24649        /**
24650         * Called when the status bar changes visibility because of a call to
24651         * {@link View#setSystemUiVisibility(int)}.
24652         *
24653         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
24654         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
24655         * This tells you the <strong>global</strong> state of these UI visibility
24656         * flags, not what your app is currently applying.
24657         */
24658        public void onSystemUiVisibilityChange(int visibility);
24659    }
24660
24661    /**
24662     * Interface definition for a callback to be invoked when this view is attached
24663     * or detached from its window.
24664     */
24665    public interface OnAttachStateChangeListener {
24666        /**
24667         * Called when the view is attached to a window.
24668         * @param v The view that was attached
24669         */
24670        public void onViewAttachedToWindow(View v);
24671        /**
24672         * Called when the view is detached from a window.
24673         * @param v The view that was detached
24674         */
24675        public void onViewDetachedFromWindow(View v);
24676    }
24677
24678    /**
24679     * Listener for applying window insets on a view in a custom way.
24680     *
24681     * <p>Apps may choose to implement this interface if they want to apply custom policy
24682     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
24683     * is set, its
24684     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
24685     * method will be called instead of the View's own
24686     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
24687     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
24688     * the View's normal behavior as part of its own.</p>
24689     */
24690    public interface OnApplyWindowInsetsListener {
24691        /**
24692         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
24693         * on a View, this listener method will be called instead of the view's own
24694         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
24695         *
24696         * @param v The view applying window insets
24697         * @param insets The insets to apply
24698         * @return The insets supplied, minus any insets that were consumed
24699         */
24700        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
24701    }
24702
24703    private final class UnsetPressedState implements Runnable {
24704        @Override
24705        public void run() {
24706            setPressed(false);
24707        }
24708    }
24709
24710    /**
24711     * When a view becomes invisible checks if autofill considers the view invisible too. This
24712     * happens after the regular removal operation to make sure the operation is finished by the
24713     * time this is called.
24714     */
24715    private static class VisibilityChangeForAutofillHandler extends Handler {
24716        private final AutofillManager mAfm;
24717        private final View mView;
24718
24719        private VisibilityChangeForAutofillHandler(@NonNull AutofillManager afm,
24720                @NonNull View view) {
24721            mAfm = afm;
24722            mView = view;
24723        }
24724
24725        @Override
24726        public void handleMessage(Message msg) {
24727            mAfm.notifyViewVisibilityChange(mView, mView.isShown());
24728        }
24729    }
24730
24731    /**
24732     * Base class for derived classes that want to save and restore their own
24733     * state in {@link android.view.View#onSaveInstanceState()}.
24734     */
24735    public static class BaseSavedState extends AbsSavedState {
24736        static final int START_ACTIVITY_REQUESTED_WHO_SAVED = 0b1;
24737        static final int IS_AUTOFILLED = 0b10;
24738        static final int ACCESSIBILITY_ID = 0b100;
24739
24740        // Flags that describe what data in this state is valid
24741        int mSavedData;
24742        String mStartActivityRequestWhoSaved;
24743        boolean mIsAutofilled;
24744        int mAccessibilityViewId;
24745
24746        /**
24747         * Constructor used when reading from a parcel. Reads the state of the superclass.
24748         *
24749         * @param source parcel to read from
24750         */
24751        public BaseSavedState(Parcel source) {
24752            this(source, null);
24753        }
24754
24755        /**
24756         * Constructor used when reading from a parcel using a given class loader.
24757         * Reads the state of the superclass.
24758         *
24759         * @param source parcel to read from
24760         * @param loader ClassLoader to use for reading
24761         */
24762        public BaseSavedState(Parcel source, ClassLoader loader) {
24763            super(source, loader);
24764            mSavedData = source.readInt();
24765            mStartActivityRequestWhoSaved = source.readString();
24766            mIsAutofilled = source.readBoolean();
24767            mAccessibilityViewId = source.readInt();
24768        }
24769
24770        /**
24771         * Constructor called by derived classes when creating their SavedState objects
24772         *
24773         * @param superState The state of the superclass of this view
24774         */
24775        public BaseSavedState(Parcelable superState) {
24776            super(superState);
24777        }
24778
24779        @Override
24780        public void writeToParcel(Parcel out, int flags) {
24781            super.writeToParcel(out, flags);
24782
24783            out.writeInt(mSavedData);
24784            out.writeString(mStartActivityRequestWhoSaved);
24785            out.writeBoolean(mIsAutofilled);
24786            out.writeInt(mAccessibilityViewId);
24787        }
24788
24789        public static final Parcelable.Creator<BaseSavedState> CREATOR
24790                = new Parcelable.ClassLoaderCreator<BaseSavedState>() {
24791            @Override
24792            public BaseSavedState createFromParcel(Parcel in) {
24793                return new BaseSavedState(in);
24794            }
24795
24796            @Override
24797            public BaseSavedState createFromParcel(Parcel in, ClassLoader loader) {
24798                return new BaseSavedState(in, loader);
24799            }
24800
24801            @Override
24802            public BaseSavedState[] newArray(int size) {
24803                return new BaseSavedState[size];
24804            }
24805        };
24806    }
24807
24808    /**
24809     * A set of information given to a view when it is attached to its parent
24810     * window.
24811     */
24812    final static class AttachInfo {
24813        interface Callbacks {
24814            void playSoundEffect(int effectId);
24815            boolean performHapticFeedback(int effectId, boolean always);
24816        }
24817
24818        /**
24819         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
24820         * to a Handler. This class contains the target (View) to invalidate and
24821         * the coordinates of the dirty rectangle.
24822         *
24823         * For performance purposes, this class also implements a pool of up to
24824         * POOL_LIMIT objects that get reused. This reduces memory allocations
24825         * whenever possible.
24826         */
24827        static class InvalidateInfo {
24828            private static final int POOL_LIMIT = 10;
24829
24830            private static final SynchronizedPool<InvalidateInfo> sPool =
24831                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
24832
24833            View target;
24834
24835            int left;
24836            int top;
24837            int right;
24838            int bottom;
24839
24840            public static InvalidateInfo obtain() {
24841                InvalidateInfo instance = sPool.acquire();
24842                return (instance != null) ? instance : new InvalidateInfo();
24843            }
24844
24845            public void recycle() {
24846                target = null;
24847                sPool.release(this);
24848            }
24849        }
24850
24851        final IWindowSession mSession;
24852
24853        final IWindow mWindow;
24854
24855        final IBinder mWindowToken;
24856
24857        Display mDisplay;
24858
24859        final Callbacks mRootCallbacks;
24860
24861        IWindowId mIWindowId;
24862        WindowId mWindowId;
24863
24864        /**
24865         * The top view of the hierarchy.
24866         */
24867        View mRootView;
24868
24869        IBinder mPanelParentWindowToken;
24870
24871        boolean mHardwareAccelerated;
24872        boolean mHardwareAccelerationRequested;
24873        ThreadedRenderer mThreadedRenderer;
24874        List<RenderNode> mPendingAnimatingRenderNodes;
24875
24876        /**
24877         * The state of the display to which the window is attached, as reported
24878         * by {@link Display#getState()}.  Note that the display state constants
24879         * declared by {@link Display} do not exactly line up with the screen state
24880         * constants declared by {@link View} (there are more display states than
24881         * screen states).
24882         */
24883        int mDisplayState = Display.STATE_UNKNOWN;
24884
24885        /**
24886         * Scale factor used by the compatibility mode
24887         */
24888        float mApplicationScale;
24889
24890        /**
24891         * Indicates whether the application is in compatibility mode
24892         */
24893        boolean mScalingRequired;
24894
24895        /**
24896         * Left position of this view's window
24897         */
24898        int mWindowLeft;
24899
24900        /**
24901         * Top position of this view's window
24902         */
24903        int mWindowTop;
24904
24905        /**
24906         * Indicates whether views need to use 32-bit drawing caches
24907         */
24908        boolean mUse32BitDrawingCache;
24909
24910        /**
24911         * For windows that are full-screen but using insets to layout inside
24912         * of the screen areas, these are the current insets to appear inside
24913         * the overscan area of the display.
24914         */
24915        final Rect mOverscanInsets = new Rect();
24916
24917        /**
24918         * For windows that are full-screen but using insets to layout inside
24919         * of the screen decorations, these are the current insets for the
24920         * content of the window.
24921         */
24922        final Rect mContentInsets = new Rect();
24923
24924        /**
24925         * For windows that are full-screen but using insets to layout inside
24926         * of the screen decorations, these are the current insets for the
24927         * actual visible parts of the window.
24928         */
24929        final Rect mVisibleInsets = new Rect();
24930
24931        /**
24932         * For windows that are full-screen but using insets to layout inside
24933         * of the screen decorations, these are the current insets for the
24934         * stable system windows.
24935         */
24936        final Rect mStableInsets = new Rect();
24937
24938        /**
24939         * For windows that include areas that are not covered by real surface these are the outsets
24940         * for real surface.
24941         */
24942        final Rect mOutsets = new Rect();
24943
24944        /**
24945         * In multi-window we force show the navigation bar. Because we don't want that the surface
24946         * size changes in this mode, we instead have a flag whether the navigation bar size should
24947         * always be consumed, so the app is treated like there is no virtual navigation bar at all.
24948         */
24949        boolean mAlwaysConsumeNavBar;
24950
24951        /**
24952         * The internal insets given by this window.  This value is
24953         * supplied by the client (through
24954         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
24955         * be given to the window manager when changed to be used in laying
24956         * out windows behind it.
24957         */
24958        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
24959                = new ViewTreeObserver.InternalInsetsInfo();
24960
24961        /**
24962         * Set to true when mGivenInternalInsets is non-empty.
24963         */
24964        boolean mHasNonEmptyGivenInternalInsets;
24965
24966        /**
24967         * All views in the window's hierarchy that serve as scroll containers,
24968         * used to determine if the window can be resized or must be panned
24969         * to adjust for a soft input area.
24970         */
24971        final ArrayList<View> mScrollContainers = new ArrayList<View>();
24972
24973        final KeyEvent.DispatcherState mKeyDispatchState
24974                = new KeyEvent.DispatcherState();
24975
24976        /**
24977         * Indicates whether the view's window currently has the focus.
24978         */
24979        boolean mHasWindowFocus;
24980
24981        /**
24982         * The current visibility of the window.
24983         */
24984        int mWindowVisibility;
24985
24986        /**
24987         * Indicates the time at which drawing started to occur.
24988         */
24989        long mDrawingTime;
24990
24991        /**
24992         * Indicates whether or not ignoring the DIRTY_MASK flags.
24993         */
24994        boolean mIgnoreDirtyState;
24995
24996        /**
24997         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
24998         * to avoid clearing that flag prematurely.
24999         */
25000        boolean mSetIgnoreDirtyState = false;
25001
25002        /**
25003         * Indicates whether the view's window is currently in touch mode.
25004         */
25005        boolean mInTouchMode;
25006
25007        /**
25008         * Indicates whether the view has requested unbuffered input dispatching for the current
25009         * event stream.
25010         */
25011        boolean mUnbufferedDispatchRequested;
25012
25013        /**
25014         * Indicates that ViewAncestor should trigger a global layout change
25015         * the next time it performs a traversal
25016         */
25017        boolean mRecomputeGlobalAttributes;
25018
25019        /**
25020         * Always report new attributes at next traversal.
25021         */
25022        boolean mForceReportNewAttributes;
25023
25024        /**
25025         * Set during a traveral if any views want to keep the screen on.
25026         */
25027        boolean mKeepScreenOn;
25028
25029        /**
25030         * Set during a traveral if the light center needs to be updated.
25031         */
25032        boolean mNeedsUpdateLightCenter;
25033
25034        /**
25035         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
25036         */
25037        int mSystemUiVisibility;
25038
25039        /**
25040         * Hack to force certain system UI visibility flags to be cleared.
25041         */
25042        int mDisabledSystemUiVisibility;
25043
25044        /**
25045         * Last global system UI visibility reported by the window manager.
25046         */
25047        int mGlobalSystemUiVisibility = -1;
25048
25049        /**
25050         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
25051         * attached.
25052         */
25053        boolean mHasSystemUiListeners;
25054
25055        /**
25056         * Set if the window has requested to extend into the overscan region
25057         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
25058         */
25059        boolean mOverscanRequested;
25060
25061        /**
25062         * Set if the visibility of any views has changed.
25063         */
25064        boolean mViewVisibilityChanged;
25065
25066        /**
25067         * Set to true if a view has been scrolled.
25068         */
25069        boolean mViewScrollChanged;
25070
25071        /**
25072         * Set to true if high contrast mode enabled
25073         */
25074        boolean mHighContrastText;
25075
25076        /**
25077         * Set to true if a pointer event is currently being handled.
25078         */
25079        boolean mHandlingPointerEvent;
25080
25081        /**
25082         * Global to the view hierarchy used as a temporary for dealing with
25083         * x/y points in the transparent region computations.
25084         */
25085        final int[] mTransparentLocation = new int[2];
25086
25087        /**
25088         * Global to the view hierarchy used as a temporary for dealing with
25089         * x/y points in the ViewGroup.invalidateChild implementation.
25090         */
25091        final int[] mInvalidateChildLocation = new int[2];
25092
25093        /**
25094         * Global to the view hierarchy used as a temporary for dealing with
25095         * computing absolute on-screen location.
25096         */
25097        final int[] mTmpLocation = new int[2];
25098
25099        /**
25100         * Global to the view hierarchy used as a temporary for dealing with
25101         * x/y location when view is transformed.
25102         */
25103        final float[] mTmpTransformLocation = new float[2];
25104
25105        /**
25106         * The view tree observer used to dispatch global events like
25107         * layout, pre-draw, touch mode change, etc.
25108         */
25109        final ViewTreeObserver mTreeObserver;
25110
25111        /**
25112         * A Canvas used by the view hierarchy to perform bitmap caching.
25113         */
25114        Canvas mCanvas;
25115
25116        /**
25117         * The view root impl.
25118         */
25119        final ViewRootImpl mViewRootImpl;
25120
25121        /**
25122         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
25123         * handler can be used to pump events in the UI events queue.
25124         */
25125        final Handler mHandler;
25126
25127        /**
25128         * Temporary for use in computing invalidate rectangles while
25129         * calling up the hierarchy.
25130         */
25131        final Rect mTmpInvalRect = new Rect();
25132
25133        /**
25134         * Temporary for use in computing hit areas with transformed views
25135         */
25136        final RectF mTmpTransformRect = new RectF();
25137
25138        /**
25139         * Temporary for use in computing hit areas with transformed views
25140         */
25141        final RectF mTmpTransformRect1 = new RectF();
25142
25143        /**
25144         * Temporary list of rectanges.
25145         */
25146        final List<RectF> mTmpRectList = new ArrayList<>();
25147
25148        /**
25149         * Temporary for use in transforming invalidation rect
25150         */
25151        final Matrix mTmpMatrix = new Matrix();
25152
25153        /**
25154         * Temporary for use in transforming invalidation rect
25155         */
25156        final Transformation mTmpTransformation = new Transformation();
25157
25158        /**
25159         * Temporary for use in querying outlines from OutlineProviders
25160         */
25161        final Outline mTmpOutline = new Outline();
25162
25163        /**
25164         * Temporary list for use in collecting focusable descendents of a view.
25165         */
25166        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
25167
25168        /**
25169         * The id of the window for accessibility purposes.
25170         */
25171        int mAccessibilityWindowId = AccessibilityWindowInfo.UNDEFINED_WINDOW_ID;
25172
25173        /**
25174         * Flags related to accessibility processing.
25175         *
25176         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
25177         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
25178         */
25179        int mAccessibilityFetchFlags;
25180
25181        /**
25182         * The drawable for highlighting accessibility focus.
25183         */
25184        Drawable mAccessibilityFocusDrawable;
25185
25186        /**
25187         * The drawable for highlighting autofilled views.
25188         *
25189         * @see #isAutofilled()
25190         */
25191        Drawable mAutofilledDrawable;
25192
25193        /**
25194         * Show where the margins, bounds and layout bounds are for each view.
25195         */
25196        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
25197
25198        /**
25199         * Point used to compute visible regions.
25200         */
25201        final Point mPoint = new Point();
25202
25203        /**
25204         * Used to track which View originated a requestLayout() call, used when
25205         * requestLayout() is called during layout.
25206         */
25207        View mViewRequestingLayout;
25208
25209        /**
25210         * Used to track views that need (at least) a partial relayout at their current size
25211         * during the next traversal.
25212         */
25213        List<View> mPartialLayoutViews = new ArrayList<>();
25214
25215        /**
25216         * Swapped with mPartialLayoutViews during layout to avoid concurrent
25217         * modification. Lazily assigned during ViewRootImpl layout.
25218         */
25219        List<View> mEmptyPartialLayoutViews;
25220
25221        /**
25222         * Used to track the identity of the current drag operation.
25223         */
25224        IBinder mDragToken;
25225
25226        /**
25227         * The drag shadow surface for the current drag operation.
25228         */
25229        public Surface mDragSurface;
25230
25231
25232        /**
25233         * The view that currently has a tooltip displayed.
25234         */
25235        View mTooltipHost;
25236
25237        /**
25238         * Creates a new set of attachment information with the specified
25239         * events handler and thread.
25240         *
25241         * @param handler the events handler the view must use
25242         */
25243        AttachInfo(IWindowSession session, IWindow window, Display display,
25244                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer,
25245                Context context) {
25246            mSession = session;
25247            mWindow = window;
25248            mWindowToken = window.asBinder();
25249            mDisplay = display;
25250            mViewRootImpl = viewRootImpl;
25251            mHandler = handler;
25252            mRootCallbacks = effectPlayer;
25253            mTreeObserver = new ViewTreeObserver(context);
25254        }
25255    }
25256
25257    /**
25258     * <p>ScrollabilityCache holds various fields used by a View when scrolling
25259     * is supported. This avoids keeping too many unused fields in most
25260     * instances of View.</p>
25261     */
25262    private static class ScrollabilityCache implements Runnable {
25263
25264        /**
25265         * Scrollbars are not visible
25266         */
25267        public static final int OFF = 0;
25268
25269        /**
25270         * Scrollbars are visible
25271         */
25272        public static final int ON = 1;
25273
25274        /**
25275         * Scrollbars are fading away
25276         */
25277        public static final int FADING = 2;
25278
25279        public boolean fadeScrollBars;
25280
25281        public int fadingEdgeLength;
25282        public int scrollBarDefaultDelayBeforeFade;
25283        public int scrollBarFadeDuration;
25284
25285        public int scrollBarSize;
25286        public int scrollBarMinTouchTarget;
25287        public ScrollBarDrawable scrollBar;
25288        public float[] interpolatorValues;
25289        public View host;
25290
25291        public final Paint paint;
25292        public final Matrix matrix;
25293        public Shader shader;
25294
25295        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
25296
25297        private static final float[] OPAQUE = { 255 };
25298        private static final float[] TRANSPARENT = { 0.0f };
25299
25300        /**
25301         * When fading should start. This time moves into the future every time
25302         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
25303         */
25304        public long fadeStartTime;
25305
25306
25307        /**
25308         * The current state of the scrollbars: ON, OFF, or FADING
25309         */
25310        public int state = OFF;
25311
25312        private int mLastColor;
25313
25314        public final Rect mScrollBarBounds = new Rect();
25315        public final Rect mScrollBarTouchBounds = new Rect();
25316
25317        public static final int NOT_DRAGGING = 0;
25318        public static final int DRAGGING_VERTICAL_SCROLL_BAR = 1;
25319        public static final int DRAGGING_HORIZONTAL_SCROLL_BAR = 2;
25320        public int mScrollBarDraggingState = NOT_DRAGGING;
25321
25322        public float mScrollBarDraggingPos = 0;
25323
25324        public ScrollabilityCache(ViewConfiguration configuration, View host) {
25325            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
25326            scrollBarSize = configuration.getScaledScrollBarSize();
25327            scrollBarMinTouchTarget = configuration.getScaledMinScrollbarTouchTarget();
25328            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
25329            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
25330
25331            paint = new Paint();
25332            matrix = new Matrix();
25333            // use use a height of 1, and then wack the matrix each time we
25334            // actually use it.
25335            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
25336            paint.setShader(shader);
25337            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
25338
25339            this.host = host;
25340        }
25341
25342        public void setFadeColor(int color) {
25343            if (color != mLastColor) {
25344                mLastColor = color;
25345
25346                if (color != 0) {
25347                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
25348                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
25349                    paint.setShader(shader);
25350                    // Restore the default transfer mode (src_over)
25351                    paint.setXfermode(null);
25352                } else {
25353                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
25354                    paint.setShader(shader);
25355                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
25356                }
25357            }
25358        }
25359
25360        public void run() {
25361            long now = AnimationUtils.currentAnimationTimeMillis();
25362            if (now >= fadeStartTime) {
25363
25364                // the animation fades the scrollbars out by changing
25365                // the opacity (alpha) from fully opaque to fully
25366                // transparent
25367                int nextFrame = (int) now;
25368                int framesCount = 0;
25369
25370                Interpolator interpolator = scrollBarInterpolator;
25371
25372                // Start opaque
25373                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
25374
25375                // End transparent
25376                nextFrame += scrollBarFadeDuration;
25377                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
25378
25379                state = FADING;
25380
25381                // Kick off the fade animation
25382                host.invalidate(true);
25383            }
25384        }
25385    }
25386
25387    /**
25388     * Resuable callback for sending
25389     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
25390     */
25391    private class SendViewScrolledAccessibilityEvent implements Runnable {
25392        public volatile boolean mIsPending;
25393
25394        public void run() {
25395            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
25396            mIsPending = false;
25397        }
25398    }
25399
25400    /**
25401     * <p>
25402     * This class represents a delegate that can be registered in a {@link View}
25403     * to enhance accessibility support via composition rather via inheritance.
25404     * It is specifically targeted to widget developers that extend basic View
25405     * classes i.e. classes in package android.view, that would like their
25406     * applications to be backwards compatible.
25407     * </p>
25408     * <div class="special reference">
25409     * <h3>Developer Guides</h3>
25410     * <p>For more information about making applications accessible, read the
25411     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
25412     * developer guide.</p>
25413     * </div>
25414     * <p>
25415     * A scenario in which a developer would like to use an accessibility delegate
25416     * is overriding a method introduced in a later API version than the minimal API
25417     * version supported by the application. For example, the method
25418     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
25419     * in API version 4 when the accessibility APIs were first introduced. If a
25420     * developer would like his application to run on API version 4 devices (assuming
25421     * all other APIs used by the application are version 4 or lower) and take advantage
25422     * of this method, instead of overriding the method which would break the application's
25423     * backwards compatibility, he can override the corresponding method in this
25424     * delegate and register the delegate in the target View if the API version of
25425     * the system is high enough, i.e. the API version is the same as or higher than the API
25426     * version that introduced
25427     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
25428     * </p>
25429     * <p>
25430     * Here is an example implementation:
25431     * </p>
25432     * <code><pre><p>
25433     * if (Build.VERSION.SDK_INT >= 14) {
25434     *     // If the API version is equal of higher than the version in
25435     *     // which onInitializeAccessibilityNodeInfo was introduced we
25436     *     // register a delegate with a customized implementation.
25437     *     View view = findViewById(R.id.view_id);
25438     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
25439     *         public void onInitializeAccessibilityNodeInfo(View host,
25440     *                 AccessibilityNodeInfo info) {
25441     *             // Let the default implementation populate the info.
25442     *             super.onInitializeAccessibilityNodeInfo(host, info);
25443     *             // Set some other information.
25444     *             info.setEnabled(host.isEnabled());
25445     *         }
25446     *     });
25447     * }
25448     * </code></pre></p>
25449     * <p>
25450     * This delegate contains methods that correspond to the accessibility methods
25451     * in View. If a delegate has been specified the implementation in View hands
25452     * off handling to the corresponding method in this delegate. The default
25453     * implementation the delegate methods behaves exactly as the corresponding
25454     * method in View for the case of no accessibility delegate been set. Hence,
25455     * to customize the behavior of a View method, clients can override only the
25456     * corresponding delegate method without altering the behavior of the rest
25457     * accessibility related methods of the host view.
25458     * </p>
25459     * <p>
25460     * <strong>Note:</strong> On platform versions prior to
25461     * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on
25462     * views in the {@code android.widget.*} package are called <i>before</i>
25463     * host methods. This prevents certain properties such as class name from
25464     * being modified by overriding
25465     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)},
25466     * as any changes will be overwritten by the host class.
25467     * <p>
25468     * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate
25469     * methods are called <i>after</i> host methods, which all properties to be
25470     * modified without being overwritten by the host class.
25471     */
25472    public static class AccessibilityDelegate {
25473
25474        /**
25475         * Sends an accessibility event of the given type. If accessibility is not
25476         * enabled this method has no effect.
25477         * <p>
25478         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
25479         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
25480         * been set.
25481         * </p>
25482         *
25483         * @param host The View hosting the delegate.
25484         * @param eventType The type of the event to send.
25485         *
25486         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
25487         */
25488        public void sendAccessibilityEvent(View host, int eventType) {
25489            host.sendAccessibilityEventInternal(eventType);
25490        }
25491
25492        /**
25493         * Performs the specified accessibility action on the view. For
25494         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
25495         * <p>
25496         * The default implementation behaves as
25497         * {@link View#performAccessibilityAction(int, Bundle)
25498         *  View#performAccessibilityAction(int, Bundle)} for the case of
25499         *  no accessibility delegate been set.
25500         * </p>
25501         *
25502         * @param action The action to perform.
25503         * @return Whether the action was performed.
25504         *
25505         * @see View#performAccessibilityAction(int, Bundle)
25506         *      View#performAccessibilityAction(int, Bundle)
25507         */
25508        public boolean performAccessibilityAction(View host, int action, Bundle args) {
25509            return host.performAccessibilityActionInternal(action, args);
25510        }
25511
25512        /**
25513         * Sends an accessibility event. This method behaves exactly as
25514         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
25515         * empty {@link AccessibilityEvent} and does not perform a check whether
25516         * accessibility is enabled.
25517         * <p>
25518         * The default implementation behaves as
25519         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
25520         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
25521         * the case of no accessibility delegate been set.
25522         * </p>
25523         *
25524         * @param host The View hosting the delegate.
25525         * @param event The event to send.
25526         *
25527         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
25528         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
25529         */
25530        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
25531            host.sendAccessibilityEventUncheckedInternal(event);
25532        }
25533
25534        /**
25535         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
25536         * to its children for adding their text content to the event.
25537         * <p>
25538         * The default implementation behaves as
25539         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
25540         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
25541         * the case of no accessibility delegate been set.
25542         * </p>
25543         *
25544         * @param host The View hosting the delegate.
25545         * @param event The event.
25546         * @return True if the event population was completed.
25547         *
25548         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
25549         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
25550         */
25551        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
25552            return host.dispatchPopulateAccessibilityEventInternal(event);
25553        }
25554
25555        /**
25556         * Gives a chance to the host View to populate the accessibility event with its
25557         * text content.
25558         * <p>
25559         * The default implementation behaves as
25560         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
25561         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
25562         * the case of no accessibility delegate been set.
25563         * </p>
25564         *
25565         * @param host The View hosting the delegate.
25566         * @param event The accessibility event which to populate.
25567         *
25568         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
25569         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
25570         */
25571        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
25572            host.onPopulateAccessibilityEventInternal(event);
25573        }
25574
25575        /**
25576         * Initializes an {@link AccessibilityEvent} with information about the
25577         * the host View which is the event source.
25578         * <p>
25579         * The default implementation behaves as
25580         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
25581         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
25582         * the case of no accessibility delegate been set.
25583         * </p>
25584         *
25585         * @param host The View hosting the delegate.
25586         * @param event The event to initialize.
25587         *
25588         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
25589         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
25590         */
25591        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
25592            host.onInitializeAccessibilityEventInternal(event);
25593        }
25594
25595        /**
25596         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
25597         * <p>
25598         * The default implementation behaves as
25599         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
25600         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
25601         * the case of no accessibility delegate been set.
25602         * </p>
25603         *
25604         * @param host The View hosting the delegate.
25605         * @param info The instance to initialize.
25606         *
25607         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
25608         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
25609         */
25610        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
25611            host.onInitializeAccessibilityNodeInfoInternal(info);
25612        }
25613
25614        /**
25615         * Adds extra data to an {@link AccessibilityNodeInfo} based on an explicit request for the
25616         * additional data.
25617         * <p>
25618         * This method only needs to be implemented if the View offers to provide additional data.
25619         * </p>
25620         * <p>
25621         * The default implementation behaves as
25622         * {@link View#addExtraDataToAccessibilityNodeInfo(AccessibilityNodeInfo, int) for
25623         * the case where no accessibility delegate is set.
25624         * </p>
25625         *
25626         * @param host The View hosting the delegate. Never {@code null}.
25627         * @param info The info to which to add the extra data. Never {@code null}.
25628         * @param extraDataKey A key specifying the type of extra data to add to the info. The
25629         *                     extra data should be added to the {@link Bundle} returned by
25630         *                     the info's {@link AccessibilityNodeInfo#getExtras} method.  Never
25631         *                     {@code null}.
25632         * @param arguments A {@link Bundle} holding any arguments relevant for this request.
25633         *                  May be {@code null} if the if the service provided no arguments.
25634         *
25635         * @see AccessibilityNodeInfo#setExtraAvailableData
25636         */
25637        public void addExtraDataToAccessibilityNodeInfo(@NonNull View host,
25638                @NonNull AccessibilityNodeInfo info, @NonNull String extraDataKey,
25639                @Nullable Bundle arguments) {
25640            host.addExtraDataToAccessibilityNodeInfo(info, extraDataKey, arguments);
25641        }
25642
25643        /**
25644         * Called when a child of the host View has requested sending an
25645         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
25646         * to augment the event.
25647         * <p>
25648         * The default implementation behaves as
25649         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
25650         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
25651         * the case of no accessibility delegate been set.
25652         * </p>
25653         *
25654         * @param host The View hosting the delegate.
25655         * @param child The child which requests sending the event.
25656         * @param event The event to be sent.
25657         * @return True if the event should be sent
25658         *
25659         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
25660         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
25661         */
25662        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
25663                AccessibilityEvent event) {
25664            return host.onRequestSendAccessibilityEventInternal(child, event);
25665        }
25666
25667        /**
25668         * Gets the provider for managing a virtual view hierarchy rooted at this View
25669         * and reported to {@link android.accessibilityservice.AccessibilityService}s
25670         * that explore the window content.
25671         * <p>
25672         * The default implementation behaves as
25673         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
25674         * the case of no accessibility delegate been set.
25675         * </p>
25676         *
25677         * @return The provider.
25678         *
25679         * @see AccessibilityNodeProvider
25680         */
25681        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
25682            return null;
25683        }
25684
25685        /**
25686         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
25687         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
25688         * This method is responsible for obtaining an accessibility node info from a
25689         * pool of reusable instances and calling
25690         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
25691         * view to initialize the former.
25692         * <p>
25693         * <strong>Note:</strong> The client is responsible for recycling the obtained
25694         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
25695         * creation.
25696         * </p>
25697         * <p>
25698         * The default implementation behaves as
25699         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
25700         * the case of no accessibility delegate been set.
25701         * </p>
25702         * @return A populated {@link AccessibilityNodeInfo}.
25703         *
25704         * @see AccessibilityNodeInfo
25705         *
25706         * @hide
25707         */
25708        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
25709            return host.createAccessibilityNodeInfoInternal();
25710        }
25711    }
25712
25713    private static class MatchIdPredicate implements Predicate<View> {
25714        public int mId;
25715
25716        @Override
25717        public boolean test(View view) {
25718            return (view.mID == mId);
25719        }
25720    }
25721
25722    private static class MatchLabelForPredicate implements Predicate<View> {
25723        private int mLabeledId;
25724
25725        @Override
25726        public boolean test(View view) {
25727            return (view.mLabelForId == mLabeledId);
25728        }
25729    }
25730
25731    private class SendViewStateChangedAccessibilityEvent implements Runnable {
25732        private int mChangeTypes = 0;
25733        private boolean mPosted;
25734        private boolean mPostedWithDelay;
25735        private long mLastEventTimeMillis;
25736
25737        @Override
25738        public void run() {
25739            mPosted = false;
25740            mPostedWithDelay = false;
25741            mLastEventTimeMillis = SystemClock.uptimeMillis();
25742            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
25743                final AccessibilityEvent event = AccessibilityEvent.obtain();
25744                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
25745                event.setContentChangeTypes(mChangeTypes);
25746                sendAccessibilityEventUnchecked(event);
25747            }
25748            mChangeTypes = 0;
25749        }
25750
25751        public void runOrPost(int changeType) {
25752            mChangeTypes |= changeType;
25753
25754            // If this is a live region or the child of a live region, collect
25755            // all events from this frame and send them on the next frame.
25756            if (inLiveRegion()) {
25757                // If we're already posted with a delay, remove that.
25758                if (mPostedWithDelay) {
25759                    removeCallbacks(this);
25760                    mPostedWithDelay = false;
25761                }
25762                // Only post if we're not already posted.
25763                if (!mPosted) {
25764                    post(this);
25765                    mPosted = true;
25766                }
25767                return;
25768            }
25769
25770            if (mPosted) {
25771                return;
25772            }
25773
25774            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
25775            final long minEventIntevalMillis =
25776                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
25777            if (timeSinceLastMillis >= minEventIntevalMillis) {
25778                removeCallbacks(this);
25779                run();
25780            } else {
25781                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
25782                mPostedWithDelay = true;
25783            }
25784        }
25785    }
25786
25787    private boolean inLiveRegion() {
25788        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
25789            return true;
25790        }
25791
25792        ViewParent parent = getParent();
25793        while (parent instanceof View) {
25794            if (((View) parent).getAccessibilityLiveRegion()
25795                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
25796                return true;
25797            }
25798            parent = parent.getParent();
25799        }
25800
25801        return false;
25802    }
25803
25804    /**
25805     * Dump all private flags in readable format, useful for documentation and
25806     * sanity checking.
25807     */
25808    private static void dumpFlags() {
25809        final HashMap<String, String> found = Maps.newHashMap();
25810        try {
25811            for (Field field : View.class.getDeclaredFields()) {
25812                final int modifiers = field.getModifiers();
25813                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
25814                    if (field.getType().equals(int.class)) {
25815                        final int value = field.getInt(null);
25816                        dumpFlag(found, field.getName(), value);
25817                    } else if (field.getType().equals(int[].class)) {
25818                        final int[] values = (int[]) field.get(null);
25819                        for (int i = 0; i < values.length; i++) {
25820                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
25821                        }
25822                    }
25823                }
25824            }
25825        } catch (IllegalAccessException e) {
25826            throw new RuntimeException(e);
25827        }
25828
25829        final ArrayList<String> keys = Lists.newArrayList();
25830        keys.addAll(found.keySet());
25831        Collections.sort(keys);
25832        for (String key : keys) {
25833            Log.d(VIEW_LOG_TAG, found.get(key));
25834        }
25835    }
25836
25837    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
25838        // Sort flags by prefix, then by bits, always keeping unique keys
25839        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
25840        final int prefix = name.indexOf('_');
25841        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
25842        final String output = bits + " " + name;
25843        found.put(key, output);
25844    }
25845
25846    /** {@hide} */
25847    public void encode(@NonNull ViewHierarchyEncoder stream) {
25848        stream.beginObject(this);
25849        encodeProperties(stream);
25850        stream.endObject();
25851    }
25852
25853    /** {@hide} */
25854    @CallSuper
25855    protected void encodeProperties(@NonNull ViewHierarchyEncoder stream) {
25856        Object resolveId = ViewDebug.resolveId(getContext(), mID);
25857        if (resolveId instanceof String) {
25858            stream.addProperty("id", (String) resolveId);
25859        } else {
25860            stream.addProperty("id", mID);
25861        }
25862
25863        stream.addProperty("misc:transformation.alpha",
25864                mTransformationInfo != null ? mTransformationInfo.mAlpha : 0);
25865        stream.addProperty("misc:transitionName", getTransitionName());
25866
25867        // layout
25868        stream.addProperty("layout:left", mLeft);
25869        stream.addProperty("layout:right", mRight);
25870        stream.addProperty("layout:top", mTop);
25871        stream.addProperty("layout:bottom", mBottom);
25872        stream.addProperty("layout:width", getWidth());
25873        stream.addProperty("layout:height", getHeight());
25874        stream.addProperty("layout:layoutDirection", getLayoutDirection());
25875        stream.addProperty("layout:layoutRtl", isLayoutRtl());
25876        stream.addProperty("layout:hasTransientState", hasTransientState());
25877        stream.addProperty("layout:baseline", getBaseline());
25878
25879        // layout params
25880        ViewGroup.LayoutParams layoutParams = getLayoutParams();
25881        if (layoutParams != null) {
25882            stream.addPropertyKey("layoutParams");
25883            layoutParams.encode(stream);
25884        }
25885
25886        // scrolling
25887        stream.addProperty("scrolling:scrollX", mScrollX);
25888        stream.addProperty("scrolling:scrollY", mScrollY);
25889
25890        // padding
25891        stream.addProperty("padding:paddingLeft", mPaddingLeft);
25892        stream.addProperty("padding:paddingRight", mPaddingRight);
25893        stream.addProperty("padding:paddingTop", mPaddingTop);
25894        stream.addProperty("padding:paddingBottom", mPaddingBottom);
25895        stream.addProperty("padding:userPaddingRight", mUserPaddingRight);
25896        stream.addProperty("padding:userPaddingLeft", mUserPaddingLeft);
25897        stream.addProperty("padding:userPaddingBottom", mUserPaddingBottom);
25898        stream.addProperty("padding:userPaddingStart", mUserPaddingStart);
25899        stream.addProperty("padding:userPaddingEnd", mUserPaddingEnd);
25900
25901        // measurement
25902        stream.addProperty("measurement:minHeight", mMinHeight);
25903        stream.addProperty("measurement:minWidth", mMinWidth);
25904        stream.addProperty("measurement:measuredWidth", mMeasuredWidth);
25905        stream.addProperty("measurement:measuredHeight", mMeasuredHeight);
25906
25907        // drawing
25908        stream.addProperty("drawing:elevation", getElevation());
25909        stream.addProperty("drawing:translationX", getTranslationX());
25910        stream.addProperty("drawing:translationY", getTranslationY());
25911        stream.addProperty("drawing:translationZ", getTranslationZ());
25912        stream.addProperty("drawing:rotation", getRotation());
25913        stream.addProperty("drawing:rotationX", getRotationX());
25914        stream.addProperty("drawing:rotationY", getRotationY());
25915        stream.addProperty("drawing:scaleX", getScaleX());
25916        stream.addProperty("drawing:scaleY", getScaleY());
25917        stream.addProperty("drawing:pivotX", getPivotX());
25918        stream.addProperty("drawing:pivotY", getPivotY());
25919        stream.addProperty("drawing:opaque", isOpaque());
25920        stream.addProperty("drawing:alpha", getAlpha());
25921        stream.addProperty("drawing:transitionAlpha", getTransitionAlpha());
25922        stream.addProperty("drawing:shadow", hasShadow());
25923        stream.addProperty("drawing:solidColor", getSolidColor());
25924        stream.addProperty("drawing:layerType", mLayerType);
25925        stream.addProperty("drawing:willNotDraw", willNotDraw());
25926        stream.addProperty("drawing:hardwareAccelerated", isHardwareAccelerated());
25927        stream.addProperty("drawing:willNotCacheDrawing", willNotCacheDrawing());
25928        stream.addProperty("drawing:drawingCacheEnabled", isDrawingCacheEnabled());
25929        stream.addProperty("drawing:overlappingRendering", hasOverlappingRendering());
25930
25931        // focus
25932        stream.addProperty("focus:hasFocus", hasFocus());
25933        stream.addProperty("focus:isFocused", isFocused());
25934        stream.addProperty("focus:focusable", getFocusable());
25935        stream.addProperty("focus:isFocusable", isFocusable());
25936        stream.addProperty("focus:isFocusableInTouchMode", isFocusableInTouchMode());
25937
25938        stream.addProperty("misc:clickable", isClickable());
25939        stream.addProperty("misc:pressed", isPressed());
25940        stream.addProperty("misc:selected", isSelected());
25941        stream.addProperty("misc:touchMode", isInTouchMode());
25942        stream.addProperty("misc:hovered", isHovered());
25943        stream.addProperty("misc:activated", isActivated());
25944
25945        stream.addProperty("misc:visibility", getVisibility());
25946        stream.addProperty("misc:fitsSystemWindows", getFitsSystemWindows());
25947        stream.addProperty("misc:filterTouchesWhenObscured", getFilterTouchesWhenObscured());
25948
25949        stream.addProperty("misc:enabled", isEnabled());
25950        stream.addProperty("misc:soundEffectsEnabled", isSoundEffectsEnabled());
25951        stream.addProperty("misc:hapticFeedbackEnabled", isHapticFeedbackEnabled());
25952
25953        // theme attributes
25954        Resources.Theme theme = getContext().getTheme();
25955        if (theme != null) {
25956            stream.addPropertyKey("theme");
25957            theme.encode(stream);
25958        }
25959
25960        // view attribute information
25961        int n = mAttributes != null ? mAttributes.length : 0;
25962        stream.addProperty("meta:__attrCount__", n/2);
25963        for (int i = 0; i < n; i += 2) {
25964            stream.addProperty("meta:__attr__" + mAttributes[i], mAttributes[i+1]);
25965        }
25966
25967        stream.addProperty("misc:scrollBarStyle", getScrollBarStyle());
25968
25969        // text
25970        stream.addProperty("text:textDirection", getTextDirection());
25971        stream.addProperty("text:textAlignment", getTextAlignment());
25972
25973        // accessibility
25974        CharSequence contentDescription = getContentDescription();
25975        stream.addProperty("accessibility:contentDescription",
25976                contentDescription == null ? "" : contentDescription.toString());
25977        stream.addProperty("accessibility:labelFor", getLabelFor());
25978        stream.addProperty("accessibility:importantForAccessibility", getImportantForAccessibility());
25979    }
25980
25981    /**
25982     * Determine if this view is rendered on a round wearable device and is the main view
25983     * on the screen.
25984     */
25985    boolean shouldDrawRoundScrollbar() {
25986        if (!mResources.getConfiguration().isScreenRound() || mAttachInfo == null) {
25987            return false;
25988        }
25989
25990        final View rootView = getRootView();
25991        final WindowInsets insets = getRootWindowInsets();
25992
25993        int height = getHeight();
25994        int width = getWidth();
25995        int displayHeight = rootView.getHeight();
25996        int displayWidth = rootView.getWidth();
25997
25998        if (height != displayHeight || width != displayWidth) {
25999            return false;
26000        }
26001
26002        getLocationInWindow(mAttachInfo.mTmpLocation);
26003        return mAttachInfo.mTmpLocation[0] == insets.getStableInsetLeft()
26004                && mAttachInfo.mTmpLocation[1] == insets.getStableInsetTop();
26005    }
26006
26007    /**
26008     * Sets the tooltip text which will be displayed in a small popup next to the view.
26009     * <p>
26010     * The tooltip will be displayed:
26011     * <ul>
26012     * <li>On long click, unless it is handled otherwise (by OnLongClickListener or a context
26013     * menu). </li>
26014     * <li>On hover, after a brief delay since the pointer has stopped moving </li>
26015     * </ul>
26016     * <p>
26017     * <strong>Note:</strong> Do not override this method, as it will have no
26018     * effect on the text displayed in the tooltip.
26019     *
26020     * @param tooltipText the tooltip text, or null if no tooltip is required
26021     * @see #getTooltipText()
26022     * @attr ref android.R.styleable#View_tooltipText
26023     */
26024    public void setTooltipText(@Nullable CharSequence tooltipText) {
26025        if (TextUtils.isEmpty(tooltipText)) {
26026            setFlags(0, TOOLTIP);
26027            hideTooltip();
26028            mTooltipInfo = null;
26029        } else {
26030            setFlags(TOOLTIP, TOOLTIP);
26031            if (mTooltipInfo == null) {
26032                mTooltipInfo = new TooltipInfo();
26033                mTooltipInfo.mShowTooltipRunnable = this::showHoverTooltip;
26034                mTooltipInfo.mHideTooltipRunnable = this::hideTooltip;
26035            }
26036            mTooltipInfo.mTooltipText = tooltipText;
26037            if (mTooltipInfo.mTooltipPopup != null && mTooltipInfo.mTooltipPopup.isShowing()) {
26038                mTooltipInfo.mTooltipPopup.updateContent(mTooltipInfo.mTooltipText);
26039            }
26040        }
26041    }
26042
26043    /**
26044     * @hide Binary compatibility stub. To be removed when we finalize O APIs.
26045     */
26046    public void setTooltip(@Nullable CharSequence tooltipText) {
26047        setTooltipText(tooltipText);
26048    }
26049
26050    /**
26051     * Returns the view's tooltip text.
26052     *
26053     * <strong>Note:</strong> Do not override this method, as it will have no
26054     * effect on the text displayed in the tooltip. You must call
26055     * {@link #setTooltipText(CharSequence)} to modify the tooltip text.
26056     *
26057     * @return the tooltip text
26058     * @see #setTooltipText(CharSequence)
26059     * @attr ref android.R.styleable#View_tooltipText
26060     */
26061    @Nullable
26062    public CharSequence getTooltipText() {
26063        return mTooltipInfo != null ? mTooltipInfo.mTooltipText : null;
26064    }
26065
26066    /**
26067     * @hide Binary compatibility stub. To be removed when we finalize O APIs.
26068     */
26069    @Nullable
26070    public CharSequence getTooltip() {
26071        return getTooltipText();
26072    }
26073
26074    private boolean showTooltip(int x, int y, boolean fromLongClick) {
26075        if (mAttachInfo == null || mTooltipInfo == null) {
26076            return false;
26077        }
26078        if ((mViewFlags & ENABLED_MASK) != ENABLED) {
26079            return false;
26080        }
26081        if (TextUtils.isEmpty(mTooltipInfo.mTooltipText)) {
26082            return false;
26083        }
26084        hideTooltip();
26085        mTooltipInfo.mTooltipFromLongClick = fromLongClick;
26086        mTooltipInfo.mTooltipPopup = new TooltipPopup(getContext());
26087        final boolean fromTouch = (mPrivateFlags3 & PFLAG3_FINGER_DOWN) == PFLAG3_FINGER_DOWN;
26088        mTooltipInfo.mTooltipPopup.show(this, x, y, fromTouch, mTooltipInfo.mTooltipText);
26089        mAttachInfo.mTooltipHost = this;
26090        return true;
26091    }
26092
26093    void hideTooltip() {
26094        if (mTooltipInfo == null) {
26095            return;
26096        }
26097        removeCallbacks(mTooltipInfo.mShowTooltipRunnable);
26098        if (mTooltipInfo.mTooltipPopup == null) {
26099            return;
26100        }
26101        mTooltipInfo.mTooltipPopup.hide();
26102        mTooltipInfo.mTooltipPopup = null;
26103        mTooltipInfo.mTooltipFromLongClick = false;
26104        if (mAttachInfo != null) {
26105            mAttachInfo.mTooltipHost = null;
26106        }
26107    }
26108
26109    private boolean showLongClickTooltip(int x, int y) {
26110        removeCallbacks(mTooltipInfo.mShowTooltipRunnable);
26111        removeCallbacks(mTooltipInfo.mHideTooltipRunnable);
26112        return showTooltip(x, y, true);
26113    }
26114
26115    private void showHoverTooltip() {
26116        showTooltip(mTooltipInfo.mAnchorX, mTooltipInfo.mAnchorY, false);
26117    }
26118
26119    boolean dispatchTooltipHoverEvent(MotionEvent event) {
26120        if (mTooltipInfo == null) {
26121            return false;
26122        }
26123        switch(event.getAction()) {
26124            case MotionEvent.ACTION_HOVER_MOVE:
26125                if ((mViewFlags & TOOLTIP) != TOOLTIP || (mViewFlags & ENABLED_MASK) != ENABLED) {
26126                    break;
26127                }
26128                if (!mTooltipInfo.mTooltipFromLongClick) {
26129                    if (mTooltipInfo.mTooltipPopup == null) {
26130                        // Schedule showing the tooltip after a timeout.
26131                        mTooltipInfo.mAnchorX = (int) event.getX();
26132                        mTooltipInfo.mAnchorY = (int) event.getY();
26133                        removeCallbacks(mTooltipInfo.mShowTooltipRunnable);
26134                        postDelayed(mTooltipInfo.mShowTooltipRunnable,
26135                                ViewConfiguration.getHoverTooltipShowTimeout());
26136                    }
26137
26138                    // Hide hover-triggered tooltip after a period of inactivity.
26139                    // Match the timeout used by NativeInputManager to hide the mouse pointer
26140                    // (depends on SYSTEM_UI_FLAG_LOW_PROFILE being set).
26141                    final int timeout;
26142                    if ((getWindowSystemUiVisibility() & SYSTEM_UI_FLAG_LOW_PROFILE)
26143                            == SYSTEM_UI_FLAG_LOW_PROFILE) {
26144                        timeout = ViewConfiguration.getHoverTooltipHideShortTimeout();
26145                    } else {
26146                        timeout = ViewConfiguration.getHoverTooltipHideTimeout();
26147                    }
26148                    removeCallbacks(mTooltipInfo.mHideTooltipRunnable);
26149                    postDelayed(mTooltipInfo.mHideTooltipRunnable, timeout);
26150                }
26151                return true;
26152
26153            case MotionEvent.ACTION_HOVER_EXIT:
26154                if (!mTooltipInfo.mTooltipFromLongClick) {
26155                    hideTooltip();
26156                }
26157                break;
26158        }
26159        return false;
26160    }
26161
26162    void handleTooltipKey(KeyEvent event) {
26163        switch (event.getAction()) {
26164            case KeyEvent.ACTION_DOWN:
26165                if (event.getRepeatCount() == 0) {
26166                    hideTooltip();
26167                }
26168                break;
26169
26170            case KeyEvent.ACTION_UP:
26171                handleTooltipUp();
26172                break;
26173        }
26174    }
26175
26176    private void handleTooltipUp() {
26177        if (mTooltipInfo == null || mTooltipInfo.mTooltipPopup == null) {
26178            return;
26179        }
26180        removeCallbacks(mTooltipInfo.mHideTooltipRunnable);
26181        postDelayed(mTooltipInfo.mHideTooltipRunnable,
26182                ViewConfiguration.getLongPressTooltipHideTimeout());
26183    }
26184
26185    private int getFocusableAttribute(TypedArray attributes) {
26186        TypedValue val = new TypedValue();
26187        if (attributes.getValue(com.android.internal.R.styleable.View_focusable, val)) {
26188            if (val.type == TypedValue.TYPE_INT_BOOLEAN) {
26189                return (val.data == 0 ? NOT_FOCUSABLE : FOCUSABLE);
26190            } else {
26191                return val.data;
26192            }
26193        } else {
26194            return FOCUSABLE_AUTO;
26195        }
26196    }
26197
26198    /**
26199     * @return The content view of the tooltip popup currently being shown, or null if the tooltip
26200     * is not showing.
26201     * @hide
26202     */
26203    @TestApi
26204    public View getTooltipView() {
26205        if (mTooltipInfo == null || mTooltipInfo.mTooltipPopup == null) {
26206            return null;
26207        }
26208        return mTooltipInfo.mTooltipPopup.getContentView();
26209    }
26210}
26211